var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
//# sourceMappingURL=babylon.types.js.map
var BABYLON;
(function (BABYLON) {
var KeyboardEventTypes = /** @class */ (function () {
function KeyboardEventTypes() {
}
Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
get: function () {
return KeyboardEventTypes._KEYDOWN;
},
enumerable: true,
configurable: true
});
Object.defineProperty(KeyboardEventTypes, "KEYUP", {
get: function () {
return KeyboardEventTypes._KEYUP;
},
enumerable: true,
configurable: true
});
KeyboardEventTypes._KEYDOWN = 0x01;
KeyboardEventTypes._KEYUP = 0x02;
return KeyboardEventTypes;
}());
BABYLON.KeyboardEventTypes = KeyboardEventTypes;
var KeyboardInfo = /** @class */ (function () {
function KeyboardInfo(type, event) {
this.type = type;
this.event = event;
}
return KeyboardInfo;
}());
BABYLON.KeyboardInfo = KeyboardInfo;
/**
* This class is used to store keyboard related info for the onPreKeyboardObservable event.
* Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
*/
var KeyboardInfoPre = /** @class */ (function (_super) {
__extends(KeyboardInfoPre, _super);
function KeyboardInfoPre(type, event) {
var _this = _super.call(this, type, event) || this;
_this.skipOnPointerObservable = false;
return _this;
}
return KeyboardInfoPre;
}(KeyboardInfo));
BABYLON.KeyboardInfoPre = KeyboardInfoPre;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.keyboardEvents.js.map
var BABYLON;
(function (BABYLON) {
var PointerEventTypes = /** @class */ (function () {
function PointerEventTypes() {
}
Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
get: function () {
return PointerEventTypes._POINTERDOWN;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PointerEventTypes, "POINTERUP", {
get: function () {
return PointerEventTypes._POINTERUP;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
get: function () {
return PointerEventTypes._POINTERMOVE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
get: function () {
return PointerEventTypes._POINTERWHEEL;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PointerEventTypes, "POINTERPICK", {
get: function () {
return PointerEventTypes._POINTERPICK;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PointerEventTypes, "POINTERTAP", {
get: function () {
return PointerEventTypes._POINTERTAP;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
get: function () {
return PointerEventTypes._POINTERDOUBLETAP;
},
enumerable: true,
configurable: true
});
PointerEventTypes._POINTERDOWN = 0x01;
PointerEventTypes._POINTERUP = 0x02;
PointerEventTypes._POINTERMOVE = 0x04;
PointerEventTypes._POINTERWHEEL = 0x08;
PointerEventTypes._POINTERPICK = 0x10;
PointerEventTypes._POINTERTAP = 0x20;
PointerEventTypes._POINTERDOUBLETAP = 0x40;
return PointerEventTypes;
}());
BABYLON.PointerEventTypes = PointerEventTypes;
var PointerInfoBase = /** @class */ (function () {
function PointerInfoBase(type, event) {
this.type = type;
this.event = event;
}
return PointerInfoBase;
}());
BABYLON.PointerInfoBase = PointerInfoBase;
/**
* This class is used to store pointer related info for the onPrePointerObservable event.
* Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
*/
var PointerInfoPre = /** @class */ (function (_super) {
__extends(PointerInfoPre, _super);
function PointerInfoPre(type, event, localX, localY) {
var _this = _super.call(this, type, event) || this;
_this.skipOnPointerObservable = false;
_this.localPosition = new BABYLON.Vector2(localX, localY);
return _this;
}
return PointerInfoPre;
}(PointerInfoBase));
BABYLON.PointerInfoPre = PointerInfoPre;
/**
* This type contains all the data related to a pointer event in Babylon.js.
* The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
*/
var PointerInfo = /** @class */ (function (_super) {
__extends(PointerInfo, _super);
function PointerInfo(type, event, pickInfo) {
var _this = _super.call(this, type, event) || this;
_this.pickInfo = pickInfo;
return _this;
}
return PointerInfo;
}(PointerInfoBase));
BABYLON.PointerInfo = PointerInfo;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.pointerEvents.js.map
var BABYLON;
(function (BABYLON) {
BABYLON.ToGammaSpace = 1 / 2.2;
BABYLON.ToLinearSpace = 2.2;
BABYLON.Epsilon = 0.001;
var Color3 = /** @class */ (function () {
/**
* Creates a new Color3 object from red, green, blue values, all between 0 and 1.
*/
function Color3(r, g, b) {
if (r === void 0) { r = 0; }
if (g === void 0) { g = 0; }
if (b === void 0) { b = 0; }
this.r = r;
this.g = g;
this.b = b;
}
/**
* Returns a string with the Color3 current values.
*/
Color3.prototype.toString = function () {
return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
};
/**
* Returns the string "Color3".
*/
Color3.prototype.getClassName = function () {
return "Color3";
};
/**
* Returns the Color3 hash code.
*/
Color3.prototype.getHashCode = function () {
var hash = this.r || 0;
hash = (hash * 397) ^ (this.g || 0);
hash = (hash * 397) ^ (this.b || 0);
return hash;
};
// Operators
/**
* Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
* Returns the Color3.
*/
Color3.prototype.toArray = function (array, index) {
if (index === undefined) {
index = 0;
}
array[index] = this.r;
array[index + 1] = this.g;
array[index + 2] = this.b;
return this;
};
/**
* Returns a new Color4 object from the current Color3 and the passed alpha.
*/
Color3.prototype.toColor4 = function (alpha) {
if (alpha === void 0) { alpha = 1; }
return new Color4(this.r, this.g, this.b, alpha);
};
/**
* Returns a new array populated with 3 numeric elements : red, green and blue values.
*/
Color3.prototype.asArray = function () {
var result = new Array();
this.toArray(result, 0);
return result;
};
/**
* Returns the luminance value (float).
*/
Color3.prototype.toLuminance = function () {
return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
};
/**
* Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
* Returns this new object.
*/
Color3.prototype.multiply = function (otherColor) {
return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
};
/**
* Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
* Returns the current Color3.
*/
Color3.prototype.multiplyToRef = function (otherColor, result) {
result.r = this.r * otherColor.r;
result.g = this.g * otherColor.g;
result.b = this.b * otherColor.b;
return this;
};
/**
* Boolean : True if the rgb values are equal to the passed ones.
*/
Color3.prototype.equals = function (otherColor) {
return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
};
/**
* Boolean : True if the rgb values are equal to the passed ones.
*/
Color3.prototype.equalsFloats = function (r, g, b) {
return this.r === r && this.g === g && this.b === b;
};
/**
* Multiplies in place each rgb value by scale.
* Returns the updated Color3.
*/
Color3.prototype.scale = function (scale) {
return new Color3(this.r * scale, this.g * scale, this.b * scale);
};
/**
* Multiplies the rgb values by scale and stores the result into "result".
* Returns the unmodified current Color3.
*/
Color3.prototype.scaleToRef = function (scale, result) {
result.r = this.r * scale;
result.g = this.g * scale;
result.b = this.b * scale;
return this;
};
/**
* Returns a new Color3 set with the added values of the current Color3 and of the passed one.
*/
Color3.prototype.add = function (otherColor) {
return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
};
/**
* Stores the result of the addition of the current Color3 and passed one rgb values into "result".
* Returns the unmodified current Color3.
*/
Color3.prototype.addToRef = function (otherColor, result) {
result.r = this.r + otherColor.r;
result.g = this.g + otherColor.g;
result.b = this.b + otherColor.b;
return this;
};
/**
* Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
*/
Color3.prototype.subtract = function (otherColor) {
return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
};
/**
* Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
* Returns the unmodified current Color3.
*/
Color3.prototype.subtractToRef = function (otherColor, result) {
result.r = this.r - otherColor.r;
result.g = this.g - otherColor.g;
result.b = this.b - otherColor.b;
return this;
};
/**
* Returns a new Color3 copied the current one.
*/
Color3.prototype.clone = function () {
return new Color3(this.r, this.g, this.b);
};
/**
* Copies the rgb values from the source in the current Color3.
* Returns the updated Color3.
*/
Color3.prototype.copyFrom = function (source) {
this.r = source.r;
this.g = source.g;
this.b = source.b;
return this;
};
/**
* Updates the Color3 rgb values from the passed floats.
* Returns the Color3.
*/
Color3.prototype.copyFromFloats = function (r, g, b) {
this.r = r;
this.g = g;
this.b = b;
return this;
};
/**
* Updates the Color3 rgb values from the passed floats.
* Returns the Color3.
*/
Color3.prototype.set = function (r, g, b) {
return this.copyFromFloats(r, g, b);
};
/**
* Returns the Color3 hexadecimal code as a string.
*/
Color3.prototype.toHexString = function () {
var intR = (this.r * 255) | 0;
var intG = (this.g * 255) | 0;
var intB = (this.b * 255) | 0;
return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
};
/**
* Returns a new Color3 converted to linear space.
*/
Color3.prototype.toLinearSpace = function () {
var convertedColor = new Color3();
this.toLinearSpaceToRef(convertedColor);
return convertedColor;
};
/**
* Converts the Color3 values to linear space and stores the result in "convertedColor".
* Returns the unmodified Color3.
*/
Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
return this;
};
/**
* Returns a new Color3 converted to gamma space.
*/
Color3.prototype.toGammaSpace = function () {
var convertedColor = new Color3();
this.toGammaSpaceToRef(convertedColor);
return convertedColor;
};
/**
* Converts the Color3 values to gamma space and stores the result in "convertedColor".
* Returns the unmodified Color3.
*/
Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
return this;
};
// Statics
/**
* Creates a new Color3 from the string containing valid hexadecimal values.
*/
Color3.FromHexString = function (hex) {
if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
//Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
return new Color3(0, 0, 0);
}
var r = parseInt(hex.substring(1, 3), 16);
var g = parseInt(hex.substring(3, 5), 16);
var b = parseInt(hex.substring(5, 7), 16);
return Color3.FromInts(r, g, b);
};
/**
* Creates a new Vector3 from the startind index of the passed array.
*/
Color3.FromArray = function (array, offset) {
if (offset === void 0) { offset = 0; }
return new Color3(array[offset], array[offset + 1], array[offset + 2]);
};
/**
* Creates a new Color3 from integer values ( < 256).
*/
Color3.FromInts = function (r, g, b) {
return new Color3(r / 255.0, g / 255.0, b / 255.0);
};
/**
* Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
*/
Color3.Lerp = function (start, end, amount) {
var r = start.r + ((end.r - start.r) * amount);
var g = start.g + ((end.g - start.g) * amount);
var b = start.b + ((end.b - start.b) * amount);
return new Color3(r, g, b);
};
Color3.Red = function () { return new Color3(1, 0, 0); };
Color3.Green = function () { return new Color3(0, 1, 0); };
Color3.Blue = function () { return new Color3(0, 0, 1); };
Color3.Black = function () { return new Color3(0, 0, 0); };
Color3.White = function () { return new Color3(1, 1, 1); };
Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
Color3.Magenta = function () { return new Color3(1, 0, 1); };
Color3.Yellow = function () { return new Color3(1, 1, 0); };
Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
return Color3;
}());
BABYLON.Color3 = Color3;
var Color4 = /** @class */ (function () {
/**
* Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
*/
function Color4(r, g, b, a) {
if (r === void 0) { r = 0; }
if (g === void 0) { g = 0; }
if (b === void 0) { b = 0; }
if (a === void 0) { a = 1; }
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
// Operators
/**
* Adds in place the passed Color4 values to the current Color4.
* Returns the updated Color4.
*/
Color4.prototype.addInPlace = function (right) {
this.r += right.r;
this.g += right.g;
this.b += right.b;
this.a += right.a;
return this;
};
/**
* Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
*/
Color4.prototype.asArray = function () {
var result = new Array();
this.toArray(result, 0);
return result;
};
/**
* Stores from the starting index in the passed array the Color4 successive values.
* Returns the Color4.
*/
Color4.prototype.toArray = function (array, index) {
if (index === undefined) {
index = 0;
}
array[index] = this.r;
array[index + 1] = this.g;
array[index + 2] = this.b;
array[index + 3] = this.a;
return this;
};
/**
* Returns a new Color4 set with the added values of the current Color4 and of the passed one.
*/
Color4.prototype.add = function (right) {
return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
};
/**
* Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
*/
Color4.prototype.subtract = function (right) {
return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
};
/**
* Subtracts the passed ones from the current Color4 values and stores the results in "result".
* Returns the Color4.
*/
Color4.prototype.subtractToRef = function (right, result) {
result.r = this.r - right.r;
result.g = this.g - right.g;
result.b = this.b - right.b;
result.a = this.a - right.a;
return this;
};
/**
* Creates a new Color4 with the current Color4 values multiplied by scale.
*/
Color4.prototype.scale = function (scale) {
return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
};
/**
* Multiplies the current Color4 values by scale and stores the result in "result".
* Returns the Color4.
*/
Color4.prototype.scaleToRef = function (scale, result) {
result.r = this.r * scale;
result.g = this.g * scale;
result.b = this.b * scale;
result.a = this.a * scale;
return this;
};
/**
* Multipy an RGBA Color4 value by another and return a new Color4 object
* @param color The Color4 (RGBA) value to multiply by
* @returns A new Color4.
*/
Color4.prototype.multiply = function (color) {
return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
};
/**
* Multipy an RGBA Color4 value by another and push the result in a reference value
* @param color The Color4 (RGBA) value to multiply by
* @param result The Color4 (RGBA) to fill the result in
* @returns the result Color4.
*/
Color4.prototype.multiplyToRef = function (color, result) {
result.r = this.r * color.r;
result.g = this.g * color.g;
result.b = this.b * color.b;
result.a = this.a * color.a;
return result;
};
/**
* Returns a string with the Color4 values.
*/
Color4.prototype.toString = function () {
return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
};
/**
* Returns the string "Color4"
*/
Color4.prototype.getClassName = function () {
return "Color4";
};
/**
* Return the Color4 hash code as a number.
*/
Color4.prototype.getHashCode = function () {
var hash = this.r || 0;
hash = (hash * 397) ^ (this.g || 0);
hash = (hash * 397) ^ (this.b || 0);
hash = (hash * 397) ^ (this.a || 0);
return hash;
};
/**
* Creates a new Color4 copied from the current one.
*/
Color4.prototype.clone = function () {
return new Color4(this.r, this.g, this.b, this.a);
};
/**
* Copies the passed Color4 values into the current one.
* Returns the updated Color4.
*/
Color4.prototype.copyFrom = function (source) {
this.r = source.r;
this.g = source.g;
this.b = source.b;
this.a = source.a;
return this;
};
/**
* Copies the passed float values into the current one.
* Returns the updated Color4.
*/
Color4.prototype.copyFromFloats = function (r, g, b, a) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
return this;
};
/**
* Copies the passed float values into the current one.
* Returns the updated Color4.
*/
Color4.prototype.set = function (r, g, b, a) {
return this.copyFromFloats(r, g, b, a);
};
/**
* Returns a string containing the hexadecimal Color4 code.
*/
Color4.prototype.toHexString = function () {
var intR = (this.r * 255) | 0;
var intG = (this.g * 255) | 0;
var intB = (this.b * 255) | 0;
var intA = (this.a * 255) | 0;
return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
};
/**
* Returns a new Color4 converted to linear space.
*/
Color4.prototype.toLinearSpace = function () {
var convertedColor = new Color4();
this.toLinearSpaceToRef(convertedColor);
return convertedColor;
};
/**
* Converts the Color4 values to linear space and stores the result in "convertedColor".
* Returns the unmodified Color4.
*/
Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
convertedColor.a = this.a;
return this;
};
/**
* Returns a new Color4 converted to gamma space.
*/
Color4.prototype.toGammaSpace = function () {
var convertedColor = new Color4();
this.toGammaSpaceToRef(convertedColor);
return convertedColor;
};
/**
* Converts the Color4 values to gamma space and stores the result in "convertedColor".
* Returns the unmodified Color4.
*/
Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
convertedColor.a = this.a;
return this;
};
// Statics
/**
* Creates a new Color4 from the valid hexadecimal value contained in the passed string.
*/
Color4.FromHexString = function (hex) {
if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
//Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
return new Color4(0.0, 0.0, 0.0, 0.0);
}
var r = parseInt(hex.substring(1, 3), 16);
var g = parseInt(hex.substring(3, 5), 16);
var b = parseInt(hex.substring(5, 7), 16);
var a = parseInt(hex.substring(7, 9), 16);
return Color4.FromInts(r, g, b, a);
};
/**
* Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
*/
Color4.Lerp = function (left, right, amount) {
var result = new Color4(0.0, 0.0, 0.0, 0.0);
Color4.LerpToRef(left, right, amount, result);
return result;
};
/**
* Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
*/
Color4.LerpToRef = function (left, right, amount, result) {
result.r = left.r + (right.r - left.r) * amount;
result.g = left.g + (right.g - left.g) * amount;
result.b = left.b + (right.b - left.b) * amount;
result.a = left.a + (right.a - left.a) * amount;
};
/**
* Creates a new Color4 from the starting index element of the passed array.
*/
Color4.FromArray = function (array, offset) {
if (offset === void 0) { offset = 0; }
return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
};
/**
* Creates a new Color4 from the passed integers ( < 256 ).
*/
Color4.FromInts = function (r, g, b, a) {
return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
};
Color4.CheckColors4 = function (colors, count) {
// Check if color3 was used
if (colors.length === count * 3) {
var colors4 = [];
for (var index = 0; index < colors.length; index += 3) {
var newIndex = (index / 3) * 4;
colors4[newIndex] = colors[index];
colors4[newIndex + 1] = colors[index + 1];
colors4[newIndex + 2] = colors[index + 2];
colors4[newIndex + 3] = 1.0;
}
return colors4;
}
return colors;
};
return Color4;
}());
BABYLON.Color4 = Color4;
var Vector2 = /** @class */ (function () {
/**
* Creates a new Vector2 from the passed x and y coordinates.
*/
function Vector2(x, y) {
this.x = x;
this.y = y;
}
/**
* Returns a string with the Vector2 coordinates.
*/
Vector2.prototype.toString = function () {
return "{X: " + this.x + " Y:" + this.y + "}";
};
/**
* Returns the string "Vector2"
*/
Vector2.prototype.getClassName = function () {
return "Vector2";
};
/**
* Returns the Vector2 hash code as a number.
*/
Vector2.prototype.getHashCode = function () {
var hash = this.x || 0;
hash = (hash * 397) ^ (this.y || 0);
return hash;
};
// Operators
/**
* Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
* Returns the Vector2.
*/
Vector2.prototype.toArray = function (array, index) {
if (index === void 0) { index = 0; }
array[index] = this.x;
array[index + 1] = this.y;
return this;
};
/**
* Returns a new array with 2 elements : the Vector2 coordinates.
*/
Vector2.prototype.asArray = function () {
var result = new Array();
this.toArray(result, 0);
return result;
};
/**
* Sets the Vector2 coordinates with the passed Vector2 coordinates.
* Returns the updated Vector2.
*/
Vector2.prototype.copyFrom = function (source) {
this.x = source.x;
this.y = source.y;
return this;
};
/**
* Sets the Vector2 coordinates with the passed floats.
* Returns the updated Vector2.
*/
Vector2.prototype.copyFromFloats = function (x, y) {
this.x = x;
this.y = y;
return this;
};
/**
* Sets the Vector2 coordinates with the passed floats.
* Returns the updated Vector2.
*/
Vector2.prototype.set = function (x, y) {
return this.copyFromFloats(x, y);
};
/**
* Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
*/
Vector2.prototype.add = function (otherVector) {
return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
};
/**
* Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
* Returns the Vector2.
*/
Vector2.prototype.addToRef = function (otherVector, result) {
result.x = this.x + otherVector.x;
result.y = this.y + otherVector.y;
return this;
};
/**
* Set the Vector2 coordinates by adding the passed Vector2 coordinates.
* Returns the updated Vector2.
*/
Vector2.prototype.addInPlace = function (otherVector) {
this.x += otherVector.x;
this.y += otherVector.y;
return this;
};
/**
* Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
*/
Vector2.prototype.addVector3 = function (otherVector) {
return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
};
/**
* Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
*/
Vector2.prototype.subtract = function (otherVector) {
return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
};
/**
* Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
* Returns the Vector2.
*/
Vector2.prototype.subtractToRef = function (otherVector, result) {
result.x = this.x - otherVector.x;
result.y = this.y - otherVector.y;
return this;
};
/**
* Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
* Returns the updated Vector2.
*/
Vector2.prototype.subtractInPlace = function (otherVector) {
this.x -= otherVector.x;
this.y -= otherVector.y;
return this;
};
/**
* Multiplies in place the current Vector2 coordinates by the passed ones.
* Returns the updated Vector2.
*/
Vector2.prototype.multiplyInPlace = function (otherVector) {
this.x *= otherVector.x;
this.y *= otherVector.y;
return this;
};
/**
* Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
*/
Vector2.prototype.multiply = function (otherVector) {
return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
};
/**
* Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
* Returns the Vector2.
*/
Vector2.prototype.multiplyToRef = function (otherVector, result) {
result.x = this.x * otherVector.x;
result.y = this.y * otherVector.y;
return this;
};
/**
* Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
*/
Vector2.prototype.multiplyByFloats = function (x, y) {
return new Vector2(this.x * x, this.y * y);
};
/**
* Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
*/
Vector2.prototype.divide = function (otherVector) {
return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
};
/**
* Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
* Returns the Vector2.
*/
Vector2.prototype.divideToRef = function (otherVector, result) {
result.x = this.x / otherVector.x;
result.y = this.y / otherVector.y;
return this;
};
/**
* Returns a new Vector2 with current Vector2 negated coordinates.
*/
Vector2.prototype.negate = function () {
return new Vector2(-this.x, -this.y);
};
/**
* Multiply the Vector2 coordinates by scale.
* Returns the updated Vector2.
*/
Vector2.prototype.scaleInPlace = function (scale) {
this.x *= scale;
this.y *= scale;
return this;
};
/**
* Returns a new Vector2 scaled by "scale" from the current Vector2.
*/
Vector2.prototype.scale = function (scale) {
return new Vector2(this.x * scale, this.y * scale);
};
/**
* Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
*/
Vector2.prototype.equals = function (otherVector) {
return otherVector && this.x === otherVector.x && this.y === otherVector.y;
};
/**
* Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
*/
Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
};
// Properties
/**
* Returns the vector length (float).
*/
Vector2.prototype.length = function () {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
/**
* Returns the vector squared length (float);
*/
Vector2.prototype.lengthSquared = function () {
return (this.x * this.x + this.y * this.y);
};
// Methods
/**
* Normalize the vector.
* Returns the updated Vector2.
*/
Vector2.prototype.normalize = function () {
var len = this.length();
if (len === 0)
return this;
var num = 1.0 / len;
this.x *= num;
this.y *= num;
return this;
};
/**
* Returns a new Vector2 copied from the Vector2.
*/
Vector2.prototype.clone = function () {
return new Vector2(this.x, this.y);
};
// Statics
/**
* Returns a new Vector2(0, 0)
*/
Vector2.Zero = function () {
return new Vector2(0, 0);
};
/**
* Returns a new Vector2(1, 1)
*/
Vector2.One = function () {
return new Vector2(1, 1);
};
/**
* Returns a new Vector2 set from the passed index element of the passed array.
*/
Vector2.FromArray = function (array, offset) {
if (offset === void 0) { offset = 0; }
return new Vector2(array[offset], array[offset + 1]);
};
/**
* Sets "result" from the passed index element of the passed array.
*/
Vector2.FromArrayToRef = function (array, offset, result) {
result.x = array[offset];
result.y = array[offset + 1];
};
/**
* Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
*/
Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
(((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
(((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
return new Vector2(x, y);
};
/**
* Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
* If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
* If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
*/
Vector2.Clamp = function (value, min, max) {
var x = value.x;
x = (x > max.x) ? max.x : x;
x = (x < min.x) ? min.x : x;
var y = value.y;
y = (y > max.y) ? max.y : y;
y = (y < min.y) ? min.y : y;
return new Vector2(x, y);
};
/**
* Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
*/
Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
var part2 = (-2.0 * cubed) + (3.0 * squared);
var part3 = (cubed - (2.0 * squared)) + amount;
var part4 = cubed - squared;
var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
return new Vector2(x, y);
};
/**
* Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
*/
Vector2.Lerp = function (start, end, amount) {
var x = start.x + ((end.x - start.x) * amount);
var y = start.y + ((end.y - start.y) * amount);
return new Vector2(x, y);
};
/**
* Returns the dot product (float) of the vector "left" and the vector "right".
*/
Vector2.Dot = function (left, right) {
return left.x * right.x + left.y * right.y;
};
/**
* Returns a new Vector2 equal to the normalized passed vector.
*/
Vector2.Normalize = function (vector) {
var newVector = vector.clone();
newVector.normalize();
return newVector;
};
/**
* Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
*/
Vector2.Minimize = function (left, right) {
var x = (left.x < right.x) ? left.x : right.x;
var y = (left.y < right.y) ? left.y : right.y;
return new Vector2(x, y);
};
/**
* Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
*/
Vector2.Maximize = function (left, right) {
var x = (left.x > right.x) ? left.x : right.x;
var y = (left.y > right.y) ? left.y : right.y;
return new Vector2(x, y);
};
/**
* Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
*/
Vector2.Transform = function (vector, transformation) {
var r = Vector2.Zero();
Vector2.TransformToRef(vector, transformation, r);
return r;
};
/**
* Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
*/
Vector2.TransformToRef = function (vector, transformation, result) {
var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
result.x = x;
result.y = y;
};
/**
* Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
*/
Vector2.PointInTriangle = function (p, p0, p1, p2) {
var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
var sign = a < 0 ? -1 : 1;
var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
return s > 0 && t > 0 && (s + t) < 2 * a * sign;
};
/**
* Returns the distance (float) between the vectors "value1" and "value2".
*/
Vector2.Distance = function (value1, value2) {
return Math.sqrt(Vector2.DistanceSquared(value1, value2));
};
/**
* Returns the squared distance (float) between the vectors "value1" and "value2".
*/
Vector2.DistanceSquared = function (value1, value2) {
var x = value1.x - value2.x;
var y = value1.y - value2.y;
return (x * x) + (y * y);
};
/**
* Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
*/
Vector2.Center = function (value1, value2) {
var center = value1.add(value2);
center.scaleInPlace(0.5);
return center;
};
/**
* Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
*/
Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
var l2 = Vector2.DistanceSquared(segA, segB);
if (l2 === 0.0) {
return Vector2.Distance(p, segA);
}
var v = segB.subtract(segA);
var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
var proj = segA.add(v.multiplyByFloats(t, t));
return Vector2.Distance(p, proj);
};
return Vector2;
}());
BABYLON.Vector2 = Vector2;
var Vector3 = /** @class */ (function () {
/**
* Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
* A Vector3 is the main object used in 3D geometry.
* It can represent etiher the coordinates of a point the space, either a direction.
*/
function Vector3(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Returns a string with the Vector3 coordinates.
*/
Vector3.prototype.toString = function () {
return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
};
/**
* Returns the string "Vector3"
*/
Vector3.prototype.getClassName = function () {
return "Vector3";
};
/**
* Returns the Vector hash code.
*/
Vector3.prototype.getHashCode = function () {
var hash = this.x || 0;
hash = (hash * 397) ^ (this.y || 0);
hash = (hash * 397) ^ (this.z || 0);
return hash;
};
// Operators
/**
* Returns a new array with three elements : the coordinates the Vector3.
*/
Vector3.prototype.asArray = function () {
var result = [];
this.toArray(result, 0);
return result;
};
/**
* Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
* Returns the Vector3.
*/
Vector3.prototype.toArray = function (array, index) {
if (index === void 0) { index = 0; }
array[index] = this.x;
array[index + 1] = this.y;
array[index + 2] = this.z;
return this;
};
/**
* Returns a new Quaternion object, computed from the Vector3 coordinates.
*/
Vector3.prototype.toQuaternion = function () {
var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
var coszMinusx = Math.cos((this.z - this.x) * 0.5);
var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
var cosy = Math.cos(this.y * 0.5);
var siny = Math.sin(this.y * 0.5);
result.x = coszMinusx * siny;
result.y = -sinzMinusx * siny;
result.z = sinxPlusz * cosy;
result.w = cosxPlusz * cosy;
return result;
};
/**
* Adds the passed vector to the current Vector3.
* Returns the updated Vector3.
*/
Vector3.prototype.addInPlace = function (otherVector) {
this.x += otherVector.x;
this.y += otherVector.y;
this.z += otherVector.z;
return this;
};
/**
* Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
*/
Vector3.prototype.add = function (otherVector) {
return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
};
/**
* Adds the current Vector3 to the passed one and stores the result in the vector "result".
* Returns the current Vector3.
*/
Vector3.prototype.addToRef = function (otherVector, result) {
result.x = this.x + otherVector.x;
result.y = this.y + otherVector.y;
result.z = this.z + otherVector.z;
return this;
};
/**
* Subtract the passed vector from the current Vector3.
* Returns the updated Vector3.
*/
Vector3.prototype.subtractInPlace = function (otherVector) {
this.x -= otherVector.x;
this.y -= otherVector.y;
this.z -= otherVector.z;
return this;
};
/**
* Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
*/
Vector3.prototype.subtract = function (otherVector) {
return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
};
/**
* Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
* Returns the current Vector3.
*/
Vector3.prototype.subtractToRef = function (otherVector, result) {
result.x = this.x - otherVector.x;
result.y = this.y - otherVector.y;
result.z = this.z - otherVector.z;
return this;
};
/**
* Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
*/
Vector3.prototype.subtractFromFloats = function (x, y, z) {
return new Vector3(this.x - x, this.y - y, this.z - z);
};
/**
* Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
* Returns the current Vector3.
*/
Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
result.x = this.x - x;
result.y = this.y - y;
result.z = this.z - z;
return this;
};
/**
* Returns a new Vector3 set with the current Vector3 negated coordinates.
*/
Vector3.prototype.negate = function () {
return new Vector3(-this.x, -this.y, -this.z);
};
/**
* Multiplies the Vector3 coordinates by the float "scale".
* Returns the updated Vector3.
*/
Vector3.prototype.scaleInPlace = function (scale) {
this.x *= scale;
this.y *= scale;
this.z *= scale;
return this;
};
/**
* Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
*/
Vector3.prototype.scale = function (scale) {
return new Vector3(this.x * scale, this.y * scale, this.z * scale);
};
/**
* Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
* Returns the current Vector3.
*/
Vector3.prototype.scaleToRef = function (scale, result) {
result.x = this.x * scale;
result.y = this.y * scale;
result.z = this.z * scale;
return this;
};
/**
* Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
*/
Vector3.prototype.equals = function (otherVector) {
return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
};
/**
* Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
*/
Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
};
/**
* Boolean : True if the current Vector3 coordinate equal the passed floats.
*/
Vector3.prototype.equalsToFloats = function (x, y, z) {
return this.x === x && this.y === y && this.z === z;
};
/**
* Muliplies the current Vector3 coordinates by the passed ones.
* Returns the updated Vector3.
*/
Vector3.prototype.multiplyInPlace = function (otherVector) {
this.x *= otherVector.x;
this.y *= otherVector.y;
this.z *= otherVector.z;
return this;
};
/**
* Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
*/
Vector3.prototype.multiply = function (otherVector) {
return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
};
/**
* Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
* Returns the current Vector3.
*/
Vector3.prototype.multiplyToRef = function (otherVector, result) {
result.x = this.x * otherVector.x;
result.y = this.y * otherVector.y;
result.z = this.z * otherVector.z;
return this;
};
/**
* Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
*/
Vector3.prototype.multiplyByFloats = function (x, y, z) {
return new Vector3(this.x * x, this.y * y, this.z * z);
};
/**
* Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
*/
Vector3.prototype.divide = function (otherVector) {
return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
};
/**
* Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
* Returns the current Vector3.
*/
Vector3.prototype.divideToRef = function (otherVector, result) {
result.x = this.x / otherVector.x;
result.y = this.y / otherVector.y;
result.z = this.z / otherVector.z;
return this;
};
/**
* Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
* Returns the updated Vector3.
*/
Vector3.prototype.MinimizeInPlace = function (other) {
if (other.x < this.x)
this.x = other.x;
if (other.y < this.y)
this.y = other.y;
if (other.z < this.z)
this.z = other.z;
return this;
};
/**
* Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
* Returns the updated Vector3.
*/
Vector3.prototype.MaximizeInPlace = function (other) {
if (other.x > this.x)
this.x = other.x;
if (other.y > this.y)
this.y = other.y;
if (other.z > this.z)
this.z = other.z;
return this;
};
Object.defineProperty(Vector3.prototype, "isNonUniform", {
/**
* Return true is the vector is non uniform meaning x, y or z are not all the same.
*/
get: function () {
var absX = Math.abs(this.x);
var absY = Math.abs(this.y);
if (absX !== absY) {
return true;
}
var absZ = Math.abs(this.z);
if (absX !== absZ) {
return true;
}
if (absY !== absZ) {
return true;
}
return false;
},
enumerable: true,
configurable: true
});
// Properties
/**
* Returns the length of the Vector3 (float).
*/
Vector3.prototype.length = function () {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
};
/**
* Returns the squared length of the Vector3 (float).
*/
Vector3.prototype.lengthSquared = function () {
return (this.x * this.x + this.y * this.y + this.z * this.z);
};
/**
* Normalize the current Vector3.
* Returns the updated Vector3.
* /!\ In place operation.
*/
Vector3.prototype.normalize = function () {
var len = this.length();
if (len === 0 || len === 1.0)
return this;
var num = 1.0 / len;
this.x *= num;
this.y *= num;
this.z *= num;
return this;
};
/**
* Normalize the current Vector3 to a new vector.
* @returns the new Vector3.
*/
Vector3.prototype.normalizeToNew = function () {
var normalized = new Vector3(0, 0, 0);
this.normalizeToRef(normalized);
return normalized;
};
/**
* Normalize the current Vector3 to the reference.
* @param the reference to update.
* @returns the updated Vector3.
*/
Vector3.prototype.normalizeToRef = function (reference) {
var len = this.length();
if (len === 0 || len === 1.0) {
reference.set(this.x, this.y, this.z);
return reference;
}
var scale = 1.0 / len;
this.scaleToRef(scale, reference);
return reference;
};
/**
* Returns a new Vector3 copied from the current Vector3.
*/
Vector3.prototype.clone = function () {
return new Vector3(this.x, this.y, this.z);
};
/**
* Copies the passed vector coordinates to the current Vector3 ones.
* Returns the updated Vector3.
*/
Vector3.prototype.copyFrom = function (source) {
this.x = source.x;
this.y = source.y;
this.z = source.z;
return this;
};
/**
* Copies the passed floats to the current Vector3 coordinates.
* Returns the updated Vector3.
*/
Vector3.prototype.copyFromFloats = function (x, y, z) {
this.x = x;
this.y = y;
this.z = z;
return this;
};
/**
* Copies the passed floats to the current Vector3 coordinates.
* Returns the updated Vector3.
*/
Vector3.prototype.set = function (x, y, z) {
return this.copyFromFloats(x, y, z);
};
// Statics
/**
*
*/
Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
var d0 = Vector3.Dot(vector0, axis) - size;
var d1 = Vector3.Dot(vector1, axis) - size;
var s = d0 / (d0 - d1);
return s;
};
/**
* Returns a new Vector3 set from the index "offset" of the passed array.
*/
Vector3.FromArray = function (array, offset) {
if (!offset) {
offset = 0;
}
return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
};
/**
* Returns a new Vector3 set from the index "offset" of the passed Float32Array.
* This function is deprecated. Use FromArray instead.
*/
Vector3.FromFloatArray = function (array, offset) {
return Vector3.FromArray(array, offset);
};
/**
* Sets the passed vector "result" with the element values from the index "offset" of the passed array.
*/
Vector3.FromArrayToRef = function (array, offset, result) {
result.x = array[offset];
result.y = array[offset + 1];
result.z = array[offset + 2];
};
/**
* Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
* This function is deprecated. Use FromArrayToRef instead.
*/
Vector3.FromFloatArrayToRef = function (array, offset, result) {
return Vector3.FromArrayToRef(array, offset, result);
};
/**
* Sets the passed vector "result" with the passed floats.
*/
Vector3.FromFloatsToRef = function (x, y, z, result) {
result.x = x;
result.y = y;
result.z = z;
};
/**
* Returns a new Vector3 set to (0.0, 0.0, 0.0).
*/
Vector3.Zero = function () {
return new Vector3(0.0, 0.0, 0.0);
};
/**
* Returns a new Vector3 set to (1.0, 1.0, 1.0).
*/
Vector3.One = function () {
return new Vector3(1.0, 1.0, 1.0);
};
/**
* Returns a new Vector3 set to (0.0, 1.0, 0.0)
*/
Vector3.Up = function () {
return new Vector3(0.0, 1.0, 0.0);
};
/**
* Returns a new Vector3 set to (0.0, 0.0, 1.0)
*/
Vector3.Forward = function () {
return new Vector3(0.0, 0.0, 1.0);
};
/**
* Returns a new Vector3 set to (1.0, 0.0, 0.0)
*/
Vector3.Right = function () {
return new Vector3(1.0, 0.0, 0.0);
};
/**
* Returns a new Vector3 set to (-1.0, 0.0, 0.0)
*/
Vector3.Left = function () {
return new Vector3(-1.0, 0.0, 0.0);
};
/**
* Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
* This method computes tranformed coordinates only, not transformed direction vectors.
*/
Vector3.TransformCoordinates = function (vector, transformation) {
var result = Vector3.Zero();
Vector3.TransformCoordinatesToRef(vector, transformation, result);
return result;
};
/**
* Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
* This method computes tranformed coordinates only, not transformed direction vectors.
*/
Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
result.x = x / w;
result.y = y / w;
result.z = z / w;
};
/**
* Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
* This method computes tranformed coordinates only, not transformed direction vectors.
*/
Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
result.x = rx / rw;
result.y = ry / rw;
result.z = rz / rw;
};
/**
* Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
* This methods computes transformed normalized direction vectors only.
*/
Vector3.TransformNormal = function (vector, transformation) {
var result = Vector3.Zero();
Vector3.TransformNormalToRef(vector, transformation, result);
return result;
};
/**
* Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
* This methods computes transformed normalized direction vectors only.
*/
Vector3.TransformNormalToRef = function (vector, transformation, result) {
var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
result.x = x;
result.y = y;
result.z = z;
};
/**
* Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
* This methods computes transformed normalized direction vectors only.
*/
Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
};
/**
* Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
*/
Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
(((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
(((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
(((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
return new Vector3(x, y, z);
};
/**
* Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
* If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
* If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
*/
Vector3.Clamp = function (value, min, max) {
var x = value.x;
x = (x > max.x) ? max.x : x;
x = (x < min.x) ? min.x : x;
var y = value.y;
y = (y > max.y) ? max.y : y;
y = (y < min.y) ? min.y : y;
var z = value.z;
z = (z > max.z) ? max.z : z;
z = (z < min.z) ? min.z : z;
return new Vector3(x, y, z);
};
/**
* Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
*/
Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
var part2 = (-2.0 * cubed) + (3.0 * squared);
var part3 = (cubed - (2.0 * squared)) + amount;
var part4 = cubed - squared;
var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
return new Vector3(x, y, z);
};
/**
* Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
*/
Vector3.Lerp = function (start, end, amount) {
var result = new Vector3(0, 0, 0);
Vector3.LerpToRef(start, end, amount, result);
return result;
};
/**
* Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
*/
Vector3.LerpToRef = function (start, end, amount, result) {
result.x = start.x + ((end.x - start.x) * amount);
result.y = start.y + ((end.y - start.y) * amount);
result.z = start.z + ((end.z - start.z) * amount);
};
/**
* Returns the dot product (float) between the vectors "left" and "right".
*/
Vector3.Dot = function (left, right) {
return (left.x * right.x + left.y * right.y + left.z * right.z);
};
/**
* Returns a new Vector3 as the cross product of the vectors "left" and "right".
* The cross product is then orthogonal to both "left" and "right".
*/
Vector3.Cross = function (left, right) {
var result = Vector3.Zero();
Vector3.CrossToRef(left, right, result);
return result;
};
/**
* Sets the passed vector "result" with the cross product of "left" and "right".
* The cross product is then orthogonal to both "left" and "right".
*/
Vector3.CrossToRef = function (left, right, result) {
MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
result.copyFrom(MathTmp.Vector3[0]);
};
/**
* Returns a new Vector3 as the normalization of the passed vector.
*/
Vector3.Normalize = function (vector) {
var result = Vector3.Zero();
Vector3.NormalizeToRef(vector, result);
return result;
};
/**
* Sets the passed vector "result" with the normalization of the passed first vector.
*/
Vector3.NormalizeToRef = function (vector, result) {
result.copyFrom(vector);
result.normalize();
};
Vector3.Project = function (vector, world, transform, viewport) {
var cw = viewport.width;
var ch = viewport.height;
var cx = viewport.x;
var cy = viewport.y;
var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
var matrix = MathTmp.Matrix[0];
world.multiplyToRef(transform, matrix);
matrix.multiplyToRef(viewportMatrix, matrix);
return Vector3.TransformCoordinates(vector, matrix);
};
Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
var matrix = MathTmp.Matrix[0];
world.multiplyToRef(transform, matrix);
matrix.invert();
source.x = source.x / viewportWidth * 2 - 1;
source.y = -(source.y / viewportHeight * 2 - 1);
var vector = Vector3.TransformCoordinates(source, matrix);
var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
vector = vector.scale(1.0 / num);
}
return vector;
};
Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
var result = Vector3.Zero();
Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
return result;
};
Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
};
Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
var matrix = MathTmp.Matrix[0];
world.multiplyToRef(view, matrix);
matrix.multiplyToRef(projection, matrix);
matrix.invert();
var screenSource = MathTmp.Vector3[0];
screenSource.x = sourceX / viewportWidth * 2 - 1;
screenSource.y = -(sourceY / viewportHeight * 2 - 1);
screenSource.z = 2 * sourceZ - 1.0;
Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
result.scaleInPlace(1.0 / num);
}
};
Vector3.Minimize = function (left, right) {
var min = left.clone();
min.MinimizeInPlace(right);
return min;
};
Vector3.Maximize = function (left, right) {
var max = left.clone();
max.MaximizeInPlace(right);
return max;
};
/**
* Returns the distance (float) between the vectors "value1" and "value2".
*/
Vector3.Distance = function (value1, value2) {
return Math.sqrt(Vector3.DistanceSquared(value1, value2));
};
/**
* Returns the squared distance (float) between the vectors "value1" and "value2".
*/
Vector3.DistanceSquared = function (value1, value2) {
var x = value1.x - value2.x;
var y = value1.y - value2.y;
var z = value1.z - value2.z;
return (x * x) + (y * y) + (z * z);
};
/**
* Returns a new Vector3 located at the center between "value1" and "value2".
*/
Vector3.Center = function (value1, value2) {
var center = value1.add(value2);
center.scaleInPlace(0.5);
return center;
};
/**
* Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
* RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
* to something in order to rotate it from its local system to the given target system.
* Note : axis1, axis2 and axis3 are normalized during this operation.
* Returns a new Vector3.
*/
Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
var rotation = Vector3.Zero();
Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
return rotation;
};
/**
* The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
*/
Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
var quat = MathTmp.Quaternion[0];
Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
quat.toEulerAnglesToRef(ref);
};
return Vector3;
}());
BABYLON.Vector3 = Vector3;
//Vector4 class created for EulerAngle class conversion to Quaternion
var Vector4 = /** @class */ (function () {
/**
* Creates a Vector4 object from the passed floats.
*/
function Vector4(x, y, z, w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Returns the string with the Vector4 coordinates.
*/
Vector4.prototype.toString = function () {
return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
};
/**
* Returns the string "Vector4".
*/
Vector4.prototype.getClassName = function () {
return "Vector4";
};
/**
* Returns the Vector4 hash code.
*/
Vector4.prototype.getHashCode = function () {
var hash = this.x || 0;
hash = (hash * 397) ^ (this.y || 0);
hash = (hash * 397) ^ (this.z || 0);
hash = (hash * 397) ^ (this.w || 0);
return hash;
};
// Operators
/**
* Returns a new array populated with 4 elements : the Vector4 coordinates.
*/
Vector4.prototype.asArray = function () {
var result = new Array();
this.toArray(result, 0);
return result;
};
/**
* Populates the passed array from the passed index with the Vector4 coordinates.
* Returns the Vector4.
*/
Vector4.prototype.toArray = function (array, index) {
if (index === undefined) {
index = 0;
}
array[index] = this.x;
array[index + 1] = this.y;
array[index + 2] = this.z;
array[index + 3] = this.w;
return this;
};
/**
* Adds the passed vector to the current Vector4.
* Returns the updated Vector4.
*/
Vector4.prototype.addInPlace = function (otherVector) {
this.x += otherVector.x;
this.y += otherVector.y;
this.z += otherVector.z;
this.w += otherVector.w;
return this;
};
/**
* Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
*/
Vector4.prototype.add = function (otherVector) {
return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
};
/**
* Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
* Returns the current Vector4.
*/
Vector4.prototype.addToRef = function (otherVector, result) {
result.x = this.x + otherVector.x;
result.y = this.y + otherVector.y;
result.z = this.z + otherVector.z;
result.w = this.w + otherVector.w;
return this;
};
/**
* Subtract in place the passed vector from the current Vector4.
* Returns the updated Vector4.
*/
Vector4.prototype.subtractInPlace = function (otherVector) {
this.x -= otherVector.x;
this.y -= otherVector.y;
this.z -= otherVector.z;
this.w -= otherVector.w;
return this;
};
/**
* Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
*/
Vector4.prototype.subtract = function (otherVector) {
return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
};
/**
* Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
* Returns the current Vector4.
*/
Vector4.prototype.subtractToRef = function (otherVector, result) {
result.x = this.x - otherVector.x;
result.y = this.y - otherVector.y;
result.z = this.z - otherVector.z;
result.w = this.w - otherVector.w;
return this;
};
/**
* Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
*/
Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
};
/**
* Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
* Returns the current Vector4.
*/
Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
result.x = this.x - x;
result.y = this.y - y;
result.z = this.z - z;
result.w = this.w - w;
return this;
};
/**
* Returns a new Vector4 set with the current Vector4 negated coordinates.
*/
Vector4.prototype.negate = function () {
return new Vector4(-this.x, -this.y, -this.z, -this.w);
};
/**
* Multiplies the current Vector4 coordinates by scale (float).
* Returns the updated Vector4.
*/
Vector4.prototype.scaleInPlace = function (scale) {
this.x *= scale;
this.y *= scale;
this.z *= scale;
this.w *= scale;
return this;
};
/**
* Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
*/
Vector4.prototype.scale = function (scale) {
return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
};
/**
* Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
* Returns the current Vector4.
*/
Vector4.prototype.scaleToRef = function (scale, result) {
result.x = this.x * scale;
result.y = this.y * scale;
result.z = this.z * scale;
result.w = this.w * scale;
return this;
};
/**
* Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
*/
Vector4.prototype.equals = function (otherVector) {
return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
};
/**
* Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
*/
Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
return otherVector
&& BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
&& BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
&& BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
&& BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
};
/**
* Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
*/
Vector4.prototype.equalsToFloats = function (x, y, z, w) {
return this.x === x && this.y === y && this.z === z && this.w === w;
};
/**
* Multiplies in place the current Vector4 by the passed one.
* Returns the updated Vector4.
*/
Vector4.prototype.multiplyInPlace = function (otherVector) {
this.x *= otherVector.x;
this.y *= otherVector.y;
this.z *= otherVector.z;
this.w *= otherVector.w;
return this;
};
/**
* Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
*/
Vector4.prototype.multiply = function (otherVector) {
return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
};
/**
* Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
* Returns the current Vector4.
*/
Vector4.prototype.multiplyToRef = function (otherVector, result) {
result.x = this.x * otherVector.x;
result.y = this.y * otherVector.y;
result.z = this.z * otherVector.z;
result.w = this.w * otherVector.w;
return this;
};
/**
* Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
*/
Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
};
/**
* Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
*/
Vector4.prototype.divide = function (otherVector) {
return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
};
/**
* Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
* Returns the current Vector4.
*/
Vector4.prototype.divideToRef = function (otherVector, result) {
result.x = this.x / otherVector.x;
result.y = this.y / otherVector.y;
result.z = this.z / otherVector.z;
result.w = this.w / otherVector.w;
return this;
};
/**
* Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
*/
Vector4.prototype.MinimizeInPlace = function (other) {
if (other.x < this.x)
this.x = other.x;
if (other.y < this.y)
this.y = other.y;
if (other.z < this.z)
this.z = other.z;
if (other.w < this.w)
this.w = other.w;
return this;
};
/**
* Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
*/
Vector4.prototype.MaximizeInPlace = function (other) {
if (other.x > this.x)
this.x = other.x;
if (other.y > this.y)
this.y = other.y;
if (other.z > this.z)
this.z = other.z;
if (other.w > this.w)
this.w = other.w;
return this;
};
// Properties
/**
* Returns the Vector4 length (float).
*/
Vector4.prototype.length = function () {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
};
/**
* Returns the Vector4 squared length (float).
*/
Vector4.prototype.lengthSquared = function () {
return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
};
// Methods
/**
* Normalizes in place the Vector4.
* Returns the updated Vector4.
*/
Vector4.prototype.normalize = function () {
var len = this.length();
if (len === 0)
return this;
var num = 1.0 / len;
this.x *= num;
this.y *= num;
this.z *= num;
this.w *= num;
return this;
};
/**
* Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
*/
Vector4.prototype.toVector3 = function () {
return new Vector3(this.x, this.y, this.z);
};
/**
* Returns a new Vector4 copied from the current one.
*/
Vector4.prototype.clone = function () {
return new Vector4(this.x, this.y, this.z, this.w);
};
/**
* Updates the current Vector4 with the passed one coordinates.
* Returns the updated Vector4.
*/
Vector4.prototype.copyFrom = function (source) {
this.x = source.x;
this.y = source.y;
this.z = source.z;
this.w = source.w;
return this;
};
/**
* Updates the current Vector4 coordinates with the passed floats.
* Returns the updated Vector4.
*/
Vector4.prototype.copyFromFloats = function (x, y, z, w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
};
/**
* Updates the current Vector4 coordinates with the passed floats.
* Returns the updated Vector4.
*/
Vector4.prototype.set = function (x, y, z, w) {
return this.copyFromFloats(x, y, z, w);
};
// Statics
/**
* Returns a new Vector4 set from the starting index of the passed array.
*/
Vector4.FromArray = function (array, offset) {
if (!offset) {
offset = 0;
}
return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
};
/**
* Updates the passed vector "result" from the starting index of the passed array.
*/
Vector4.FromArrayToRef = function (array, offset, result) {
result.x = array[offset];
result.y = array[offset + 1];
result.z = array[offset + 2];
result.w = array[offset + 3];
};
/**
* Updates the passed vector "result" from the starting index of the passed Float32Array.
*/
Vector4.FromFloatArrayToRef = function (array, offset, result) {
Vector4.FromArrayToRef(array, offset, result);
};
/**
* Updates the passed vector "result" coordinates from the passed floats.
*/
Vector4.FromFloatsToRef = function (x, y, z, w, result) {
result.x = x;
result.y = y;
result.z = z;
result.w = w;
};
/**
* Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
*/
Vector4.Zero = function () {
return new Vector4(0.0, 0.0, 0.0, 0.0);
};
/**
* Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
*/
Vector4.One = function () {
return new Vector4(1.0, 1.0, 1.0, 1.0);
};
/**
* Returns a new normalized Vector4 from the passed one.
*/
Vector4.Normalize = function (vector) {
var result = Vector4.Zero();
Vector4.NormalizeToRef(vector, result);
return result;
};
/**
* Updates the passed vector "result" from the normalization of the passed one.
*/
Vector4.NormalizeToRef = function (vector, result) {
result.copyFrom(vector);
result.normalize();
};
Vector4.Minimize = function (left, right) {
var min = left.clone();
min.MinimizeInPlace(right);
return min;
};
Vector4.Maximize = function (left, right) {
var max = left.clone();
max.MaximizeInPlace(right);
return max;
};
/**
* Returns the distance (float) between the vectors "value1" and "value2".
*/
Vector4.Distance = function (value1, value2) {
return Math.sqrt(Vector4.DistanceSquared(value1, value2));
};
/**
* Returns the squared distance (float) between the vectors "value1" and "value2".
*/
Vector4.DistanceSquared = function (value1, value2) {
var x = value1.x - value2.x;
var y = value1.y - value2.y;
var z = value1.z - value2.z;
var w = value1.w - value2.w;
return (x * x) + (y * y) + (z * z) + (w * w);
};
/**
* Returns a new Vector4 located at the center between the vectors "value1" and "value2".
*/
Vector4.Center = function (value1, value2) {
var center = value1.add(value2);
center.scaleInPlace(0.5);
return center;
};
/**
* Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
* This methods computes transformed normalized direction vectors only.
*/
Vector4.TransformNormal = function (vector, transformation) {
var result = Vector4.Zero();
Vector4.TransformNormalToRef(vector, transformation, result);
return result;
};
/**
* Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
* This methods computes transformed normalized direction vectors only.
*/
Vector4.TransformNormalToRef = function (vector, transformation, result) {
var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
result.x = x;
result.y = y;
result.z = z;
result.w = vector.w;
};
/**
* Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
* This methods computes transformed normalized direction vectors only.
*/
Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
result.w = w;
};
return Vector4;
}());
BABYLON.Vector4 = Vector4;
var Size = /** @class */ (function () {
/**
* Creates a Size object from the passed width and height (floats).
*/
function Size(width, height) {
this.width = width;
this.height = height;
}
// Returns a string with the Size width and height.
Size.prototype.toString = function () {
return "{W: " + this.width + ", H: " + this.height + "}";
};
/**
* Returns the string "Size"
*/
Size.prototype.getClassName = function () {
return "Size";
};
/**
* Returns the Size hash code.
*/
Size.prototype.getHashCode = function () {
var hash = this.width || 0;
hash = (hash * 397) ^ (this.height || 0);
return hash;
};
/**
* Updates the current size from the passed one.
* Returns the updated Size.
*/
Size.prototype.copyFrom = function (src) {
this.width = src.width;
this.height = src.height;
};
/**
* Updates in place the current Size from the passed floats.
* Returns the updated Size.
*/
Size.prototype.copyFromFloats = function (width, height) {
this.width = width;
this.height = height;
return this;
};
/**
* Updates in place the current Size from the passed floats.
* Returns the updated Size.
*/
Size.prototype.set = function (width, height) {
return this.copyFromFloats(width, height);
};
/**
* Returns a new Size set with the multiplication result of the current Size and the passed floats.
*/
Size.prototype.multiplyByFloats = function (w, h) {
return new Size(this.width * w, this.height * h);
};
/**
* Returns a new Size copied from the passed one.
*/
Size.prototype.clone = function () {
return new Size(this.width, this.height);
};
/**
* Boolean : True if the current Size and the passed one width and height are strictly equal.
*/
Size.prototype.equals = function (other) {
if (!other) {
return false;
}
return (this.width === other.width) && (this.height === other.height);
};
Object.defineProperty(Size.prototype, "surface", {
/**
* Returns the surface of the Size : width * height (float).
*/
get: function () {
return this.width * this.height;
},
enumerable: true,
configurable: true
});
/**
* Returns a new Size set to (0.0, 0.0)
*/
Size.Zero = function () {
return new Size(0.0, 0.0);
};
/**
* Returns a new Size set as the addition result of the current Size and the passed one.
*/
Size.prototype.add = function (otherSize) {
var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
return r;
};
/**
* Returns a new Size set as the subtraction result of the passed one from the current Size.
*/
Size.prototype.subtract = function (otherSize) {
var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
return r;
};
/**
* Returns a new Size set at the linear interpolation "amount" between "start" and "end".
*/
Size.Lerp = function (start, end, amount) {
var w = start.width + ((end.width - start.width) * amount);
var h = start.height + ((end.height - start.height) * amount);
return new Size(w, h);
};
return Size;
}());
BABYLON.Size = Size;
var Quaternion = /** @class */ (function () {
/**
* Creates a new Quaternion from the passed floats.
*/
function Quaternion(x, y, z, w) {
if (x === void 0) { x = 0.0; }
if (y === void 0) { y = 0.0; }
if (z === void 0) { z = 0.0; }
if (w === void 0) { w = 1.0; }
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Returns a string with the Quaternion coordinates.
*/
Quaternion.prototype.toString = function () {
return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
};
/**
* Returns the string "Quaternion".
*/
Quaternion.prototype.getClassName = function () {
return "Quaternion";
};
/**
* Returns the Quaternion hash code.
*/
Quaternion.prototype.getHashCode = function () {
var hash = this.x || 0;
hash = (hash * 397) ^ (this.y || 0);
hash = (hash * 397) ^ (this.z || 0);
hash = (hash * 397) ^ (this.w || 0);
return hash;
};
/**
* Returns a new array populated with 4 elements : the Quaternion coordinates.
*/
Quaternion.prototype.asArray = function () {
return [this.x, this.y, this.z, this.w];
};
/**
* Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
*/
Quaternion.prototype.equals = function (otherQuaternion) {
return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
};
/**
* Returns a new Quaternion copied from the current one.
*/
Quaternion.prototype.clone = function () {
return new Quaternion(this.x, this.y, this.z, this.w);
};
/**
* Updates the current Quaternion from the passed one coordinates.
* Returns the updated Quaterion.
*/
Quaternion.prototype.copyFrom = function (other) {
this.x = other.x;
this.y = other.y;
this.z = other.z;
this.w = other.w;
return this;
};
/**
* Updates the current Quaternion from the passed float coordinates.
* Returns the updated Quaterion.
*/
Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
};
/**
* Updates the current Quaternion from the passed float coordinates.
* Returns the updated Quaterion.
*/
Quaternion.prototype.set = function (x, y, z, w) {
return this.copyFromFloats(x, y, z, w);
};
/**
* Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
*/
Quaternion.prototype.add = function (other) {
return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
};
/**
* Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
*/
Quaternion.prototype.subtract = function (other) {
return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
};
/**
* Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
*/
Quaternion.prototype.scale = function (value) {
return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
};
/**
* Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
*/
Quaternion.prototype.multiply = function (q1) {
var result = new Quaternion(0, 0, 0, 1.0);
this.multiplyToRef(q1, result);
return result;
};
/**
* Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
* Returns the current Quaternion.
*/
Quaternion.prototype.multiplyToRef = function (q1, result) {
var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
result.copyFromFloats(x, y, z, w);
return this;
};
/**
* Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
* Returns the updated Quaternion.
*/
Quaternion.prototype.multiplyInPlace = function (q1) {
this.multiplyToRef(q1, this);
return this;
};
/**
* Sets the passed "ref" with the conjugation of the current Quaternion.
* Returns the current Quaternion.
*/
Quaternion.prototype.conjugateToRef = function (ref) {
ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
return this;
};
/**
* Conjugates in place the current Quaternion.
* Returns the updated Quaternion.
*/
Quaternion.prototype.conjugateInPlace = function () {
this.x *= -1;
this.y *= -1;
this.z *= -1;
return this;
};
/**
* Returns a new Quaternion as the conjugate of the current Quaternion.
*/
Quaternion.prototype.conjugate = function () {
var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
return result;
};
/**
* Returns the Quaternion length (float).
*/
Quaternion.prototype.length = function () {
return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
};
/**
* Normalize in place the current Quaternion.
* Returns the updated Quaternion.
*/
Quaternion.prototype.normalize = function () {
var length = 1.0 / this.length();
this.x *= length;
this.y *= length;
this.z *= length;
this.w *= length;
return this;
};
/**
* Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
*/
Quaternion.prototype.toEulerAngles = function (order) {
if (order === void 0) { order = "YZX"; }
var result = Vector3.Zero();
this.toEulerAnglesToRef(result, order);
return result;
};
/**
* Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
* Returns the current Quaternion.
*/
Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
if (order === void 0) { order = "YZX"; }
var qz = this.z;
var qx = this.x;
var qy = this.y;
var qw = this.w;
var sqw = qw * qw;
var sqz = qz * qz;
var sqx = qx * qx;
var sqy = qy * qy;
var zAxisY = qy * qz - qx * qw;
var limit = .4999999;
if (zAxisY < -limit) {
result.y = 2 * Math.atan2(qy, qw);
result.x = Math.PI / 2;
result.z = 0;
}
else if (zAxisY > limit) {
result.y = 2 * Math.atan2(qy, qw);
result.x = -Math.PI / 2;
result.z = 0;
}
else {
result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
}
return this;
};
/**
* Updates the passed rotation matrix with the current Quaternion values.
* Returns the current Quaternion.
*/
Quaternion.prototype.toRotationMatrix = function (result) {
var xx = this.x * this.x;
var yy = this.y * this.y;
var zz = this.z * this.z;
var xy = this.x * this.y;
var zw = this.z * this.w;
var zx = this.z * this.x;
var yw = this.y * this.w;
var yz = this.y * this.z;
var xw = this.x * this.w;
result.m[0] = 1.0 - (2.0 * (yy + zz));
result.m[1] = 2.0 * (xy + zw);
result.m[2] = 2.0 * (zx - yw);
result.m[3] = 0;
result.m[4] = 2.0 * (xy - zw);
result.m[5] = 1.0 - (2.0 * (zz + xx));
result.m[6] = 2.0 * (yz + xw);
result.m[7] = 0;
result.m[8] = 2.0 * (zx + yw);
result.m[9] = 2.0 * (yz - xw);
result.m[10] = 1.0 - (2.0 * (yy + xx));
result.m[11] = 0;
result.m[12] = 0;
result.m[13] = 0;
result.m[14] = 0;
result.m[15] = 1.0;
result._markAsUpdated();
return this;
};
/**
* Updates the current Quaternion from the passed rotation matrix values.
* Returns the updated Quaternion.
*/
Quaternion.prototype.fromRotationMatrix = function (matrix) {
Quaternion.FromRotationMatrixToRef(matrix, this);
return this;
};
// Statics
/**
* Returns a new Quaternion set from the passed rotation matrix values.
*/
Quaternion.FromRotationMatrix = function (matrix) {
var result = new Quaternion();
Quaternion.FromRotationMatrixToRef(matrix, result);
return result;
};
/**
* Updates the passed quaternion "result" with the passed rotation matrix values.
*/
Quaternion.FromRotationMatrixToRef = function (matrix, result) {
var data = matrix.m;
var m11 = data[0], m12 = data[4], m13 = data[8];
var m21 = data[1], m22 = data[5], m23 = data[9];
var m31 = data[2], m32 = data[6], m33 = data[10];
var trace = m11 + m22 + m33;
var s;
if (trace > 0) {
s = 0.5 / Math.sqrt(trace + 1.0);
result.w = 0.25 / s;
result.x = (m32 - m23) * s;
result.y = (m13 - m31) * s;
result.z = (m21 - m12) * s;
}
else if (m11 > m22 && m11 > m33) {
s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
result.w = (m32 - m23) / s;
result.x = 0.25 * s;
result.y = (m12 + m21) / s;
result.z = (m13 + m31) / s;
}
else if (m22 > m33) {
s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
result.w = (m13 - m31) / s;
result.x = (m12 + m21) / s;
result.y = 0.25 * s;
result.z = (m23 + m32) / s;
}
else {
s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
result.w = (m21 - m12) / s;
result.x = (m13 + m31) / s;
result.y = (m23 + m32) / s;
result.z = 0.25 * s;
}
};
/**
* Returns a new Quaternion set to (0.0, 0.0, 0.0).
*/
Quaternion.Zero = function () {
return new Quaternion(0.0, 0.0, 0.0, 0.0);
};
/**
* Returns a new Quaternion as the inverted current Quaternion.
*/
Quaternion.Inverse = function (q) {
return new Quaternion(-q.x, -q.y, -q.z, q.w);
};
/**
* Returns the identity Quaternion.
*/
Quaternion.Identity = function () {
return new Quaternion(0.0, 0.0, 0.0, 1.0);
};
Quaternion.IsIdentity = function (quaternion) {
return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
};
/**
* Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
*/
Quaternion.RotationAxis = function (axis, angle) {
return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
};
/**
* Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
*/
Quaternion.RotationAxisToRef = function (axis, angle, result) {
var sin = Math.sin(angle / 2);
axis.normalize();
result.w = Math.cos(angle / 2);
result.x = axis.x * sin;
result.y = axis.y * sin;
result.z = axis.z * sin;
return result;
};
/**
* Retuns a new Quaternion set from the starting index of the passed array.
*/
Quaternion.FromArray = function (array, offset) {
if (!offset) {
offset = 0;
}
return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
};
/**
* Returns a new Quaternion set from the passed Euler float angles (y, x, z).
*/
Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
var q = new Quaternion();
Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
return q;
};
/**
* Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
*/
Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
// Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
var halfRoll = roll * 0.5;
var halfPitch = pitch * 0.5;
var halfYaw = yaw * 0.5;
var sinRoll = Math.sin(halfRoll);
var cosRoll = Math.cos(halfRoll);
var sinPitch = Math.sin(halfPitch);
var cosPitch = Math.cos(halfPitch);
var sinYaw = Math.sin(halfYaw);
var cosYaw = Math.cos(halfYaw);
result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
};
/**
* Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
*/
Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
var result = new Quaternion();
Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
return result;
};
/**
* Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
*/
Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
// Produces a quaternion from Euler angles in the z-x-z orientation
var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
var halfBeta = beta * 0.5;
result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
};
/**
* Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
* cf to Vector3.RotationFromAxis() documentation.
* Note : axis1, axis2 and axis3 are normalized during this operation.
*/
Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
return quat;
};
/**
* Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
* cf to Vector3.RotationFromAxis() documentation.
* Note : axis1, axis2 and axis3 are normalized during this operation.
*/
Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
var rotMat = MathTmp.Matrix[0];
Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
Quaternion.FromRotationMatrixToRef(rotMat, ref);
};
Quaternion.Slerp = function (left, right, amount) {
var result = Quaternion.Identity();
Quaternion.SlerpToRef(left, right, amount, result);
return result;
};
Quaternion.SlerpToRef = function (left, right, amount, result) {
var num2;
var num3;
var num = amount;
var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
var flag = false;
if (num4 < 0) {
flag = true;
num4 = -num4;
}
if (num4 > 0.999999) {
num3 = 1 - num;
num2 = flag ? -num : num;
}
else {
var num5 = Math.acos(num4);
var num6 = (1.0 / Math.sin(num5));
num3 = (Math.sin((1.0 - num) * num5)) * num6;
num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
}
result.x = (num3 * left.x) + (num2 * right.x);
result.y = (num3 * left.y) + (num2 * right.y);
result.z = (num3 * left.z) + (num2 * right.z);
result.w = (num3 * left.w) + (num2 * right.w);
};
/**
* Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
*/
Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
var part2 = (-2.0 * cubed) + (3.0 * squared);
var part3 = (cubed - (2.0 * squared)) + amount;
var part4 = cubed - squared;
var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
return new Quaternion(x, y, z, w);
};
return Quaternion;
}());
BABYLON.Quaternion = Quaternion;
var Matrix = /** @class */ (function () {
function Matrix() {
this._isIdentity = false;
this._isIdentityDirty = true;
this.m = new Float32Array(16);
this._markAsUpdated();
}
Matrix.prototype._markAsUpdated = function () {
this.updateFlag = Matrix._updateFlagSeed++;
this._isIdentityDirty = true;
};
// Properties
/**
* Boolean : True is the matrix is the identity matrix
*/
Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
if (this._isIdentityDirty) {
this._isIdentityDirty = false;
if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
this._isIdentity = false;
}
else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
this._isIdentity = false;
}
else {
this._isIdentity = true;
}
if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
this._isIdentity = false;
}
}
return this._isIdentity;
};
/**
* Returns the matrix determinant (float).
*/
Matrix.prototype.determinant = function () {
var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
(this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
(this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
};
// Methods
/**
* Returns the matrix underlying array.
*/
Matrix.prototype.toArray = function () {
return this.m;
};
/**
* Returns the matrix underlying array.
*/
Matrix.prototype.asArray = function () {
return this.toArray();
};
/**
* Inverts in place the Matrix.
* Returns the Matrix inverted.
*/
Matrix.prototype.invert = function () {
this.invertToRef(this);
return this;
};
/**
* Sets all the matrix elements to zero.
* Returns the Matrix.
*/
Matrix.prototype.reset = function () {
for (var index = 0; index < 16; index++) {
this.m[index] = 0.0;
}
this._markAsUpdated();
return this;
};
/**
* Returns a new Matrix as the addition result of the current Matrix and the passed one.
*/
Matrix.prototype.add = function (other) {
var result = new Matrix();
this.addToRef(other, result);
return result;
};
/**
* Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
* Returns the Matrix.
*/
Matrix.prototype.addToRef = function (other, result) {
for (var index = 0; index < 16; index++) {
result.m[index] = this.m[index] + other.m[index];
}
result._markAsUpdated();
return this;
};
/**
* Adds in place the passed matrix to the current Matrix.
* Returns the updated Matrix.
*/
Matrix.prototype.addToSelf = function (other) {
for (var index = 0; index < 16; index++) {
this.m[index] += other.m[index];
}
this._markAsUpdated();
return this;
};
/**
* Sets the passed matrix with the current inverted Matrix.
* Returns the unmodified current Matrix.
*/
Matrix.prototype.invertToRef = function (other) {
var l1 = this.m[0];
var l2 = this.m[1];
var l3 = this.m[2];
var l4 = this.m[3];
var l5 = this.m[4];
var l6 = this.m[5];
var l7 = this.m[6];
var l8 = this.m[7];
var l9 = this.m[8];
var l10 = this.m[9];
var l11 = this.m[10];
var l12 = this.m[11];
var l13 = this.m[12];
var l14 = this.m[13];
var l15 = this.m[14];
var l16 = this.m[15];
var l17 = (l11 * l16) - (l12 * l15);
var l18 = (l10 * l16) - (l12 * l14);
var l19 = (l10 * l15) - (l11 * l14);
var l20 = (l9 * l16) - (l12 * l13);
var l21 = (l9 * l15) - (l11 * l13);
var l22 = (l9 * l14) - (l10 * l13);
var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
var l28 = (l7 * l16) - (l8 * l15);
var l29 = (l6 * l16) - (l8 * l14);
var l30 = (l6 * l15) - (l7 * l14);
var l31 = (l5 * l16) - (l8 * l13);
var l32 = (l5 * l15) - (l7 * l13);
var l33 = (l5 * l14) - (l6 * l13);
var l34 = (l7 * l12) - (l8 * l11);
var l35 = (l6 * l12) - (l8 * l10);
var l36 = (l6 * l11) - (l7 * l10);
var l37 = (l5 * l12) - (l8 * l9);
var l38 = (l5 * l11) - (l7 * l9);
var l39 = (l5 * l10) - (l6 * l9);
other.m[0] = l23 * l27;
other.m[4] = l24 * l27;
other.m[8] = l25 * l27;
other.m[12] = l26 * l27;
other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
other._markAsUpdated();
return this;
};
/**
* Inserts the translation vector (using 3 x floats) in the current Matrix.
* Returns the updated Matrix.
*/
Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
this.m[12] = x;
this.m[13] = y;
this.m[14] = z;
this._markAsUpdated();
return this;
};
/**
* Inserts the translation vector in the current Matrix.
* Returns the updated Matrix.
*/
Matrix.prototype.setTranslation = function (vector3) {
this.m[12] = vector3.x;
this.m[13] = vector3.y;
this.m[14] = vector3.z;
this._markAsUpdated();
return this;
};
/**
* Returns a new Vector3 as the extracted translation from the Matrix.
*/
Matrix.prototype.getTranslation = function () {
return new Vector3(this.m[12], this.m[13], this.m[14]);
};
/**
* Fill a Vector3 with the extracted translation from the Matrix.
*/
Matrix.prototype.getTranslationToRef = function (result) {
result.x = this.m[12];
result.y = this.m[13];
result.z = this.m[14];
return this;
};
/**
* Remove rotation and scaling part from the Matrix.
* Returns the updated Matrix.
*/
Matrix.prototype.removeRotationAndScaling = function () {
this.setRowFromFloats(0, 1, 0, 0, 0);
this.setRowFromFloats(1, 0, 1, 0, 0);
this.setRowFromFloats(2, 0, 0, 1, 0);
return this;
};
/**
* Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
*/
Matrix.prototype.multiply = function (other) {
var result = new Matrix();
this.multiplyToRef(other, result);
return result;
};
/**
* Updates the current Matrix from the passed one values.
* Returns the updated Matrix.
*/
Matrix.prototype.copyFrom = function (other) {
for (var index = 0; index < 16; index++) {
this.m[index] = other.m[index];
}
this._markAsUpdated();
return this;
};
/**
* Populates the passed array from the starting index with the Matrix values.
* Returns the Matrix.
*/
Matrix.prototype.copyToArray = function (array, offset) {
if (offset === void 0) { offset = 0; }
for (var index = 0; index < 16; index++) {
array[offset + index] = this.m[index];
}
return this;
};
/**
* Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
*/
Matrix.prototype.multiplyToRef = function (other, result) {
this.multiplyToArray(other, result.m, 0);
result._markAsUpdated();
return this;
};
/**
* Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
*/
Matrix.prototype.multiplyToArray = function (other, result, offset) {
var tm0 = this.m[0];
var tm1 = this.m[1];
var tm2 = this.m[2];
var tm3 = this.m[3];
var tm4 = this.m[4];
var tm5 = this.m[5];
var tm6 = this.m[6];
var tm7 = this.m[7];
var tm8 = this.m[8];
var tm9 = this.m[9];
var tm10 = this.m[10];
var tm11 = this.m[11];
var tm12 = this.m[12];
var tm13 = this.m[13];
var tm14 = this.m[14];
var tm15 = this.m[15];
var om0 = other.m[0];
var om1 = other.m[1];
var om2 = other.m[2];
var om3 = other.m[3];
var om4 = other.m[4];
var om5 = other.m[5];
var om6 = other.m[6];
var om7 = other.m[7];
var om8 = other.m[8];
var om9 = other.m[9];
var om10 = other.m[10];
var om11 = other.m[11];
var om12 = other.m[12];
var om13 = other.m[13];
var om14 = other.m[14];
var om15 = other.m[15];
result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
return this;
};
/**
* Boolean : True is the current Matrix and the passed one values are strictly equal.
*/
Matrix.prototype.equals = function (value) {
return value &&
(this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
};
/**
* Returns a new Matrix from the current Matrix.
*/
Matrix.prototype.clone = function () {
return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
};
/**
* Returns the string "Matrix"
*/
Matrix.prototype.getClassName = function () {
return "Matrix";
};
/**
* Returns the Matrix hash code.
*/
Matrix.prototype.getHashCode = function () {
var hash = this.m[0] || 0;
for (var i = 1; i < 16; i++) {
hash = (hash * 397) ^ (this.m[i] || 0);
}
return hash;
};
/**
* Decomposes the current Matrix into :
* - a scale vector3 passed as a reference to update,
* - a rotation quaternion passed as a reference to update,
* - a translation vector3 passed as a reference to update.
* Returns the boolean `true`.
*/
Matrix.prototype.decompose = function (scale, rotation, translation) {
translation.x = this.m[12];
translation.y = this.m[13];
translation.z = this.m[14];
scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
if (this.determinant() <= 0) {
scale.y *= -1;
}
if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
rotation.x = 0;
rotation.y = 0;
rotation.z = 0;
rotation.w = 1;
return false;
}
Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
return true;
};
/**
* Returns a new Matrix as the extracted rotation matrix from the current one.
*/
Matrix.prototype.getRotationMatrix = function () {
var result = Matrix.Identity();
this.getRotationMatrixToRef(result);
return result;
};
/**
* Extracts the rotation matrix from the current one and sets it as the passed "result".
* Returns the current Matrix.
*/
Matrix.prototype.getRotationMatrixToRef = function (result) {
var m = this.m;
var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
return this;
};
// Statics
/**
* Returns a new Matrix set from the starting index of the passed array.
*/
Matrix.FromArray = function (array, offset) {
var result = new Matrix();
if (!offset) {
offset = 0;
}
Matrix.FromArrayToRef(array, offset, result);
return result;
};
/**
* Sets the passed "result" matrix from the starting index of the passed array.
*/
Matrix.FromArrayToRef = function (array, offset, result) {
for (var index = 0; index < 16; index++) {
result.m[index] = array[index + offset];
}
result._markAsUpdated();
};
/**
* Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
*/
Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
for (var index = 0; index < 16; index++) {
result.m[index] = array[index + offset] * scale;
}
result._markAsUpdated();
};
/**
* Sets the passed matrix "result" with the 16 passed floats.
*/
Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
result.m[0] = initialM11;
result.m[1] = initialM12;
result.m[2] = initialM13;
result.m[3] = initialM14;
result.m[4] = initialM21;
result.m[5] = initialM22;
result.m[6] = initialM23;
result.m[7] = initialM24;
result.m[8] = initialM31;
result.m[9] = initialM32;
result.m[10] = initialM33;
result.m[11] = initialM34;
result.m[12] = initialM41;
result.m[13] = initialM42;
result.m[14] = initialM43;
result.m[15] = initialM44;
result._markAsUpdated();
};
/**
* Returns the index-th row of the current matrix as a new Vector4.
*/
Matrix.prototype.getRow = function (index) {
if (index < 0 || index > 3) {
return null;
}
var i = index * 4;
return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
};
/**
* Sets the index-th row of the current matrix with the passed Vector4 values.
* Returns the updated Matrix.
*/
Matrix.prototype.setRow = function (index, row) {
if (index < 0 || index > 3) {
return this;
}
var i = index * 4;
this.m[i + 0] = row.x;
this.m[i + 1] = row.y;
this.m[i + 2] = row.z;
this.m[i + 3] = row.w;
this._markAsUpdated();
return this;
};
/**
* Compute the transpose of the matrix.
* Returns a new Matrix.
*/
Matrix.prototype.transpose = function () {
return Matrix.Transpose(this);
};
/**
* Compute the transpose of the matrix.
* Returns the current matrix.
*/
Matrix.prototype.transposeToRef = function (result) {
Matrix.TransposeToRef(this, result);
return this;
};
/**
* Sets the index-th row of the current matrix with the passed 4 x float values.
* Returns the updated Matrix.
*/
Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
if (index < 0 || index > 3) {
return this;
}
var i = index * 4;
this.m[i + 0] = x;
this.m[i + 1] = y;
this.m[i + 2] = z;
this.m[i + 3] = w;
this._markAsUpdated();
return this;
};
Object.defineProperty(Matrix, "IdentityReadOnly", {
/**
* Static identity matrix to be used as readonly matrix
* Must not be updated.
*/
get: function () {
return Matrix._identityReadOnly;
},
enumerable: true,
configurable: true
});
/**
* Returns a new Matrix set from the 16 passed floats.
*/
Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
var result = new Matrix();
result.m[0] = initialM11;
result.m[1] = initialM12;
result.m[2] = initialM13;
result.m[3] = initialM14;
result.m[4] = initialM21;
result.m[5] = initialM22;
result.m[6] = initialM23;
result.m[7] = initialM24;
result.m[8] = initialM31;
result.m[9] = initialM32;
result.m[10] = initialM33;
result.m[11] = initialM34;
result.m[12] = initialM41;
result.m[13] = initialM42;
result.m[14] = initialM43;
result.m[15] = initialM44;
return result;
};
/**
* Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
*/
Matrix.Compose = function (scale, rotation, translation) {
var result = Matrix.Identity();
Matrix.ComposeToRef(scale, rotation, translation, result);
return result;
};
/**
* Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
*/
Matrix.ComposeToRef = function (scale, rotation, translation, result) {
Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
rotation.toRotationMatrix(MathTmp.Matrix[0]);
MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
result.setTranslation(translation);
};
/**
* Returns a new indentity Matrix.
*/
Matrix.Identity = function () {
return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
};
/**
* Sets the passed "result" as an identity matrix.
*/
Matrix.IdentityToRef = function (result) {
Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
};
/**
* Returns a new zero Matrix.
*/
Matrix.Zero = function () {
return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
};
/**
* Returns a new rotation matrix for "angle" radians around the X axis.
*/
Matrix.RotationX = function (angle) {
var result = new Matrix();
Matrix.RotationXToRef(angle, result);
return result;
};
/**
* Returns a new Matrix as the passed inverted one.
*/
Matrix.Invert = function (source) {
var result = new Matrix();
source.invertToRef(result);
return result;
};
/**
* Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
*/
Matrix.RotationXToRef = function (angle, result) {
var s = Math.sin(angle);
var c = Math.cos(angle);
result.m[0] = 1.0;
result.m[15] = 1.0;
result.m[5] = c;
result.m[10] = c;
result.m[9] = -s;
result.m[6] = s;
result.m[1] = 0.0;
result.m[2] = 0.0;
result.m[3] = 0.0;
result.m[4] = 0.0;
result.m[7] = 0.0;
result.m[8] = 0.0;
result.m[11] = 0.0;
result.m[12] = 0.0;
result.m[13] = 0.0;
result.m[14] = 0.0;
result._markAsUpdated();
};
/**
* Returns a new rotation matrix for "angle" radians around the Y axis.
*/
Matrix.RotationY = function (angle) {
var result = new Matrix();
Matrix.RotationYToRef(angle, result);
return result;
};
/**
* Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
*/
Matrix.RotationYToRef = function (angle, result) {
var s = Math.sin(angle);
var c = Math.cos(angle);
result.m[5] = 1.0;
result.m[15] = 1.0;
result.m[0] = c;
result.m[2] = -s;
result.m[8] = s;
result.m[10] = c;
result.m[1] = 0.0;
result.m[3] = 0.0;
result.m[4] = 0.0;
result.m[6] = 0.0;
result.m[7] = 0.0;
result.m[9] = 0.0;
result.m[11] = 0.0;
result.m[12] = 0.0;
result.m[13] = 0.0;
result.m[14] = 0.0;
result._markAsUpdated();
};
/**
* Returns a new rotation matrix for "angle" radians around the Z axis.
*/
Matrix.RotationZ = function (angle) {
var result = new Matrix();
Matrix.RotationZToRef(angle, result);
return result;
};
/**
* Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
*/
Matrix.RotationZToRef = function (angle, result) {
var s = Math.sin(angle);
var c = Math.cos(angle);
result.m[10] = 1.0;
result.m[15] = 1.0;
result.m[0] = c;
result.m[1] = s;
result.m[4] = -s;
result.m[5] = c;
result.m[2] = 0.0;
result.m[3] = 0.0;
result.m[6] = 0.0;
result.m[7] = 0.0;
result.m[8] = 0.0;
result.m[9] = 0.0;
result.m[11] = 0.0;
result.m[12] = 0.0;
result.m[13] = 0.0;
result.m[14] = 0.0;
result._markAsUpdated();
};
/**
* Returns a new rotation matrix for "angle" radians around the passed axis.
*/
Matrix.RotationAxis = function (axis, angle) {
var result = Matrix.Zero();
Matrix.RotationAxisToRef(axis, angle, result);
return result;
};
/**
* Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
*/
Matrix.RotationAxisToRef = function (axis, angle, result) {
var s = Math.sin(-angle);
var c = Math.cos(-angle);
var c1 = 1 - c;
axis.normalize();
result.m[0] = (axis.x * axis.x) * c1 + c;
result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
result.m[3] = 0.0;
result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
result.m[5] = (axis.y * axis.y) * c1 + c;
result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
result.m[7] = 0.0;
result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
result.m[10] = (axis.z * axis.z) * c1 + c;
result.m[11] = 0.0;
result.m[15] = 1.0;
result._markAsUpdated();
};
/**
* Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
*/
Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
var result = new Matrix();
Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
return result;
};
/**
* Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
*/
Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
this._tempQuaternion.toRotationMatrix(result);
};
/**
* Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
*/
Matrix.Scaling = function (x, y, z) {
var result = Matrix.Zero();
Matrix.ScalingToRef(x, y, z, result);
return result;
};
/**
* Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
*/
Matrix.ScalingToRef = function (x, y, z, result) {
result.m[0] = x;
result.m[1] = 0.0;
result.m[2] = 0.0;
result.m[3] = 0.0;
result.m[4] = 0.0;
result.m[5] = y;
result.m[6] = 0.0;
result.m[7] = 0.0;
result.m[8] = 0.0;
result.m[9] = 0.0;
result.m[10] = z;
result.m[11] = 0.0;
result.m[12] = 0.0;
result.m[13] = 0.0;
result.m[14] = 0.0;
result.m[15] = 1.0;
result._markAsUpdated();
};
/**
* Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
*/
Matrix.Translation = function (x, y, z) {
var result = Matrix.Identity();
Matrix.TranslationToRef(x, y, z, result);
return result;
};
/**
* Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
*/
Matrix.TranslationToRef = function (x, y, z, result) {
Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
};
/**
* Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
*/
Matrix.Lerp = function (startValue, endValue, gradient) {
var result = Matrix.Zero();
for (var index = 0; index < 16; index++) {
result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
}
result._markAsUpdated();
return result;
};
/**
* Returns a new Matrix whose values are computed by :
* - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
* - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
* - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
*/
Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
var startScale = new Vector3(0, 0, 0);
var startRotation = new Quaternion();
var startTranslation = new Vector3(0, 0, 0);
startValue.decompose(startScale, startRotation, startTranslation);
var endScale = new Vector3(0, 0, 0);
var endRotation = new Quaternion();
var endTranslation = new Vector3(0, 0, 0);
endValue.decompose(endScale, endRotation, endTranslation);
var resultScale = Vector3.Lerp(startScale, endScale, gradient);
var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
return Matrix.Compose(resultScale, resultRotation, resultTranslation);
};
/**
* Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
* This methods works for a Left-Handed system.
*/
Matrix.LookAtLH = function (eye, target, up) {
var result = Matrix.Zero();
Matrix.LookAtLHToRef(eye, target, up, result);
return result;
};
/**
* Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
* This methods works for a Left-Handed system.
*/
Matrix.LookAtLHToRef = function (eye, target, up, result) {
// Z axis
target.subtractToRef(eye, this._zAxis);
this._zAxis.normalize();
// X axis
Vector3.CrossToRef(up, this._zAxis, this._xAxis);
if (this._xAxis.lengthSquared() === 0) {
this._xAxis.x = 1.0;
}
else {
this._xAxis.normalize();
}
// Y axis
Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
this._yAxis.normalize();
// Eye angles
var ex = -Vector3.Dot(this._xAxis, eye);
var ey = -Vector3.Dot(this._yAxis, eye);
var ez = -Vector3.Dot(this._zAxis, eye);
return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
};
/**
* Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
* This methods works for a Right-Handed system.
*/
Matrix.LookAtRH = function (eye, target, up) {
var result = Matrix.Zero();
Matrix.LookAtRHToRef(eye, target, up, result);
return result;
};
/**
* Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
* This methods works for a Left-Handed system.
*/
Matrix.LookAtRHToRef = function (eye, target, up, result) {
// Z axis
eye.subtractToRef(target, this._zAxis);
this._zAxis.normalize();
// X axis
Vector3.CrossToRef(up, this._zAxis, this._xAxis);
if (this._xAxis.lengthSquared() === 0) {
this._xAxis.x = 1.0;
}
else {
this._xAxis.normalize();
}
// Y axis
Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
this._yAxis.normalize();
// Eye angles
var ex = -Vector3.Dot(this._xAxis, eye);
var ey = -Vector3.Dot(this._yAxis, eye);
var ez = -Vector3.Dot(this._zAxis, eye);
return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
};
/**
* Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
*/
Matrix.OrthoLH = function (width, height, znear, zfar) {
var matrix = Matrix.Zero();
Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
return matrix;
};
/**
* Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
*/
Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
var n = znear;
var f = zfar;
var a = 2.0 / width;
var b = 2.0 / height;
var c = 2.0 / (f - n);
var d = -(f + n) / (f - n);
Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
};
/**
* Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
*/
Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
var matrix = Matrix.Zero();
Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
return matrix;
};
/**
* Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
*/
Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
var n = znear;
var f = zfar;
var a = 2.0 / (right - left);
var b = 2.0 / (top - bottom);
var c = 2.0 / (f - n);
var d = -(f + n) / (f - n);
var i0 = (left + right) / (left - right);
var i1 = (top + bottom) / (bottom - top);
Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
};
/**
* Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
*/
Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
var matrix = Matrix.Zero();
Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
return matrix;
};
/**
* Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
*/
Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
result.m[10] *= -1.0;
};
/**
* Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
*/
Matrix.PerspectiveLH = function (width, height, znear, zfar) {
var matrix = Matrix.Zero();
var n = znear;
var f = zfar;
var a = 2.0 * n / width;
var b = 2.0 * n / height;
var c = (f + n) / (f - n);
var d = -2.0 * f * n / (f - n);
Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
return matrix;
};
/**
* Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
*/
Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
var matrix = Matrix.Zero();
Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
return matrix;
};
/**
* Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
*/
Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
var n = znear;
var f = zfar;
var t = 1.0 / (Math.tan(fov * 0.5));
var a = isVerticalFovFixed ? (t / aspect) : t;
var b = isVerticalFovFixed ? t : (t * aspect);
var c = (f + n) / (f - n);
var d = -2.0 * f * n / (f - n);
Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
};
/**
* Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
*/
Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
var matrix = Matrix.Zero();
Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
return matrix;
};
/**
* Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
*/
Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
//alternatively this could be expressed as:
// m = PerspectiveFovLHToRef
// m[10] *= -1.0;
// m[11] *= -1.0;
if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
var n = znear;
var f = zfar;
var t = 1.0 / (Math.tan(fov * 0.5));
var a = isVerticalFovFixed ? (t / aspect) : t;
var b = isVerticalFovFixed ? t : (t * aspect);
var c = -(f + n) / (f - n);
var d = -2 * f * n / (f - n);
Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
};
/**
* Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
*/
Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
if (rightHanded === void 0) { rightHanded = false; }
var rightHandedFactor = rightHanded ? -1 : 1;
var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
var xScale = 2.0 / (leftTan + rightTan);
var yScale = 2.0 / (upTan + downTan);
result.m[0] = xScale;
result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
result.m[5] = yScale;
result.m[6] = result.m[7] = 0.0;
result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
//result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
result.m[10] = -zfar / (znear - zfar);
result.m[11] = 1.0 * rightHandedFactor;
result.m[12] = result.m[13] = result.m[15] = 0.0;
result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
// result.m[14] = (znear * zfar) / (znear - zfar);
result._markAsUpdated();
};
/**
* Returns the final transformation matrix : world * view * projection * viewport
*/
Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
var cw = viewport.width;
var ch = viewport.height;
var cx = viewport.x;
var cy = viewport.y;
var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
return world.multiply(view).multiply(projection).multiply(viewportMatrix);
};
/**
* Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
*/
Matrix.GetAsMatrix2x2 = function (matrix) {
return new Float32Array([
matrix.m[0], matrix.m[1],
matrix.m[4], matrix.m[5]
]);
};
/**
* Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
*/
Matrix.GetAsMatrix3x3 = function (matrix) {
return new Float32Array([
matrix.m[0], matrix.m[1], matrix.m[2],
matrix.m[4], matrix.m[5], matrix.m[6],
matrix.m[8], matrix.m[9], matrix.m[10]
]);
};
/**
* Compute the transpose of the passed Matrix.
* Returns a new Matrix.
*/
Matrix.Transpose = function (matrix) {
var result = new Matrix();
Matrix.TransposeToRef(matrix, result);
return result;
};
/**
* Compute the transpose of the passed Matrix and store it in the result matrix.
*/
Matrix.TransposeToRef = function (matrix, result) {
result.m[0] = matrix.m[0];
result.m[1] = matrix.m[4];
result.m[2] = matrix.m[8];
result.m[3] = matrix.m[12];
result.m[4] = matrix.m[1];
result.m[5] = matrix.m[5];
result.m[6] = matrix.m[9];
result.m[7] = matrix.m[13];
result.m[8] = matrix.m[2];
result.m[9] = matrix.m[6];
result.m[10] = matrix.m[10];
result.m[11] = matrix.m[14];
result.m[12] = matrix.m[3];
result.m[13] = matrix.m[7];
result.m[14] = matrix.m[11];
result.m[15] = matrix.m[15];
};
/**
* Returns a new Matrix as the reflection matrix across the passed plane.
*/
Matrix.Reflection = function (plane) {
var matrix = new Matrix();
Matrix.ReflectionToRef(plane, matrix);
return matrix;
};
/**
* Sets the passed matrix "result" as the reflection matrix across the passed plane.
*/
Matrix.ReflectionToRef = function (plane, result) {
plane.normalize();
var x = plane.normal.x;
var y = plane.normal.y;
var z = plane.normal.z;
var temp = -2 * x;
var temp2 = -2 * y;
var temp3 = -2 * z;
result.m[0] = (temp * x) + 1;
result.m[1] = temp2 * x;
result.m[2] = temp3 * x;
result.m[3] = 0.0;
result.m[4] = temp * y;
result.m[5] = (temp2 * y) + 1;
result.m[6] = temp3 * y;
result.m[7] = 0.0;
result.m[8] = temp * z;
result.m[9] = temp2 * z;
result.m[10] = (temp3 * z) + 1;
result.m[11] = 0.0;
result.m[12] = temp * plane.d;
result.m[13] = temp2 * plane.d;
result.m[14] = temp3 * plane.d;
result.m[15] = 1.0;
result._markAsUpdated();
};
/**
* Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
*/
Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
result.m[0] = xaxis.x;
result.m[1] = xaxis.y;
result.m[2] = xaxis.z;
result.m[3] = 0.0;
result.m[4] = yaxis.x;
result.m[5] = yaxis.y;
result.m[6] = yaxis.z;
result.m[7] = 0.0;
result.m[8] = zaxis.x;
result.m[9] = zaxis.y;
result.m[10] = zaxis.z;
result.m[11] = 0.0;
result.m[12] = 0.0;
result.m[13] = 0.0;
result.m[14] = 0.0;
result.m[15] = 1.0;
result._markAsUpdated();
};
/**
* Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
*/
Matrix.FromQuaternionToRef = function (quat, result) {
var xx = quat.x * quat.x;
var yy = quat.y * quat.y;
var zz = quat.z * quat.z;
var xy = quat.x * quat.y;
var zw = quat.z * quat.w;
var zx = quat.z * quat.x;
var yw = quat.y * quat.w;
var yz = quat.y * quat.z;
var xw = quat.x * quat.w;
result.m[0] = 1.0 - (2.0 * (yy + zz));
result.m[1] = 2.0 * (xy + zw);
result.m[2] = 2.0 * (zx - yw);
result.m[3] = 0.0;
result.m[4] = 2.0 * (xy - zw);
result.m[5] = 1.0 - (2.0 * (zz + xx));
result.m[6] = 2.0 * (yz + xw);
result.m[7] = 0.0;
result.m[8] = 2.0 * (zx + yw);
result.m[9] = 2.0 * (yz - xw);
result.m[10] = 1.0 - (2.0 * (yy + xx));
result.m[11] = 0.0;
result.m[12] = 0.0;
result.m[13] = 0.0;
result.m[14] = 0.0;
result.m[15] = 1.0;
result._markAsUpdated();
};
Matrix._tempQuaternion = new Quaternion();
Matrix._xAxis = Vector3.Zero();
Matrix._yAxis = Vector3.Zero();
Matrix._zAxis = Vector3.Zero();
Matrix._updateFlagSeed = 0;
Matrix._identityReadOnly = Matrix.Identity();
return Matrix;
}());
BABYLON.Matrix = Matrix;
var Plane = /** @class */ (function () {
/**
* Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
*/
function Plane(a, b, c, d) {
this.normal = new Vector3(a, b, c);
this.d = d;
}
/**
* Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
*/
Plane.prototype.asArray = function () {
return [this.normal.x, this.normal.y, this.normal.z, this.d];
};
// Methods
/**
* Returns a new plane copied from the current Plane.
*/
Plane.prototype.clone = function () {
return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
};
/**
* Returns the string "Plane".
*/
Plane.prototype.getClassName = function () {
return "Plane";
};
/**
* Returns the Plane hash code.
*/
Plane.prototype.getHashCode = function () {
var hash = this.normal.getHashCode();
hash = (hash * 397) ^ (this.d || 0);
return hash;
};
/**
* Normalize the current Plane in place.
* Returns the updated Plane.
*/
Plane.prototype.normalize = function () {
var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
var magnitude = 0.0;
if (norm !== 0) {
magnitude = 1.0 / norm;
}
this.normal.x *= magnitude;
this.normal.y *= magnitude;
this.normal.z *= magnitude;
this.d *= magnitude;
return this;
};
/**
* Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
*/
Plane.prototype.transform = function (transformation) {
var transposedMatrix = Matrix.Transpose(transformation);
var x = this.normal.x;
var y = this.normal.y;
var z = this.normal.z;
var d = this.d;
var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
return new Plane(normalX, normalY, normalZ, finalD);
};
/**
* Returns the dot product (float) of the point coordinates and the plane normal.
*/
Plane.prototype.dotCoordinate = function (point) {
return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
};
/**
* Updates the current Plane from the plane defined by the three passed points.
* Returns the updated Plane.
*/
Plane.prototype.copyFromPoints = function (point1, point2, point3) {
var x1 = point2.x - point1.x;
var y1 = point2.y - point1.y;
var z1 = point2.z - point1.z;
var x2 = point3.x - point1.x;
var y2 = point3.y - point1.y;
var z2 = point3.z - point1.z;
var yz = (y1 * z2) - (z1 * y2);
var xz = (z1 * x2) - (x1 * z2);
var xy = (x1 * y2) - (y1 * x2);
var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
var invPyth;
if (pyth !== 0) {
invPyth = 1.0 / pyth;
}
else {
invPyth = 0.0;
}
this.normal.x = yz * invPyth;
this.normal.y = xz * invPyth;
this.normal.z = xy * invPyth;
this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
return this;
};
/**
* Boolean : True is the vector "direction" is the same side than the plane normal.
*/
Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
var dot = Vector3.Dot(this.normal, direction);
return (dot <= epsilon);
};
/**
* Returns the signed distance (float) from the passed point to the Plane.
*/
Plane.prototype.signedDistanceTo = function (point) {
return Vector3.Dot(point, this.normal) + this.d;
};
// Statics
/**
* Returns a new Plane from the passed array.
*/
Plane.FromArray = function (array) {
return new Plane(array[0], array[1], array[2], array[3]);
};
/**
* Returns a new Plane defined by the three passed points.
*/
Plane.FromPoints = function (point1, point2, point3) {
var result = new Plane(0.0, 0.0, 0.0, 0.0);
result.copyFromPoints(point1, point2, point3);
return result;
};
/**
* Returns a new Plane the normal vector to this plane at the passed origin point.
* Note : the vector "normal" is updated because normalized.
*/
Plane.FromPositionAndNormal = function (origin, normal) {
var result = new Plane(0.0, 0.0, 0.0, 0.0);
normal.normalize();
result.normal = normal;
result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
return result;
};
/**
* Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
*/
Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
return Vector3.Dot(point, normal) + d;
};
return Plane;
}());
BABYLON.Plane = Plane;
var Viewport = /** @class */ (function () {
/**
* Creates a Viewport object located at (x, y) and sized (width, height).
*/
function Viewport(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
if (renderWidthOrEngine.getRenderWidth) {
var engine = renderWidthOrEngine;
return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
}
var renderWidth = renderWidthOrEngine;
return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
};
/**
* Returns a new Viewport copied from the current one.
*/
Viewport.prototype.clone = function () {
return new Viewport(this.x, this.y, this.width, this.height);
};
return Viewport;
}());
BABYLON.Viewport = Viewport;
var Frustum = /** @class */ (function () {
function Frustum() {
}
/**
* Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
*/
Frustum.GetPlanes = function (transform) {
var frustumPlanes = [];
for (var index = 0; index < 6; index++) {
frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
}
Frustum.GetPlanesToRef(transform, frustumPlanes);
return frustumPlanes;
};
Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] + transform.m[2];
frustumPlane.normal.y = transform.m[7] + transform.m[6];
frustumPlane.normal.z = transform.m[11] + transform.m[10];
frustumPlane.d = transform.m[15] + transform.m[14];
frustumPlane.normalize();
};
Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] - transform.m[2];
frustumPlane.normal.y = transform.m[7] - transform.m[6];
frustumPlane.normal.z = transform.m[11] - transform.m[10];
frustumPlane.d = transform.m[15] - transform.m[14];
frustumPlane.normalize();
};
Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] + transform.m[0];
frustumPlane.normal.y = transform.m[7] + transform.m[4];
frustumPlane.normal.z = transform.m[11] + transform.m[8];
frustumPlane.d = transform.m[15] + transform.m[12];
frustumPlane.normalize();
};
Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] - transform.m[0];
frustumPlane.normal.y = transform.m[7] - transform.m[4];
frustumPlane.normal.z = transform.m[11] - transform.m[8];
frustumPlane.d = transform.m[15] - transform.m[12];
frustumPlane.normalize();
};
Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] - transform.m[1];
frustumPlane.normal.y = transform.m[7] - transform.m[5];
frustumPlane.normal.z = transform.m[11] - transform.m[9];
frustumPlane.d = transform.m[15] - transform.m[13];
frustumPlane.normalize();
};
Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] + transform.m[1];
frustumPlane.normal.y = transform.m[7] + transform.m[5];
frustumPlane.normal.z = transform.m[11] + transform.m[9];
frustumPlane.d = transform.m[15] + transform.m[13];
frustumPlane.normalize();
};
/**
* Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
*/
Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
// Near
Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
// Far
Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
// Left
Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
// Right
Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
// Top
Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
// Bottom
Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
};
return Frustum;
}());
BABYLON.Frustum = Frustum;
var Space;
(function (Space) {
Space[Space["LOCAL"] = 0] = "LOCAL";
Space[Space["WORLD"] = 1] = "WORLD";
Space[Space["BONE"] = 2] = "BONE";
})(Space = BABYLON.Space || (BABYLON.Space = {}));
var Axis = /** @class */ (function () {
function Axis() {
}
Axis.X = new Vector3(1.0, 0.0, 0.0);
Axis.Y = new Vector3(0.0, 1.0, 0.0);
Axis.Z = new Vector3(0.0, 0.0, 1.0);
return Axis;
}());
BABYLON.Axis = Axis;
;
var BezierCurve = /** @class */ (function () {
function BezierCurve() {
}
/**
* Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
*/
BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
// Extract X (which is equal to time here)
var f0 = 1 - 3 * x2 + 3 * x1;
var f1 = 3 * x2 - 6 * x1;
var f2 = 3 * x1;
var refinedT = t;
for (var i = 0; i < 5; i++) {
var refinedT2 = refinedT * refinedT;
var refinedT3 = refinedT2 * refinedT;
var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
refinedT -= (x - t) * slope;
refinedT = Math.min(1, Math.max(0, refinedT));
}
// Resolve cubic bezier for the given x
return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
Math.pow(refinedT, 3);
};
return BezierCurve;
}());
BABYLON.BezierCurve = BezierCurve;
var Orientation;
(function (Orientation) {
Orientation[Orientation["CW"] = 0] = "CW";
Orientation[Orientation["CCW"] = 1] = "CCW";
})(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
var Angle = /** @class */ (function () {
/**
* Creates an Angle object of "radians" radians (float).
*/
function Angle(radians) {
var _this = this;
/**
* Returns the Angle value in degrees (float).
*/
this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
/**
* Returns the Angle value in radians (float).
*/
this.radians = function () { return _this._radians; };
this._radians = radians;
if (this._radians < 0.0)
this._radians += (2.0 * Math.PI);
}
/**
* Returns a new Angle object valued with the angle value in radians between the two passed vectors.
*/
Angle.BetweenTwoPoints = function (a, b) {
var delta = b.subtract(a);
var theta = Math.atan2(delta.y, delta.x);
return new Angle(theta);
};
/**
* Returns a new Angle object from the passed float in radians.
*/
Angle.FromRadians = function (radians) {
return new Angle(radians);
};
/**
* Returns a new Angle object from the passed float in degrees.
*/
Angle.FromDegrees = function (degrees) {
return new Angle(degrees * Math.PI / 180.0);
};
return Angle;
}());
BABYLON.Angle = Angle;
var Arc2 = /** @class */ (function () {
/**
* Creates an Arc object from the three passed points : start, middle and end.
*/
function Arc2(startPoint, midPoint, endPoint) {
this.startPoint = startPoint;
this.midPoint = midPoint;
this.endPoint = endPoint;
var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
this.radius = this.centerPoint.subtract(this.startPoint).length();
this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
var a1 = this.startAngle.degrees();
var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
// angles correction
if (a2 - a1 > +180.0)
a2 -= 360.0;
if (a2 - a1 < -180.0)
a2 += 360.0;
if (a3 - a2 > +180.0)
a3 -= 360.0;
if (a3 - a2 < -180.0)
a3 += 360.0;
this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
}
return Arc2;
}());
BABYLON.Arc2 = Arc2;
var Path2 = /** @class */ (function () {
/**
* Creates a Path2 object from the starting 2D coordinates x and y.
*/
function Path2(x, y) {
this._points = new Array();
this._length = 0.0;
this.closed = false;
this._points.push(new Vector2(x, y));
}
/**
* Adds a new segment until the passed coordinates (x, y) to the current Path2.
* Returns the updated Path2.
*/
Path2.prototype.addLineTo = function (x, y) {
if (this.closed) {
//Tools.Error("cannot add lines to closed paths");
return this;
}
var newPoint = new Vector2(x, y);
var previousPoint = this._points[this._points.length - 1];
this._points.push(newPoint);
this._length += newPoint.subtract(previousPoint).length();
return this;
};
/**
* Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
* Returns the updated Path2.
*/
Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
if (numberOfSegments === void 0) { numberOfSegments = 36; }
if (this.closed) {
//Tools.Error("cannot add arcs to closed paths");
return this;
}
var startPoint = this._points[this._points.length - 1];
var midPoint = new Vector2(midX, midY);
var endPoint = new Vector2(endX, endY);
var arc = new Arc2(startPoint, midPoint, endPoint);
var increment = arc.angle.radians() / numberOfSegments;
if (arc.orientation === Orientation.CW)
increment *= -1;
var currentAngle = arc.startAngle.radians() + increment;
for (var i = 0; i < numberOfSegments; i++) {
var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
this.addLineTo(x, y);
currentAngle += increment;
}
return this;
};
/**
* Closes the Path2.
* Returns the Path2.
*/
Path2.prototype.close = function () {
this.closed = true;
return this;
};
/**
* Returns the Path2 total length (float).
*/
Path2.prototype.length = function () {
var result = this._length;
if (!this.closed) {
var lastPoint = this._points[this._points.length - 1];
var firstPoint = this._points[0];
result += (firstPoint.subtract(lastPoint).length());
}
return result;
};
/**
* Returns the Path2 internal array of points.
*/
Path2.prototype.getPoints = function () {
return this._points;
};
/**
* Returns a new Vector2 located at a percentage of the Path2 total length on this path.
*/
Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
//Tools.Error("normalized length position should be between 0 and 1.");
return Vector2.Zero();
}
var lengthPosition = normalizedLengthPosition * this.length();
var previousOffset = 0;
for (var i = 0; i < this._points.length; i++) {
var j = (i + 1) % this._points.length;
var a = this._points[i];
var b = this._points[j];
var bToA = b.subtract(a);
var nextOffset = (bToA.length() + previousOffset);
if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
var dir = bToA.normalize();
var localOffset = lengthPosition - previousOffset;
return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
}
previousOffset = nextOffset;
}
//Tools.Error("internal error");
return Vector2.Zero();
};
/**
* Returns a new Path2 starting at the coordinates (x, y).
*/
Path2.StartingAt = function (x, y) {
return new Path2(x, y);
};
return Path2;
}());
BABYLON.Path2 = Path2;
var Path3D = /** @class */ (function () {
/**
* new Path3D(path, normal, raw)
* Creates a Path3D. A Path3D is a logical math object, so not a mesh.
* please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
* path : an array of Vector3, the curve axis of the Path3D
* normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
* raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
*/
function Path3D(path, firstNormal, raw) {
if (firstNormal === void 0) { firstNormal = null; }
this.path = path;
this._curve = new Array();
this._distances = new Array();
this._tangents = new Array();
this._normals = new Array();
this._binormals = new Array();
for (var p = 0; p < path.length; p++) {
this._curve[p] = path[p].clone(); // hard copy
}
this._raw = raw || false;
this._compute(firstNormal);
}
/**
* Returns the Path3D array of successive Vector3 designing its curve.
*/
Path3D.prototype.getCurve = function () {
return this._curve;
};
/**
* Returns an array populated with tangent vectors on each Path3D curve point.
*/
Path3D.prototype.getTangents = function () {
return this._tangents;
};
/**
* Returns an array populated with normal vectors on each Path3D curve point.
*/
Path3D.prototype.getNormals = function () {
return this._normals;
};
/**
* Returns an array populated with binormal vectors on each Path3D curve point.
*/
Path3D.prototype.getBinormals = function () {
return this._binormals;
};
/**
* Returns an array populated with distances (float) of the i-th point from the first curve point.
*/
Path3D.prototype.getDistances = function () {
return this._distances;
};
/**
* Forces the Path3D tangent, normal, binormal and distance recomputation.
* Returns the same object updated.
*/
Path3D.prototype.update = function (path, firstNormal) {
if (firstNormal === void 0) { firstNormal = null; }
for (var p = 0; p < path.length; p++) {
this._curve[p].x = path[p].x;
this._curve[p].y = path[p].y;
this._curve[p].z = path[p].z;
}
this._compute(firstNormal);
return this;
};
// private function compute() : computes tangents, normals and binormals
Path3D.prototype._compute = function (firstNormal) {
var l = this._curve.length;
// first and last tangents
this._tangents[0] = this._getFirstNonNullVector(0);
if (!this._raw) {
this._tangents[0].normalize();
}
this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
if (!this._raw) {
this._tangents[l - 1].normalize();
}
// normals and binormals at first point : arbitrary vector with _normalVector()
var tg0 = this._tangents[0];
var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
this._normals[0] = pp0;
if (!this._raw) {
this._normals[0].normalize();
}
this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
if (!this._raw) {
this._binormals[0].normalize();
}
this._distances[0] = 0.0;
// normals and binormals : next points
var prev; // previous vector (segment)
var cur; // current vector (segment)
var curTang; // current tangent
// previous normal
var prevBinor; // previous binormal
for (var i = 1; i < l; i++) {
// tangents
prev = this._getLastNonNullVector(i);
if (i < l - 1) {
cur = this._getFirstNonNullVector(i);
this._tangents[i] = prev.add(cur);
this._tangents[i].normalize();
}
this._distances[i] = this._distances[i - 1] + prev.length();
// normals and binormals
// http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
curTang = this._tangents[i];
prevBinor = this._binormals[i - 1];
this._normals[i] = Vector3.Cross(prevBinor, curTang);
if (!this._raw) {
this._normals[i].normalize();
}
this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
if (!this._raw) {
this._binormals[i].normalize();
}
}
};
// private function getFirstNonNullVector(index)
// returns the first non null vector from index : curve[index + N].subtract(curve[index])
Path3D.prototype._getFirstNonNullVector = function (index) {
var i = 1;
var nNVector = this._curve[index + i].subtract(this._curve[index]);
while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
i++;
nNVector = this._curve[index + i].subtract(this._curve[index]);
}
return nNVector;
};
// private function getLastNonNullVector(index)
// returns the last non null vector from index : curve[index].subtract(curve[index - N])
Path3D.prototype._getLastNonNullVector = function (index) {
var i = 1;
var nLVector = this._curve[index].subtract(this._curve[index - i]);
while (nLVector.length() === 0 && index > i + 1) {
i++;
nLVector = this._curve[index].subtract(this._curve[index - i]);
}
return nLVector;
};
// private function normalVector(v0, vt, va) :
// returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
// if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
Path3D.prototype._normalVector = function (v0, vt, va) {
var normal0;
var tgl = vt.length();
if (tgl === 0.0) {
tgl = 1.0;
}
if (va === undefined || va === null) {
var point;
if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
point = new Vector3(0.0, -1.0, 0.0);
}
else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
point = new Vector3(1.0, 0.0, 0.0);
}
else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
point = new Vector3(0.0, 0.0, 1.0);
}
else {
point = Vector3.Zero();
}
normal0 = Vector3.Cross(vt, point);
}
else {
normal0 = Vector3.Cross(vt, va);
Vector3.CrossToRef(normal0, vt, normal0);
}
normal0.normalize();
return normal0;
};
return Path3D;
}());
BABYLON.Path3D = Path3D;
var Curve3 = /** @class */ (function () {
/**
* A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
* A Curve3 is designed from a series of successive Vector3.
* Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
*/
function Curve3(points) {
this._length = 0.0;
this._points = points;
this._length = this._computeLength(points);
}
/**
* Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
* @param v0 (Vector3) the origin point of the Quadratic Bezier
* @param v1 (Vector3) the control point
* @param v2 (Vector3) the end point of the Quadratic Bezier
* @param nbPoints (integer) the wanted number of points in the curve
*/
Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
nbPoints = nbPoints > 2 ? nbPoints : 3;
var bez = new Array();
var equation = function (t, val0, val1, val2) {
var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
return res;
};
for (var i = 0; i <= nbPoints; i++) {
bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
}
return new Curve3(bez);
};
/**
* Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
* @param v0 (Vector3) the origin point of the Cubic Bezier
* @param v1 (Vector3) the first control point
* @param v2 (Vector3) the second control point
* @param v3 (Vector3) the end point of the Cubic Bezier
* @param nbPoints (integer) the wanted number of points in the curve
*/
Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
nbPoints = nbPoints > 3 ? nbPoints : 4;
var bez = new Array();
var equation = function (t, val0, val1, val2, val3) {
var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
return res;
};
for (var i = 0; i <= nbPoints; i++) {
bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
}
return new Curve3(bez);
};
/**
* Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
* @param p1 (Vector3) the origin point of the Hermite Spline
* @param t1 (Vector3) the tangent vector at the origin point
* @param p2 (Vector3) the end point of the Hermite Spline
* @param t2 (Vector3) the tangent vector at the end point
* @param nbPoints (integer) the wanted number of points in the curve
*/
Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
var hermite = new Array();
var step = 1.0 / nbPoints;
for (var i = 0; i <= nbPoints; i++) {
hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
}
return new Curve3(hermite);
};
/**
* Returns a Curve3 object along a CatmullRom Spline curve :
* @param points (array of Vector3) the points the spline must pass through. At least, four points required.
* @param nbPoints (integer) the wanted number of points between each curve control points.
*/
Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
var totalPoints = new Array();
totalPoints.push(points[0].clone());
Array.prototype.push.apply(totalPoints, points);
totalPoints.push(points[points.length - 1].clone());
var catmullRom = new Array();
var step = 1.0 / nbPoints;
var amount = 0.0;
for (var i = 0; i < totalPoints.length - 3; i++) {
amount = 0;
for (var c = 0; c < nbPoints; c++) {
catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
amount += step;
}
}
i--;
catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
return new Curve3(catmullRom);
};
/**
* Returns the Curve3 stored array of successive Vector3
*/
Curve3.prototype.getPoints = function () {
return this._points;
};
/**
* Returns the computed length (float) of the curve.
*/
Curve3.prototype.length = function () {
return this._length;
};
/**
* Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
* This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
* curveA and curveB keep unchanged.
*/
Curve3.prototype.continue = function (curve) {
var lastPoint = this._points[this._points.length - 1];
var continuedPoints = this._points.slice();
var curvePoints = curve.getPoints();
for (var i = 1; i < curvePoints.length; i++) {
continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
}
var continuedCurve = new Curve3(continuedPoints);
return continuedCurve;
};
Curve3.prototype._computeLength = function (path) {
var l = 0;
for (var i = 1; i < path.length; i++) {
l += (path[i].subtract(path[i - 1])).length();
}
return l;
};
return Curve3;
}());
BABYLON.Curve3 = Curve3;
// Vertex formats
var PositionNormalVertex = /** @class */ (function () {
function PositionNormalVertex(position, normal) {
if (position === void 0) { position = Vector3.Zero(); }
if (normal === void 0) { normal = Vector3.Up(); }
this.position = position;
this.normal = normal;
}
PositionNormalVertex.prototype.clone = function () {
return new PositionNormalVertex(this.position.clone(), this.normal.clone());
};
return PositionNormalVertex;
}());
BABYLON.PositionNormalVertex = PositionNormalVertex;
var PositionNormalTextureVertex = /** @class */ (function () {
function PositionNormalTextureVertex(position, normal, uv) {
if (position === void 0) { position = Vector3.Zero(); }
if (normal === void 0) { normal = Vector3.Up(); }
if (uv === void 0) { uv = Vector2.Zero(); }
this.position = position;
this.normal = normal;
this.uv = uv;
}
PositionNormalTextureVertex.prototype.clone = function () {
return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
};
return PositionNormalTextureVertex;
}());
BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
// Temporary pre-allocated objects for engine internal use
// usage in any internal function :
// var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
// There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
var Tmp = /** @class */ (function () {
function Tmp() {
}
Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
Matrix.Zero(), Matrix.Zero(),
Matrix.Zero(), Matrix.Zero(),
Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
return Tmp;
}());
BABYLON.Tmp = Tmp;
// Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
var MathTmp = /** @class */ (function () {
function MathTmp() {
}
MathTmp.Vector3 = [Vector3.Zero()];
MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
MathTmp.Quaternion = [Quaternion.Zero()];
return MathTmp;
}());
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.math.js.map
var BABYLON;
(function (BABYLON) {
var Scalar = /** @class */ (function () {
function Scalar() {
}
/**
* Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
*/
Scalar.WithinEpsilon = function (a, b, epsilon) {
if (epsilon === void 0) { epsilon = 1.401298E-45; }
var num = a - b;
return -epsilon <= num && num <= epsilon;
};
/**
* Returns a string : the upper case translation of the number i to hexadecimal.
*/
Scalar.ToHex = function (i) {
var str = i.toString(16);
if (i <= 15) {
return ("0" + str).toUpperCase();
}
return str.toUpperCase();
};
/**
* Returns -1 if value is negative and +1 is value is positive.
* Returns the value itself if it's equal to zero.
*/
Scalar.Sign = function (value) {
value = +value; // convert to a number
if (value === 0 || isNaN(value))
return value;
return value > 0 ? 1 : -1;
};
/**
* Returns the value itself if it's between min and max.
* Returns min if the value is lower than min.
* Returns max if the value is greater than max.
*/
Scalar.Clamp = function (value, min, max) {
if (min === void 0) { min = 0; }
if (max === void 0) { max = 1; }
return Math.min(max, Math.max(min, value));
};
/**
* Returns the log2 of value.
*/
Scalar.Log2 = function (value) {
return Math.log(value) * Math.LOG2E;
};
/**
* Loops the value, so that it is never larger than length and never smaller than 0.
*
* This is similar to the modulo operator but it works with floating point numbers.
* For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
* With t = 5 and length = 2.5, the result would be 0.0.
* Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
*/
Scalar.Repeat = function (value, length) {
return value - Math.floor(value / length) * length;
};
/**
* Normalize the value between 0.0 and 1.0 using min and max values
*/
Scalar.Normalize = function (value, min, max) {
return (value - min) / (max - min);
};
/**
* Denormalize the value from 0.0 and 1.0 using min and max values
*/
Scalar.Denormalize = function (normalized, min, max) {
return (normalized * (max - min) + min);
};
/**
* Calculates the shortest difference between two given angles given in degrees.
*/
Scalar.DeltaAngle = function (current, target) {
var num = Scalar.Repeat(target - current, 360.0);
if (num > 180.0) {
num -= 360.0;
}
return num;
};
/**
* PingPongs the value t, so that it is never larger than length and never smaller than 0.
*
* The returned value will move back and forth between 0 and length
*/
Scalar.PingPong = function (tx, length) {
var t = Scalar.Repeat(tx, length * 2.0);
return length - Math.abs(t - length);
};
/**
* Interpolates between min and max with smoothing at the limits.
*
* This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
* from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
*/
Scalar.SmoothStep = function (from, to, tx) {
var t = Scalar.Clamp(tx);
t = -2.0 * t * t * t + 3.0 * t * t;
return to * t + from * (1.0 - t);
};
/**
* Moves a value current towards target.
*
* This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
* Negative values of maxDelta pushes the value away from target.
*/
Scalar.MoveTowards = function (current, target, maxDelta) {
var result = 0;
if (Math.abs(target - current) <= maxDelta) {
result = target;
}
else {
result = current + Scalar.Sign(target - current) * maxDelta;
}
return result;
};
/**
* Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
*
* Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
* are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
*/
Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
var num = Scalar.DeltaAngle(current, target);
var result = 0;
if (-maxDelta < num && num < maxDelta) {
result = target;
}
else {
target = current + num;
result = Scalar.MoveTowards(current, target, maxDelta);
}
return result;
};
/**
* Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
*/
Scalar.Lerp = function (start, end, amount) {
return start + ((end - start) * amount);
};
/**
* Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
* The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
*/
Scalar.LerpAngle = function (start, end, amount) {
var num = Scalar.Repeat(end - start, 360.0);
if (num > 180.0) {
num -= 360.0;
}
return start + num * Scalar.Clamp(amount);
};
/**
* Calculates the linear parameter t that produces the interpolant value within the range [a, b].
*/
Scalar.InverseLerp = function (a, b, value) {
var result = 0;
if (a != b) {
result = Scalar.Clamp((value - a) / (b - a));
}
else {
result = 0.0;
}
return result;
};
/**
* Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
*/
Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
var part2 = (-2.0 * cubed) + (3.0 * squared);
var part3 = (cubed - (2.0 * squared)) + amount;
var part4 = cubed - squared;
return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
};
/**
* Returns a random float number between and min and max values
*/
Scalar.RandomRange = function (min, max) {
if (min === max)
return min;
return ((Math.random() * (max - min)) + min);
};
/**
* This function returns percentage of a number in a given range.
*
* RangeToPercent(40,20,60) will return 0.5 (50%)
* RangeToPercent(34,0,100) will return 0.34 (34%)
*/
Scalar.RangeToPercent = function (number, min, max) {
return ((number - min) / (max - min));
};
/**
* This function returns number that corresponds to the percentage in a given range.
*
* PercentToRange(0.34,0,100) will return 34.
*/
Scalar.PercentToRange = function (percent, min, max) {
return ((max - min) * percent + min);
};
/**
* Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
* @param angle The angle to normalize in radian.
* @return The converted angle.
*/
Scalar.NormalizeRadians = function (angle) {
// More precise but slower version kept for reference.
// angle = angle % Tools.TwoPi;
// angle = (angle + Tools.TwoPi) % Tools.TwoPi;
//if (angle > Math.PI) {
// angle -= Tools.TwoPi;
//}
angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
return angle;
};
/**
* Two pi constants convenient for computation.
*/
Scalar.TwoPi = Math.PI * 2;
return Scalar;
}());
BABYLON.Scalar = Scalar;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.math.scalar.js.map
//# sourceMappingURL=babylon.mixins.js.map
var BABYLON;
(function (BABYLON) {
var __decoratorInitialStore = {};
var __mergedStore = {};
var _copySource = function (creationFunction, source, instanciate) {
var destination = creationFunction();
// Tags
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(destination, source.tags);
}
var classStore = getMergedStore(destination);
// Properties
for (var property in classStore) {
var propertyDescriptor = classStore[property];
var sourceProperty = source[property];
var propertyType = propertyDescriptor.type;
if (sourceProperty !== undefined && sourceProperty !== null) {
switch (propertyType) {
case 0: // Value
case 6:// Mesh reference
destination[property] = sourceProperty;
break;
case 1:// Texture
destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
break;
case 2: // Color3
case 3: // FresnelParameters
case 4: // Vector2
case 5: // Vector3
case 7: // Color Curves
case 10:// Quaternion
destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
break;
}
}
}
return destination;
};
function getDirectStore(target) {
var classKey = target.getClassName();
if (!__decoratorInitialStore[classKey]) {
__decoratorInitialStore[classKey] = {};
}
return __decoratorInitialStore[classKey];
}
/**
* Return the list of properties flagged as serializable
* @param target: host object
*/
function getMergedStore(target) {
var classKey = target.getClassName();
if (__mergedStore[classKey]) {
return __mergedStore[classKey];
}
__mergedStore[classKey] = {};
var store = __mergedStore[classKey];
var currentTarget = target;
var currentKey = classKey;
while (currentKey) {
var initialStore = __decoratorInitialStore[currentKey];
for (var property in initialStore) {
store[property] = initialStore[property];
}
var parent_1 = void 0;
var done = false;
do {
parent_1 = Object.getPrototypeOf(currentTarget);
if (!parent_1.getClassName) {
done = true;
break;
}
if (parent_1.getClassName() !== currentKey) {
break;
}
currentTarget = parent_1;
} while (parent_1);
if (done) {
break;
}
currentKey = parent_1.getClassName();
currentTarget = parent_1;
}
return store;
}
function generateSerializableMember(type, sourceName) {
return function (target, propertyKey) {
var classStore = getDirectStore(target);
if (!classStore[propertyKey]) {
classStore[propertyKey] = { type: type, sourceName: sourceName };
}
};
}
function generateExpandMember(setCallback, targetKey) {
if (targetKey === void 0) { targetKey = null; }
return function (target, propertyKey) {
var key = targetKey || ("_" + propertyKey);
Object.defineProperty(target, propertyKey, {
get: function () {
return this[key];
},
set: function (value) {
if (this[key] === value) {
return;
}
this[key] = value;
target[setCallback].apply(this);
},
enumerable: true,
configurable: true
});
};
}
function expandToProperty(callback, targetKey) {
if (targetKey === void 0) { targetKey = null; }
return generateExpandMember(callback, targetKey);
}
BABYLON.expandToProperty = expandToProperty;
function serialize(sourceName) {
return generateSerializableMember(0, sourceName); // value member
}
BABYLON.serialize = serialize;
function serializeAsTexture(sourceName) {
return generateSerializableMember(1, sourceName); // texture member
}
BABYLON.serializeAsTexture = serializeAsTexture;
function serializeAsColor3(sourceName) {
return generateSerializableMember(2, sourceName); // color3 member
}
BABYLON.serializeAsColor3 = serializeAsColor3;
function serializeAsFresnelParameters(sourceName) {
return generateSerializableMember(3, sourceName); // fresnel parameters member
}
BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
function serializeAsVector2(sourceName) {
return generateSerializableMember(4, sourceName); // vector2 member
}
BABYLON.serializeAsVector2 = serializeAsVector2;
function serializeAsVector3(sourceName) {
return generateSerializableMember(5, sourceName); // vector3 member
}
BABYLON.serializeAsVector3 = serializeAsVector3;
function serializeAsMeshReference(sourceName) {
return generateSerializableMember(6, sourceName); // mesh reference member
}
BABYLON.serializeAsMeshReference = serializeAsMeshReference;
function serializeAsColorCurves(sourceName) {
return generateSerializableMember(7, sourceName); // color curves
}
BABYLON.serializeAsColorCurves = serializeAsColorCurves;
function serializeAsColor4(sourceName) {
return generateSerializableMember(8, sourceName); // color 4
}
BABYLON.serializeAsColor4 = serializeAsColor4;
function serializeAsImageProcessingConfiguration(sourceName) {
return generateSerializableMember(9, sourceName); // image processing
}
BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
function serializeAsQuaternion(sourceName) {
return generateSerializableMember(10, sourceName); // quaternion member
}
BABYLON.serializeAsQuaternion = serializeAsQuaternion;
var SerializationHelper = /** @class */ (function () {
function SerializationHelper() {
}
SerializationHelper.Serialize = function (entity, serializationObject) {
if (!serializationObject) {
serializationObject = {};
}
// Tags
if (BABYLON.Tags) {
serializationObject.tags = BABYLON.Tags.GetTags(entity);
}
var serializedProperties = getMergedStore(entity);
// Properties
for (var property in serializedProperties) {
var propertyDescriptor = serializedProperties[property];
var targetPropertyName = propertyDescriptor.sourceName || property;
var propertyType = propertyDescriptor.type;
var sourceProperty = entity[property];
if (sourceProperty !== undefined && sourceProperty !== null) {
switch (propertyType) {
case 0:// Value
serializationObject[targetPropertyName] = sourceProperty;
break;
case 1:// Texture
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
case 2:// Color3
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 3:// FresnelParameters
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
case 4:// Vector2
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 5:// Vector3
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 6:// Mesh reference
serializationObject[targetPropertyName] = sourceProperty.id;
break;
case 7:// Color Curves
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
case 8:// Color 4
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 9:// Image Processing
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
}
}
}
return serializationObject;
};
SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
if (rootUrl === void 0) { rootUrl = null; }
var destination = creationFunction();
if (!rootUrl) {
rootUrl = "";
}
// Tags
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(destination, source.tags);
}
var classStore = getMergedStore(destination);
// Properties
for (var property in classStore) {
var propertyDescriptor = classStore[property];
var sourceProperty = source[propertyDescriptor.sourceName || property];
var propertyType = propertyDescriptor.type;
if (sourceProperty !== undefined && sourceProperty !== null) {
var dest = destination;
switch (propertyType) {
case 0:// Value
dest[property] = sourceProperty;
break;
case 1:// Texture
if (scene) {
dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
}
break;
case 2:// Color3
dest[property] = BABYLON.Color3.FromArray(sourceProperty);
break;
case 3:// FresnelParameters
dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
break;
case 4:// Vector2
dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
break;
case 5:// Vector3
dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
break;
case 6:// Mesh reference
if (scene) {
dest[property] = scene.getLastMeshByID(sourceProperty);
}
break;
case 7:// Color Curves
dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
break;
case 8:// Color 4
dest[property] = BABYLON.Color4.FromArray(sourceProperty);
break;
case 9:// Image Processing
dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
break;
}
}
}
return destination;
};
SerializationHelper.Clone = function (creationFunction, source) {
return _copySource(creationFunction, source, false);
};
SerializationHelper.Instanciate = function (creationFunction, source) {
return _copySource(creationFunction, source, true);
};
return SerializationHelper;
}());
BABYLON.SerializationHelper = SerializationHelper;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.decorators.js.map
var BABYLON;
(function (BABYLON) {
/**
* A class serves as a medium between the observable and its observers
*/
var EventState = /** @class */ (function () {
/**
* If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
*/
function EventState(mask, skipNextObservers, target, currentTarget) {
if (skipNextObservers === void 0) { skipNextObservers = false; }
this.initalize(mask, skipNextObservers, target, currentTarget);
}
EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
if (skipNextObservers === void 0) { skipNextObservers = false; }
this.mask = mask;
this.skipNextObservers = skipNextObservers;
this.target = target;
this.currentTarget = currentTarget;
return this;
};
return EventState;
}());
BABYLON.EventState = EventState;
/**
* Represent an Observer registered to a given Observable object.
*/
var Observer = /** @class */ (function () {
function Observer(callback, mask, scope) {
if (scope === void 0) { scope = null; }
this.callback = callback;
this.mask = mask;
this.scope = scope;
}
return Observer;
}());
BABYLON.Observer = Observer;
/**
* Represent a list of observers registered to multiple Observables object.
*/
var MultiObserver = /** @class */ (function () {
function MultiObserver() {
}
MultiObserver.prototype.dispose = function () {
if (this._observers && this._observables) {
for (var index = 0; index < this._observers.length; index++) {
this._observables[index].remove(this._observers[index]);
}
}
this._observers = null;
this._observables = null;
};
MultiObserver.Watch = function (observables, callback, mask, scope) {
if (mask === void 0) { mask = -1; }
if (scope === void 0) { scope = null; }
var result = new MultiObserver();
result._observers = new Array();
result._observables = observables;
for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
var observable = observables_1[_i];
var observer = observable.add(callback, mask, false, scope);
if (observer) {
result._observers.push(observer);
}
}
return result;
};
return MultiObserver;
}());
BABYLON.MultiObserver = MultiObserver;
/**
* The Observable class is a simple implementation of the Observable pattern.
* There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
* This enable a more fine grained execution without having to rely on multiple different Observable objects.
* For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
* A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
*/
var Observable = /** @class */ (function () {
function Observable(onObserverAdded) {
this._observers = new Array();
this._eventState = new EventState(0);
if (onObserverAdded) {
this._onObserverAdded = onObserverAdded;
}
}
/**
* Create a new Observer with the specified callback
* @param callback the callback that will be executed for that Observer
* @param mask the mask used to filter observers
* @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
* @param scope optional scope for the callback to be called from
*/
Observable.prototype.add = function (callback, mask, insertFirst, scope) {
if (mask === void 0) { mask = -1; }
if (insertFirst === void 0) { insertFirst = false; }
if (scope === void 0) { scope = null; }
if (!callback) {
return null;
}
var observer = new Observer(callback, mask, scope);
if (insertFirst) {
this._observers.unshift(observer);
}
else {
this._observers.push(observer);
}
if (this._onObserverAdded) {
this._onObserverAdded(observer);
}
return observer;
};
/**
* Remove an Observer from the Observable object
* @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
*/
Observable.prototype.remove = function (observer) {
if (!observer) {
return false;
}
var index = this._observers.indexOf(observer);
if (index !== -1) {
this._observers.splice(index, 1);
return true;
}
return false;
};
/**
* Remove a callback from the Observable object
* @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
*/
Observable.prototype.removeCallback = function (callback) {
for (var index = 0; index < this._observers.length; index++) {
if (this._observers[index].callback === callback) {
this._observers.splice(index, 1);
return true;
}
}
return false;
};
/**
* Notify all Observers by calling their respective callback with the given data
* Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
* @param eventData
* @param mask
*/
Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
if (mask === void 0) { mask = -1; }
if (!this._observers.length) {
return true;
}
var state = this._eventState;
state.mask = mask;
state.target = target;
state.currentTarget = currentTarget;
state.skipNextObservers = false;
for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
var obs = _a[_i];
if (obs.mask & mask) {
if (obs.scope) {
obs.callback.apply(obs.scope, [eventData, state]);
}
else {
obs.callback(eventData, state);
}
}
if (state.skipNextObservers) {
return false;
}
}
return true;
};
/**
* Notify a specific observer
* @param eventData
* @param mask
*/
Observable.prototype.notifyObserver = function (observer, eventData, mask) {
if (mask === void 0) { mask = -1; }
var state = this._eventState;
state.mask = mask;
state.skipNextObservers = false;
observer.callback(eventData, state);
};
/**
* return true is the Observable has at least one Observer registered
*/
Observable.prototype.hasObservers = function () {
return this._observers.length > 0;
};
/**
* Clear the list of observers
*/
Observable.prototype.clear = function () {
this._observers = new Array();
this._onObserverAdded = null;
};
/**
* Clone the current observable
*/
Observable.prototype.clone = function () {
var result = new Observable();
result._observers = this._observers.slice(0);
return result;
};
/**
* Does this observable handles observer registered with a given mask
* @param {number} trigger - the mask to be tested
* @return {boolean} whether or not one observer registered with the given mask is handeled
**/
Observable.prototype.hasSpecificMask = function (mask) {
if (mask === void 0) { mask = -1; }
for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
var obs = _a[_i];
if (obs.mask & mask || obs.mask === mask) {
return true;
}
}
return false;
};
return Observable;
}());
BABYLON.Observable = Observable;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.observable.js.map
var BABYLON;
(function (BABYLON) {
var SmartArray = /** @class */ (function () {
function SmartArray(capacity) {
this.length = 0;
this.data = new Array(capacity);
this._id = SmartArray._GlobalId++;
}
SmartArray.prototype.push = function (value) {
this.data[this.length++] = value;
if (this.length > this.data.length) {
this.data.length *= 2;
}
};
SmartArray.prototype.forEach = function (func) {
for (var index = 0; index < this.length; index++) {
func(this.data[index]);
}
};
SmartArray.prototype.sort = function (compareFn) {
this.data.sort(compareFn);
};
SmartArray.prototype.reset = function () {
this.length = 0;
};
SmartArray.prototype.dispose = function () {
this.reset();
if (this.data) {
this.data.length = 0;
this.data = [];
}
};
SmartArray.prototype.concat = function (array) {
if (array.length === 0) {
return;
}
if (this.length + array.length > this.data.length) {
this.data.length = (this.length + array.length) * 2;
}
for (var index = 0; index < array.length; index++) {
this.data[this.length++] = (array.data || array)[index];
}
};
SmartArray.prototype.indexOf = function (value) {
var position = this.data.indexOf(value);
if (position >= this.length) {
return -1;
}
return position;
};
SmartArray.prototype.contains = function (value) {
return this.data.indexOf(value) !== -1;
};
// Statics
SmartArray._GlobalId = 0;
return SmartArray;
}());
BABYLON.SmartArray = SmartArray;
var SmartArrayNoDuplicate = /** @class */ (function (_super) {
__extends(SmartArrayNoDuplicate, _super);
function SmartArrayNoDuplicate() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._duplicateId = 0;
return _this;
}
SmartArrayNoDuplicate.prototype.push = function (value) {
_super.prototype.push.call(this, value);
if (!value.__smartArrayFlags) {
value.__smartArrayFlags = {};
}
value.__smartArrayFlags[this._id] = this._duplicateId;
};
SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
return false;
}
this.push(value);
return true;
};
SmartArrayNoDuplicate.prototype.reset = function () {
_super.prototype.reset.call(this);
this._duplicateId++;
};
SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
if (array.length === 0) {
return;
}
if (this.length + array.length > this.data.length) {
this.data.length = (this.length + array.length) * 2;
}
for (var index = 0; index < array.length; index++) {
var item = (array.data || array)[index];
this.pushNoDuplicate(item);
}
};
return SmartArrayNoDuplicate;
}(SmartArray));
BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.smartArray.js.map
var BABYLON;
(function (BABYLON) {
// See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
// and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
var LoadFileError = /** @class */ (function (_super) {
__extends(LoadFileError, _super);
function LoadFileError(message, request) {
var _this = _super.call(this, message) || this;
_this.request = request;
_this.name = "LoadFileError";
LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
return _this;
}
// Polyfill for Object.setPrototypeOf if necessary.
LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
return LoadFileError;
}(Error));
BABYLON.LoadFileError = LoadFileError;
var RetryStrategy = /** @class */ (function () {
function RetryStrategy() {
}
RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
if (maxRetries === void 0) { maxRetries = 3; }
if (baseInterval === void 0) { baseInterval = 500; }
return function (url, request, retryIndex) {
if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
return -1;
}
return Math.pow(2, retryIndex) * baseInterval;
};
};
return RetryStrategy;
}());
BABYLON.RetryStrategy = RetryStrategy;
// Screenshots
var screenshotCanvas;
var cloneValue = function (source, destinationObject) {
if (!source)
return null;
if (source instanceof BABYLON.Mesh) {
return null;
}
if (source instanceof BABYLON.SubMesh) {
return source.clone(destinationObject);
}
else if (source.clone) {
return source.clone();
}
return null;
};
var Tools = /** @class */ (function () {
function Tools() {
}
/**
* Interpolates between a and b via alpha
* @param a The lower value (returned when alpha = 0)
* @param b The upper value (returned when alpha = 1)
* @param alpha The interpolation-factor
* @return The mixed value
*/
Tools.Mix = function (a, b, alpha) {
return a * (1 - alpha) + b * alpha;
};
Tools.Instantiate = function (className) {
if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
return Tools.RegisteredExternalClasses[className];
}
var arr = className.split(".");
var fn = (window || this);
for (var i = 0, len = arr.length; i < len; i++) {
fn = fn[arr[i]];
}
if (typeof fn !== "function") {
return null;
}
return fn;
};
Tools.SetImmediate = function (action) {
if (window.setImmediate) {
window.setImmediate(action);
}
else {
setTimeout(action, 1);
}
};
Tools.IsExponentOfTwo = function (value) {
var count = 1;
do {
count *= 2;
} while (count < value);
return count === value;
};
/**
* Find the next highest power of two.
* @param x Number to start search from.
* @return Next highest power of two.
*/
Tools.CeilingPOT = function (x) {
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
};
/**
* Find the next lowest power of two.
* @param x Number to start search from.
* @return Next lowest power of two.
*/
Tools.FloorPOT = function (x) {
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
return x - (x >> 1);
};
/**
* Find the nearest power of two.
* @param x Number to start search from.
* @return Next nearest power of two.
*/
Tools.NearestPOT = function (x) {
var c = Tools.CeilingPOT(x);
var f = Tools.FloorPOT(x);
return (c - x) > (x - f) ? f : c;
};
Tools.GetExponentOfTwo = function (value, max, mode) {
if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
var pot;
switch (mode) {
case BABYLON.Engine.SCALEMODE_FLOOR:
pot = Tools.FloorPOT(value);
break;
case BABYLON.Engine.SCALEMODE_NEAREST:
pot = Tools.NearestPOT(value);
break;
case BABYLON.Engine.SCALEMODE_CEILING:
default:
pot = Tools.CeilingPOT(value);
break;
}
return Math.min(pot, max);
};
Tools.GetFilename = function (path) {
var index = path.lastIndexOf("/");
if (index < 0)
return path;
return path.substring(index + 1);
};
Tools.GetFolderPath = function (uri) {
var index = uri.lastIndexOf("/");
if (index < 0)
return "";
return uri.substring(0, index + 1);
};
Tools.GetDOMTextContent = function (element) {
var result = "";
var child = element.firstChild;
while (child) {
if (child.nodeType === 3) {
result += child.textContent;
}
child = child.nextSibling;
}
return result;
};
Tools.ToDegrees = function (angle) {
return angle * 180 / Math.PI;
};
Tools.ToRadians = function (angle) {
return angle * Math.PI / 180;
};
Tools.EncodeArrayBufferTobase64 = function (buffer) {
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
var bytes = new Uint8Array(buffer);
while (i < bytes.length) {
chr1 = bytes[i++];
chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
}
else if (isNaN(chr3)) {
enc4 = 64;
}
output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
keyStr.charAt(enc3) + keyStr.charAt(enc4);
}
return "data:image/png;base64," + output;
};
Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
if (bias === void 0) { bias = null; }
var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
for (var index = indexStart; index < indexStart + indexCount; index++) {
var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
minimum = BABYLON.Vector3.Minimize(current, minimum);
maximum = BABYLON.Vector3.Maximize(current, maximum);
}
if (bias) {
minimum.x -= minimum.x * bias.x + bias.y;
minimum.y -= minimum.y * bias.x + bias.y;
minimum.z -= minimum.z * bias.x + bias.y;
maximum.x += maximum.x * bias.x + bias.y;
maximum.y += maximum.y * bias.x + bias.y;
maximum.z += maximum.z * bias.x + bias.y;
}
return {
minimum: minimum,
maximum: maximum
};
};
Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
if (bias === void 0) { bias = null; }
var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
if (!stride) {
stride = 3;
}
for (var index = start; index < start + count; index++) {
var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
minimum = BABYLON.Vector3.Minimize(current, minimum);
maximum = BABYLON.Vector3.Maximize(current, maximum);
}
if (bias) {
minimum.x -= minimum.x * bias.x + bias.y;
minimum.y -= minimum.y * bias.x + bias.y;
minimum.z -= minimum.z * bias.x + bias.y;
maximum.x += maximum.x * bias.x + bias.y;
maximum.y += maximum.y * bias.x + bias.y;
maximum.z += maximum.z * bias.x + bias.y;
}
return {
minimum: minimum,
maximum: maximum
};
};
Tools.Vector2ArrayFeeder = function (array) {
return function (index) {
var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
var length = isFloatArray ? array.length / 2 : array.length;
if (index >= length) {
return null;
}
if (isFloatArray) {
var fa = array;
return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
}
var a = array;
return a[index];
};
};
Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
if (bias === void 0) { bias = null; }
var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
var i = 0;
var cur = feeder(i++);
while (cur) {
minimum = BABYLON.Vector2.Minimize(cur, minimum);
maximum = BABYLON.Vector2.Maximize(cur, maximum);
cur = feeder(i++);
}
if (bias) {
minimum.x -= minimum.x * bias.x + bias.y;
minimum.y -= minimum.y * bias.x + bias.y;
maximum.x += maximum.x * bias.x + bias.y;
maximum.y += maximum.y * bias.x + bias.y;
}
return {
minimum: minimum,
maximum: maximum
};
};
Tools.MakeArray = function (obj, allowsNullUndefined) {
if (allowsNullUndefined !== true && (obj === undefined || obj == null))
return null;
return Array.isArray(obj) ? obj : [obj];
};
// Misc.
Tools.GetPointerPrefix = function () {
var eventPrefix = "pointer";
// Check if pointer events are supported
if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
eventPrefix = "mouse";
}
return eventPrefix;
};
/**
* @param func - the function to be called
* @param requester - the object that will request the next frame. Falls back to window.
*/
Tools.QueueNewFrame = function (func, requester) {
if (!Tools.IsWindowObjectExist()) {
return setTimeout(func, 16);
}
if (!requester) {
requester = window;
}
if (requester.requestAnimationFrame) {
return requester.requestAnimationFrame(func);
}
else if (requester.msRequestAnimationFrame) {
return requester.msRequestAnimationFrame(func);
}
else if (requester.webkitRequestAnimationFrame) {
return requester.webkitRequestAnimationFrame(func);
}
else if (requester.mozRequestAnimationFrame) {
return requester.mozRequestAnimationFrame(func);
}
else if (requester.oRequestAnimationFrame) {
return requester.oRequestAnimationFrame(func);
}
else {
return window.setTimeout(func, 16);
}
};
Tools.RequestFullscreen = function (element) {
var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
if (!requestFunction)
return;
requestFunction.call(element);
};
Tools.ExitFullscreen = function () {
if (document.exitFullscreen) {
document.exitFullscreen();
}
else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
}
else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
else if (document.msCancelFullScreen) {
document.msCancelFullScreen();
}
};
Tools.SetCorsBehavior = function (url, element) {
if (url && url.indexOf("data:") === 0) {
return;
}
if (Tools.CorsBehavior) {
if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
element.crossOrigin = Tools.CorsBehavior;
}
else {
var result = Tools.CorsBehavior(url);
if (result) {
element.crossOrigin = result;
}
}
}
};
// External files
Tools.CleanUrl = function (url) {
url = url.replace(/#/mg, "%23");
return url;
};
Tools.LoadImage = function (url, onLoad, onError, database) {
if (url instanceof ArrayBuffer) {
url = Tools.EncodeArrayBufferTobase64(url);
}
url = Tools.CleanUrl(url);
url = Tools.PreprocessUrl(url);
var img = new Image();
Tools.SetCorsBehavior(url, img);
img.onload = function () {
onLoad(img);
};
img.onerror = function (err) {
Tools.Error("Error while trying to load image: " + url);
if (onError) {
onError("Error while trying to load image: " + url, err);
}
};
var noIndexedDB = function () {
img.src = url;
};
var loadFromIndexedDB = function () {
if (database) {
database.loadImageFromDB(url, img);
}
};
//ANY database to do!
if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
database.openAsync(loadFromIndexedDB, noIndexedDB);
}
else {
if (url.indexOf("file:") !== -1) {
var textureName = decodeURIComponent(url.substring(5).toLowerCase());
if (BABYLON.FilesInput.FilesToLoad[textureName]) {
try {
var blobURL;
try {
blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
}
catch (ex) {
// Chrome doesn't support oneTimeOnly parameter
blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
}
img.src = blobURL;
}
catch (e) {
img.src = "";
}
return img;
}
}
noIndexedDB();
}
return img;
};
Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError, onRetry, retryStrategy) {
if (retryStrategy === void 0) { retryStrategy = null; }
url = Tools.CleanUrl(url);
url = Tools.PreprocessUrl(url);
var request = null;
var noIndexedDB = function (retryIndex) {
var oldRequest = request;
request = new XMLHttpRequest();
var loadUrl = Tools.BaseUrl + url;
request.open('GET', loadUrl, true);
if (useArrayBuffer) {
request.responseType = "arraybuffer";
}
if (progressCallBack) {
request.onprogress = progressCallBack;
}
request.onreadystatechange = function () {
var req = request;
// In case of undefined state in some browsers.
if (req.readyState === (XMLHttpRequest.DONE || 4)) {
req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
callback(!useArrayBuffer ? req.responseText : req.response, req.responseURL);
return;
}
retryStrategy = retryStrategy || Tools.DefaultRetryStrategy;
if (retryStrategy) {
var waitTime = retryStrategy(loadUrl, req, retryIndex || 0);
if (waitTime !== -1) {
setTimeout(function () { return noIndexedDB((retryIndex || 0) + 1); }, waitTime);
return;
}
}
var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
if (onError) {
onError(req, e);
}
else {
throw e;
}
}
};
request.send();
if (oldRequest && onRetry) {
onRetry(oldRequest, request);
}
};
var loadFromIndexedDB = function () {
if (database) {
database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
}
};
// If file and file input are set
if (url.indexOf("file:") !== -1) {
var fileName = decodeURIComponent(url.substring(5).toLowerCase());
if (BABYLON.FilesInput.FilesToLoad[fileName]) {
Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
return request;
}
}
// Caching all files
if (database && database.enableSceneOffline) {
database.openAsync(loadFromIndexedDB, noIndexedDB);
}
else {
noIndexedDB();
}
return request;
};
/**
* Load a script (identified by an url). When the url returns, the
* content of this file is added into a new script element, attached to the DOM (body element)
*/
Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptUrl;
script.onload = function () {
if (onSuccess) {
onSuccess();
}
};
script.onerror = function (e) {
if (onError) {
onError("Unable to load script", e);
}
};
head.appendChild(script);
};
Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
var reader = new FileReader();
reader.onload = function (e) {
//target doesn't have result from ts 1.3
callback(e.target['result']);
};
reader.onprogress = progressCallback;
reader.readAsDataURL(fileToLoad);
};
Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
var reader = new FileReader();
reader.onerror = function (e) {
Tools.Log("Error while reading file: " + fileToLoad.name);
callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
};
reader.onload = function (e) {
//target doesn't have result from ts 1.3
callback(e.target['result']);
};
if (progressCallBack) {
reader.onprogress = progressCallBack;
}
if (!useArrayBuffer) {
// Asynchronous read
reader.readAsText(fileToLoad);
}
else {
reader.readAsArrayBuffer(fileToLoad);
}
};
//returns a downloadable url to a file content.
Tools.FileAsURL = function (content) {
var fileBlob = new Blob([content]);
var url = window.URL || window.webkitURL;
var link = url.createObjectURL(fileBlob);
return link;
};
// Misc.
Tools.Format = function (value, decimals) {
if (decimals === void 0) { decimals = 2; }
return value.toFixed(decimals);
};
Tools.CheckExtends = function (v, min, max) {
if (v.x < min.x)
min.x = v.x;
if (v.y < min.y)
min.y = v.y;
if (v.z < min.z)
min.z = v.z;
if (v.x > max.x)
max.x = v.x;
if (v.y > max.y)
max.y = v.y;
if (v.z > max.z)
max.z = v.z;
};
Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
for (var prop in source) {
if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
continue;
}
if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
continue;
}
var sourceValue = source[prop];
var typeOfSourceValue = typeof sourceValue;
if (typeOfSourceValue === "function") {
continue;
}
if (typeOfSourceValue === "object") {
if (sourceValue instanceof Array) {
destination[prop] = [];
if (sourceValue.length > 0) {
if (typeof sourceValue[0] == "object") {
for (var index = 0; index < sourceValue.length; index++) {
var clonedValue = cloneValue(sourceValue[index], destination);
if (destination[prop].indexOf(clonedValue) === -1) {
destination[prop].push(clonedValue);
}
}
}
else {
destination[prop] = sourceValue.slice(0);
}
}
}
else {
destination[prop] = cloneValue(sourceValue, destination);
}
}
else {
destination[prop] = sourceValue;
}
}
};
Tools.IsEmpty = function (obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
return false;
}
}
return true;
};
Tools.RegisterTopRootEvents = function (events) {
for (var index = 0; index < events.length; index++) {
var event = events[index];
window.addEventListener(event.name, event.handler, false);
try {
if (window.parent) {
window.parent.addEventListener(event.name, event.handler, false);
}
}
catch (e) {
// Silently fails...
}
}
};
Tools.UnregisterTopRootEvents = function (events) {
for (var index = 0; index < events.length; index++) {
var event = events[index];
window.removeEventListener(event.name, event.handler);
try {
if (window.parent) {
window.parent.removeEventListener(event.name, event.handler);
}
}
catch (e) {
// Silently fails...
}
}
};
Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
if (mimeType === void 0) { mimeType = "image/png"; }
// Read the contents of the framebuffer
var numberOfChannelsByLine = width * 4;
var halfHeight = height / 2;
//Reading datas from WebGL
var data = engine.readPixels(0, 0, width, height);
//To flip image on Y axis.
for (var i = 0; i < halfHeight; i++) {
for (var j = 0; j < numberOfChannelsByLine; j++) {
var currentCell = j + i * numberOfChannelsByLine;
var targetLine = height - i - 1;
var targetCell = j + targetLine * numberOfChannelsByLine;
var temp = data[currentCell];
data[currentCell] = data[targetCell];
data[targetCell] = temp;
}
}
// Create a 2D canvas to store the result
if (!screenshotCanvas) {
screenshotCanvas = document.createElement('canvas');
}
screenshotCanvas.width = width;
screenshotCanvas.height = height;
var context = screenshotCanvas.getContext('2d');
if (context) {
// Copy the pixels to a 2D canvas
var imageData = context.createImageData(width, height);
var castData = (imageData.data);
castData.set(data);
context.putImageData(imageData, 0, 0);
Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
}
};
Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
if (mimeType === void 0) { mimeType = "image/png"; }
var base64Image = screenshotCanvas.toDataURL(mimeType);
if (successCallback) {
successCallback(base64Image);
}
else {
// We need HTMLCanvasElement.toBlob for HD screenshots
if (!screenshotCanvas.toBlob) {
// low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
screenshotCanvas.toBlob = function (callback, type, quality) {
var _this = this;
setTimeout(function () {
var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
callback(new Blob([arr], { type: type || 'image/png' }));
});
};
}
screenshotCanvas.toBlob(function (blob) {
var url = URL.createObjectURL(blob);
//Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
if (("download" in document.createElement("a"))) {
var a = window.document.createElement("a");
a.href = url;
if (fileName) {
a.setAttribute("download", fileName);
}
else {
var date = new Date();
var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
a.setAttribute("download", "screenshot_" + stringDate + ".png");
}
window.document.body.appendChild(a);
a.addEventListener("click", function () {
if (a.parentElement) {
a.parentElement.removeChild(a);
}
});
a.click();
}
else {
var newWindow = window.open("");
if (!newWindow)
return;
var img = newWindow.document.createElement("img");
img.onload = function () {
// no longer need to read the blob so it's revoked
URL.revokeObjectURL(url);
};
img.src = url;
newWindow.document.body.appendChild(img);
}
});
}
};
Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
if (mimeType === void 0) { mimeType = "image/png"; }
var width;
var height;
// If a precision value is specified
if (size.precision) {
width = Math.round(engine.getRenderWidth() * size.precision);
height = Math.round(width / engine.getAspectRatio(camera));
}
else if (size.width && size.height) {
width = size.width;
height = size.height;
}
else if (size.width && !size.height) {
width = size.width;
height = Math.round(width / engine.getAspectRatio(camera));
}
else if (size.height && !size.width) {
height = size.height;
width = Math.round(height * engine.getAspectRatio(camera));
}
else if (!isNaN(size)) {
height = size;
width = size;
}
else {
Tools.Error("Invalid 'size' parameter !");
return;
}
if (!screenshotCanvas) {
screenshotCanvas = document.createElement('canvas');
}
screenshotCanvas.width = width;
screenshotCanvas.height = height;
var renderContext = screenshotCanvas.getContext("2d");
var ratio = engine.getRenderWidth() / engine.getRenderHeight();
var newWidth = width;
var newHeight = newWidth / ratio;
if (newHeight > height) {
newHeight = height;
newWidth = newHeight * ratio;
}
var offsetX = Math.max(0, width - newWidth) / 2;
var offsetY = Math.max(0, height - newHeight) / 2;
var renderingCanvas = engine.getRenderingCanvas();
if (renderContext && renderingCanvas) {
renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
}
Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
};
Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
if (mimeType === void 0) { mimeType = "image/png"; }
if (samples === void 0) { samples = 1; }
if (antialiasing === void 0) { antialiasing = false; }
var width;
var height;
//If a precision value is specified
if (size.precision) {
width = Math.round(engine.getRenderWidth() * size.precision);
height = Math.round(width / engine.getAspectRatio(camera));
size = { width: width, height: height };
}
else if (size.width && size.height) {
width = size.width;
height = size.height;
}
else if (size.width && !size.height) {
width = size.width;
height = Math.round(width / engine.getAspectRatio(camera));
size = { width: width, height: height };
}
else if (size.height && !size.width) {
height = size.height;
width = Math.round(height * engine.getAspectRatio(camera));
size = { width: width, height: height };
}
else if (!isNaN(size)) {
height = size;
width = size;
}
else {
Tools.Error("Invalid 'size' parameter !");
return;
}
var scene = camera.getScene();
var previousCamera = null;
if (scene.activeCamera !== camera) {
previousCamera = scene.activeCamera;
scene.activeCamera = camera;
}
//At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
texture.renderList = null;
texture.samples = samples;
if (antialiasing) {
texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
}
texture.onAfterRenderObservable.add(function () {
Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
});
scene.incrementRenderId();
scene.resetCachedMaterial();
texture.render(true);
texture.dispose();
if (previousCamera) {
scene.activeCamera = previousCamera;
}
camera.getProjectionMatrix(true); // Force cache refresh;
};
// XHR response validator for local file scenario
Tools.ValidateXHRData = function (xhr, dataType) {
// 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
if (dataType === void 0) { dataType = 7; }
try {
if (dataType & 1) {
if (xhr.responseText && xhr.responseText.length > 0) {
return true;
}
else if (dataType === 1) {
return false;
}
}
if (dataType & 2) {
// Check header width and height since there is no "TGA" magic number
var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
return true;
}
else if (dataType === 2) {
return false;
}
}
if (dataType & 4) {
// Check for the "DDS" magic number
var ddsHeader = new Uint8Array(xhr.response, 0, 3);
if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
return true;
}
else {
return false;
}
}
}
catch (e) {
// Global protection
}
return false;
};
/**
* Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
* Be aware Math.random() could cause collisions, but:
* "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
*/
Tools.RandomId = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
Object.defineProperty(Tools, "NoneLogLevel", {
get: function () {
return Tools._NoneLogLevel;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tools, "MessageLogLevel", {
get: function () {
return Tools._MessageLogLevel;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tools, "WarningLogLevel", {
get: function () {
return Tools._WarningLogLevel;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tools, "ErrorLogLevel", {
get: function () {
return Tools._ErrorLogLevel;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tools, "AllLogLevel", {
get: function () {
return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
},
enumerable: true,
configurable: true
});
Tools._AddLogEntry = function (entry) {
Tools._LogCache = entry + Tools._LogCache;
if (Tools.OnNewCacheEntry) {
Tools.OnNewCacheEntry(entry);
}
};
Tools._FormatMessage = function (message) {
var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
var date = new Date();
return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
};
Tools._LogDisabled = function (message) {
// nothing to do
};
Tools._LogEnabled = function (message) {
var formattedMessage = Tools._FormatMessage(message);
console.log("BJS - " + formattedMessage);
var entry = "
" + formattedMessage + "
";
Tools._AddLogEntry(entry);
};
Tools._WarnDisabled = function (message) {
// nothing to do
};
Tools._WarnEnabled = function (message) {
var formattedMessage = Tools._FormatMessage(message);
console.warn("BJS - " + formattedMessage);
var entry = "
" + formattedMessage + "
";
Tools._AddLogEntry(entry);
};
Tools._ErrorDisabled = function (message) {
// nothing to do
};
Tools._ErrorEnabled = function (message) {
Tools.errorsCount++;
var formattedMessage = Tools._FormatMessage(message);
console.error("BJS - " + formattedMessage);
var entry = "
" + formattedMessage + "
";
Tools._AddLogEntry(entry);
};
Object.defineProperty(Tools, "LogCache", {
get: function () {
return Tools._LogCache;
},
enumerable: true,
configurable: true
});
Tools.ClearLogCache = function () {
Tools._LogCache = "";
Tools.errorsCount = 0;
};
Object.defineProperty(Tools, "LogLevels", {
set: function (level) {
if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
Tools.Log = Tools._LogEnabled;
}
else {
Tools.Log = Tools._LogDisabled;
}
if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
Tools.Warn = Tools._WarnEnabled;
}
else {
Tools.Warn = Tools._WarnDisabled;
}
if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
Tools.Error = Tools._ErrorEnabled;
}
else {
Tools.Error = Tools._ErrorDisabled;
}
},
enumerable: true,
configurable: true
});
Tools.IsWindowObjectExist = function () {
return (typeof window) !== "undefined";
};
Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
get: function () {
return Tools._PerformanceNoneLogLevel;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
get: function () {
return Tools._PerformanceUserMarkLogLevel;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
get: function () {
return Tools._PerformanceConsoleLogLevel;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tools, "PerformanceLogLevel", {
set: function (level) {
if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
Tools.StartPerformanceCounter = Tools._StartUserMark;
Tools.EndPerformanceCounter = Tools._EndUserMark;
return;
}
if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
return;
}
Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
},
enumerable: true,
configurable: true
});
Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
};
Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
};
Tools._StartUserMark = function (counterName, condition) {
if (condition === void 0) { condition = true; }
if (!Tools._performance) {
if (!Tools.IsWindowObjectExist()) {
return;
}
Tools._performance = window.performance;
}
if (!condition || !Tools._performance.mark) {
return;
}
Tools._performance.mark(counterName + "-Begin");
};
Tools._EndUserMark = function (counterName, condition) {
if (condition === void 0) { condition = true; }
if (!condition || !Tools._performance.mark) {
return;
}
Tools._performance.mark(counterName + "-End");
Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
};
Tools._StartPerformanceConsole = function (counterName, condition) {
if (condition === void 0) { condition = true; }
if (!condition) {
return;
}
Tools._StartUserMark(counterName, condition);
if (console.time) {
console.time(counterName);
}
};
Tools._EndPerformanceConsole = function (counterName, condition) {
if (condition === void 0) { condition = true; }
if (!condition) {
return;
}
Tools._EndUserMark(counterName, condition);
if (console.time) {
console.timeEnd(counterName);
}
};
Object.defineProperty(Tools, "Now", {
get: function () {
if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
return window.performance.now();
}
return new Date().getTime();
},
enumerable: true,
configurable: true
});
/**
* This method will return the name of the class used to create the instance of the given object.
* It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
* @param object the object to get the class name from
* @return the name of the class, will be "object" for a custom data type not using the @className decorator
*/
Tools.GetClassName = function (object, isType) {
if (isType === void 0) { isType = false; }
var name = null;
if (!isType && object.getClassName) {
name = object.getClassName();
}
else {
if (object instanceof Object) {
var classObj = isType ? object : Object.getPrototypeOf(object);
name = classObj.constructor["__bjsclassName__"];
}
if (!name) {
name = typeof object;
}
}
return name;
};
Tools.First = function (array, predicate) {
for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
var el = array_1[_i];
if (predicate(el)) {
return el;
}
}
return null;
};
/**
* This method will return the name of the full name of the class, including its owning module (if any).
* It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
* @param object the object to get the class name from
* @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
*/
Tools.getFullClassName = function (object, isType) {
if (isType === void 0) { isType = false; }
var className = null;
var moduleName = null;
if (!isType && object.getClassName) {
className = object.getClassName();
}
else {
if (object instanceof Object) {
var classObj = isType ? object : Object.getPrototypeOf(object);
className = classObj.constructor["__bjsclassName__"];
moduleName = classObj.constructor["__bjsmoduleName__"];
}
if (!className) {
className = typeof object;
}
}
if (!className) {
return null;
}
return ((moduleName != null) ? (moduleName + ".") : "") + className;
};
/**
* This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
* @param array
*/
Tools.arrayOrStringFeeder = function (array) {
return function (index) {
if (index >= array.length) {
return null;
}
var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
if (val && val.getHashCode) {
val = val.getHashCode();
}
if (typeof val === "string") {
return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
}
return val;
};
};
/**
* Compute the hashCode of a stream of number
* To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
* @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
* @return the hash code computed
*/
Tools.hashCodeFromStream = function (feeder) {
// Based from here: http://stackoverflow.com/a/7616484/802124
var hash = 0;
var index = 0;
var chr = feeder(index++);
while (chr != null) {
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
chr = feeder(index++);
}
return hash;
};
Tools.BaseUrl = "";
Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
/**
* Default behaviour for cors in the application.
* It can be a string if the expected behavior is identical in the entire app.
* Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
*/
Tools.CorsBehavior = "anonymous";
Tools.UseFallbackTexture = true;
/**
* Use this object to register external classes like custom textures or material
* to allow the laoders to instantiate them
*/
Tools.RegisteredExternalClasses = {};
// Used in case of a texture loading problem
Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
Tools.PreprocessUrl = function (url) {
return url;
};
// Logs
Tools._NoneLogLevel = 0;
Tools._MessageLogLevel = 1;
Tools._WarningLogLevel = 2;
Tools._ErrorLogLevel = 4;
Tools._LogCache = "";
Tools.errorsCount = 0;
Tools.Log = Tools._LogEnabled;
Tools.Warn = Tools._WarnEnabled;
Tools.Error = Tools._ErrorEnabled;
// Performances
Tools._PerformanceNoneLogLevel = 0;
Tools._PerformanceUserMarkLogLevel = 1;
Tools._PerformanceConsoleLogLevel = 2;
Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
return Tools;
}());
BABYLON.Tools = Tools;
/**
* This class is used to track a performance counter which is number based.
* The user has access to many properties which give statistics of different nature
*
* The implementer can track two kinds of Performance Counter: time and count
* For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
* For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
*/
var PerfCounter = /** @class */ (function () {
function PerfCounter() {
this._startMonitoringTime = 0;
this._min = 0;
this._max = 0;
this._average = 0;
this._lastSecAverage = 0;
this._current = 0;
this._totalValueCount = 0;
this._totalAccumulated = 0;
this._lastSecAccumulated = 0;
this._lastSecTime = 0;
this._lastSecValueCount = 0;
}
Object.defineProperty(PerfCounter.prototype, "min", {
/**
* Returns the smallest value ever
*/
get: function () {
return this._min;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter.prototype, "max", {
/**
* Returns the biggest value ever
*/
get: function () {
return this._max;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter.prototype, "average", {
/**
* Returns the average value since the performance counter is running
*/
get: function () {
return this._average;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
/**
* Returns the average value of the last second the counter was monitored
*/
get: function () {
return this._lastSecAverage;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter.prototype, "current", {
/**
* Returns the current value
*/
get: function () {
return this._current;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter.prototype, "total", {
get: function () {
return this._totalAccumulated;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter.prototype, "count", {
get: function () {
return this._totalValueCount;
},
enumerable: true,
configurable: true
});
/**
* Call this method to start monitoring a new frame.
* This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
*/
PerfCounter.prototype.fetchNewFrame = function () {
this._totalValueCount++;
this._current = 0;
this._lastSecValueCount++;
};
/**
* Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
* @param newCount the count value to add to the monitored count
* @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
*/
PerfCounter.prototype.addCount = function (newCount, fetchResult) {
if (!PerfCounter.Enabled) {
return;
}
this._current += newCount;
if (fetchResult) {
this._fetchResult();
}
};
/**
* Start monitoring this performance counter
*/
PerfCounter.prototype.beginMonitoring = function () {
if (!PerfCounter.Enabled) {
return;
}
this._startMonitoringTime = Tools.Now;
};
/**
* Compute the time lapsed since the previous beginMonitoring() call.
* @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
*/
PerfCounter.prototype.endMonitoring = function (newFrame) {
if (newFrame === void 0) { newFrame = true; }
if (!PerfCounter.Enabled) {
return;
}
if (newFrame) {
this.fetchNewFrame();
}
var currentTime = Tools.Now;
this._current = currentTime - this._startMonitoringTime;
if (newFrame) {
this._fetchResult();
}
};
PerfCounter.prototype._fetchResult = function () {
this._totalAccumulated += this._current;
this._lastSecAccumulated += this._current;
// Min/Max update
this._min = Math.min(this._min, this._current);
this._max = Math.max(this._max, this._current);
this._average = this._totalAccumulated / this._totalValueCount;
// Reset last sec?
var now = Tools.Now;
if ((now - this._lastSecTime) > 1000) {
this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
this._lastSecTime = now;
this._lastSecAccumulated = 0;
this._lastSecValueCount = 0;
}
};
PerfCounter.Enabled = true;
return PerfCounter;
}());
BABYLON.PerfCounter = PerfCounter;
/**
* Use this className as a decorator on a given class definition to add it a name and optionally its module.
* You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
* This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
* @param name The name of the class, case should be preserved
* @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
*/
function className(name, module) {
return function (target) {
target["__bjsclassName__"] = name;
target["__bjsmoduleName__"] = (module != null) ? module : null;
};
}
BABYLON.className = className;
/**
* An implementation of a loop for asynchronous functions.
*/
var AsyncLoop = /** @class */ (function () {
/**
* Constroctor.
* @param iterations the number of iterations.
* @param _fn the function to run each iteration
* @param _successCallback the callback that will be called upon succesful execution
* @param offset starting offset.
*/
function AsyncLoop(iterations, _fn, _successCallback, offset) {
if (offset === void 0) { offset = 0; }
this.iterations = iterations;
this._fn = _fn;
this._successCallback = _successCallback;
this.index = offset - 1;
this._done = false;
}
/**
* Execute the next iteration. Must be called after the last iteration was finished.
*/
AsyncLoop.prototype.executeNext = function () {
if (!this._done) {
if (this.index + 1 < this.iterations) {
++this.index;
this._fn(this);
}
else {
this.breakLoop();
}
}
};
/**
* Break the loop and run the success callback.
*/
AsyncLoop.prototype.breakLoop = function () {
this._done = true;
this._successCallback();
};
/**
* Helper function
*/
AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
if (offset === void 0) { offset = 0; }
var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
loop.executeNext();
return loop;
};
/**
* A for-loop that will run a given number of iterations synchronous and the rest async.
* @param iterations total number of iterations
* @param syncedIterations number of synchronous iterations in each async iteration.
* @param fn the function to call each iteration.
* @param callback a success call back that will be called when iterating stops.
* @param breakFunction a break condition (optional)
* @param timeout timeout settings for the setTimeout function. default - 0.
* @constructor
*/
AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
if (timeout === void 0) { timeout = 0; }
AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
if (breakFunction && breakFunction())
loop.breakLoop();
else {
setTimeout(function () {
for (var i = 0; i < syncedIterations; ++i) {
var iteration = (loop.index * syncedIterations) + i;
if (iteration >= iterations)
break;
fn(iteration);
if (breakFunction && breakFunction()) {
loop.breakLoop();
break;
}
}
loop.executeNext();
}, timeout);
}
}, callback);
};
return AsyncLoop;
}());
BABYLON.AsyncLoop = AsyncLoop;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.tools.js.map
var BABYLON;
(function (BABYLON) {
var Internals;
(function (Internals) {
var _AlphaState = /** @class */ (function () {
/**
* Initializes the state.
*/
function _AlphaState() {
this._isAlphaBlendDirty = false;
this._isBlendFunctionParametersDirty = false;
this._isBlendEquationParametersDirty = false;
this._isBlendConstantsDirty = false;
this._alphaBlend = false;
this._blendFunctionParameters = new Array(4);
this._blendEquationParameters = new Array(2);
this._blendConstants = new Array(4);
this.reset();
}
Object.defineProperty(_AlphaState.prototype, "isDirty", {
get: function () {
return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
get: function () {
return this._alphaBlend;
},
set: function (value) {
if (this._alphaBlend === value) {
return;
}
this._alphaBlend = value;
this._isAlphaBlendDirty = true;
},
enumerable: true,
configurable: true
});
_AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
if (this._blendConstants[0] === r &&
this._blendConstants[1] === g &&
this._blendConstants[2] === b &&
this._blendConstants[3] === a) {
return;
}
this._blendConstants[0] = r;
this._blendConstants[1] = g;
this._blendConstants[2] = b;
this._blendConstants[3] = a;
this._isBlendConstantsDirty = true;
};
_AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
if (this._blendFunctionParameters[0] === value0 &&
this._blendFunctionParameters[1] === value1 &&
this._blendFunctionParameters[2] === value2 &&
this._blendFunctionParameters[3] === value3) {
return;
}
this._blendFunctionParameters[0] = value0;
this._blendFunctionParameters[1] = value1;
this._blendFunctionParameters[2] = value2;
this._blendFunctionParameters[3] = value3;
this._isBlendFunctionParametersDirty = true;
};
_AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
if (this._blendEquationParameters[0] === rgb &&
this._blendEquationParameters[1] === alpha) {
return;
}
this._blendEquationParameters[0] = rgb;
this._blendEquationParameters[1] = alpha;
this._isBlendEquationParametersDirty = true;
};
_AlphaState.prototype.reset = function () {
this._alphaBlend = false;
this._blendFunctionParameters[0] = null;
this._blendFunctionParameters[1] = null;
this._blendFunctionParameters[2] = null;
this._blendFunctionParameters[3] = null;
this._blendEquationParameters[0] = null;
this._blendEquationParameters[1] = null;
this._blendConstants[0] = null;
this._blendConstants[1] = null;
this._blendConstants[2] = null;
this._blendConstants[3] = null;
this._isAlphaBlendDirty = true;
this._isBlendFunctionParametersDirty = false;
this._isBlendEquationParametersDirty = false;
this._isBlendConstantsDirty = false;
};
_AlphaState.prototype.apply = function (gl) {
if (!this.isDirty) {
return;
}
// Alpha blend
if (this._isAlphaBlendDirty) {
if (this._alphaBlend) {
gl.enable(gl.BLEND);
}
else {
gl.disable(gl.BLEND);
}
this._isAlphaBlendDirty = false;
}
// Alpha function
if (this._isBlendFunctionParametersDirty) {
gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
this._isBlendFunctionParametersDirty = false;
}
// Alpha equation
if (this._isBlendEquationParametersDirty) {
gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
this._isBlendEquationParametersDirty = false;
}
// Constants
if (this._isBlendConstantsDirty) {
gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
this._isBlendConstantsDirty = false;
}
};
return _AlphaState;
}());
Internals._AlphaState = _AlphaState;
})(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.alphaCullingState.js.map
var BABYLON;
(function (BABYLON) {
var Internals;
(function (Internals) {
var _DepthCullingState = /** @class */ (function () {
/**
* Initializes the state.
*/
function _DepthCullingState() {
this._isDepthTestDirty = false;
this._isDepthMaskDirty = false;
this._isDepthFuncDirty = false;
this._isCullFaceDirty = false;
this._isCullDirty = false;
this._isZOffsetDirty = false;
this.reset();
}
Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
get: function () {
return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
get: function () {
return this._zOffset;
},
set: function (value) {
if (this._zOffset === value) {
return;
}
this._zOffset = value;
this._isZOffsetDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
get: function () {
return this._cullFace;
},
set: function (value) {
if (this._cullFace === value) {
return;
}
this._cullFace = value;
this._isCullFaceDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState.prototype, "cull", {
get: function () {
return this._cull;
},
set: function (value) {
if (this._cull === value) {
return;
}
this._cull = value;
this._isCullDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
get: function () {
return this._depthFunc;
},
set: function (value) {
if (this._depthFunc === value) {
return;
}
this._depthFunc = value;
this._isDepthFuncDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
get: function () {
return this._depthMask;
},
set: function (value) {
if (this._depthMask === value) {
return;
}
this._depthMask = value;
this._isDepthMaskDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
get: function () {
return this._depthTest;
},
set: function (value) {
if (this._depthTest === value) {
return;
}
this._depthTest = value;
this._isDepthTestDirty = true;
},
enumerable: true,
configurable: true
});
_DepthCullingState.prototype.reset = function () {
this._depthMask = true;
this._depthTest = true;
this._depthFunc = null;
this._cullFace = null;
this._cull = null;
this._zOffset = 0;
this._isDepthTestDirty = true;
this._isDepthMaskDirty = true;
this._isDepthFuncDirty = false;
this._isCullFaceDirty = false;
this._isCullDirty = false;
this._isZOffsetDirty = false;
};
_DepthCullingState.prototype.apply = function (gl) {
if (!this.isDirty) {
return;
}
// Cull
if (this._isCullDirty) {
if (this.cull) {
gl.enable(gl.CULL_FACE);
}
else {
gl.disable(gl.CULL_FACE);
}
this._isCullDirty = false;
}
// Cull face
if (this._isCullFaceDirty) {
gl.cullFace(this.cullFace);
this._isCullFaceDirty = false;
}
// Depth mask
if (this._isDepthMaskDirty) {
gl.depthMask(this.depthMask);
this._isDepthMaskDirty = false;
}
// Depth test
if (this._isDepthTestDirty) {
if (this.depthTest) {
gl.enable(gl.DEPTH_TEST);
}
else {
gl.disable(gl.DEPTH_TEST);
}
this._isDepthTestDirty = false;
}
// Depth func
if (this._isDepthFuncDirty) {
gl.depthFunc(this.depthFunc);
this._isDepthFuncDirty = false;
}
// zOffset
if (this._isZOffsetDirty) {
if (this.zOffset) {
gl.enable(gl.POLYGON_OFFSET_FILL);
gl.polygonOffset(this.zOffset, 0);
}
else {
gl.disable(gl.POLYGON_OFFSET_FILL);
}
this._isZOffsetDirty = false;
}
};
return _DepthCullingState;
}());
Internals._DepthCullingState = _DepthCullingState;
})(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.depthCullingState.js.map
var BABYLON;
(function (BABYLON) {
var Internals;
(function (Internals) {
var _StencilState = /** @class */ (function () {
function _StencilState() {
this._isStencilTestDirty = false;
this._isStencilMaskDirty = false;
this._isStencilFuncDirty = false;
this._isStencilOpDirty = false;
this.reset();
}
Object.defineProperty(_StencilState.prototype, "isDirty", {
get: function () {
return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState.prototype, "stencilFunc", {
get: function () {
return this._stencilFunc;
},
set: function (value) {
if (this._stencilFunc === value) {
return;
}
this._stencilFunc = value;
this._isStencilFuncDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
get: function () {
return this._stencilFuncRef;
},
set: function (value) {
if (this._stencilFuncRef === value) {
return;
}
this._stencilFuncRef = value;
this._isStencilFuncDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
get: function () {
return this._stencilFuncMask;
},
set: function (value) {
if (this._stencilFuncMask === value) {
return;
}
this._stencilFuncMask = value;
this._isStencilFuncDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
get: function () {
return this._stencilOpStencilFail;
},
set: function (value) {
if (this._stencilOpStencilFail === value) {
return;
}
this._stencilOpStencilFail = value;
this._isStencilOpDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
get: function () {
return this._stencilOpDepthFail;
},
set: function (value) {
if (this._stencilOpDepthFail === value) {
return;
}
this._stencilOpDepthFail = value;
this._isStencilOpDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
get: function () {
return this._stencilOpStencilDepthPass;
},
set: function (value) {
if (this._stencilOpStencilDepthPass === value) {
return;
}
this._stencilOpStencilDepthPass = value;
this._isStencilOpDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState.prototype, "stencilMask", {
get: function () {
return this._stencilMask;
},
set: function (value) {
if (this._stencilMask === value) {
return;
}
this._stencilMask = value;
this._isStencilMaskDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState.prototype, "stencilTest", {
get: function () {
return this._stencilTest;
},
set: function (value) {
if (this._stencilTest === value) {
return;
}
this._stencilTest = value;
this._isStencilTestDirty = true;
},
enumerable: true,
configurable: true
});
_StencilState.prototype.reset = function () {
this._stencilTest = false;
this._stencilMask = 0xFF;
this._stencilFunc = BABYLON.Engine.ALWAYS;
this._stencilFuncRef = 1;
this._stencilFuncMask = 0xFF;
this._stencilOpStencilFail = BABYLON.Engine.KEEP;
this._stencilOpDepthFail = BABYLON.Engine.KEEP;
this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
this._isStencilTestDirty = true;
this._isStencilMaskDirty = true;
this._isStencilFuncDirty = true;
this._isStencilOpDirty = true;
};
_StencilState.prototype.apply = function (gl) {
if (!this.isDirty) {
return;
}
// Stencil test
if (this._isStencilTestDirty) {
if (this.stencilTest) {
gl.enable(gl.STENCIL_TEST);
}
else {
gl.disable(gl.STENCIL_TEST);
}
this._isStencilTestDirty = false;
}
// Stencil mask
if (this._isStencilMaskDirty) {
gl.stencilMask(this.stencilMask);
this._isStencilMaskDirty = false;
}
// Stencil func
if (this._isStencilFuncDirty) {
gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
this._isStencilFuncDirty = false;
}
// Stencil op
if (this._isStencilOpDirty) {
gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
this._isStencilOpDirty = false;
}
};
return _StencilState;
}());
Internals._StencilState = _StencilState;
})(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.stencilState.js.map
var BABYLON;
(function (BABYLON) {
var compileShader = function (gl, source, type, defines, shaderVersion) {
return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
};
var compileRawShader = function (gl, source, type) {
var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
var log = gl.getShaderInfoLog(shader);
if (log) {
throw new Error(log);
}
}
if (!shader) {
throw new Error("Something went wrong while compile the shader.");
}
return shader;
};
var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
var magFilter = gl.NEAREST;
var minFilter = gl.NEAREST;
switch (samplingMode) {
case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_NEAREST;
}
else {
minFilter = gl.LINEAR;
}
break;
case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_LINEAR;
}
else {
minFilter = gl.LINEAR;
}
break;
case BABYLON.Texture.NEAREST_SAMPLINGMODE:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_LINEAR;
}
else {
minFilter = gl.NEAREST;
}
break;
case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_NEAREST;
}
else {
minFilter = gl.NEAREST;
}
break;
case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_NEAREST;
}
else {
minFilter = gl.LINEAR;
}
break;
case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_LINEAR;
}
else {
minFilter = gl.LINEAR;
}
break;
case BABYLON.Texture.NEAREST_LINEAR:
magFilter = gl.NEAREST;
minFilter = gl.LINEAR;
break;
case BABYLON.Texture.NEAREST_NEAREST:
magFilter = gl.NEAREST;
minFilter = gl.NEAREST;
break;
case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_NEAREST;
}
else {
minFilter = gl.NEAREST;
}
break;
case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_LINEAR;
}
else {
minFilter = gl.NEAREST;
}
break;
case BABYLON.Texture.LINEAR_LINEAR:
magFilter = gl.LINEAR;
minFilter = gl.LINEAR;
break;
case BABYLON.Texture.LINEAR_NEAREST:
magFilter = gl.LINEAR;
minFilter = gl.NEAREST;
break;
}
return {
min: minFilter,
mag: magFilter
};
};
var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
if (onErrorCallBack === void 0) { onErrorCallBack = null; }
var img;
var onload = function () {
loadedImages[index] = img;
loadedImages._internalCount++;
if (scene) {
scene._removePendingData(img);
}
if (loadedImages._internalCount === 6) {
onfinish(loadedImages);
}
};
var onerror = function (message, exception) {
if (scene) {
scene._removePendingData(img);
}
if (onErrorCallBack) {
onErrorCallBack(message, exception);
}
};
img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
if (scene) {
scene._addPendingData(img);
}
};
var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
if (onError === void 0) { onError = null; }
var loadedImages = [];
loadedImages._internalCount = 0;
for (var index = 0; index < 6; index++) {
partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
}
};
var partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
if (onErrorCallBack === void 0) { onErrorCallBack = null; }
var onload = function (data) {
loadedFiles[index] = data;
loadedFiles._internalCount++;
if (loadedFiles._internalCount === 6) {
onfinish(loadedFiles);
}
};
var onerror = function (request, exception) {
if (onErrorCallBack && request) {
onErrorCallBack(request.status + " " + request.statusText, exception);
}
};
BABYLON.Tools.LoadFile(url, onload, undefined, undefined, true, onerror);
};
var cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
if (onError === void 0) { onError = null; }
var loadedFiles = [];
loadedFiles._internalCount = 0;
for (var index = 0; index < 6; index++) {
partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
}
};
var BufferPointer = /** @class */ (function () {
function BufferPointer() {
}
return BufferPointer;
}());
var InstancingAttributeInfo = /** @class */ (function () {
function InstancingAttributeInfo() {
}
return InstancingAttributeInfo;
}());
BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
/**
* Define options used to create a render target texture
*/
var RenderTargetCreationOptions = /** @class */ (function () {
function RenderTargetCreationOptions() {
}
return RenderTargetCreationOptions;
}());
BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
/**
* Regroup several parameters relative to the browser in use
*/
var EngineCapabilities = /** @class */ (function () {
function EngineCapabilities() {
}
return EngineCapabilities;
}());
BABYLON.EngineCapabilities = EngineCapabilities;
/**
* The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
*/
var Engine = /** @class */ (function () {
/**
* @constructor
* @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
* @param {boolean} [antialias] - enable antialias
* @param options - further options to be sent to the getContext function
*/
function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
var _this = this;
// Public members
this.forcePOTTextures = false;
this.isFullscreen = false;
this.isPointerLock = false;
this.cullBackFaces = true;
this.renderEvenInBackground = true;
this.preventCacheWipeBetweenFrames = false;
// To enable/disable IDB support and avoid XHR on .manifest
this.enableOfflineSupport = false;
this.scenes = new Array();
this.postProcesses = new Array();
// Observables
/**
* Observable event triggered each time the rendering canvas is resized
*/
this.onResizeObservable = new BABYLON.Observable();
/**
* Observable event triggered each time the canvas loses focus
*/
this.onCanvasBlurObservable = new BABYLON.Observable();
/**
* Observable event triggered each time the canvas gains focus
*/
this.onCanvasFocusObservable = new BABYLON.Observable();
/**
* Observable event triggered each time the canvas receives pointerout event
*/
this.onCanvasPointerOutObservable = new BABYLON.Observable();
/**
* Observable event triggered before each texture is initialized
*/
this.onBeforeTextureInitObservable = new BABYLON.Observable();
//WebVR
this._vrDisplay = undefined;
this._vrSupported = false;
this._vrExclusivePointerMode = false;
// Uniform buffers list
this.disableUniformBuffers = false;
this._uniformBuffers = new Array();
// Observables
/**
* Observable raised when the engine begins a new frame
*/
this.onBeginFrameObservable = new BABYLON.Observable();
/**
* Observable raised when the engine ends the current frame
*/
this.onEndFrameObservable = new BABYLON.Observable();
/**
* Observable raised when the engine is about to compile a shader
*/
this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
/**
* Observable raised when the engine has jsut compiled a shader
*/
this.onAfterShaderCompilationObservable = new BABYLON.Observable();
this._windowIsBackground = false;
this._webGLVersion = 1.0;
this._badOS = false;
this._badDesktopOS = false;
this.onVRDisplayChangedObservable = new BABYLON.Observable();
this.onVRRequestPresentComplete = new BABYLON.Observable();
this.onVRRequestPresentStart = new BABYLON.Observable();
this._colorWrite = true;
this._drawCalls = new BABYLON.PerfCounter();
this._renderingQueueLaunched = false;
this._activeRenderLoops = new Array();
// Deterministic lockstepMaxSteps
this._deterministicLockstep = false;
this._lockstepMaxSteps = 4;
// Lost context
this.onContextLostObservable = new BABYLON.Observable();
this.onContextRestoredObservable = new BABYLON.Observable();
this._contextWasLost = false;
this._doNotHandleContextLost = false;
// FPS
this._performanceMonitor = new BABYLON.PerformanceMonitor();
this._fps = 60;
this._deltaTime = 0;
/**
* Turn this value on if you want to pause FPS computation when in background
*/
this.disablePerformanceMonitorInBackground = false;
// States
this._depthCullingState = new BABYLON.Internals._DepthCullingState();
this._stencilState = new BABYLON.Internals._StencilState();
this._alphaState = new BABYLON.Internals._AlphaState();
this._alphaMode = Engine.ALPHA_DISABLE;
// Cache
this._internalTexturesCache = new Array();
this._boundTexturesCache = {};
this._boundTexturesOrder = new Array();
this._compiledEffects = {};
this._vertexAttribArraysEnabled = [];
this._uintIndicesCurrentlySet = false;
this._currentBoundBuffer = new Array();
this._currentBufferPointers = new Array();
this._currentInstanceLocations = new Array();
this._currentInstanceBuffers = new Array();
this._vaoRecordInProgress = false;
this._mustWipeVertexAttributes = false;
this._nextFreeTextureSlot = 0;
// Hardware supported Compressed Textures
this._texturesSupported = new Array();
this._onVRFullScreenTriggered = function () {
if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
//get the old size before we change
_this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
_this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
//get the width and height, change the render size
var leftEye = _this._vrDisplay.getEyeParameters('left');
_this.setHardwareScalingLevel(1);
_this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
}
else {
_this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
_this.setSize(_this._oldSize.width, _this._oldSize.height);
}
};
this._boundUniforms = {};
var canvas = null;
Engine.Instances.push(this);
if (!canvasOrContext) {
return;
}
options = options || {};
if (canvasOrContext.getContext) {
canvas = canvasOrContext;
this._renderingCanvas = canvas;
if (antialias != null) {
options.antialias = antialias;
}
if (options.deterministicLockstep === undefined) {
options.deterministicLockstep = false;
}
if (options.lockstepMaxSteps === undefined) {
options.lockstepMaxSteps = 4;
}
if (options.preserveDrawingBuffer === undefined) {
options.preserveDrawingBuffer = false;
}
if (options.audioEngine === undefined) {
options.audioEngine = true;
}
if (options.stencil === undefined) {
options.stencil = true;
}
this._deterministicLockstep = options.deterministicLockstep;
this._lockstepMaxSteps = options.lockstepMaxSteps;
this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
// Exceptions
if (!options.disableWebGL2Support) {
if (navigator && navigator.userAgent) {
var ua = navigator.userAgent;
for (var _i = 0, _a = Engine.WebGL2UniformBuffersExceptionList; _i < _a.length; _i++) {
var exception = _a[_i];
if (ua.indexOf(exception) > -1) {
this.disableUniformBuffers = true;
break;
}
}
}
}
// GL
if (!options.disableWebGL2Support) {
try {
this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
if (this._gl) {
this._webGLVersion = 2.0;
}
}
catch (e) {
// Do nothing
}
}
if (!this._gl) {
if (!canvas) {
throw new Error("The provided canvas is null or undefined.");
}
try {
this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
}
catch (e) {
throw new Error("WebGL not supported");
}
}
if (!this._gl) {
throw new Error("WebGL not supported");
}
this._onCanvasFocus = function () {
_this.onCanvasFocusObservable.notifyObservers(_this);
};
this._onCanvasBlur = function () {
_this.onCanvasBlurObservable.notifyObservers(_this);
};
canvas.addEventListener("focus", this._onCanvasFocus);
canvas.addEventListener("blur", this._onCanvasBlur);
this._onBlur = function () {
if (_this.disablePerformanceMonitorInBackground) {
_this._performanceMonitor.disable();
}
_this._windowIsBackground = true;
};
this._onFocus = function () {
if (_this.disablePerformanceMonitorInBackground) {
_this._performanceMonitor.enable();
}
_this._windowIsBackground = false;
};
this._onCanvasPointerOut = function () {
_this.onCanvasPointerOutObservable.notifyObservers(_this);
};
window.addEventListener("blur", this._onBlur);
window.addEventListener("focus", this._onFocus);
canvas.addEventListener("pointerout", this._onCanvasPointerOut);
// Context lost
if (!this._doNotHandleContextLost) {
this._onContextLost = function (evt) {
evt.preventDefault();
_this._contextWasLost = true;
BABYLON.Tools.Warn("WebGL context lost.");
_this.onContextLostObservable.notifyObservers(_this);
};
this._onContextRestored = function (evt) {
// Adding a timeout to avoid race condition at browser level
setTimeout(function () {
// Rebuild gl context
_this._initGLContext();
// Rebuild effects
_this._rebuildEffects();
// Rebuild textures
_this._rebuildInternalTextures();
// Rebuild buffers
_this._rebuildBuffers();
// Cache
_this.wipeCaches(true);
BABYLON.Tools.Warn("WebGL context successfully restored.");
_this.onContextRestoredObservable.notifyObservers(_this);
_this._contextWasLost = false;
}, 0);
};
canvas.addEventListener("webglcontextlost", this._onContextLost, false);
canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
}
}
else {
this._gl = canvasOrContext;
this._renderingCanvas = this._gl.canvas;
if (this._gl.renderbufferStorageMultisample) {
this._webGLVersion = 2.0;
}
options.stencil = this._gl.getContextAttributes().stencil;
}
// Viewport
var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
this.resize();
this._isStencilEnable = options.stencil ? true : false;
this._initGLContext();
if (canvas) {
// Fullscreen
this._onFullscreenChange = function () {
if (document.fullscreen !== undefined) {
_this.isFullscreen = document.fullscreen;
}
else if (document.mozFullScreen !== undefined) {
_this.isFullscreen = document.mozFullScreen;
}
else if (document.webkitIsFullScreen !== undefined) {
_this.isFullscreen = document.webkitIsFullScreen;
}
else if (document.msIsFullScreen !== undefined) {
_this.isFullscreen = document.msIsFullScreen;
}
// Pointer lock
if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
canvas.requestPointerLock = canvas.requestPointerLock ||
canvas.msRequestPointerLock ||
canvas.mozRequestPointerLock ||
canvas.webkitRequestPointerLock;
if (canvas.requestPointerLock) {
canvas.requestPointerLock();
}
}
};
document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
// Pointer lock
this._onPointerLockChange = function () {
_this.isPointerLock = (document.mozPointerLockElement === canvas ||
document.webkitPointerLockElement === canvas ||
document.msPointerLockElement === canvas ||
document.pointerLockElement === canvas);
};
document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
this._onVRDisplayPointerRestricted = function () {
if (canvas) {
canvas.requestPointerLock();
}
};
this._onVRDisplayPointerUnrestricted = function () {
document.exitPointerLock();
};
window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
}
if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
Engine.audioEngine = new BABYLON.AudioEngine();
}
// Prepare buffer pointers
for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
this._currentBufferPointers[i] = new BufferPointer();
}
// Load WebVR Devices
if (options.autoEnableWebVR) {
this.initWebVR();
}
// Detect if we are running on a faulty buggy OS.
this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
// Detect if we are running on a faulty buggy desktop OS.
this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
this.enableOfflineSupport = (BABYLON.Database !== undefined);
}
Object.defineProperty(Engine, "LastCreatedEngine", {
get: function () {
if (Engine.Instances.length === 0) {
return null;
}
return Engine.Instances[Engine.Instances.length - 1];
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "LastCreatedScene", {
get: function () {
var lastCreatedEngine = Engine.LastCreatedEngine;
if (!lastCreatedEngine) {
return null;
}
if (lastCreatedEngine.scenes.length === 0) {
return null;
}
return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
},
enumerable: true,
configurable: true
});
/**
* Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
*/
Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
var engine = Engine.Instances[engineIndex];
for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
}
}
};
Object.defineProperty(Engine, "NEVER", {
get: function () {
return Engine._NEVER;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALWAYS", {
get: function () {
return Engine._ALWAYS;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "LESS", {
get: function () {
return Engine._LESS;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "EQUAL", {
get: function () {
return Engine._EQUAL;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "LEQUAL", {
get: function () {
return Engine._LEQUAL;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "GREATER", {
get: function () {
return Engine._GREATER;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "GEQUAL", {
get: function () {
return Engine._GEQUAL;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "NOTEQUAL", {
get: function () {
return Engine._NOTEQUAL;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "KEEP", {
get: function () {
return Engine._KEEP;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "REPLACE", {
get: function () {
return Engine._REPLACE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "INCR", {
get: function () {
return Engine._INCR;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "DECR", {
get: function () {
return Engine._DECR;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "INVERT", {
get: function () {
return Engine._INVERT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "INCR_WRAP", {
get: function () {
return Engine._INCR_WRAP;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "DECR_WRAP", {
get: function () {
return Engine._DECR_WRAP;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALPHA_DISABLE", {
get: function () {
return Engine._ALPHA_DISABLE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALPHA_ONEONE", {
get: function () {
return Engine._ALPHA_ONEONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALPHA_ADD", {
get: function () {
return Engine._ALPHA_ADD;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALPHA_COMBINE", {
get: function () {
return Engine._ALPHA_COMBINE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
get: function () {
return Engine._ALPHA_SUBTRACT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
get: function () {
return Engine._ALPHA_MULTIPLY;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
get: function () {
return Engine._ALPHA_MAXIMIZED;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
get: function () {
return Engine._ALPHA_PREMULTIPLIED;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
get: function () {
return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
get: function () {
return Engine._ALPHA_INTERPOLATE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
get: function () {
return Engine._ALPHA_SCREENMODE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
get: function () {
return Engine._DELAYLOADSTATE_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
get: function () {
return Engine._DELAYLOADSTATE_LOADED;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
get: function () {
return Engine._DELAYLOADSTATE_LOADING;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
get: function () {
return Engine._DELAYLOADSTATE_NOTLOADED;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
get: function () {
return Engine._TEXTUREFORMAT_ALPHA;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
get: function () {
return Engine._TEXTUREFORMAT_LUMINANCE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
get: function () {
return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
get: function () {
return Engine._TEXTUREFORMAT_RGB;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
get: function () {
return Engine._TEXTUREFORMAT_RGBA;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
get: function () {
return Engine._TEXTURETYPE_UNSIGNED_INT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
get: function () {
return Engine._TEXTURETYPE_FLOAT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
get: function () {
return Engine._TEXTURETYPE_HALF_FLOAT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
get: function () {
return Engine._SCALEMODE_FLOOR;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
get: function () {
return Engine._SCALEMODE_NEAREST;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "SCALEMODE_CEILING", {
get: function () {
return Engine._SCALEMODE_CEILING;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine, "Version", {
get: function () {
return "3.2.0-alpha0";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
get: function () {
return this._vrExclusivePointerMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
get: function () {
return this.webGLVersion > 1 && !this.disableUniformBuffers;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "needPOTTextures", {
get: function () {
return this._webGLVersion < 2 || this.forcePOTTextures;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "badOS", {
get: function () {
return this._badOS;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "badDesktopOS", {
get: function () {
return this._badDesktopOS;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "performanceMonitor", {
get: function () {
return this._performanceMonitor;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "texturesSupported", {
get: function () {
return this._texturesSupported;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "textureFormatInUse", {
get: function () {
return this._textureFormatInUse;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "currentViewport", {
get: function () {
return this._cachedViewport;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "emptyTexture", {
// Empty texture
get: function () {
if (!this._emptyTexture) {
this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
}
return this._emptyTexture;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "emptyTexture3D", {
get: function () {
if (!this._emptyTexture3D) {
this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
}
return this._emptyTexture3D;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
get: function () {
if (!this._emptyCubeTexture) {
var faceData = new Uint8Array(4);
var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
}
return this._emptyCubeTexture;
},
enumerable: true,
configurable: true
});
Engine.prototype._rebuildInternalTextures = function () {
var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
var internalTexture = currentState_1[_i];
internalTexture._rebuild();
}
};
Engine.prototype._rebuildEffects = function () {
for (var key in this._compiledEffects) {
var effect = this._compiledEffects[key];
effect._prepareEffect();
}
BABYLON.Effect.ResetCache();
};
Engine.prototype._rebuildBuffers = function () {
// Index / Vertex
for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
var scene = _a[_i];
scene.resetCachedMaterial();
scene._rebuildGeometries();
scene._rebuildTextures();
}
// Uniforms
for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
var uniformBuffer = _c[_b];
uniformBuffer._rebuild();
}
};
Engine.prototype._initGLContext = function () {
// Caps
this._caps = new EngineCapabilities();
this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
// Infos
this._glVersion = this._gl.getParameter(this._gl.VERSION);
var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
if (rendererInfo != null) {
this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
}
if (!this._glVendor) {
this._glVendor = "Unknown vendor";
}
if (!this._glRenderer) {
this._glRenderer = "Unknown renderer";
}
// Constants
this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
if (this._gl.RGBA16F !== 0x881A) {
this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
}
if (this._gl.RGBA32F !== 0x8814) {
this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
}
if (this._gl.DEPTH24_STENCIL8 !== 35056) {
this._gl.DEPTH24_STENCIL8 = 35056;
}
// Extensions
this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
this._caps.highPrecisionShaderSupported = true;
this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
if (this._caps.timerQuery) {
if (this._webGLVersion === 1) {
this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
}
this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
}
// Checks if some of the format renders first to allow the use of webgl inspector.
this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
if (this._webGLVersion > 1) {
this._gl.HALF_FLOAT_OES = 0x140B;
}
this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
// Draw buffers
if (this._webGLVersion > 1) {
this._caps.drawBuffersExtension = true;
}
else {
var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
if (drawBuffersExtension !== null) {
this._caps.drawBuffersExtension = true;
this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
for (var i = 0; i < 16; i++) {
this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
}
}
else {
this._caps.drawBuffersExtension = false;
}
}
// Depth Texture
if (this._webGLVersion > 1) {
this._caps.depthTextureExtension = true;
}
else {
var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
if (depthTextureExtension != null) {
this._caps.depthTextureExtension = true;
}
}
// Vertex array object
if (this._webGLVersion > 1) {
this._caps.vertexArrayObject = true;
}
else {
var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
if (vertexArrayObjectExtension != null) {
this._caps.vertexArrayObject = true;
this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
}
else {
this._caps.vertexArrayObject = false;
}
}
// Instances count
if (this._webGLVersion > 1) {
this._caps.instancedArrays = true;
}
else {
var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
if (instanceExtension != null) {
this._caps.instancedArrays = true;
this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
}
else {
this._caps.instancedArrays = false;
}
}
// Intelligently add supported compressed formats in order to check for.
// Check for ASTC support first as it is most powerful and to be very cross platform.
// Next PVRTC & DXT, which are probably superior to ETC1/2.
// Likely no hardware which supports both PVR & DXT, so order matters little.
// ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
if (this._caps.astc)
this.texturesSupported.push('-astc.ktx');
if (this._caps.s3tc)
this.texturesSupported.push('-dxt.ktx');
if (this._caps.pvrtc)
this.texturesSupported.push('-pvrtc.ktx');
if (this._caps.etc2)
this.texturesSupported.push('-etc2.ktx');
if (this._caps.etc1)
this.texturesSupported.push('-etc1.ktx');
if (this._gl.getShaderPrecisionFormat) {
var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
if (highp) {
this._caps.highPrecisionShaderSupported = highp.precision !== 0;
}
}
// Depth buffer
this.setDepthBuffer(true);
this.setDepthFunctionToLessOrEqual();
this.setDepthWrite(true);
};
Object.defineProperty(Engine.prototype, "webGLVersion", {
get: function () {
return this._webGLVersion;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "isStencilEnable", {
/**
* Returns true if the stencil buffer has been enabled through the creation option of the context.
*/
get: function () {
return this._isStencilEnable;
},
enumerable: true,
configurable: true
});
Engine.prototype._prepareWorkingCanvas = function () {
if (this._workingCanvas) {
return;
}
this._workingCanvas = document.createElement("canvas");
var context = this._workingCanvas.getContext("2d");
if (context) {
this._workingContext = context;
}
};
Engine.prototype.resetTextureCache = function () {
for (var key in this._boundTexturesCache) {
var boundTexture = this._boundTexturesCache[key];
if (boundTexture) {
this._removeDesignatedSlot(boundTexture);
}
this._boundTexturesCache[key] = null;
}
this._nextFreeTextureSlot = 0;
this._activeChannel = -1;
};
Engine.prototype.isDeterministicLockStep = function () {
return this._deterministicLockstep;
};
Engine.prototype.getLockstepMaxSteps = function () {
return this._lockstepMaxSteps;
};
Engine.prototype.getGlInfo = function () {
return {
vendor: this._glVendor,
renderer: this._glRenderer,
version: this._glVersion
};
};
Engine.prototype.getAspectRatio = function (camera, useScreen) {
if (useScreen === void 0) { useScreen = false; }
var viewport = camera.viewport;
return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
};
Engine.prototype.getRenderWidth = function (useScreen) {
if (useScreen === void 0) { useScreen = false; }
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.width;
}
return this._gl.drawingBufferWidth;
};
Engine.prototype.getRenderHeight = function (useScreen) {
if (useScreen === void 0) { useScreen = false; }
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.height;
}
return this._gl.drawingBufferHeight;
};
Engine.prototype.getRenderingCanvas = function () {
return this._renderingCanvas;
};
Engine.prototype.getRenderingCanvasClientRect = function () {
if (!this._renderingCanvas) {
return null;
}
return this._renderingCanvas.getBoundingClientRect();
};
Engine.prototype.setHardwareScalingLevel = function (level) {
this._hardwareScalingLevel = level;
this.resize();
};
Engine.prototype.getHardwareScalingLevel = function () {
return this._hardwareScalingLevel;
};
Engine.prototype.getLoadedTexturesCache = function () {
return this._internalTexturesCache;
};
Engine.prototype.getCaps = function () {
return this._caps;
};
Object.defineProperty(Engine.prototype, "drawCalls", {
/** The number of draw calls submitted last frame */
get: function () {
BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
return 0;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
get: function () {
BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Engine.prototype.getDepthFunction = function () {
return this._depthCullingState.depthFunc;
};
Engine.prototype.setDepthFunction = function (depthFunc) {
this._depthCullingState.depthFunc = depthFunc;
};
Engine.prototype.setDepthFunctionToGreater = function () {
this._depthCullingState.depthFunc = this._gl.GREATER;
};
Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
this._depthCullingState.depthFunc = this._gl.GEQUAL;
};
Engine.prototype.setDepthFunctionToLess = function () {
this._depthCullingState.depthFunc = this._gl.LESS;
};
Engine.prototype.setDepthFunctionToLessOrEqual = function () {
this._depthCullingState.depthFunc = this._gl.LEQUAL;
};
Engine.prototype.getStencilBuffer = function () {
return this._stencilState.stencilTest;
};
Engine.prototype.setStencilBuffer = function (enable) {
this._stencilState.stencilTest = enable;
};
Engine.prototype.getStencilMask = function () {
return this._stencilState.stencilMask;
};
Engine.prototype.setStencilMask = function (mask) {
this._stencilState.stencilMask = mask;
};
Engine.prototype.getStencilFunction = function () {
return this._stencilState.stencilFunc;
};
Engine.prototype.getStencilFunctionReference = function () {
return this._stencilState.stencilFuncRef;
};
Engine.prototype.getStencilFunctionMask = function () {
return this._stencilState.stencilFuncMask;
};
Engine.prototype.setStencilFunction = function (stencilFunc) {
this._stencilState.stencilFunc = stencilFunc;
};
Engine.prototype.setStencilFunctionReference = function (reference) {
this._stencilState.stencilFuncRef = reference;
};
Engine.prototype.setStencilFunctionMask = function (mask) {
this._stencilState.stencilFuncMask = mask;
};
Engine.prototype.getStencilOperationFail = function () {
return this._stencilState.stencilOpStencilFail;
};
Engine.prototype.getStencilOperationDepthFail = function () {
return this._stencilState.stencilOpDepthFail;
};
Engine.prototype.getStencilOperationPass = function () {
return this._stencilState.stencilOpStencilDepthPass;
};
Engine.prototype.setStencilOperationFail = function (operation) {
this._stencilState.stencilOpStencilFail = operation;
};
Engine.prototype.setStencilOperationDepthFail = function (operation) {
this._stencilState.stencilOpDepthFail = operation;
};
Engine.prototype.setStencilOperationPass = function (operation) {
this._stencilState.stencilOpStencilDepthPass = operation;
};
Engine.prototype.setDitheringState = function (value) {
if (value) {
this._gl.enable(this._gl.DITHER);
}
else {
this._gl.disable(this._gl.DITHER);
}
};
Engine.prototype.setRasterizerState = function (value) {
if (value) {
this._gl.disable(this._gl.RASTERIZER_DISCARD);
}
else {
this._gl.enable(this._gl.RASTERIZER_DISCARD);
}
};
/**
* stop executing a render loop function and remove it from the execution array
* @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
*/
Engine.prototype.stopRenderLoop = function (renderFunction) {
if (!renderFunction) {
this._activeRenderLoops = [];
return;
}
var index = this._activeRenderLoops.indexOf(renderFunction);
if (index >= 0) {
this._activeRenderLoops.splice(index, 1);
}
};
Engine.prototype._renderLoop = function () {
if (!this._contextWasLost) {
var shouldRender = true;
if (!this.renderEvenInBackground && this._windowIsBackground) {
shouldRender = false;
}
if (shouldRender) {
// Start new frame
this.beginFrame();
for (var index = 0; index < this._activeRenderLoops.length; index++) {
var renderFunction = this._activeRenderLoops[index];
renderFunction();
}
// Present
this.endFrame();
}
}
if (this._activeRenderLoops.length > 0) {
// Register new frame
var requester = null;
if (this._vrDisplay && this._vrDisplay.isPresenting)
requester = this._vrDisplay;
this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
}
else {
this._renderingQueueLaunched = false;
}
};
/**
* Register and execute a render loop. The engine can have more than one render function.
* @param {Function} renderFunction - the function to continuously execute starting the next render loop.
* @example
* engine.runRenderLoop(function () {
* scene.render()
* })
*/
Engine.prototype.runRenderLoop = function (renderFunction) {
if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
return;
}
this._activeRenderLoops.push(renderFunction);
if (!this._renderingQueueLaunched) {
this._renderingQueueLaunched = true;
this._bindedRenderFunction = this._renderLoop.bind(this);
this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
}
};
/**
* Toggle full screen mode.
* @param {boolean} requestPointerLock - should a pointer lock be requested from the user
* @param {any} options - an options object to be sent to the requestFullscreen function
*/
Engine.prototype.switchFullscreen = function (requestPointerLock) {
if (this.isFullscreen) {
BABYLON.Tools.ExitFullscreen();
}
else {
this._pointerLockRequested = requestPointerLock;
if (this._renderingCanvas) {
BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
}
}
};
Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
if (stencil === void 0) { stencil = false; }
this.applyStates();
var mode = 0;
if (backBuffer && color) {
this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
mode |= this._gl.COLOR_BUFFER_BIT;
}
if (depth) {
this._gl.clearDepth(1.0);
mode |= this._gl.DEPTH_BUFFER_BIT;
}
if (stencil) {
this._gl.clearStencil(0);
mode |= this._gl.STENCIL_BUFFER_BIT;
}
this._gl.clear(mode);
};
Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
var gl = this._gl;
// Save state
var curScissor = gl.getParameter(gl.SCISSOR_TEST);
var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
// Change state
gl.enable(gl.SCISSOR_TEST);
gl.scissor(x, y, width, height);
// Clear
this.clear(clearColor, true, true, true);
// Restore state
gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
if (curScissor === true) {
gl.enable(gl.SCISSOR_TEST);
}
else {
gl.disable(gl.SCISSOR_TEST);
}
};
/**
* Set the WebGL's viewport
* @param {BABYLON.Viewport} viewport - the viewport element to be used.
* @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
* @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
*/
Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
var width = requiredWidth || this.getRenderWidth();
var height = requiredHeight || this.getRenderHeight();
var x = viewport.x || 0;
var y = viewport.y || 0;
this._cachedViewport = viewport;
this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
};
/**
* Directly set the WebGL Viewport
* The x, y, width & height are directly passed to the WebGL call
* @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
*/
Engine.prototype.setDirectViewport = function (x, y, width, height) {
var currentViewport = this._cachedViewport;
this._cachedViewport = null;
this._gl.viewport(x, y, width, height);
return currentViewport;
};
Engine.prototype.beginFrame = function () {
this.onBeginFrameObservable.notifyObservers(this);
this._measureFps();
};
Engine.prototype.endFrame = function () {
//force a flush in case we are using a bad OS.
if (this._badOS) {
this.flushFramebuffer();
}
//submit frame to the vr device, if enabled
if (this._vrDisplay && this._vrDisplay.isPresenting) {
// TODO: We should only submit the frame if we read frameData successfully.
this._vrDisplay.submitFrame();
}
this.onEndFrameObservable.notifyObservers(this);
};
/**
* resize the view according to the canvas' size.
* @example
* window.addEventListener("resize", function () {
* engine.resize();
* });
*/
Engine.prototype.resize = function () {
// We're not resizing the size of the canvas while in VR mode & presenting
if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
}
};
/**
* force a specific size of the canvas
* @param {number} width - the new canvas' width
* @param {number} height - the new canvas' height
*/
Engine.prototype.setSize = function (width, height) {
if (!this._renderingCanvas) {
return;
}
if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
return;
}
this._renderingCanvas.width = width;
this._renderingCanvas.height = height;
for (var index = 0; index < this.scenes.length; index++) {
var scene = this.scenes[index];
for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
var cam = scene.cameras[camIndex];
cam._currentRenderId = 0;
}
}
if (this.onResizeObservable.hasObservers) {
this.onResizeObservable.notifyObservers(this);
}
};
// WebVR functions
Engine.prototype.isVRDevicePresent = function () {
return !!this._vrDisplay;
};
Engine.prototype.getVRDevice = function () {
return this._vrDisplay;
};
Engine.prototype.initWebVR = function () {
var _this = this;
var notifyObservers = function () {
var eventArgs = {
vrDisplay: _this._vrDisplay,
vrSupported: _this._vrSupported
};
_this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
};
if (!this._onVrDisplayConnect) {
this._onVrDisplayConnect = function (event) {
_this._vrDisplay = event.display;
notifyObservers();
};
this._onVrDisplayDisconnect = function () {
_this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
_this._vrDisplay = undefined;
_this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
notifyObservers();
};
this._onVrDisplayPresentChange = function () {
_this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
};
window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
}
this._getVRDisplays(notifyObservers);
return this.onVRDisplayChangedObservable;
};
Engine.prototype.enableVR = function () {
var _this = this;
if (this._vrDisplay && !this._vrDisplay.isPresenting) {
var onResolved = function () {
_this.onVRRequestPresentComplete.notifyObservers(true);
_this._onVRFullScreenTriggered();
};
var onRejected = function () {
_this.onVRRequestPresentComplete.notifyObservers(false);
};
this.onVRRequestPresentStart.notifyObservers(this);
this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
}
};
Engine.prototype.disableVR = function () {
if (this._vrDisplay && this._vrDisplay.isPresenting) {
this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
}
};
Engine.prototype._getVRDisplays = function (callback) {
var _this = this;
var getWebVRDevices = function (devices) {
_this._vrSupported = true;
// note that devices may actually be an empty array. This is fine;
// we expect this._vrDisplay to be undefined in this case.
return _this._vrDisplay = devices[0];
};
if (navigator.getVRDisplays) {
navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
// TODO: System CANNOT support WebVR, despite API presence.
_this._vrSupported = false;
callback();
});
}
else {
// TODO: Browser does not support WebVR
this._vrDisplay = undefined;
this._vrSupported = false;
callback();
}
};
Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
if (this._currentRenderTarget) {
this.unBindFramebuffer(this._currentRenderTarget);
}
this._currentRenderTarget = texture;
this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
var gl = this._gl;
if (texture.isCube) {
if (faceIndex === undefined) {
faceIndex = 0;
}
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
}
if (this._cachedViewport && !forceFullscreenViewport) {
this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
}
else {
gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
}
this.wipeCaches();
};
Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
if (this._currentFramebuffer !== framebuffer) {
this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
this._currentFramebuffer = framebuffer;
}
};
Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
this._currentRenderTarget = null;
// If MSAA, we need to bitblt back to main texture
var gl = this._gl;
if (texture._MSAAFramebuffer) {
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
}
if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
this._bindTextureDirectly(gl.TEXTURE_2D, texture);
gl.generateMipmap(gl.TEXTURE_2D);
this._bindTextureDirectly(gl.TEXTURE_2D, null);
}
if (onBeforeUnbind) {
if (texture._MSAAFramebuffer) {
// Bind the correct framebuffer
this.bindUnboundFramebuffer(texture._framebuffer);
}
onBeforeUnbind();
}
this.bindUnboundFramebuffer(null);
};
Engine.prototype.generateMipMapsForCubemap = function (texture) {
if (texture.generateMipMaps) {
var gl = this._gl;
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
}
};
Engine.prototype.flushFramebuffer = function () {
this._gl.flush();
};
Engine.prototype.restoreDefaultFramebuffer = function () {
if (this._currentRenderTarget) {
this.unBindFramebuffer(this._currentRenderTarget);
}
else {
this.bindUnboundFramebuffer(null);
}
if (this._cachedViewport) {
this.setViewport(this._cachedViewport);
}
this.wipeCaches();
};
// UBOs
Engine.prototype.createUniformBuffer = function (elements) {
var ubo = this._gl.createBuffer();
if (!ubo) {
throw new Error("Unable to create uniform buffer");
}
this.bindUniformBuffer(ubo);
if (elements instanceof Float32Array) {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
}
else {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
}
this.bindUniformBuffer(null);
ubo.references = 1;
return ubo;
};
Engine.prototype.createDynamicUniformBuffer = function (elements) {
var ubo = this._gl.createBuffer();
if (!ubo) {
throw new Error("Unable to create dynamic uniform buffer");
}
this.bindUniformBuffer(ubo);
if (elements instanceof Float32Array) {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
}
else {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
}
this.bindUniformBuffer(null);
ubo.references = 1;
return ubo;
};
Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
this.bindUniformBuffer(uniformBuffer);
if (offset === undefined) {
offset = 0;
}
if (count === undefined) {
if (elements instanceof Float32Array) {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
}
else {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
}
}
else {
if (elements instanceof Float32Array) {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
}
else {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
}
}
this.bindUniformBuffer(null);
};
// VBOs
Engine.prototype._resetVertexBufferBinding = function () {
this.bindArrayBuffer(null);
this._cachedVertexBuffers = null;
};
Engine.prototype.createVertexBuffer = function (vertices) {
var vbo = this._gl.createBuffer();
if (!vbo) {
throw new Error("Unable to create vertex buffer");
}
this.bindArrayBuffer(vbo);
if (vertices instanceof Float32Array) {
this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
}
else {
this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
}
this._resetVertexBufferBinding();
vbo.references = 1;
return vbo;
};
Engine.prototype.createDynamicVertexBuffer = function (vertices) {
var vbo = this._gl.createBuffer();
if (!vbo) {
throw new Error("Unable to create dynamic vertex buffer");
}
this.bindArrayBuffer(vbo);
if (vertices instanceof Float32Array) {
this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
}
else {
this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
}
this._resetVertexBufferBinding();
vbo.references = 1;
return vbo;
};
Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
if (offset === void 0) { offset = 0; }
// Force cache update
this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
this.bindIndexBuffer(indexBuffer);
var arrayBuffer;
if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
arrayBuffer = indices;
}
else {
arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
}
this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
this._resetIndexBufferBinding();
};
Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
this.bindArrayBuffer(vertexBuffer);
if (offset === undefined) {
offset = 0;
}
if (count === undefined) {
if (vertices instanceof Float32Array) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
}
else {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
}
}
else {
if (vertices instanceof Float32Array) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
}
else {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
}
}
this._resetVertexBufferBinding();
};
Engine.prototype._resetIndexBufferBinding = function () {
this.bindIndexBuffer(null);
this._cachedIndexBuffer = null;
};
Engine.prototype.createIndexBuffer = function (indices, updatable) {
var vbo = this._gl.createBuffer();
if (!vbo) {
throw new Error("Unable to create index buffer");
}
this.bindIndexBuffer(vbo);
// Check for 32 bits indices
var arrayBuffer;
var need32Bits = false;
if (indices instanceof Uint16Array) {
arrayBuffer = indices;
}
else {
//check 32 bit support
if (this._caps.uintIndices) {
if (indices instanceof Uint32Array) {
arrayBuffer = indices;
need32Bits = true;
}
else {
//number[] or Int32Array, check if 32 bit is necessary
for (var index = 0; index < indices.length; index++) {
if (indices[index] > 65535) {
need32Bits = true;
break;
}
}
arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
}
}
else {
//no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
arrayBuffer = new Uint16Array(indices);
}
}
this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
this._resetIndexBufferBinding();
vbo.references = 1;
vbo.is32Bits = need32Bits;
return vbo;
};
Engine.prototype.bindArrayBuffer = function (buffer) {
if (!this._vaoRecordInProgress) {
this._unbindVertexArrayObject();
}
this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
};
Engine.prototype.bindUniformBuffer = function (buffer) {
this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
};
Engine.prototype.bindUniformBufferBase = function (buffer, location) {
this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
};
Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
};
;
Engine.prototype.bindIndexBuffer = function (buffer) {
if (!this._vaoRecordInProgress) {
this._unbindVertexArrayObject();
}
this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
};
Engine.prototype.bindBuffer = function (buffer, target) {
if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
this._gl.bindBuffer(target, buffer);
this._currentBoundBuffer[target] = buffer;
}
};
Engine.prototype.updateArrayBuffer = function (data) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
};
Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
var pointer = this._currentBufferPointers[indx];
var changed = false;
if (!pointer.active) {
changed = true;
pointer.active = true;
pointer.index = indx;
pointer.size = size;
pointer.type = type;
pointer.normalized = normalized;
pointer.stride = stride;
pointer.offset = offset;
pointer.buffer = buffer;
}
else {
if (pointer.buffer !== buffer) {
pointer.buffer = buffer;
changed = true;
}
if (pointer.size !== size) {
pointer.size = size;
changed = true;
}
if (pointer.type !== type) {
pointer.type = type;
changed = true;
}
if (pointer.normalized !== normalized) {
pointer.normalized = normalized;
changed = true;
}
if (pointer.stride !== stride) {
pointer.stride = stride;
changed = true;
}
if (pointer.offset !== offset) {
pointer.offset = offset;
changed = true;
}
}
if (changed || this._vaoRecordInProgress) {
this.bindArrayBuffer(buffer);
this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
}
};
Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
if (indexBuffer == null) {
return;
}
if (this._cachedIndexBuffer !== indexBuffer) {
this._cachedIndexBuffer = indexBuffer;
this.bindIndexBuffer(indexBuffer);
this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
}
};
Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
var attributes = effect.getAttributesNames();
if (!this._vaoRecordInProgress) {
this._unbindVertexArrayObject();
}
this.unbindAllAttributes();
for (var index = 0; index < attributes.length; index++) {
var order = effect.getAttributeLocation(index);
if (order >= 0) {
var vertexBuffer = vertexBuffers[attributes[index]];
if (!vertexBuffer) {
continue;
}
this._gl.enableVertexAttribArray(order);
if (!this._vaoRecordInProgress) {
this._vertexAttribArraysEnabled[order] = true;
}
var buffer = vertexBuffer.getBuffer();
if (buffer) {
this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
if (vertexBuffer.getIsInstanced()) {
this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
if (!this._vaoRecordInProgress) {
this._currentInstanceLocations.push(order);
this._currentInstanceBuffers.push(buffer);
}
}
}
}
}
};
Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
var vao = this._gl.createVertexArray();
this._vaoRecordInProgress = true;
this._gl.bindVertexArray(vao);
this._mustWipeVertexAttributes = true;
this._bindVertexBuffersAttributes(vertexBuffers, effect);
this.bindIndexBuffer(indexBuffer);
this._vaoRecordInProgress = false;
this._gl.bindVertexArray(null);
return vao;
};
Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
if (this._cachedVertexArrayObject !== vertexArrayObject) {
this._cachedVertexArrayObject = vertexArrayObject;
this._gl.bindVertexArray(vertexArrayObject);
this._cachedVertexBuffers = null;
this._cachedIndexBuffer = null;
this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
this._mustWipeVertexAttributes = true;
}
};
Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
this._cachedVertexBuffers = vertexBuffer;
this._cachedEffectForVertexBuffers = effect;
var attributesCount = effect.getAttributesCount();
this._unbindVertexArrayObject();
this.unbindAllAttributes();
var offset = 0;
for (var index = 0; index < attributesCount; index++) {
if (index < vertexDeclaration.length) {
var order = effect.getAttributeLocation(index);
if (order >= 0) {
this._gl.enableVertexAttribArray(order);
this._vertexAttribArraysEnabled[order] = true;
this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
}
offset += vertexDeclaration[index] * 4;
}
}
}
this._bindIndexBufferWithCache(indexBuffer);
};
Engine.prototype._unbindVertexArrayObject = function () {
if (!this._cachedVertexArrayObject) {
return;
}
this._cachedVertexArrayObject = null;
this._gl.bindVertexArray(null);
};
Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
this._cachedVertexBuffers = vertexBuffers;
this._cachedEffectForVertexBuffers = effect;
this._bindVertexBuffersAttributes(vertexBuffers, effect);
}
this._bindIndexBufferWithCache(indexBuffer);
};
Engine.prototype.unbindInstanceAttributes = function () {
var boundBuffer;
for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
var instancesBuffer = this._currentInstanceBuffers[i];
if (boundBuffer != instancesBuffer && instancesBuffer.references) {
boundBuffer = instancesBuffer;
this.bindArrayBuffer(instancesBuffer);
}
var offsetLocation = this._currentInstanceLocations[i];
this._gl.vertexAttribDivisor(offsetLocation, 0);
}
this._currentInstanceBuffers.length = 0;
this._currentInstanceLocations.length = 0;
};
Engine.prototype.releaseVertexArrayObject = function (vao) {
this._gl.deleteVertexArray(vao);
};
Engine.prototype._releaseBuffer = function (buffer) {
buffer.references--;
if (buffer.references === 0) {
this._gl.deleteBuffer(buffer);
return true;
}
return false;
};
Engine.prototype.createInstancesBuffer = function (capacity) {
var buffer = this._gl.createBuffer();
if (!buffer) {
throw new Error("Unable to create instance buffer");
}
buffer.capacity = capacity;
this.bindArrayBuffer(buffer);
this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
return buffer;
};
Engine.prototype.deleteInstancesBuffer = function (buffer) {
this._gl.deleteBuffer(buffer);
};
Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
this.bindArrayBuffer(instancesBuffer);
if (data) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
}
if (offsetLocations[0].index !== undefined) {
var stride = 0;
for (var i = 0; i < offsetLocations.length; i++) {
var ai = offsetLocations[i];
stride += ai.attributeSize * 4;
}
for (var i = 0; i < offsetLocations.length; i++) {
var ai = offsetLocations[i];
if (!this._vertexAttribArraysEnabled[ai.index]) {
this._gl.enableVertexAttribArray(ai.index);
this._vertexAttribArraysEnabled[ai.index] = true;
}
this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
this._gl.vertexAttribDivisor(ai.index, 1);
this._currentInstanceLocations.push(ai.index);
this._currentInstanceBuffers.push(instancesBuffer);
}
}
else {
for (var index = 0; index < 4; index++) {
var offsetLocation = offsetLocations[index];
if (!this._vertexAttribArraysEnabled[offsetLocation]) {
this._gl.enableVertexAttribArray(offsetLocation);
this._vertexAttribArraysEnabled[offsetLocation] = true;
}
this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
this._gl.vertexAttribDivisor(offsetLocation, 1);
this._currentInstanceLocations.push(offsetLocation);
this._currentInstanceBuffers.push(instancesBuffer);
}
}
};
Engine.prototype.applyStates = function () {
this._depthCullingState.apply(this._gl);
this._stencilState.apply(this._gl);
this._alphaState.apply(this._gl);
};
Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
};
Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
};
Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
};
Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
// Apply states
this.applyStates();
this._drawCalls.addCount(1, false);
// Render
var drawMode = this.DrawMode(fillMode);
var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
var mult = this._uintIndicesCurrentlySet ? 4 : 2;
if (instancesCount) {
this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
}
else {
this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
}
};
Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
// Apply states
this.applyStates();
this._drawCalls.addCount(1, false);
var drawMode = this.DrawMode(fillMode);
if (instancesCount) {
this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
}
else {
this._gl.drawArrays(drawMode, verticesStart, verticesCount);
}
};
Engine.prototype.DrawMode = function (fillMode) {
switch (fillMode) {
// Triangle views
case BABYLON.Material.TriangleFillMode:
return this._gl.TRIANGLES;
case BABYLON.Material.PointFillMode:
return this._gl.POINTS;
case BABYLON.Material.WireFrameFillMode:
return this._gl.LINES;
// Draw modes
case BABYLON.Material.PointListDrawMode:
return this._gl.POINTS;
case BABYLON.Material.LineListDrawMode:
return this._gl.LINES;
case BABYLON.Material.LineLoopDrawMode:
return this._gl.LINE_LOOP;
case BABYLON.Material.LineStripDrawMode:
return this._gl.LINE_STRIP;
case BABYLON.Material.TriangleStripDrawMode:
return this._gl.TRIANGLE_STRIP;
case BABYLON.Material.TriangleFanDrawMode:
return this._gl.TRIANGLE_FAN;
default:
return this._gl.TRIANGLES;
}
};
// Shaders
Engine.prototype._releaseEffect = function (effect) {
if (this._compiledEffects[effect._key]) {
delete this._compiledEffects[effect._key];
this._deleteProgram(effect.getProgram());
}
};
Engine.prototype._deleteProgram = function (program) {
if (program) {
program.__SPECTOR_rebuildProgram = null;
if (program.transformFeedback) {
this.deleteTransformFeedback(program.transformFeedback);
program.transformFeedback = null;
}
this._gl.deleteProgram(program);
}
};
/**
* @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
* @param samplers An array of string used to represent textures
*/
Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
var vertex = baseName.vertexElement || baseName.vertex || baseName;
var fragment = baseName.fragmentElement || baseName.fragment || baseName;
var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
if (this._compiledEffects[name]) {
var compiledEffect = this._compiledEffects[name];
if (onCompiled && compiledEffect.isReady()) {
onCompiled(compiledEffect);
}
return compiledEffect;
}
var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
effect._key = name;
this._compiledEffects[name] = effect;
return effect;
};
Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
if (uniformsNames === void 0) { uniformsNames = []; }
if (samplers === void 0) { samplers = []; }
if (defines === void 0) { defines = ""; }
return this.createEffect({
vertex: "particles",
fragmentElement: fragmentName
}, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
};
Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
context = context || this._gl;
var vertexShader = compileRawShader(context, vertexCode, "vertex");
var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
};
Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
context = context || this._gl;
this.onBeforeShaderCompilationObservable.notifyObservers(this);
var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
this.onAfterShaderCompilationObservable.notifyObservers(this);
return program;
};
Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
var shaderProgram = context.createProgram();
if (!shaderProgram) {
throw new Error("Unable to create program");
}
context.attachShader(shaderProgram, vertexShader);
context.attachShader(shaderProgram, fragmentShader);
if (this.webGLVersion > 1 && transformFeedbackVaryings) {
var transformFeedback = this.createTransformFeedback();
this.bindTransformFeedback(transformFeedback);
this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
shaderProgram.transformFeedback = transformFeedback;
}
context.linkProgram(shaderProgram);
if (this.webGLVersion > 1 && transformFeedbackVaryings) {
this.bindTransformFeedback(null);
}
var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
if (!linked) {
context.validateProgram(shaderProgram);
var error = context.getProgramInfoLog(shaderProgram);
if (error) {
throw new Error(error);
}
}
context.deleteShader(vertexShader);
context.deleteShader(fragmentShader);
return shaderProgram;
};
Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
var results = new Array();
for (var index = 0; index < uniformsNames.length; index++) {
results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
}
return results;
};
Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
var results = [];
for (var index = 0; index < attributesNames.length; index++) {
try {
results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
}
catch (e) {
results.push(-1);
}
}
return results;
};
Engine.prototype.enableEffect = function (effect) {
if (!effect) {
return;
}
// Use program
this.bindSamplers(effect);
this._currentEffect = effect;
if (effect.onBind) {
effect.onBind(effect);
}
effect.onBindObservable.notifyObservers(effect);
};
Engine.prototype.setIntArray = function (uniform, array) {
if (!uniform)
return;
this._gl.uniform1iv(uniform, array);
};
Engine.prototype.setIntArray2 = function (uniform, array) {
if (!uniform || array.length % 2 !== 0)
return;
this._gl.uniform2iv(uniform, array);
};
Engine.prototype.setIntArray3 = function (uniform, array) {
if (!uniform || array.length % 3 !== 0)
return;
this._gl.uniform3iv(uniform, array);
};
Engine.prototype.setIntArray4 = function (uniform, array) {
if (!uniform || array.length % 4 !== 0)
return;
this._gl.uniform4iv(uniform, array);
};
Engine.prototype.setFloatArray = function (uniform, array) {
if (!uniform)
return;
this._gl.uniform1fv(uniform, array);
};
Engine.prototype.setFloatArray2 = function (uniform, array) {
if (!uniform || array.length % 2 !== 0)
return;
this._gl.uniform2fv(uniform, array);
};
Engine.prototype.setFloatArray3 = function (uniform, array) {
if (!uniform || array.length % 3 !== 0)
return;
this._gl.uniform3fv(uniform, array);
};
Engine.prototype.setFloatArray4 = function (uniform, array) {
if (!uniform || array.length % 4 !== 0)
return;
this._gl.uniform4fv(uniform, array);
};
Engine.prototype.setArray = function (uniform, array) {
if (!uniform)
return;
this._gl.uniform1fv(uniform, array);
};
Engine.prototype.setArray2 = function (uniform, array) {
if (!uniform || array.length % 2 !== 0)
return;
this._gl.uniform2fv(uniform, array);
};
Engine.prototype.setArray3 = function (uniform, array) {
if (!uniform || array.length % 3 !== 0)
return;
this._gl.uniform3fv(uniform, array);
};
Engine.prototype.setArray4 = function (uniform, array) {
if (!uniform || array.length % 4 !== 0)
return;
this._gl.uniform4fv(uniform, array);
};
Engine.prototype.setMatrices = function (uniform, matrices) {
if (!uniform)
return;
this._gl.uniformMatrix4fv(uniform, false, matrices);
};
Engine.prototype.setMatrix = function (uniform, matrix) {
if (!uniform)
return;
this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
};
Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
if (!uniform)
return;
this._gl.uniformMatrix3fv(uniform, false, matrix);
};
Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
if (!uniform)
return;
this._gl.uniformMatrix2fv(uniform, false, matrix);
};
Engine.prototype.setFloat = function (uniform, value) {
if (!uniform)
return;
this._gl.uniform1f(uniform, value);
};
Engine.prototype.setFloat2 = function (uniform, x, y) {
if (!uniform)
return;
this._gl.uniform2f(uniform, x, y);
};
Engine.prototype.setFloat3 = function (uniform, x, y, z) {
if (!uniform)
return;
this._gl.uniform3f(uniform, x, y, z);
};
Engine.prototype.setBool = function (uniform, bool) {
if (!uniform)
return;
this._gl.uniform1i(uniform, bool);
};
Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
if (!uniform)
return;
this._gl.uniform4f(uniform, x, y, z, w);
};
Engine.prototype.setColor3 = function (uniform, color3) {
if (!uniform)
return;
this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
};
Engine.prototype.setColor4 = function (uniform, color3, alpha) {
if (!uniform)
return;
this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
};
// States
Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
if (zOffset === void 0) { zOffset = 0; }
if (reverseSide === void 0) { reverseSide = false; }
// Culling
var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
var cullFace = this.cullBackFaces ? showSide : hideSide;
if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
if (culling) {
this._depthCullingState.cullFace = cullFace;
this._depthCullingState.cull = true;
}
else {
this._depthCullingState.cull = false;
}
}
// Z offset
this.setZOffset(zOffset);
};
Engine.prototype.setZOffset = function (value) {
this._depthCullingState.zOffset = value;
};
Engine.prototype.getZOffset = function () {
return this._depthCullingState.zOffset;
};
Engine.prototype.setDepthBuffer = function (enable) {
this._depthCullingState.depthTest = enable;
};
Engine.prototype.getDepthWrite = function () {
return this._depthCullingState.depthMask;
};
Engine.prototype.setDepthWrite = function (enable) {
this._depthCullingState.depthMask = enable;
};
Engine.prototype.setColorWrite = function (enable) {
this._gl.colorMask(enable, enable, enable, enable);
this._colorWrite = enable;
};
Engine.prototype.getColorWrite = function () {
return this._colorWrite;
};
Engine.prototype.setAlphaConstants = function (r, g, b, a) {
this._alphaState.setAlphaBlendConstants(r, g, b, a);
};
Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
if (this._alphaMode === mode) {
return;
}
switch (mode) {
case Engine.ALPHA_DISABLE:
this._alphaState.alphaBlend = false;
break;
case Engine.ALPHA_PREMULTIPLIED:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
this._alphaState.alphaBlend = true;
break;
case Engine.ALPHA_COMBINE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine.ALPHA_ONEONE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine.ALPHA_ADD:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine.ALPHA_SUBTRACT:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine.ALPHA_MULTIPLY:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine.ALPHA_MAXIMIZED:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine.ALPHA_INTERPOLATE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
this._alphaState.alphaBlend = true;
break;
case Engine.ALPHA_SCREENMODE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
this._alphaState.alphaBlend = true;
break;
}
if (!noDepthWriteChange) {
this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
}
this._alphaMode = mode;
};
Engine.prototype.getAlphaMode = function () {
return this._alphaMode;
};
Engine.prototype.setAlphaTesting = function (enable) {
this._alphaTest = enable;
};
Engine.prototype.getAlphaTesting = function () {
return !!this._alphaTest;
};
// Textures
Engine.prototype.wipeCaches = function (bruteForce) {
if (this.preventCacheWipeBetweenFrames && !bruteForce) {
return;
}
this.resetTextureCache();
this._currentEffect = null;
// 6/8/2017: deltakosh: Should not be required anymore.
// This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
if (bruteForce) {
this._currentProgram = null;
this._stencilState.reset();
this._depthCullingState.reset();
this.setDepthFunctionToLessOrEqual();
this._alphaState.reset();
}
this._cachedVertexBuffers = null;
this._cachedIndexBuffer = null;
this._cachedEffectForVertexBuffers = null;
this._unbindVertexArrayObject();
this.bindIndexBuffer(null);
this.bindArrayBuffer(null);
};
/**
* Set the compressed texture format to use, based on the formats you have, and the formats
* supported by the hardware / browser.
*
* Khronos Texture Container (.ktx) files are used to support this. This format has the
* advantage of being specifically designed for OpenGL. Header elements directly correspond
* to API arguments needed to compressed textures. This puts the burden on the container
* generator to house the arcane code for determining these for current & future formats.
*
* for description see https://www.khronos.org/opengles/sdk/tools/KTX/
* for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
*
* Note: The result of this call is not taken into account when a texture is base64.
*
* @param {Array} formatsAvailable- The list of those format families you have created
* on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
*
* Current families are astc, dxt, pvrtc, etc2, & etc1.
* @returns The extension selected.
*/
Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
return this._textureFormatInUse = this._texturesSupported[i];
}
}
}
// actively set format to nothing, to allow this to be called more than once
// and possibly fail the 2nd time
this._textureFormatInUse = null;
return null;
};
Engine.prototype._createTexture = function () {
var texture = this._gl.createTexture();
if (!texture) {
throw new Error("Unable to create texture");
}
return texture;
};
/**
* Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
* @param {string} urlArg- This contains one of the following:
* 1. A conventional http URL, e.g. 'http://...' or 'file://...'
* 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
* 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
*
* @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
* @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
* @param {Scene} scene- Needed for loading to the correct scene.
* @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
* @param {callback} onLoad- Optional callback to be called upon successful completion.
* @param {callback} onError- Optional callback to be called upon failure.
* @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
* @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
* @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
*
* @returns {WebGLTexture} for assignment back into BABYLON.Texture
*/
Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
var _this = this;
if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (buffer === void 0) { buffer = null; }
if (fallBack === void 0) { fallBack = null; }
if (format === void 0) { format = null; }
var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
var fromData = url.substr(0, 5) === "data:";
var fromBlob = url.substr(0, 5) === "blob:";
var isBase64 = fromData && url.indexOf("base64") !== -1;
var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
// establish the file extension, if possible
var lastDot = url.lastIndexOf('.');
var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
var isDDS = this.getCaps().s3tc && (extension === ".dds");
var isTGA = (extension === ".tga");
// determine if a ktx file should be substituted
var isKTX = false;
if (this._textureFormatInUse && !isBase64 && !fallBack) {
url = url.substring(0, lastDot) + this._textureFormatInUse;
isKTX = true;
}
if (scene) {
scene._addPendingData(texture);
}
texture.url = url;
texture.generateMipMaps = !noMipmap;
texture.samplingMode = samplingMode;
texture.invertY = invertY;
if (!this._doNotHandleContextLost) {
// Keep a link to the buffer only if we plan to handle context lost
texture._buffer = buffer;
}
var onLoadObserver = null;
if (onLoad && !fallBack) {
onLoadObserver = texture.onLoadedObservable.add(onLoad);
}
if (!fallBack)
this._internalTexturesCache.push(texture);
var onerror = function (message, exception) {
if (scene) {
scene._removePendingData(texture);
}
if (onLoadObserver) {
texture.onLoadedObservable.remove(onLoadObserver);
}
// fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
if (isKTX) {
_this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
}
else if (BABYLON.Tools.UseFallbackTexture) {
_this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
}
if (onError) {
onError(message || "Unknown error", exception);
}
};
var callback = null;
// processing for non-image formats
if (isKTX || isTGA || isDDS) {
if (isKTX) {
callback = function (data) {
var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
_this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
ktx.uploadLevels(_this._gl, !noMipmap);
return false;
}, samplingMode);
};
}
else if (isTGA) {
callback = function (arrayBuffer) {
var data = new Uint8Array(arrayBuffer);
var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
_this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
return false;
}, samplingMode);
};
}
else if (isDDS) {
callback = function (data) {
var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
_this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
return false;
}, samplingMode);
};
}
if (!buffer) {
BABYLON.Tools.LoadFile(url, function (data) {
if (callback) {
callback(data);
}
}, undefined, scene ? scene.database : undefined, true, function (request, exception) {
onerror("Unable to load " + (request ? request.responseURL : url, exception));
});
}
else {
if (callback) {
callback(buffer);
}
}
// image format processing
}
else {
var onload = function (img) {
if (fromBlob && !_this._doNotHandleContextLost) {
// We need to store the image if we need to rebuild the texture
// in case of a webgl context lost
texture._buffer = img;
}
_this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
var gl = _this._gl;
var isPot = (img.width === potWidth && img.height === potHeight);
var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
if (isPot) {
gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
return false;
}
// Using shaders to rescale because canvas.drawImage is lossy
var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
_this._bindTextureDirectly(gl.TEXTURE_2D, source);
gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
_this._rescaleTexture(source, texture, scene, internalFormat, function () {
_this._releaseTexture(source);
_this._bindTextureDirectly(gl.TEXTURE_2D, texture);
continuationCallback();
});
return true;
}, samplingMode);
};
if (!fromData || isBase64)
if (buffer instanceof HTMLImageElement) {
onload(buffer);
}
else {
BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
}
else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
else
onload(buffer);
}
return texture;
};
Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
var _this = this;
var rtt = this.createRenderTargetTexture({
width: destination.width,
height: destination.height,
}, {
generateMipMaps: false,
type: Engine.TEXTURETYPE_UNSIGNED_INT,
samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
generateDepthBuffer: false,
generateStencilBuffer: false
});
if (!this._rescalePostProcess) {
this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
}
this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
_this._rescalePostProcess.onApply = function (effect) {
effect._bindTexture("textureSampler", source);
};
var hostingScene = scene;
if (!hostingScene) {
hostingScene = _this.scenes[_this.scenes.length - 1];
}
hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
_this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
_this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
_this.unBindFramebuffer(rtt);
_this._releaseTexture(rtt);
if (onComplete) {
onComplete();
}
});
};
Engine.prototype._getInternalFormat = function (format) {
var internalFormat = this._gl.RGBA;
switch (format) {
case Engine.TEXTUREFORMAT_ALPHA:
internalFormat = this._gl.ALPHA;
break;
case Engine.TEXTUREFORMAT_LUMINANCE:
internalFormat = this._gl.LUMINANCE;
break;
case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
internalFormat = this._gl.LUMINANCE_ALPHA;
break;
case Engine.TEXTUREFORMAT_RGB:
internalFormat = this._gl.RGB;
break;
case Engine.TEXTUREFORMAT_RGBA:
internalFormat = this._gl.RGBA;
break;
}
return internalFormat;
};
Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
if (compression === void 0) { compression = null; }
if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
if (!texture) {
return;
}
var internalFormat = this._getInternalFormat(format);
var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
var textureType = this._getWebGLTextureType(type);
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
if (!this._doNotHandleContextLost) {
texture._bufferView = data;
texture.format = format;
texture.type = type;
texture.invertY = invertY;
texture._compression = compression;
}
if (texture.width % 4 !== 0) {
this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
}
if (compression && data) {
this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
}
else {
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
}
if (texture.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
this.resetTextureCache();
texture.isReady = true;
};
Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
if (compression === void 0) { compression = null; }
if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.format = format;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
texture.invertY = invertY;
texture._compression = compression;
texture.type = type;
if (!this._doNotHandleContextLost) {
texture._bufferView = data;
}
this.updateRawTexture(texture, data, format, invertY, compression, type);
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
// Filters
var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
if (generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
this._internalTexturesCache.push(texture);
return texture;
};
Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
texture.baseWidth = width;
texture.baseHeight = height;
if (generateMipMaps) {
width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
}
this.resetTextureCache();
texture.width = width;
texture.height = height;
texture.isReady = false;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
this.updateTextureSamplingMode(samplingMode, texture);
this._internalTexturesCache.push(texture);
return texture;
};
Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
if (texture.isCube) {
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
}
else if (texture.is3D) {
this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
}
else {
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
}
texture.samplingMode = samplingMode;
};
Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
if (premulAlpha === void 0) { premulAlpha = false; }
if (!texture) {
return;
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
if (premulAlpha) {
this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
}
var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
if (texture.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
if (premulAlpha) {
this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
}
this.resetTextureCache();
texture.isReady = true;
};
Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
if (!texture || texture._isDisabled) {
return;
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
try {
// Testing video texture support
if (this._videoTextureSupported === undefined) {
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
if (this._gl.getError() !== 0) {
this._videoTextureSupported = false;
}
else {
this._videoTextureSupported = true;
}
}
// Copy video through the current working canvas if video texture is not supported
if (!this._videoTextureSupported) {
if (!texture._workingCanvas) {
texture._workingCanvas = document.createElement("canvas");
var context = texture._workingCanvas.getContext("2d");
if (!context) {
throw new Error("Unable to get 2d context");
}
texture._workingContext = context;
texture._workingCanvas.width = texture.width;
texture._workingCanvas.height = texture.height;
}
texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
}
else {
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
}
if (texture.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
this.resetTextureCache();
texture.isReady = true;
}
catch (ex) {
// Something unexpected
// Let's disable the texture
texture._isDisabled = true;
}
};
Engine.prototype.createRenderTargetTexture = function (size, options) {
var fullOptions = new RenderTargetCreationOptions();
if (options !== undefined && typeof options === "object") {
fullOptions.generateMipMaps = options.generateMipMaps;
fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
}
else {
fullOptions.generateMipMaps = options;
fullOptions.generateDepthBuffer = true;
fullOptions.generateStencilBuffer = false;
fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
}
if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
// if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
}
else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
// if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
}
var gl = this._gl;
var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
this._bindTextureDirectly(gl.TEXTURE_2D, texture);
var width = size.width || size;
var height = size.height || size;
var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
}
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
// Create the framebuffer
var framebuffer = gl.createFramebuffer();
this.bindUnboundFramebuffer(framebuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
if (fullOptions.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
// Unbind
this._bindTextureDirectly(gl.TEXTURE_2D, null);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
this.bindUnboundFramebuffer(null);
texture._framebuffer = framebuffer;
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.isReady = true;
texture.samples = 1;
texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
texture.samplingMode = fullOptions.samplingMode;
texture.type = fullOptions.type;
texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
this.resetTextureCache();
this._internalTexturesCache.push(texture);
return texture;
};
Engine.prototype.createMultipleRenderTarget = function (size, options) {
var generateMipMaps = false;
var generateDepthBuffer = true;
var generateStencilBuffer = false;
var generateDepthTexture = false;
var textureCount = 1;
var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
var types = [], samplingModes = [];
if (options !== undefined) {
generateMipMaps = options.generateMipMaps;
generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
generateStencilBuffer = options.generateStencilBuffer;
generateDepthTexture = options.generateDepthTexture;
textureCount = options.textureCount || 1;
if (options.types) {
types = options.types;
}
if (options.samplingModes) {
samplingModes = options.samplingModes;
}
}
var gl = this._gl;
// Create the framebuffer
var framebuffer = gl.createFramebuffer();
this.bindUnboundFramebuffer(framebuffer);
var width = size.width || size;
var height = size.height || size;
var textures = [];
var attachments = [];
var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
for (var i = 0; i < textureCount; i++) {
var samplingMode = samplingModes[i] || defaultSamplingMode;
var type = types[i] || defaultType;
if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
// if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
}
else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
// if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
}
var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
type = Engine.TEXTURETYPE_UNSIGNED_INT;
BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
}
var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
textures.push(texture);
attachments.push(attachment);
gl.activeTexture(gl["TEXTURE" + i]);
gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
if (generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
// Unbind
this._bindTextureDirectly(gl.TEXTURE_2D, null);
texture._framebuffer = framebuffer;
texture._depthStencilBuffer = depthStencilBuffer;
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.isReady = true;
texture.samples = 1;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
texture.type = type;
texture._generateDepthBuffer = generateDepthBuffer;
texture._generateStencilBuffer = generateStencilBuffer;
this._internalTexturesCache.push(texture);
}
if (generateDepthTexture && this._caps.depthTextureExtension) {
// Depth texture
var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
depthTexture._framebuffer = framebuffer;
depthTexture.baseWidth = width;
depthTexture.baseHeight = height;
depthTexture.width = width;
depthTexture.height = height;
depthTexture.isReady = true;
depthTexture.samples = 1;
depthTexture.generateMipMaps = generateMipMaps;
depthTexture.samplingMode = gl.NEAREST;
depthTexture._generateDepthBuffer = generateDepthBuffer;
depthTexture._generateStencilBuffer = generateStencilBuffer;
textures.push(depthTexture);
this._internalTexturesCache.push(depthTexture);
}
gl.drawBuffers(attachments);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
this.bindUnboundFramebuffer(null);
this.resetTextureCache();
return textures;
};
Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
if (samples === void 0) { samples = 1; }
var depthStencilBuffer = null;
var gl = this._gl;
// Create the depth/stencil buffer
if (generateStencilBuffer) {
depthStencilBuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
if (samples > 1) {
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
}
else {
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
}
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
}
else if (generateDepthBuffer) {
depthStencilBuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
if (samples > 1) {
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
}
else {
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
}
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
}
return depthStencilBuffer;
};
Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
if (this.webGLVersion < 2 || !texture) {
return 1;
}
if (texture.samples === samples) {
return samples;
}
var gl = this._gl;
samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
// Dispose previous render buffers
if (texture._depthStencilBuffer) {
gl.deleteRenderbuffer(texture._depthStencilBuffer);
}
if (texture._MSAAFramebuffer) {
gl.deleteFramebuffer(texture._MSAAFramebuffer);
}
if (texture._MSAARenderBuffer) {
gl.deleteRenderbuffer(texture._MSAARenderBuffer);
}
if (samples > 1) {
var framebuffer = gl.createFramebuffer();
if (!framebuffer) {
throw new Error("Unable to create multi sampled framebuffer");
}
texture._MSAAFramebuffer = framebuffer;
this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
var colorRenderbuffer = gl.createRenderbuffer();
if (!colorRenderbuffer) {
throw new Error("Unable to create multi sampled framebuffer");
}
gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
texture._MSAARenderBuffer = colorRenderbuffer;
}
else {
this.bindUnboundFramebuffer(texture._framebuffer);
}
texture.samples = samples;
texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
this.bindUnboundFramebuffer(null);
return samples;
};
Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
};
Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
};
Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
var gl = this._gl;
var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
var generateMipMaps = true;
var generateDepthBuffer = true;
var generateStencilBuffer = false;
var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
if (options !== undefined) {
generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
if (options.samplingMode !== undefined) {
samplingMode = options.samplingMode;
}
}
texture.isCube = true;
texture.generateMipMaps = generateMipMaps;
texture.samples = 1;
texture.samplingMode = samplingMode;
var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
for (var face = 0; face < 6; face++) {
gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
}
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
// Create the framebuffer
var framebuffer = gl.createFramebuffer();
this.bindUnboundFramebuffer(framebuffer);
texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
// Mipmaps
if (texture.generateMipMaps) {
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
}
// Unbind
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
this.bindUnboundFramebuffer(null);
texture._framebuffer = framebuffer;
texture.width = size;
texture.height = size;
texture.isReady = true;
this.resetTextureCache();
this._internalTexturesCache.push(texture);
return texture;
};
Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
var _this = this;
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (forcedExtension === void 0) { forcedExtension = null; }
var callback = function (loadData) {
if (!loadData) {
if (onLoad) {
onLoad(null);
}
return;
}
var texture = loadData.texture;
texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
texture._lodGenerationScale = scale;
texture._lodGenerationOffset = offset;
if (_this._caps.textureLOD) {
// Do not add extra process if texture lod is supported.
if (onLoad) {
onLoad(texture);
}
return;
}
var mipSlices = 3;
var gl = _this._gl;
var width = loadData.width;
if (!width) {
return;
}
var textures = [];
for (var i = 0; i < mipSlices; i++) {
//compute LOD from even spacing in smoothness (matching shader calculation)
var smoothness = i / (mipSlices - 1);
var roughness = 1 - smoothness;
var minLODIndex = offset; // roughness = 0
var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
glTextureFromLod.isCube = true;
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
if (loadData.isDDS) {
var info = loadData.info;
var data = loadData.data;
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
}
else {
BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
}
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
// Wrap in a base texture for easy binding.
var lodTexture = new BABYLON.BaseTexture(scene);
lodTexture.isCube = true;
lodTexture._texture = glTextureFromLod;
glTextureFromLod.isReady = true;
textures.push(lodTexture);
}
texture._lodTextureHigh = textures[2];
texture._lodTextureMid = textures[1];
texture._lodTextureLow = textures[0];
if (onLoad) {
onLoad(texture);
}
};
return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
};
Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
var _this = this;
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (forcedExtension === void 0) { forcedExtension = null; }
var gl = this._gl;
var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
texture.isCube = true;
texture.url = rootUrl;
texture.generateMipMaps = !noMipmap;
if (!this._doNotHandleContextLost) {
texture._extension = forcedExtension;
texture._files = files;
}
var isKTX = false;
var isDDS = false;
var lastDot = rootUrl.lastIndexOf('.');
var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
if (this._textureFormatInUse) {
extension = this._textureFormatInUse;
rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
isKTX = true;
}
else {
isDDS = (extension === ".dds");
}
var onerror = function (request, exception) {
if (onError && request) {
onError(request.status + " " + request.statusText, exception);
}
};
if (isKTX) {
BABYLON.Tools.LoadFile(rootUrl, function (data) {
var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
ktx.uploadLevels(_this._gl, !noMipmap);
_this.setCubeMapTextureParams(gl, loadMipmap);
texture.width = ktx.pixelWidth;
texture.height = ktx.pixelHeight;
texture.isReady = true;
}, undefined, undefined, true, onerror);
}
else if (isDDS) {
if (files && files.length === 6) {
cascadeLoadFiles(rootUrl, scene, function (imgs) {
var info;
var loadMipmap = false;
var width = 0;
for (var index = 0; index < imgs.length; index++) {
var data = imgs[index];
info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
}
texture.width = info.width;
texture.height = info.height;
texture.type = info.textureType;
width = info.width;
}
_this.setCubeMapTextureParams(gl, loadMipmap);
texture.isReady = true;
if (onLoad) {
onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
}
}, files, onError);
}
else {
BABYLON.Tools.LoadFile(rootUrl, function (data) {
var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
}
_this.setCubeMapTextureParams(gl, loadMipmap);
texture.width = info.width;
texture.height = info.height;
texture.isReady = true;
texture.type = info.textureType;
if (onLoad) {
onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
}
}, undefined, undefined, true, onerror);
}
}
else {
if (!files) {
throw new Error("Cannot load cubemap because files were not defined");
}
cascadeLoadImgs(rootUrl, scene, function (imgs) {
var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
var height = width;
_this._prepareWorkingCanvas();
if (!_this._workingCanvas || !_this._workingContext) {
return;
}
_this._workingCanvas.width = width;
_this._workingCanvas.height = height;
var faces = [
gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
];
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
for (var index = 0; index < faces.length; index++) {
_this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
}
if (!noMipmap) {
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
}
_this.setCubeMapTextureParams(gl, !noMipmap);
texture.width = width;
texture.height = height;
texture.isReady = true;
if (format) {
texture.format = format;
}
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad();
}
}, files, onError);
}
this._internalTexturesCache.push(texture);
return texture;
};
Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
this.resetTextureCache();
};
Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
if (compression === void 0) { compression = null; }
if (level === void 0) { level = 0; }
texture._bufferViewArray = data;
texture.format = format;
texture.type = type;
texture.invertY = invertY;
texture._compression = compression;
var gl = this._gl;
var textureType = this._getWebGLTextureType(type);
var internalFormat = this._getInternalFormat(format);
var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
var needConversion = false;
if (internalFormat === gl.RGB) {
internalFormat = gl.RGBA;
needConversion = true;
}
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
if (texture.width % 4 !== 0) {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
}
// Data are known to be in +X +Y +Z -X -Y -Z
for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
var faceData = data[faceIndex];
if (compression) {
gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
}
else {
if (needConversion) {
faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
}
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
}
}
var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
if (isPot && texture.generateMipMaps && level === 0) {
this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
}
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
this.resetTextureCache();
texture.isReady = true;
};
Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
if (compression === void 0) { compression = null; }
var gl = this._gl;
var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
texture.isCube = true;
texture.generateMipMaps = generateMipMaps;
texture.format = format;
texture.type = type;
if (!this._doNotHandleContextLost) {
texture._bufferViewArray = data;
}
var textureType = this._getWebGLTextureType(type);
var internalFormat = this._getInternalFormat(format);
if (internalFormat === gl.RGB) {
internalFormat = gl.RGBA;
}
var width = size;
var height = width;
texture.width = width;
texture.height = height;
// Double check on POT to generate Mips.
var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
if (!isPot) {
generateMipMaps = false;
}
// Upload data if needed. The texture won't be ready until then.
if (data) {
this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
}
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
// Filters
if (data && generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
}
if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
}
else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
}
else {
var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
}
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
return texture;
};
Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
var _this = this;
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
if (invertY === void 0) { invertY = false; }
var gl = this._gl;
var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
scene._addPendingData(texture);
texture.url = url;
this._internalTexturesCache.push(texture);
var onerror = function (request, exception) {
scene._removePendingData(texture);
if (onError && request) {
onError(request.status + " " + request.statusText, exception);
}
};
var internalCallback = function (data) {
var width = texture.width;
var faceDataArrays = callback(data);
if (!faceDataArrays) {
return;
}
if (mipmmapGenerator) {
var textureType = _this._getWebGLTextureType(type);
var internalFormat = _this._getInternalFormat(format);
var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
var needConversion = false;
if (internalFormat === gl.RGB) {
internalFormat = gl.RGBA;
needConversion = true;
}
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
var mipData = mipmmapGenerator(faceDataArrays);
for (var level = 0; level < mipData.length; level++) {
var mipSize = width >> level;
for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
var mipFaceData = mipData[level][faceIndex];
if (needConversion) {
mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
}
gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
}
}
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
}
else {
texture.generateMipMaps = !noMipmap;
_this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
}
texture.isReady = true;
_this.resetTextureCache();
scene._removePendingData(texture);
if (onLoad) {
onLoad();
}
};
BABYLON.Tools.LoadFile(url, function (data) {
internalCallback(data);
}, undefined, scene.database, true, onerror);
return texture;
};
;
Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
if (compression === void 0) { compression = null; }
var internalFormat = this._getInternalFormat(format);
this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
if (!this._doNotHandleContextLost) {
texture._bufferView = data;
texture.format = format;
texture.invertY = invertY;
texture._compression = compression;
}
if (texture.width % 4 !== 0) {
this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
}
if (compression && data) {
this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
}
else {
this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
}
if (texture.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_3D);
}
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
this.resetTextureCache();
texture.isReady = true;
};
Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
if (compression === void 0) { compression = null; }
var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
texture.baseWidth = width;
texture.baseHeight = height;
texture.baseDepth = depth;
texture.width = width;
texture.height = height;
texture.depth = depth;
texture.format = format;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
texture.is3D = true;
if (!this._doNotHandleContextLost) {
texture._bufferView = data;
}
this.updateRawTexture3D(texture, data, format, invertY, compression);
this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
// Filters
var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
if (generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_3D);
}
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
this._internalTexturesCache.push(texture);
return texture;
};
Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
var gl = this._gl;
if (!gl) {
return;
}
var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
if (!noMipmap && !isCompressed) {
gl.generateMipmap(gl.TEXTURE_2D);
}
this._bindTextureDirectly(gl.TEXTURE_2D, null);
this.resetTextureCache();
if (scene) {
scene._removePendingData(texture);
}
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
};
Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
var _this = this;
if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
var gl = this._gl;
if (!gl) {
return;
}
if (!texture._webGLTexture) {
this.resetTextureCache();
if (scene) {
scene._removePendingData(texture);
}
return;
}
this._bindTextureDirectly(gl.TEXTURE_2D, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = potWidth;
texture.height = potHeight;
texture.isReady = true;
if (processFunction(potWidth, potHeight, function () {
_this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
})) {
// Returning as texture needs extra async steps
return;
}
this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
};
Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
// Create new RGBA data container.
var rgbaData;
if (textureType === Engine.TEXTURETYPE_FLOAT) {
rgbaData = new Float32Array(width * height * 4);
}
else {
rgbaData = new Uint32Array(width * height * 4);
}
// Convert each pixel.
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
var index = (y * width + x) * 3;
var newIndex = (y * width + x) * 4;
// Map Old Value to new value.
rgbaData[newIndex + 0] = rgbData[index + 0];
rgbaData[newIndex + 1] = rgbData[index + 1];
rgbaData[newIndex + 2] = rgbData[index + 2];
// Add fully opaque alpha channel.
rgbaData[newIndex + 3] = 1;
}
}
return rgbaData;
};
Engine.prototype._releaseFramebufferObjects = function (texture) {
var gl = this._gl;
if (texture._framebuffer) {
gl.deleteFramebuffer(texture._framebuffer);
texture._framebuffer = null;
}
if (texture._depthStencilBuffer) {
gl.deleteRenderbuffer(texture._depthStencilBuffer);
texture._depthStencilBuffer = null;
}
if (texture._MSAAFramebuffer) {
gl.deleteFramebuffer(texture._MSAAFramebuffer);
texture._MSAAFramebuffer = null;
}
if (texture._MSAARenderBuffer) {
gl.deleteRenderbuffer(texture._MSAARenderBuffer);
texture._MSAARenderBuffer = null;
}
};
Engine.prototype._releaseTexture = function (texture) {
var gl = this._gl;
this._releaseFramebufferObjects(texture);
gl.deleteTexture(texture._webGLTexture);
// Unbind channels
this.unbindAllTextures();
var index = this._internalTexturesCache.indexOf(texture);
if (index !== -1) {
this._internalTexturesCache.splice(index, 1);
}
// Integrated fixed lod samplers.
if (texture._lodTextureHigh) {
texture._lodTextureHigh.dispose();
}
if (texture._lodTextureMid) {
texture._lodTextureMid.dispose();
}
if (texture._lodTextureLow) {
texture._lodTextureLow.dispose();
}
};
Engine.prototype.setProgram = function (program) {
if (this._currentProgram !== program) {
this._gl.useProgram(program);
this._currentProgram = program;
}
};
Engine.prototype.bindSamplers = function (effect) {
this.setProgram(effect.getProgram());
var samplers = effect.getSamplers();
for (var index = 0; index < samplers.length; index++) {
var uniform = effect.getUniform(samplers[index]);
if (uniform) {
this._boundUniforms[index] = uniform;
}
}
this._currentEffect = null;
};
Engine.prototype._activateTextureChannel = function (channel) {
if (this._activeChannel !== channel) {
this._gl.activeTexture(this._gl.TEXTURE0 + channel);
this._activeChannel = channel;
}
};
Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
var index = this._boundTexturesOrder.indexOf(internalTexture);
if (index > -1 && index !== this._boundTexturesOrder.length - 1) {
this._boundTexturesOrder.splice(index, 1);
this._boundTexturesOrder.push(internalTexture);
}
};
Engine.prototype._removeDesignatedSlot = function (internalTexture) {
var currentSlot = internalTexture._designatedSlot;
internalTexture._designatedSlot = -1;
var index = this._boundTexturesOrder.indexOf(internalTexture);
if (index > -1) {
this._boundTexturesOrder.splice(index, 1);
}
return currentSlot;
};
Engine.prototype._bindTextureDirectly = function (target, texture, isPartOfTextureArray) {
if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
var currentTextureBound = this._boundTexturesCache[this._activeChannel];
var isTextureForRendering = texture && texture._initialSlot > -1;
if (currentTextureBound !== texture) {
if (currentTextureBound) {
this._removeDesignatedSlot(currentTextureBound);
}
this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
if (this._activeChannel >= 0) {
this._boundTexturesCache[this._activeChannel] = texture;
if (isTextureForRendering) {
this._boundTexturesOrder.push(texture);
}
}
}
if (isTextureForRendering) {
texture._designatedSlot = this._activeChannel;
if (!isPartOfTextureArray) {
this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
}
}
};
Engine.prototype._bindTexture = function (channel, texture) {
if (channel < 0) {
return;
}
if (texture) {
channel = this._getCorrectTextureChannel(channel, texture);
}
this._activateTextureChannel(channel);
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
};
Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
};
Engine.prototype.unbindAllTextures = function () {
for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
this._activateTextureChannel(channel);
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
if (this.webGLVersion > 1) {
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
}
}
};
Engine.prototype.setTexture = function (channel, uniform, texture) {
if (channel < 0) {
return;
}
if (uniform) {
this._boundUniforms[channel] = uniform;
}
this._setTexture(channel, texture);
};
Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
if (!internalTexture) {
return -1;
}
internalTexture._initialSlot = channel;
if (channel !== internalTexture._designatedSlot) {
if (internalTexture._designatedSlot > -1) {
channel = internalTexture._designatedSlot;
}
else {
if (this._nextFreeTextureSlot > -1) {
channel = this._nextFreeTextureSlot;
this._nextFreeTextureSlot++;
if (this._nextFreeTextureSlot >= this._caps.maxTexturesImageUnits) {
this._nextFreeTextureSlot = -1; // No more free slots, we will recycle
}
}
else {
channel = this._removeDesignatedSlot(this._boundTexturesOrder[0]);
}
}
}
return channel;
};
Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
var uniform = this._boundUniforms[sourceSlot];
this._gl.uniform1i(uniform, destination);
};
Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
// Not ready?
if (!texture) {
if (this._boundTexturesCache[channel] != null) {
this._activateTextureChannel(channel);
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
if (this.webGLVersion > 1) {
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
}
}
return false;
}
// Video
var alreadyActivated = false;
if (texture.video) {
this._activateTextureChannel(channel);
alreadyActivated = true;
texture.update();
}
else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
texture.delayLoad();
return false;
}
var internalTexture;
if (texture.isReady()) {
internalTexture = texture.getInternalTexture();
}
else if (texture.isCube) {
internalTexture = this.emptyCubeTexture;
}
else if (texture.is3D) {
internalTexture = this.emptyTexture3D;
}
else {
internalTexture = this.emptyTexture;
}
if (!isPartOfTextureArray) {
channel = this._getCorrectTextureChannel(channel, internalTexture);
}
if (this._boundTexturesCache[channel] === internalTexture) {
this._moveBoundTextureOnTop(internalTexture);
if (!isPartOfTextureArray) {
this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
}
return false;
}
if (!alreadyActivated) {
this._activateTextureChannel(channel);
}
if (internalTexture && internalTexture.is3D) {
this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
internalTexture._cachedWrapU = texture.wrapU;
switch (texture.wrapU) {
case BABYLON.Texture.WRAP_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
break;
case BABYLON.Texture.CLAMP_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
break;
case BABYLON.Texture.MIRROR_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
break;
}
}
if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
internalTexture._cachedWrapV = texture.wrapV;
switch (texture.wrapV) {
case BABYLON.Texture.WRAP_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
break;
case BABYLON.Texture.CLAMP_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
break;
case BABYLON.Texture.MIRROR_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
break;
}
}
if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
internalTexture._cachedWrapR = texture.wrapR;
switch (texture.wrapV) {
case BABYLON.Texture.WRAP_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
break;
case BABYLON.Texture.CLAMP_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
break;
case BABYLON.Texture.MIRROR_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
break;
}
}
this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
}
else if (internalTexture && internalTexture.isCube) {
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
// CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
}
this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
}
else {
this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
internalTexture._cachedWrapU = texture.wrapU;
switch (texture.wrapU) {
case BABYLON.Texture.WRAP_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
break;
case BABYLON.Texture.CLAMP_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
break;
case BABYLON.Texture.MIRROR_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
break;
}
}
if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
internalTexture._cachedWrapV = texture.wrapV;
switch (texture.wrapV) {
case BABYLON.Texture.WRAP_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
break;
case BABYLON.Texture.CLAMP_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
break;
case BABYLON.Texture.MIRROR_ADDRESSMODE:
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
break;
}
}
this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
}
return true;
};
Engine.prototype.setTextureArray = function (channel, uniform, textures) {
if (channel < 0 || !uniform) {
return;
}
if (!this._textureUnits || this._textureUnits.length !== textures.length) {
this._textureUnits = new Int32Array(textures.length);
}
for (var i = 0; i < textures.length; i++) {
this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
}
this._gl.uniform1iv(uniform, this._textureUnits);
for (var index = 0; index < textures.length; index++) {
this._setTexture(this._textureUnits[index], textures[index], true);
}
};
Engine.prototype._setAnisotropicLevel = function (key, texture) {
var internalTexture = texture.getInternalTexture();
if (!internalTexture) {
return;
}
var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
var value = texture.anisotropicFilteringLevel;
if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
&& internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
&& internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
}
if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
internalTexture._cachedAnisotropicFilteringLevel = value;
}
};
Engine.prototype.readPixels = function (x, y, width, height) {
var data = new Uint8Array(height * width * 4);
this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
return data;
};
/**
* Add an externaly attached data from its key.
* This method call will fail and return false, if such key already exists.
* If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
* @param key the unique key that identifies the data
* @param data the data object to associate to the key for this Engine instance
* @return true if no such key were already present and the data was added successfully, false otherwise
*/
Engine.prototype.addExternalData = function (key, data) {
if (!this._externalData) {
this._externalData = new BABYLON.StringDictionary();
}
return this._externalData.add(key, data);
};
/**
* Get an externaly attached data from its key
* @param key the unique key that identifies the data
* @return the associated data, if present (can be null), or undefined if not present
*/
Engine.prototype.getExternalData = function (key) {
if (!this._externalData) {
this._externalData = new BABYLON.StringDictionary();
}
return this._externalData.get(key);
};
/**
* Get an externaly attached data from its key, create it using a factory if it's not already present
* @param key the unique key that identifies the data
* @param factory the factory that will be called to create the instance if and only if it doesn't exists
* @return the associated data, can be null if the factory returned null.
*/
Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
if (!this._externalData) {
this._externalData = new BABYLON.StringDictionary();
}
return this._externalData.getOrAddWithFactory(key, factory);
};
/**
* Remove an externaly attached data from the Engine instance
* @param key the unique key that identifies the data
* @return true if the data was successfully removed, false if it doesn't exist
*/
Engine.prototype.removeExternalData = function (key) {
if (!this._externalData) {
this._externalData = new BABYLON.StringDictionary();
}
return this._externalData.remove(key);
};
Engine.prototype.unbindAllAttributes = function () {
if (this._mustWipeVertexAttributes) {
this._mustWipeVertexAttributes = false;
for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
this._gl.disableVertexAttribArray(i);
this._vertexAttribArraysEnabled[i] = false;
this._currentBufferPointers[i].active = false;
}
return;
}
for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
continue;
}
this._gl.disableVertexAttribArray(i);
this._vertexAttribArraysEnabled[i] = false;
this._currentBufferPointers[i].active = false;
}
};
Engine.prototype.releaseEffects = function () {
for (var name in this._compiledEffects) {
this._deleteProgram(this._compiledEffects[name]._program);
}
this._compiledEffects = {};
};
// Dispose
Engine.prototype.dispose = function () {
this.hideLoadingUI();
this.stopRenderLoop();
// Release postProcesses
while (this.postProcesses.length) {
this.postProcesses[0].dispose();
}
// Empty texture
if (this._emptyTexture) {
this._releaseTexture(this._emptyTexture);
this._emptyTexture = null;
}
if (this._emptyCubeTexture) {
this._releaseTexture(this._emptyCubeTexture);
this._emptyCubeTexture = null;
}
// Rescale PP
if (this._rescalePostProcess) {
this._rescalePostProcess.dispose();
}
// Release scenes
while (this.scenes.length) {
this.scenes[0].dispose();
}
// Release audio engine
if (Engine.audioEngine) {
Engine.audioEngine.dispose();
}
// Release effects
this.releaseEffects();
// Unbind
this.unbindAllAttributes();
if (this._dummyFramebuffer) {
this._gl.deleteFramebuffer(this._dummyFramebuffer);
}
//WebVR
this.disableVR();
// Events
if (BABYLON.Tools.IsWindowObjectExist()) {
window.removeEventListener("blur", this._onBlur);
window.removeEventListener("focus", this._onFocus);
window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
if (this._renderingCanvas) {
this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
if (!this._doNotHandleContextLost) {
this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
}
}
document.removeEventListener("fullscreenchange", this._onFullscreenChange);
document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
document.removeEventListener("pointerlockchange", this._onPointerLockChange);
document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
if (this._onVrDisplayConnect) {
window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
if (this._onVrDisplayDisconnect) {
window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
}
if (this._onVrDisplayPresentChange) {
window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
}
this._onVrDisplayConnect = null;
this._onVrDisplayDisconnect = null;
}
}
// Remove from Instances
var index = Engine.Instances.indexOf(this);
if (index >= 0) {
Engine.Instances.splice(index, 1);
}
this._workingCanvas = null;
this._workingContext = null;
this._currentBufferPointers = [];
this._renderingCanvas = null;
this._currentProgram = null;
this.onResizeObservable.clear();
this.onCanvasBlurObservable.clear();
this.onCanvasFocusObservable.clear();
this.onCanvasPointerOutObservable.clear();
this.onBeginFrameObservable.clear();
this.onEndFrameObservable.clear();
BABYLON.Effect.ResetCache();
};
// Loading screen
Engine.prototype.displayLoadingUI = function () {
if (!BABYLON.Tools.IsWindowObjectExist()) {
return;
}
var loadingScreen = this.loadingScreen;
if (loadingScreen) {
loadingScreen.displayLoadingUI();
}
};
Engine.prototype.hideLoadingUI = function () {
if (!BABYLON.Tools.IsWindowObjectExist()) {
return;
}
var loadingScreen = this.loadingScreen;
if (loadingScreen) {
loadingScreen.hideLoadingUI();
}
};
Object.defineProperty(Engine.prototype, "loadingScreen", {
get: function () {
if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
return this._loadingScreen;
},
set: function (loadingScreen) {
this._loadingScreen = loadingScreen;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "loadingUIText", {
set: function (text) {
this.loadingScreen.loadingUIText = text;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
set: function (color) {
this.loadingScreen.loadingUIBackgroundColor = color;
},
enumerable: true,
configurable: true
});
Engine.prototype.attachContextLostEvent = function (callback) {
if (this._renderingCanvas) {
this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
}
};
Engine.prototype.attachContextRestoredEvent = function (callback) {
if (this._renderingCanvas) {
this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
}
};
Engine.prototype.getVertexShaderSource = function (program) {
var shaders = this._gl.getAttachedShaders(program);
if (!shaders) {
return null;
}
return this._gl.getShaderSource(shaders[0]);
};
Engine.prototype.getFragmentShaderSource = function (program) {
var shaders = this._gl.getAttachedShaders(program);
if (!shaders) {
return null;
}
return this._gl.getShaderSource(shaders[1]);
};
Engine.prototype.getError = function () {
return this._gl.getError();
};
// FPS
Engine.prototype.getFps = function () {
return this._fps;
};
Engine.prototype.getDeltaTime = function () {
return this._deltaTime;
};
Engine.prototype._measureFps = function () {
this._performanceMonitor.sampleFrame();
this._fps = this._performanceMonitor.averageFPS;
this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
};
Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
if (faceIndex === void 0) { faceIndex = -1; }
var gl = this._gl;
if (!this._dummyFramebuffer) {
var dummy = gl.createFramebuffer();
if (!dummy) {
throw new Error("Unable to create dummy framebuffer");
}
this._dummyFramebuffer = dummy;
}
gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
if (faceIndex > -1) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
}
else {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
}
var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
var buffer;
switch (readType) {
case gl.UNSIGNED_BYTE:
buffer = new Uint8Array(4 * width * height);
readType = gl.UNSIGNED_BYTE;
break;
default:
buffer = new Float32Array(4 * width * height);
readType = gl.FLOAT;
break;
}
gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
return buffer;
};
Engine.prototype._canRenderToFloatFramebuffer = function () {
if (this._webGLVersion > 1) {
return this._caps.colorBufferFloat;
}
return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
};
Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
if (this._webGLVersion > 1) {
return this._caps.colorBufferFloat;
}
return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
};
// Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
Engine.prototype._canRenderToFramebuffer = function (type) {
var gl = this._gl;
//clear existing errors
while (gl.getError() !== gl.NO_ERROR) { }
var successful = true;
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
var fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
successful = successful && (gl.getError() === gl.NO_ERROR);
//try render by clearing frame buffer's color buffer
if (successful) {
gl.clear(gl.COLOR_BUFFER_BIT);
successful = successful && (gl.getError() === gl.NO_ERROR);
}
//try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
if (successful) {
//in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
var readFormat = gl.RGBA;
var readType = gl.UNSIGNED_BYTE;
var buffer = new Uint8Array(4);
gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
successful = successful && (gl.getError() === gl.NO_ERROR);
}
//clean up
gl.deleteTexture(texture);
gl.deleteFramebuffer(fb);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
//clear accumulated errors
while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
return successful;
};
Engine.prototype._getWebGLTextureType = function (type) {
if (type === Engine.TEXTURETYPE_FLOAT) {
return this._gl.FLOAT;
}
else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
// Add Half Float Constant.
return this._gl.HALF_FLOAT_OES;
}
return this._gl.UNSIGNED_BYTE;
};
;
Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
if (this._webGLVersion === 1) {
return this._gl.RGBA;
}
if (type === Engine.TEXTURETYPE_FLOAT) {
return this._gl.RGBA32F;
}
else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
return this._gl.RGBA16F;
}
return this._gl.RGBA;
};
;
Engine.prototype.createQuery = function () {
return this._gl.createQuery();
};
Engine.prototype.deleteQuery = function (query) {
this._gl.deleteQuery(query);
return this;
};
Engine.prototype.isQueryResultAvailable = function (query) {
return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
};
Engine.prototype.getQueryResult = function (query) {
return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
};
Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
var glAlgorithm = this.getGlAlgorithmType(algorithmType);
this._gl.beginQuery(glAlgorithm, query);
return this;
};
Engine.prototype.endOcclusionQuery = function (algorithmType) {
var glAlgorithm = this.getGlAlgorithmType(algorithmType);
this._gl.endQuery(glAlgorithm);
return this;
};
/* Time queries */
Engine.prototype._createTimeQuery = function () {
var timerQuery = this._caps.timerQuery;
if (timerQuery.createQueryEXT) {
return timerQuery.createQueryEXT();
}
return this.createQuery();
};
Engine.prototype._deleteTimeQuery = function (query) {
var timerQuery = this._caps.timerQuery;
if (timerQuery.deleteQueryEXT) {
timerQuery.deleteQueryEXT(query);
return;
}
this.deleteQuery(query);
};
Engine.prototype._getTimeQueryResult = function (query) {
var timerQuery = this._caps.timerQuery;
if (timerQuery.getQueryObjectEXT) {
return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
}
return this.getQueryResult(query);
};
Engine.prototype._getTimeQueryAvailability = function (query) {
var timerQuery = this._caps.timerQuery;
if (timerQuery.getQueryObjectEXT) {
return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
}
return this.isQueryResultAvailable(query);
};
Engine.prototype.startTimeQuery = function () {
var timerQuery = this._caps.timerQuery;
if (!timerQuery) {
return null;
}
var token = new BABYLON._TimeToken();
this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
if (this._caps.canUseTimestampForTimerQuery) {
token._startTimeQuery = this._createTimeQuery();
timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
}
else {
if (this._currentNonTimestampToken) {
return this._currentNonTimestampToken;
}
token._timeElapsedQuery = this._createTimeQuery();
if (timerQuery.beginQueryEXT) {
timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
}
else {
this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
}
this._currentNonTimestampToken = token;
}
return token;
};
Engine.prototype.endTimeQuery = function (token) {
var timerQuery = this._caps.timerQuery;
if (!timerQuery || !token) {
return -1;
}
if (this._caps.canUseTimestampForTimerQuery) {
if (!token._startTimeQuery) {
return -1;
}
if (!token._endTimeQuery) {
token._endTimeQuery = this._createTimeQuery();
timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
}
}
else if (!token._timeElapsedQueryEnded) {
if (!token._timeElapsedQuery) {
return -1;
}
if (timerQuery.endQueryEXT) {
timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
}
else {
this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
}
token._timeElapsedQueryEnded = true;
}
var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
var available = false;
if (token._endTimeQuery) {
available = this._getTimeQueryAvailability(token._endTimeQuery);
}
else if (token._timeElapsedQuery) {
available = this._getTimeQueryAvailability(token._timeElapsedQuery);
}
if (available && !disjoint) {
var result = 0;
if (this._caps.canUseTimestampForTimerQuery) {
if (!token._startTimeQuery || !token._endTimeQuery) {
return -1;
}
var timeStart = this._getTimeQueryResult(token._startTimeQuery);
var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
result = timeEnd - timeStart;
this._deleteTimeQuery(token._startTimeQuery);
this._deleteTimeQuery(token._endTimeQuery);
token._startTimeQuery = null;
token._endTimeQuery = null;
}
else {
if (!token._timeElapsedQuery) {
return -1;
}
result = this._getTimeQueryResult(token._timeElapsedQuery);
this._deleteTimeQuery(token._timeElapsedQuery);
token._timeElapsedQuery = null;
token._timeElapsedQueryEnded = false;
this._currentNonTimestampToken = null;
}
return result;
}
return -1;
};
Engine.prototype.getGlAlgorithmType = function (algorithmType) {
return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
};
// Transform feedback
Engine.prototype.createTransformFeedback = function () {
return this._gl.createTransformFeedback();
};
Engine.prototype.deleteTransformFeedback = function (value) {
this._gl.deleteTransformFeedback(value);
};
Engine.prototype.bindTransformFeedback = function (value) {
this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
};
Engine.prototype.beginTransformFeedback = function (usePoints) {
if (usePoints === void 0) { usePoints = true; }
this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
};
Engine.prototype.endTransformFeedback = function () {
this._gl.endTransformFeedback();
};
Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
};
Engine.prototype.bindTransformFeedbackBuffer = function (value) {
this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
};
// Statics
Engine.isSupported = function () {
try {
var tempcanvas = document.createElement("canvas");
var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
return gl != null && !!window.WebGLRenderingContext;
}
catch (e) {
return false;
}
};
/** Use this array to turn off some WebGL2 features on known buggy browsers version */
Engine.WebGL2UniformBuffersExceptionList = ["Chrome/63"];
Engine.Instances = new Array();
// Const statics
Engine._ALPHA_DISABLE = 0;
Engine._ALPHA_ADD = 1;
Engine._ALPHA_COMBINE = 2;
Engine._ALPHA_SUBTRACT = 3;
Engine._ALPHA_MULTIPLY = 4;
Engine._ALPHA_MAXIMIZED = 5;
Engine._ALPHA_ONEONE = 6;
Engine._ALPHA_PREMULTIPLIED = 7;
Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
Engine._ALPHA_INTERPOLATE = 9;
Engine._ALPHA_SCREENMODE = 10;
Engine._DELAYLOADSTATE_NONE = 0;
Engine._DELAYLOADSTATE_LOADED = 1;
Engine._DELAYLOADSTATE_LOADING = 2;
Engine._DELAYLOADSTATE_NOTLOADED = 4;
Engine._TEXTUREFORMAT_ALPHA = 0;
Engine._TEXTUREFORMAT_LUMINANCE = 1;
Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
Engine._TEXTUREFORMAT_RGB = 4;
Engine._TEXTUREFORMAT_RGBA = 5;
Engine._TEXTURETYPE_UNSIGNED_INT = 0;
Engine._TEXTURETYPE_FLOAT = 1;
Engine._TEXTURETYPE_HALF_FLOAT = 2;
// Depht or Stencil test Constants.
Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
// Stencil Actions Constants.
Engine._KEEP = 0x1E00;
Engine._REPLACE = 0x1E01;
Engine._INCR = 0x1E02;
Engine._DECR = 0x1E03;
Engine._INVERT = 0x150A;
Engine._INCR_WRAP = 0x8507;
Engine._DECR_WRAP = 0x8508;
// Texture rescaling mode
Engine._SCALEMODE_FLOOR = 1;
Engine._SCALEMODE_NEAREST = 2;
Engine._SCALEMODE_CEILING = 3;
// Updatable statics so stick with vars here
Engine.CollisionsEpsilon = 0.001;
Engine.CodeRepository = "src/";
Engine.ShadersRepository = "src/Shaders/";
return Engine;
}());
BABYLON.Engine = Engine;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.engine.js.map
var BABYLON;
(function (BABYLON) {
/**
* Node is the basic class for all scene objects (Mesh, Light Camera).
*/
var Node = /** @class */ (function () {
/**
* @constructor
* @param {string} name - the name and id to be given to this node
* @param {BABYLON.Scene} the scene this node will be added to
*/
function Node(name, scene) {
if (scene === void 0) { scene = null; }
this.state = "";
this.metadata = null;
this.doNotSerialize = false;
this.animations = new Array();
this._ranges = {};
this._isEnabled = true;
this._isReady = true;
this._currentRenderId = -1;
this._parentRenderId = -1;
/**
* An event triggered when the mesh is disposed.
* @type {BABYLON.Observable}
*/
this.onDisposeObservable = new BABYLON.Observable();
// Behaviors
this._behaviors = new Array();
this.name = name;
this.id = name;
this._scene = (scene || BABYLON.Engine.LastCreatedScene);
this.uniqueId = this._scene.getUniqueId();
this._initCache();
}
Object.defineProperty(Node.prototype, "parent", {
get: function () {
return this._parentNode;
},
set: function (parent) {
if (this._parentNode === parent) {
return;
}
if (this._parentNode) {
var index = this._parentNode._children.indexOf(this);
if (index !== -1) {
this._parentNode._children.splice(index, 1);
}
}
this._parentNode = parent;
if (this._parentNode) {
if (!this._parentNode._children) {
this._parentNode._children = new Array();
}
this._parentNode._children.push(this);
}
},
enumerable: true,
configurable: true
});
Node.prototype.getClassName = function () {
return "Node";
};
Object.defineProperty(Node.prototype, "onDispose", {
set: function (callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Node.prototype.getScene = function () {
return this._scene;
};
Node.prototype.getEngine = function () {
return this._scene.getEngine();
};
Node.prototype.addBehavior = function (behavior) {
var _this = this;
var index = this._behaviors.indexOf(behavior);
if (index !== -1) {
return this;
}
behavior.init();
if (this._scene.isLoading) {
// We defer the attach when the scene will be loaded
var observer = this._scene.onDataLoadedObservable.add(function () {
behavior.attach(_this);
setTimeout(function () {
// Need to use a timeout to avoid removing an observer while iterating the list of observers
_this._scene.onDataLoadedObservable.remove(observer);
}, 0);
});
}
else {
behavior.attach(this);
}
this._behaviors.push(behavior);
return this;
};
Node.prototype.removeBehavior = function (behavior) {
var index = this._behaviors.indexOf(behavior);
if (index === -1) {
return this;
}
this._behaviors[index].detach();
this._behaviors.splice(index, 1);
return this;
};
Object.defineProperty(Node.prototype, "behaviors", {
get: function () {
return this._behaviors;
},
enumerable: true,
configurable: true
});
Node.prototype.getBehaviorByName = function (name) {
for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
var behavior = _a[_i];
if (behavior.name === name) {
return behavior;
}
}
return null;
};
// override it in derived class
Node.prototype.getWorldMatrix = function () {
return BABYLON.Matrix.Identity();
};
// override it in derived class if you add new variables to the cache
// and call the parent class method
Node.prototype._initCache = function () {
this._cache = {};
this._cache.parent = undefined;
};
Node.prototype.updateCache = function (force) {
if (!force && this.isSynchronized())
return;
this._cache.parent = this.parent;
this._updateCache();
};
// override it in derived class if you add new variables to the cache
// and call the parent class method if !ignoreParentClass
Node.prototype._updateCache = function (ignoreParentClass) {
};
// override it in derived class if you add new variables to the cache
Node.prototype._isSynchronized = function () {
return true;
};
Node.prototype._markSyncedWithParent = function () {
if (this.parent) {
this._parentRenderId = this.parent._currentRenderId;
}
};
Node.prototype.isSynchronizedWithParent = function () {
if (!this.parent) {
return true;
}
if (this._parentRenderId !== this.parent._currentRenderId) {
return false;
}
return this.parent.isSynchronized();
};
Node.prototype.isSynchronized = function (updateCache) {
var check = this.hasNewParent();
check = check || !this.isSynchronizedWithParent();
check = check || !this._isSynchronized();
if (updateCache)
this.updateCache(true);
return !check;
};
Node.prototype.hasNewParent = function (update) {
if (this._cache.parent === this.parent)
return false;
if (update)
this._cache.parent = this.parent;
return true;
};
/**
* Is this node ready to be used/rendered
* @return {boolean} is it ready
*/
Node.prototype.isReady = function () {
return this._isReady;
};
/**
* Is this node enabled.
* If the node has a parent and is enabled, the parent will be inspected as well.
* @return {boolean} whether this node (and its parent) is enabled.
* @see setEnabled
*/
Node.prototype.isEnabled = function () {
if (!this._isEnabled) {
return false;
}
if (this.parent) {
return this.parent.isEnabled();
}
return true;
};
/**
* Set the enabled state of this node.
* @param {boolean} value - the new enabled state
* @see isEnabled
*/
Node.prototype.setEnabled = function (value) {
this._isEnabled = value;
};
/**
* Is this node a descendant of the given node.
* The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
* @param {BABYLON.Node} ancestor - The parent node to inspect
* @see parent
*/
Node.prototype.isDescendantOf = function (ancestor) {
if (this.parent) {
if (this.parent === ancestor) {
return true;
}
return this.parent.isDescendantOf(ancestor);
}
return false;
};
/**
* Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
* @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
* @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
* @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
*/
Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
if (!this._children) {
return;
}
for (var index = 0; index < this._children.length; index++) {
var item = this._children[index];
if (!predicate || predicate(item)) {
results.push(item);
}
if (!directDescendantsOnly) {
item._getDescendants(results, false, predicate);
}
}
};
/**
* Will return all nodes that have this node as ascendant.
* @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
* @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
* @return {BABYLON.Node[]} all children nodes of all types.
*/
Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
var results = new Array();
this._getDescendants(results, directDescendantsOnly, predicate);
return results;
};
/**
* Get all child-meshes of this node.
*/
Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
var results = [];
this._getDescendants(results, directDescendantsOnly, function (node) {
return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
});
return results;
};
/**
* Get all child-transformNodes of this node.
*/
Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
var results = [];
this._getDescendants(results, directDescendantsOnly, function (node) {
return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
});
return results;
};
/**
* Get all direct children of this node.
*/
Node.prototype.getChildren = function (predicate) {
return this.getDescendants(true, predicate);
};
Node.prototype._setReady = function (state) {
if (state === this._isReady) {
return;
}
if (!state) {
this._isReady = false;
return;
}
this._isReady = true;
if (this.onReady) {
this.onReady(this);
}
};
Node.prototype.getAnimationByName = function (name) {
for (var i = 0; i < this.animations.length; i++) {
var animation = this.animations[i];
if (animation.name === name) {
return animation;
}
}
return null;
};
Node.prototype.createAnimationRange = function (name, from, to) {
// check name not already in use
if (!this._ranges[name]) {
this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
if (this.animations[i]) {
this.animations[i].createRange(name, from, to);
}
}
}
};
Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
if (deleteFrames === void 0) { deleteFrames = true; }
for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
if (this.animations[i]) {
this.animations[i].deleteRange(name, deleteFrames);
}
}
this._ranges[name] = null; // said much faster than 'delete this._range[name]'
};
Node.prototype.getAnimationRange = function (name) {
return this._ranges[name];
};
Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
var range = this.getAnimationRange(name);
if (!range) {
return;
}
this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
};
Node.prototype.serializeAnimationRanges = function () {
var serializationRanges = [];
for (var name in this._ranges) {
var localRange = this._ranges[name];
if (!localRange) {
continue;
}
var range = {};
range.name = name;
range.from = localRange.from;
range.to = localRange.to;
serializationRanges.push(range);
}
return serializationRanges;
};
// override it in derived class
Node.prototype.computeWorldMatrix = function (force) {
return BABYLON.Matrix.Identity();
};
Node.prototype.dispose = function () {
this.parent = null;
// Callback
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
// Behaviors
for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
var behavior = _a[_i];
behavior.detach();
}
this._behaviors = [];
};
Node.ParseAnimationRanges = function (node, parsedNode, scene) {
if (parsedNode.ranges) {
for (var index = 0; index < parsedNode.ranges.length; index++) {
var data = parsedNode.ranges[index];
node.createAnimationRange(data.name, data.from, data.to);
}
}
};
__decorate([
BABYLON.serialize()
], Node.prototype, "name", void 0);
__decorate([
BABYLON.serialize()
], Node.prototype, "id", void 0);
__decorate([
BABYLON.serialize()
], Node.prototype, "uniqueId", void 0);
__decorate([
BABYLON.serialize()
], Node.prototype, "state", void 0);
__decorate([
BABYLON.serialize()
], Node.prototype, "metadata", void 0);
return Node;
}());
BABYLON.Node = Node;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.node.js.map
var BABYLON;
(function (BABYLON) {
var BoundingSphere = /** @class */ (function () {
function BoundingSphere(minimum, maximum) {
this.minimum = minimum;
this.maximum = maximum;
this._tempRadiusVector = BABYLON.Vector3.Zero();
var distance = BABYLON.Vector3.Distance(minimum, maximum);
this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
this.radius = distance * 0.5;
this.centerWorld = BABYLON.Vector3.Zero();
this._update(BABYLON.Matrix.Identity());
}
// Methods
BoundingSphere.prototype._update = function (world) {
BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
};
BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
for (var i = 0; i < 6; i++) {
if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
return false;
}
return true;
};
BoundingSphere.prototype.intersectsPoint = function (point) {
var x = this.centerWorld.x - point.x;
var y = this.centerWorld.y - point.y;
var z = this.centerWorld.z - point.z;
var distance = Math.sqrt((x * x) + (y * y) + (z * z));
if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
return false;
return true;
};
// Statics
BoundingSphere.Intersects = function (sphere0, sphere1) {
var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
var distance = Math.sqrt((x * x) + (y * y) + (z * z));
if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
return false;
return true;
};
return BoundingSphere;
}());
BABYLON.BoundingSphere = BoundingSphere;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.boundingSphere.js.map
var BABYLON;
(function (BABYLON) {
var BoundingBox = /** @class */ (function () {
function BoundingBox(minimum, maximum) {
this.minimum = minimum;
this.maximum = maximum;
this.vectors = new Array();
this.vectorsWorld = new Array();
// Bounding vectors
this.vectors.push(this.minimum.clone());
this.vectors.push(this.maximum.clone());
this.vectors.push(this.minimum.clone());
this.vectors[2].x = this.maximum.x;
this.vectors.push(this.minimum.clone());
this.vectors[3].y = this.maximum.y;
this.vectors.push(this.minimum.clone());
this.vectors[4].z = this.maximum.z;
this.vectors.push(this.maximum.clone());
this.vectors[5].z = this.minimum.z;
this.vectors.push(this.maximum.clone());
this.vectors[6].x = this.minimum.x;
this.vectors.push(this.maximum.clone());
this.vectors[7].y = this.minimum.y;
// OBB
this.center = this.maximum.add(this.minimum).scale(0.5);
this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
// World
for (var index = 0; index < this.vectors.length; index++) {
this.vectorsWorld[index] = BABYLON.Vector3.Zero();
}
this.minimumWorld = BABYLON.Vector3.Zero();
this.maximumWorld = BABYLON.Vector3.Zero();
this.centerWorld = BABYLON.Vector3.Zero();
this.extendSizeWorld = BABYLON.Vector3.Zero();
this._update(BABYLON.Matrix.Identity());
}
// Methods
BoundingBox.prototype.getWorldMatrix = function () {
return this._worldMatrix;
};
BoundingBox.prototype.setWorldMatrix = function (matrix) {
this._worldMatrix.copyFrom(matrix);
return this;
};
BoundingBox.prototype._update = function (world) {
BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
for (var index = 0; index < this.vectors.length; index++) {
var v = this.vectorsWorld[index];
BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
if (v.x < this.minimumWorld.x)
this.minimumWorld.x = v.x;
if (v.y < this.minimumWorld.y)
this.minimumWorld.y = v.y;
if (v.z < this.minimumWorld.z)
this.minimumWorld.z = v.z;
if (v.x > this.maximumWorld.x)
this.maximumWorld.x = v.x;
if (v.y > this.maximumWorld.y)
this.maximumWorld.y = v.y;
if (v.z > this.maximumWorld.z)
this.maximumWorld.z = v.z;
}
// Extend
this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
this.extendSizeWorld.scaleInPlace(0.5);
// OBB
this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
this.centerWorld.scaleInPlace(0.5);
BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
this._worldMatrix = world;
};
BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
};
BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
};
BoundingBox.prototype.intersectsPoint = function (point) {
var delta = -BABYLON.Epsilon;
if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
return false;
if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
return false;
if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
return false;
return true;
};
BoundingBox.prototype.intersectsSphere = function (sphere) {
return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
};
BoundingBox.prototype.intersectsMinMax = function (min, max) {
if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
return false;
if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
return false;
if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
return false;
return true;
};
// Statics
BoundingBox.Intersects = function (box0, box1) {
if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
return false;
if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
return false;
if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
return false;
return true;
};
BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
return (num <= (sphereRadius * sphereRadius));
};
BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
for (var p = 0; p < 6; p++) {
for (var i = 0; i < 8; i++) {
if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
return false;
}
}
}
return true;
};
BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
for (var p = 0; p < 6; p++) {
var inCount = 8;
for (var i = 0; i < 8; i++) {
if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
--inCount;
}
else {
break;
}
}
if (inCount === 0)
return false;
}
return true;
};
return BoundingBox;
}());
BABYLON.BoundingBox = BoundingBox;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.boundingBox.js.map
var BABYLON;
(function (BABYLON) {
var computeBoxExtents = function (axis, box) {
var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
var r = r0 + r1 + r2;
return {
min: p - r,
max: p + r
};
};
var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
var axisOverlap = function (axis, box0, box1) {
var result0 = computeBoxExtents(axis, box0);
var result1 = computeBoxExtents(axis, box1);
return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
};
var BoundingInfo = /** @class */ (function () {
function BoundingInfo(minimum, maximum) {
this.minimum = minimum;
this.maximum = maximum;
this._isLocked = false;
this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
}
Object.defineProperty(BoundingInfo.prototype, "isLocked", {
get: function () {
return this._isLocked;
},
set: function (value) {
this._isLocked = value;
},
enumerable: true,
configurable: true
});
// Methods
BoundingInfo.prototype.update = function (world) {
if (this._isLocked) {
return;
}
this.boundingBox._update(world);
this.boundingSphere._update(world);
};
/**
* Recreate the bounding info to be centered around a specific point given a specific extend.
* @param center New center of the bounding info
* @param extend New extend of the bounding info
*/
BoundingInfo.prototype.centerOn = function (center, extend) {
this.minimum = center.subtract(extend);
this.maximum = center.add(extend);
this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
return this;
};
BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
if (!this.boundingSphere.isInFrustum(frustumPlanes))
return false;
return this.boundingBox.isInFrustum(frustumPlanes);
};
Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
/**
* Gets the world distance between the min and max points of the bounding box
*/
get: function () {
var boundingBox = this.boundingBox;
var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
return size.length();
},
enumerable: true,
configurable: true
});
BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
};
BoundingInfo.prototype._checkCollision = function (collider) {
return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
};
BoundingInfo.prototype.intersectsPoint = function (point) {
if (!this.boundingSphere.centerWorld) {
return false;
}
if (!this.boundingSphere.intersectsPoint(point)) {
return false;
}
if (!this.boundingBox.intersectsPoint(point)) {
return false;
}
return true;
};
BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
return false;
}
if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
return false;
}
if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
return false;
}
if (!precise) {
return true;
}
var box0 = this.boundingBox;
var box1 = boundingInfo.boundingBox;
if (!axisOverlap(box0.directions[0], box0, box1))
return false;
if (!axisOverlap(box0.directions[1], box0, box1))
return false;
if (!axisOverlap(box0.directions[2], box0, box1))
return false;
if (!axisOverlap(box1.directions[0], box0, box1))
return false;
if (!axisOverlap(box1.directions[1], box0, box1))
return false;
if (!axisOverlap(box1.directions[2], box0, box1))
return false;
if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
return false;
if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
return false;
if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
return false;
if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
return false;
if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
return false;
if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
return false;
if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
return false;
if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
return false;
if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
return false;
return true;
};
return BoundingInfo;
}());
BABYLON.BoundingInfo = BoundingInfo;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.boundingInfo.js.map
var BABYLON;
(function (BABYLON) {
var TransformNode = /** @class */ (function (_super) {
__extends(TransformNode, _super);
function TransformNode(name, scene, isPure) {
if (scene === void 0) { scene = null; }
if (isPure === void 0) { isPure = true; }
var _this = _super.call(this, name, scene) || this;
// Properties
_this._rotation = BABYLON.Vector3.Zero();
_this._scaling = BABYLON.Vector3.One();
_this._isDirty = false;
_this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
_this.scalingDeterminant = 1;
_this.infiniteDistance = false;
_this.position = BABYLON.Vector3.Zero();
_this._localWorld = BABYLON.Matrix.Zero();
_this._worldMatrix = BABYLON.Matrix.Zero();
_this._absolutePosition = BABYLON.Vector3.Zero();
_this._pivotMatrix = BABYLON.Matrix.Identity();
_this._postMultiplyPivotMatrix = false;
_this._isWorldMatrixFrozen = false;
/**
* An event triggered after the world matrix is updated
* @type {BABYLON.Observable}
*/
_this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
_this._nonUniformScaling = false;
if (isPure) {
_this.getScene().addTransformNode(_this);
}
return _this;
}
Object.defineProperty(TransformNode.prototype, "rotation", {
/**
* Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
* If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
* Default : (0.0, 0.0, 0.0)
*/
get: function () {
return this._rotation;
},
set: function (newRotation) {
this._rotation = newRotation;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TransformNode.prototype, "scaling", {
/**
* Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
* Default : (1.0, 1.0, 1.0)
*/
get: function () {
return this._scaling;
},
/**
* Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
* Default : (1.0, 1.0, 1.0)
*/
set: function (newScaling) {
this._scaling = newScaling;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
/**
* Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
* It's null by default.
* If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
*/
get: function () {
return this._rotationQuaternion;
},
set: function (quaternion) {
this._rotationQuaternion = quaternion;
//reset the rotation vector.
if (quaternion && this.rotation.length()) {
this.rotation.copyFromFloats(0.0, 0.0, 0.0);
}
},
enumerable: true,
configurable: true
});
/**
* Returns the latest update of the World matrix
* Returns a Matrix.
*/
TransformNode.prototype.getWorldMatrix = function () {
if (this._currentRenderId !== this.getScene().getRenderId()) {
this.computeWorldMatrix();
}
return this._worldMatrix;
};
Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
/**
* Returns directly the latest state of the mesh World matrix.
* A Matrix is returned.
*/
get: function () {
return this._worldMatrix;
},
enumerable: true,
configurable: true
});
/**
* Copies the paramater passed Matrix into the mesh Pose matrix.
* Returns the AbstractMesh.
*/
TransformNode.prototype.updatePoseMatrix = function (matrix) {
this._poseMatrix.copyFrom(matrix);
return this;
};
/**
* Returns the mesh Pose matrix.
* Returned object : Matrix
*/
TransformNode.prototype.getPoseMatrix = function () {
return this._poseMatrix;
};
TransformNode.prototype._isSynchronized = function () {
if (this._isDirty) {
return false;
}
if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
return false;
if (this._cache.pivotMatrixUpdated) {
return false;
}
if (this.infiniteDistance) {
return false;
}
if (!this._cache.position.equals(this.position))
return false;
if (this.rotationQuaternion) {
if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
return false;
}
if (!this._cache.rotation.equals(this.rotation))
return false;
if (!this._cache.scaling.equals(this.scaling))
return false;
return true;
};
TransformNode.prototype._initCache = function () {
_super.prototype._initCache.call(this);
this._cache.localMatrixUpdated = false;
this._cache.position = BABYLON.Vector3.Zero();
this._cache.scaling = BABYLON.Vector3.Zero();
this._cache.rotation = BABYLON.Vector3.Zero();
this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
this._cache.billboardMode = -1;
};
TransformNode.prototype.markAsDirty = function (property) {
if (property === "rotation") {
this.rotationQuaternion = null;
}
this._currentRenderId = Number.MAX_VALUE;
this._isDirty = true;
return this;
};
Object.defineProperty(TransformNode.prototype, "absolutePosition", {
/**
* Returns the current mesh absolute position.
* Retuns a Vector3.
*/
get: function () {
return this._absolutePosition;
},
enumerable: true,
configurable: true
});
/**
* Sets a new pivot matrix to the mesh.
* Returns the AbstractMesh.
*/
TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
this._pivotMatrix = matrix.clone();
this._cache.pivotMatrixUpdated = true;
this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
if (this._postMultiplyPivotMatrix) {
this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
}
return this;
};
/**
* Returns the mesh pivot matrix.
* Default : Identity.
* A Matrix is returned.
*/
TransformNode.prototype.getPivotMatrix = function () {
return this._pivotMatrix;
};
/**
* Prevents the World matrix to be computed any longer.
* Returns the AbstractMesh.
*/
TransformNode.prototype.freezeWorldMatrix = function () {
this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
this.computeWorldMatrix(true);
this._isWorldMatrixFrozen = true;
return this;
};
/**
* Allows back the World matrix computation.
* Returns the AbstractMesh.
*/
TransformNode.prototype.unfreezeWorldMatrix = function () {
this._isWorldMatrixFrozen = false;
this.computeWorldMatrix(true);
return this;
};
Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
/**
* True if the World matrix has been frozen.
* Returns a boolean.
*/
get: function () {
return this._isWorldMatrixFrozen;
},
enumerable: true,
configurable: true
});
/**
* Retuns the mesh absolute position in the World.
* Returns a Vector3.
*/
TransformNode.prototype.getAbsolutePosition = function () {
this.computeWorldMatrix();
return this._absolutePosition;
};
/**
* Sets the mesh absolute position in the World from a Vector3 or an Array(3).
* Returns the AbstractMesh.
*/
TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
if (!absolutePosition) {
return this;
}
var absolutePositionX;
var absolutePositionY;
var absolutePositionZ;
if (absolutePosition.x === undefined) {
if (arguments.length < 3) {
return this;
}
absolutePositionX = arguments[0];
absolutePositionY = arguments[1];
absolutePositionZ = arguments[2];
}
else {
absolutePositionX = absolutePosition.x;
absolutePositionY = absolutePosition.y;
absolutePositionZ = absolutePosition.z;
}
if (this.parent) {
var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
invertParentWorldMatrix.invert();
var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
}
else {
this.position.x = absolutePositionX;
this.position.y = absolutePositionY;
this.position.z = absolutePositionZ;
}
return this;
};
/**
* Sets the mesh position in its local space.
* Returns the AbstractMesh.
*/
TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
this.computeWorldMatrix();
this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
return this;
};
/**
* Returns the mesh position in the local space from the current World matrix values.
* Returns a new Vector3.
*/
TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
this.computeWorldMatrix();
var invLocalWorldMatrix = this._localWorld.clone();
invLocalWorldMatrix.invert();
return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
};
/**
* Translates the mesh along the passed Vector3 in its local space.
* Returns the AbstractMesh.
*/
TransformNode.prototype.locallyTranslate = function (vector3) {
this.computeWorldMatrix(true);
this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
return this;
};
/**
* Orients a mesh towards a target point. Mesh must be drawn facing user.
* @param targetPoint the position (must be in same space as current mesh) to look at
* @param yawCor optional yaw (y-axis) correction in radians
* @param pitchCor optional pitch (x-axis) correction in radians
* @param rollCor optional roll (z-axis) correction in radians
* @param space the choosen space of the target
* @returns the TransformNode.
*/
TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
if (yawCor === void 0) { yawCor = 0; }
if (pitchCor === void 0) { pitchCor = 0; }
if (rollCor === void 0) { rollCor = 0; }
if (space === void 0) { space = BABYLON.Space.LOCAL; }
var dv = BABYLON.AbstractMesh._lookAtVectorCache;
var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
targetPoint.subtractToRef(pos, dv);
var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
var pitch = Math.atan2(dv.y, len);
if (this.rotationQuaternion) {
BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
}
else {
this.rotation.x = pitch + pitchCor;
this.rotation.y = yaw + yawCor;
this.rotation.z = rollCor;
}
return this;
};
/**
* Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
* This Vector3 is expressed in the World space.
*/
TransformNode.prototype.getDirection = function (localAxis) {
var result = BABYLON.Vector3.Zero();
this.getDirectionToRef(localAxis, result);
return result;
};
/**
* Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
* localAxis is expressed in the mesh local space.
* result is computed in the Wordl space from the mesh World matrix.
* Returns the AbstractMesh.
*/
TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
return this;
};
TransformNode.prototype.setPivotPoint = function (point, space) {
if (space === void 0) { space = BABYLON.Space.LOCAL; }
if (this.getScene().getRenderId() == 0) {
this.computeWorldMatrix(true);
}
var wm = this.getWorldMatrix();
if (space == BABYLON.Space.WORLD) {
var tmat = BABYLON.Tmp.Matrix[0];
wm.invertToRef(tmat);
point = BABYLON.Vector3.TransformCoordinates(point, tmat);
}
BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
this._pivotMatrix.m[12] = -point.x;
this._pivotMatrix.m[13] = -point.y;
this._pivotMatrix.m[14] = -point.z;
this._cache.pivotMatrixUpdated = true;
return this;
};
/**
* Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
*/
TransformNode.prototype.getPivotPoint = function () {
var point = BABYLON.Vector3.Zero();
this.getPivotPointToRef(point);
return point;
};
/**
* Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
* Returns the AbstractMesh.
*/
TransformNode.prototype.getPivotPointToRef = function (result) {
result.x = -this._pivotMatrix.m[12];
result.y = -this._pivotMatrix.m[13];
result.z = -this._pivotMatrix.m[14];
return this;
};
/**
* Returns a new Vector3 set with the mesh pivot point World coordinates.
*/
TransformNode.prototype.getAbsolutePivotPoint = function () {
var point = BABYLON.Vector3.Zero();
this.getAbsolutePivotPointToRef(point);
return point;
};
/**
* Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
* Returns the AbstractMesh.
*/
TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
result.x = this._pivotMatrix.m[12];
result.y = this._pivotMatrix.m[13];
result.z = this._pivotMatrix.m[14];
this.getPivotPointToRef(result);
BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
return this;
};
/**
* Defines the passed node as the parent of the current node.
* The node will remain exactly where it is and its position / rotation will be updated accordingly
* Returns the TransformNode.
*/
TransformNode.prototype.setParent = function (node) {
if (node == null) {
var rotation = BABYLON.Tmp.Quaternion[0];
var position = BABYLON.Tmp.Vector3[0];
var scale = BABYLON.Tmp.Vector3[1];
if (this.parent && this.parent.computeWorldMatrix) {
this.parent.computeWorldMatrix(true);
}
this.computeWorldMatrix(true);
this.getWorldMatrix().decompose(scale, rotation, position);
if (this.rotationQuaternion) {
this.rotationQuaternion.copyFrom(rotation);
}
else {
rotation.toEulerAnglesToRef(this.rotation);
}
this.scaling.x = scale.x;
this.scaling.y = scale.y;
this.scaling.z = scale.z;
this.position.x = position.x;
this.position.y = position.y;
this.position.z = position.z;
}
else {
var rotation = BABYLON.Tmp.Quaternion[0];
var position = BABYLON.Tmp.Vector3[0];
var scale = BABYLON.Tmp.Vector3[1];
var diffMatrix = BABYLON.Tmp.Matrix[0];
var invParentMatrix = BABYLON.Tmp.Matrix[1];
this.computeWorldMatrix(true);
node.computeWorldMatrix(true);
node.getWorldMatrix().invertToRef(invParentMatrix);
this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
diffMatrix.decompose(scale, rotation, position);
if (this.rotationQuaternion) {
this.rotationQuaternion.copyFrom(rotation);
}
else {
rotation.toEulerAnglesToRef(this.rotation);
}
this.position.x = position.x;
this.position.y = position.y;
this.position.z = position.z;
this.scaling.x = scale.x;
this.scaling.y = scale.y;
this.scaling.z = scale.z;
}
this.parent = node;
return this;
};
Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
get: function () {
return this._nonUniformScaling;
},
enumerable: true,
configurable: true
});
TransformNode.prototype._updateNonUniformScalingState = function (value) {
if (this._nonUniformScaling === value) {
return false;
}
this._nonUniformScaling = true;
return true;
};
/**
* Attach the current TransformNode to another TransformNode associated with a bone
* @param bone Bone affecting the TransformNode
* @param affectedTransformNode TransformNode associated with the bone
*/
TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
this._transformToBoneReferal = affectedTransformNode;
this.parent = bone;
if (bone.getWorldMatrix().determinant() < 0) {
this.scalingDeterminant *= -1;
}
return this;
};
TransformNode.prototype.detachFromBone = function () {
if (!this.parent) {
return this;
}
if (this.parent.getWorldMatrix().determinant() < 0) {
this.scalingDeterminant *= -1;
}
this._transformToBoneReferal = null;
this.parent = null;
return this;
};
/**
* Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
* space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
* Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
* The passed axis is also normalized.
* Returns the AbstractMesh.
*/
TransformNode.prototype.rotate = function (axis, amount, space) {
axis.normalize();
if (!this.rotationQuaternion) {
this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
this.rotation = BABYLON.Vector3.Zero();
}
var rotationQuaternion;
if (!space || space === BABYLON.Space.LOCAL) {
rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
}
else {
if (this.parent) {
var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
invertParentWorldMatrix.invert();
axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
}
rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
}
return this;
};
/**
* Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
* Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
* The passed axis is also normalized.
* Returns the AbstractMesh.
* Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
*/
TransformNode.prototype.rotateAround = function (point, axis, amount) {
axis.normalize();
if (!this.rotationQuaternion) {
this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
this.rotation.copyFromFloats(0, 0, 0);
}
point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
return this;
};
/**
* Translates the mesh along the axis vector for the passed distance in the given space.
* space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
* Returns the AbstractMesh.
*/
TransformNode.prototype.translate = function (axis, distance, space) {
var displacementVector = axis.scale(distance);
if (!space || space === BABYLON.Space.LOCAL) {
var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
this.setPositionWithLocalVector(tempV3);
}
else {
this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
}
return this;
};
/**
* Adds a rotation step to the mesh current rotation.
* x, y, z are Euler angles expressed in radians.
* This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
* This means this rotation is made in the mesh local space only.
* It's useful to set a custom rotation order different from the BJS standard one YXZ.
* Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
* ```javascript
* mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
* ```
* Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
* Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
* Returns the AbstractMesh.
*/
TransformNode.prototype.addRotation = function (x, y, z) {
var rotationQuaternion;
if (this.rotationQuaternion) {
rotationQuaternion = this.rotationQuaternion;
}
else {
rotationQuaternion = BABYLON.Tmp.Quaternion[1];
BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
}
var accumulation = BABYLON.Tmp.Quaternion[0];
BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
rotationQuaternion.multiplyInPlace(accumulation);
if (!this.rotationQuaternion) {
rotationQuaternion.toEulerAnglesToRef(this.rotation);
}
return this;
};
/**
* Computes the mesh World matrix and returns it.
* If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
* If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
* If the parameter `force`is set to `true`, the actual computation is done.
* Returns the mesh World Matrix.
*/
TransformNode.prototype.computeWorldMatrix = function (force) {
if (this._isWorldMatrixFrozen) {
return this._worldMatrix;
}
if (!force && this.isSynchronized(true)) {
return this._worldMatrix;
}
this._cache.position.copyFrom(this.position);
this._cache.scaling.copyFrom(this.scaling);
this._cache.pivotMatrixUpdated = false;
this._cache.billboardMode = this.billboardMode;
this._currentRenderId = this.getScene().getRenderId();
this._isDirty = false;
// Scaling
BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
// Rotation
//rotate, if quaternion is set and rotation was used
if (this.rotationQuaternion) {
var len = this.rotation.length();
if (len) {
this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
this.rotation.copyFromFloats(0, 0, 0);
}
}
if (this.rotationQuaternion) {
this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
}
else {
BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
this._cache.rotation.copyFrom(this.rotation);
}
// Translation
var camera = this.getScene().activeCamera;
if (this.infiniteDistance && !this.parent && camera) {
var cameraWorldMatrix = camera.getWorldMatrix();
var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
}
else {
BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
}
// Composing transformations
this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
// Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
// Need to decompose each rotation here
var currentPosition = BABYLON.Tmp.Vector3[3];
if (this.parent && this.parent.getWorldMatrix) {
if (this._transformToBoneReferal) {
this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
}
else {
BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
}
}
else {
currentPosition.copyFrom(this.position);
}
currentPosition.subtractInPlace(camera.globalPosition);
var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
}
if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
}
if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
}
BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
}
else {
BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
}
BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
}
// Local world
BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
// Parent
if (this.parent && this.parent.getWorldMatrix) {
if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
if (this._transformToBoneReferal) {
this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
}
else {
BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
}
this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
this._worldMatrix.copyFrom(this._localWorld);
this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
}
else {
if (this._transformToBoneReferal) {
this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
}
else {
this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
}
}
this._markSyncedWithParent();
}
else {
this._worldMatrix.copyFrom(this._localWorld);
}
// Post multiply inverse of pivotMatrix
if (this._postMultiplyPivotMatrix) {
this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
}
// Normal matrix
if (this.scaling.isNonUniform) {
this._updateNonUniformScalingState(true);
}
else if (this.parent && this.parent._nonUniformScaling) {
this._updateNonUniformScalingState(this.parent._nonUniformScaling);
}
else {
this._updateNonUniformScalingState(false);
}
this._afterComputeWorldMatrix();
// Absolute position
this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
// Callbacks
this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
if (!this._poseMatrix) {
this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
}
return this._worldMatrix;
};
TransformNode.prototype._afterComputeWorldMatrix = function () {
};
/**
* If you'd like to be called back after the mesh position, rotation or scaling has been updated.
* @param func: callback function to add
*
* Returns the TransformNode.
*/
TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
this.onAfterWorldMatrixUpdateObservable.add(func);
return this;
};
/**
* Removes a registered callback function.
* Returns the TransformNode.
*/
TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
return this;
};
/**
* Clone the current transform node
* Returns the new transform node
* @param name Name of the new clone
* @param newParent New parent for the clone
* @param doNotCloneChildren Do not clone children hierarchy
*/
TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
var _this = this;
var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
result.name = name;
result.id = name;
if (newParent) {
result.parent = newParent;
}
if (!doNotCloneChildren) {
// Children
var directDescendants = this.getDescendants(true);
for (var index = 0; index < directDescendants.length; index++) {
var child = directDescendants[index];
if (child.clone) {
child.clone(name + "." + child.name, result);
}
}
}
return result;
};
TransformNode.prototype.serialize = function (currentSerializationObject) {
var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
serializationObject.type = this.getClassName();
// Parent
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
serializationObject.tags = BABYLON.Tags.GetTags(this);
}
serializationObject.localMatrix = this.getPivotMatrix().asArray();
serializationObject.isEnabled = this.isEnabled();
// Parent
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
return serializationObject;
};
// Statics
/**
* Returns a new TransformNode object parsed from the source provided.
* The parameter `parsedMesh` is the source.
* The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
*/
TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
}
if (parsedTransformNode.localMatrix) {
transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
}
else if (parsedTransformNode.pivotMatrix) {
transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
}
transformNode.setEnabled(parsedTransformNode.isEnabled);
// Parent
if (parsedTransformNode.parentId) {
transformNode._waitingParentId = parsedTransformNode.parentId;
}
return transformNode;
};
/**
* Disposes the TransformNode.
* By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
* Returns nothing.
*/
TransformNode.prototype.dispose = function (doNotRecurse) {
// Animations
this.getScene().stopAnimation(this);
// Remove from scene
this.getScene().removeTransformNode(this);
this._cache = {};
if (!doNotRecurse) {
// Children
var objects = this.getDescendants(true);
for (var index = 0; index < objects.length; index++) {
objects[index].dispose();
}
}
else {
var childMeshes = this.getChildMeshes(true);
for (index = 0; index < childMeshes.length; index++) {
var child = childMeshes[index];
child.parent = null;
child.computeWorldMatrix(true);
}
}
this.onAfterWorldMatrixUpdateObservable.clear();
_super.prototype.dispose.call(this);
};
// Statics
TransformNode.BILLBOARDMODE_NONE = 0;
TransformNode.BILLBOARDMODE_X = 1;
TransformNode.BILLBOARDMODE_Y = 2;
TransformNode.BILLBOARDMODE_Z = 4;
TransformNode.BILLBOARDMODE_ALL = 7;
TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
TransformNode._rotationAxisCache = new BABYLON.Quaternion();
__decorate([
BABYLON.serializeAsVector3()
], TransformNode.prototype, "_rotation", void 0);
__decorate([
BABYLON.serializeAsQuaternion()
], TransformNode.prototype, "_rotationQuaternion", void 0);
__decorate([
BABYLON.serializeAsVector3()
], TransformNode.prototype, "_scaling", void 0);
__decorate([
BABYLON.serialize()
], TransformNode.prototype, "billboardMode", void 0);
__decorate([
BABYLON.serialize()
], TransformNode.prototype, "scalingDeterminant", void 0);
__decorate([
BABYLON.serialize()
], TransformNode.prototype, "infiniteDistance", void 0);
__decorate([
BABYLON.serializeAsVector3()
], TransformNode.prototype, "position", void 0);
return TransformNode;
}(BABYLON.Node));
BABYLON.TransformNode = TransformNode;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.transformNode.js.map
var BABYLON;
(function (BABYLON) {
var AbstractMesh = /** @class */ (function (_super) {
__extends(AbstractMesh, _super);
// Constructor
function AbstractMesh(name, scene) {
if (scene === void 0) { scene = null; }
var _this = _super.call(this, name, scene, false) || this;
_this._facetNb = 0; // facet number
_this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
_this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
_this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
_this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
_this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
_this._subDiv = {
max: 1,
X: 1,
Y: 1,
Z: 1
};
_this._facetDepthSort = false; // is the facet depth sort to be computed
_this._facetDepthSortEnabled = false; // is the facet depth sort initialized
// Events
/**
* An event triggered when this mesh collides with another one
* @type {BABYLON.Observable}
*/
_this.onCollideObservable = new BABYLON.Observable();
/**
* An event triggered when the collision's position changes
* @type {BABYLON.Observable}
*/
_this.onCollisionPositionChangeObservable = new BABYLON.Observable();
/**
* An event triggered when material is changed
* @type {BABYLON.Observable}
*/
_this.onMaterialChangedObservable = new BABYLON.Observable();
// Properties
_this.definedFacingForward = true; // orientation for POV movement & rotation
/**
* This property determines the type of occlusion query algorithm to run in WebGl, you can use:
* AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
* or
* AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
* for more info check WebGl documentations
*/
_this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
/**
* This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
* OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
* OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
* OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
*/
_this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
/**
* This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
* The default value is -1 which means don't break the query and wait till the result.
*/
_this.occlusionRetryCount = -1;
_this._occlusionInternalRetryCounter = 0;
_this._isOccluded = false;
_this._isOcclusionQueryInProgress = false;
_this.visibility = 1.0;
_this.alphaIndex = Number.MAX_VALUE;
_this.isVisible = true;
_this.isPickable = true;
_this.showBoundingBox = false;
_this.showSubMeshesBoundingBox = false;
_this.isBlocker = false;
_this.enablePointerMoveEvents = false;
_this.renderingGroupId = 0;
_this._receiveShadows = false;
_this.renderOutline = false;
_this.outlineColor = BABYLON.Color3.Red();
_this.outlineWidth = 0.02;
_this.renderOverlay = false;
_this.overlayColor = BABYLON.Color3.Red();
_this.overlayAlpha = 0.5;
_this._hasVertexAlpha = false;
_this._useVertexColors = true;
_this._computeBonesUsingShaders = true;
_this._numBoneInfluencers = 4;
_this._applyFog = true;
_this.useOctreeForRenderingSelection = true;
_this.useOctreeForPicking = true;
_this.useOctreeForCollisions = true;
_this._layerMask = 0x0FFFFFFF;
/**
* True if the mesh must be rendered in any case.
*/
_this.alwaysSelectAsActiveMesh = false;
/**
* This scene's action manager
* @type {BABYLON.ActionManager}
*/
_this.actionManager = null;
// Physics
_this.physicsImpostor = null;
// Collisions
_this._checkCollisions = false;
_this._collisionMask = -1;
_this._collisionGroup = -1;
_this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
_this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
_this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
_this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
// Edges
_this.edgesWidth = 1;
_this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
// Cache
_this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
_this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
_this._isDisposed = false;
_this._renderId = 0;
_this._intersectionsInProgress = new Array();
_this._unIndexed = false;
_this._lightSources = new Array();
_this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
if (collidedMesh === void 0) { collidedMesh = null; }
//TODO move this to the collision coordinator!
if (_this.getScene().workerCollisions)
newPosition.multiplyInPlace(_this._collider._radius);
newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
_this.position.addInPlace(_this._diffPositionForCollisions);
}
if (collidedMesh) {
_this.onCollideObservable.notifyObservers(collidedMesh);
}
_this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
};
_this.getScene().addMesh(_this);
_this._resyncLightSources();
return _this;
}
Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
get: function () {
return BABYLON.TransformNode.BILLBOARDMODE_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
get: function () {
return BABYLON.TransformNode.BILLBOARDMODE_X;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
get: function () {
return BABYLON.TransformNode.BILLBOARDMODE_Y;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
get: function () {
return BABYLON.TransformNode.BILLBOARDMODE_Z;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
get: function () {
return BABYLON.TransformNode.BILLBOARDMODE_ALL;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "facetNb", {
/**
* Read-only : the number of facets in the mesh
*/
get: function () {
return this._facetNb;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
/**
* The number (integer) of subdivisions per axis in the partioning space
*/
get: function () {
return this._partitioningSubdivisions;
},
set: function (nb) {
this._partitioningSubdivisions = nb;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
/**
* The ratio (float) to apply to the bouding box size to set to the partioning space.
* Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
*/
get: function () {
return this._partitioningBBoxRatio;
},
set: function (ratio) {
this._partitioningBBoxRatio = ratio;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
/**
* Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
* Works only for updatable meshes.
* Doesn't work with multi-materials.
*/
get: function () {
return this._facetDepthSort;
},
set: function (sort) {
this._facetDepthSort = sort;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
/**
* The location (Vector3) where the facet depth sort must be computed from.
* By default, the active camera position.
* Used only when facet depth sort is enabled.
*/
get: function () {
return this._facetDepthSortFrom;
},
set: function (location) {
this._facetDepthSortFrom = location;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
/**
* Read-only boolean : is the feature facetData enabled ?
*/
get: function () {
return this._facetDataEnabled;
},
enumerable: true,
configurable: true
});
AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
return false;
}
this._markSubMeshesAsMiscDirty();
return true;
};
Object.defineProperty(AbstractMesh.prototype, "onCollide", {
set: function (callback) {
if (this._onCollideObserver) {
this.onCollideObservable.remove(this._onCollideObserver);
}
this._onCollideObserver = this.onCollideObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
set: function (callback) {
if (this._onCollisionPositionChangeObserver) {
this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
}
this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
/**
* Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
*/
get: function () {
return this._isOccluded;
},
set: function (value) {
this._isOccluded = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
/**
* Flag to check the progress status of the query
*/
get: function () {
return this._isOcclusionQueryInProgress;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "material", {
get: function () {
return this._material;
},
set: function (value) {
if (this._material === value) {
return;
}
this._material = value;
if (this.onMaterialChangedObservable.hasObservers) {
this.onMaterialChangedObservable.notifyObservers(this);
}
if (!this.subMeshes) {
return;
}
for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
subMesh.setEffect(null);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
get: function () {
return this._receiveShadows;
},
set: function (value) {
if (this._receiveShadows === value) {
return;
}
this._receiveShadows = value;
this._markSubMeshesAsLightDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
get: function () {
return this._hasVertexAlpha;
},
set: function (value) {
if (this._hasVertexAlpha === value) {
return;
}
this._hasVertexAlpha = value;
this._markSubMeshesAsAttributesDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
get: function () {
return this._useVertexColors;
},
set: function (value) {
if (this._useVertexColors === value) {
return;
}
this._useVertexColors = value;
this._markSubMeshesAsAttributesDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
get: function () {
return this._computeBonesUsingShaders;
},
set: function (value) {
if (this._computeBonesUsingShaders === value) {
return;
}
this._computeBonesUsingShaders = value;
this._markSubMeshesAsAttributesDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
get: function () {
return this._numBoneInfluencers;
},
set: function (value) {
if (this._numBoneInfluencers === value) {
return;
}
this._numBoneInfluencers = value;
this._markSubMeshesAsAttributesDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "applyFog", {
get: function () {
return this._applyFog;
},
set: function (value) {
if (this._applyFog === value) {
return;
}
this._applyFog = value;
this._markSubMeshesAsMiscDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "layerMask", {
get: function () {
return this._layerMask;
},
set: function (value) {
if (value === this._layerMask) {
return;
}
this._layerMask = value;
this._resyncLightSources();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
get: function () {
return this._collisionMask;
},
set: function (mask) {
this._collisionMask = !isNaN(mask) ? mask : -1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
get: function () {
return this._collisionGroup;
},
set: function (mask) {
this._collisionGroup = !isNaN(mask) ? mask : -1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "_positions", {
get: function () {
return null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "skeleton", {
get: function () {
return this._skeleton;
},
set: function (value) {
if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
this._skeleton._unregisterMeshWithPoseMatrix(this);
}
if (value && value.needInitialSkinMatrix) {
value._registerMeshWithPoseMatrix(this);
}
this._skeleton = value;
if (!this._skeleton) {
this._bonesTransformMatrices = null;
}
this._markSubMeshesAsAttributesDirty();
},
enumerable: true,
configurable: true
});
/**
* Boolean : true if the mesh has been disposed.
*/
AbstractMesh.prototype.isDisposed = function () {
return this._isDisposed;
};
/**
* Returns the string "AbstractMesh"
*/
AbstractMesh.prototype.getClassName = function () {
return "AbstractMesh";
};
/**
* @param {boolean} fullDetails - support for multiple levels of logging within scene loading
*/
AbstractMesh.prototype.toString = function (fullDetails) {
var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
if (this._skeleton) {
ret += ", skeleton: " + this._skeleton.name;
}
if (fullDetails) {
ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
}
return ret;
};
AbstractMesh.prototype._rebuild = function () {
if (this._occlusionQuery) {
this._occlusionQuery = null;
}
if (this._edgesRenderer) {
this._edgesRenderer._rebuild();
}
if (!this.subMeshes) {
return;
}
for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
subMesh._rebuild();
}
};
AbstractMesh.prototype._resyncLightSources = function () {
this._lightSources.length = 0;
for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
var light = _a[_i];
if (!light.isEnabled()) {
continue;
}
if (light.canAffectMesh(this)) {
this._lightSources.push(light);
}
}
this._markSubMeshesAsLightDirty();
};
AbstractMesh.prototype._resyncLighSource = function (light) {
var isIn = light.isEnabled() && light.canAffectMesh(this);
var index = this._lightSources.indexOf(light);
if (index === -1) {
if (!isIn) {
return;
}
this._lightSources.push(light);
}
else {
if (isIn) {
return;
}
this._lightSources.splice(index, 1);
}
this._markSubMeshesAsLightDirty();
};
AbstractMesh.prototype._removeLightSource = function (light) {
var index = this._lightSources.indexOf(light);
if (index === -1) {
return;
}
this._lightSources.splice(index, 1);
};
AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
if (!this.subMeshes) {
return;
}
for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
if (subMesh._materialDefines) {
func(subMesh._materialDefines);
}
}
};
AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
};
AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
};
AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
if (!this.subMeshes) {
return;
}
for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
var material = subMesh.getMaterial();
if (material) {
material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
}
}
};
Object.defineProperty(AbstractMesh.prototype, "scaling", {
/**
* Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
* Default : (1.0, 1.0, 1.0)
*/
get: function () {
return this._scaling;
},
/**
* Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
* Default : (1.0, 1.0, 1.0)
*/
set: function (newScaling) {
this._scaling = newScaling;
if (this.physicsImpostor) {
this.physicsImpostor.forceUpdate();
}
},
enumerable: true,
configurable: true
});
// Methods
/**
* Disables the mesh edger rendering mode.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.disableEdgesRendering = function () {
if (this._edgesRenderer) {
this._edgesRenderer.dispose();
this._edgesRenderer = null;
}
return this;
};
/**
* Enables the edge rendering mode on the mesh.
* This mode makes the mesh edges visible.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
if (epsilon === void 0) { epsilon = 0.95; }
if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
this.disableEdgesRendering();
this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
return this;
};
Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
/**
* Returns true if the mesh is blocked. Used by the class Mesh.
* Returns the boolean `false` by default.
*/
get: function () {
return false;
},
enumerable: true,
configurable: true
});
/**
* Returns the mesh itself by default, used by the class Mesh.
* Returned type : AbstractMesh
*/
AbstractMesh.prototype.getLOD = function (camera) {
return this;
};
/**
* Returns 0 by default, used by the class Mesh.
* Returns an integer.
*/
AbstractMesh.prototype.getTotalVertices = function () {
return 0;
};
/**
* Returns null by default, used by the class Mesh.
* Returned type : integer array
*/
AbstractMesh.prototype.getIndices = function () {
return null;
};
/**
* Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
* Returned type : float array or Float32Array
*/
AbstractMesh.prototype.getVerticesData = function (kind) {
return null;
};
/**
* Sets the vertex data of the mesh geometry for the requested `kind`.
* If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
* The `data` are either a numeric array either a Float32Array.
* The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
* The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
* Note that a new underlying VertexBuffer object is created each call.
* If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
*
* Possible `kind` values :
* - BABYLON.VertexBuffer.PositionKind
* - BABYLON.VertexBuffer.UVKind
* - BABYLON.VertexBuffer.UV2Kind
* - BABYLON.VertexBuffer.UV3Kind
* - BABYLON.VertexBuffer.UV4Kind
* - BABYLON.VertexBuffer.UV5Kind
* - BABYLON.VertexBuffer.UV6Kind
* - BABYLON.VertexBuffer.ColorKind
* - BABYLON.VertexBuffer.MatricesIndicesKind
* - BABYLON.VertexBuffer.MatricesIndicesExtraKind
* - BABYLON.VertexBuffer.MatricesWeightsKind
* - BABYLON.VertexBuffer.MatricesWeightsExtraKind
*
* Returns the Mesh.
*/
AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
return this;
};
/**
* Updates the existing vertex data of the mesh geometry for the requested `kind`.
* If the mesh has no geometry, it is simply returned as it is.
* The `data` are either a numeric array either a Float32Array.
* No new underlying VertexBuffer object is created.
* If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
* If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
*
* Possible `kind` values :
* - BABYLON.VertexBuffer.PositionKind
* - BABYLON.VertexBuffer.UVKind
* - BABYLON.VertexBuffer.UV2Kind
* - BABYLON.VertexBuffer.UV3Kind
* - BABYLON.VertexBuffer.UV4Kind
* - BABYLON.VertexBuffer.UV5Kind
* - BABYLON.VertexBuffer.UV6Kind
* - BABYLON.VertexBuffer.ColorKind
* - BABYLON.VertexBuffer.MatricesIndicesKind
* - BABYLON.VertexBuffer.MatricesIndicesExtraKind
* - BABYLON.VertexBuffer.MatricesWeightsKind
* - BABYLON.VertexBuffer.MatricesWeightsExtraKind
*
* Returns the Mesh.
*/
AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
return this;
};
/**
* Sets the mesh indices.
* Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
* If the mesh has no geometry, a new Geometry object is created and set to the mesh.
* This method creates a new index buffer each call.
* Returns the Mesh.
*/
AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
return this;
};
/** Returns false by default, used by the class Mesh.
* Returns a boolean
*/
AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
return false;
};
/**
* Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
* Returns a BoundingInfo
*/
AbstractMesh.prototype.getBoundingInfo = function () {
if (this._masterMesh) {
return this._masterMesh.getBoundingInfo();
}
if (!this._boundingInfo) {
// this._boundingInfo is being created here
this._updateBoundingInfo();
}
// cannot be null.
return this._boundingInfo;
};
/**
* Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
* @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
*/
AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
if (includeDescendants === void 0) { includeDescendants = true; }
var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
if (maxDimension === 0) {
return this;
}
var scale = 1 / maxDimension;
this.scaling.scaleInPlace(scale);
return this;
};
/**
* Sets a mesh new object BoundingInfo.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
this._boundingInfo = boundingInfo;
return this;
};
Object.defineProperty(AbstractMesh.prototype, "useBones", {
get: function () {
return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
},
enumerable: true,
configurable: true
});
AbstractMesh.prototype._preActivate = function () {
};
AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
};
AbstractMesh.prototype._activate = function (renderId) {
this._renderId = renderId;
};
/**
* Returns the latest update of the World matrix
* Returns a Matrix.
*/
AbstractMesh.prototype.getWorldMatrix = function () {
if (this._masterMesh) {
return this._masterMesh.getWorldMatrix();
}
return _super.prototype.getWorldMatrix.call(this);
};
// ================================== Point of View Movement =================================
/**
* Perform relative position change from the point of view of behind the front of the mesh.
* This is performed taking into account the meshes current rotation, so you do not have to care.
* Supports definition of mesh facing forward or backward.
* @param {number} amountRight
* @param {number} amountUp
* @param {number} amountForward
*
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
return this;
};
/**
* Calculate relative position change from the point of view of behind the front of the mesh.
* This is performed taking into account the meshes current rotation, so you do not have to care.
* Supports definition of mesh facing forward or backward.
* @param {number} amountRight
* @param {number} amountUp
* @param {number} amountForward
*
* Returns a new Vector3.
*/
AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
var rotMatrix = new BABYLON.Matrix();
var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
rotQuaternion.toRotationMatrix(rotMatrix);
var translationDelta = BABYLON.Vector3.Zero();
var defForwardMult = this.definedFacingForward ? -1 : 1;
BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
return translationDelta;
};
// ================================== Point of View Rotation =================================
/**
* Perform relative rotation change from the point of view of behind the front of the mesh.
* Supports definition of mesh facing forward or backward.
* @param {number} flipBack
* @param {number} twirlClockwise
* @param {number} tiltRight
*
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
return this;
};
/**
* Calculate relative rotation change from the point of view of behind the front of the mesh.
* Supports definition of mesh facing forward or backward.
* @param {number} flipBack
* @param {number} twirlClockwise
* @param {number} tiltRight
*
* Returns a new Vector3.
*/
AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
var defForwardMult = this.definedFacingForward ? 1 : -1;
return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
};
/**
* Return the minimum and maximum world vectors of the entire hierarchy under current mesh
* @param includeDescendants Include bounding info from descendants as well (true by default).
*/
AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
if (includeDescendants === void 0) { includeDescendants = true; }
this.computeWorldMatrix(true);
var min;
var max;
var boundingInfo = this.getBoundingInfo();
if (!this.subMeshes) {
min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
}
else {
min = boundingInfo.boundingBox.minimumWorld;
max = boundingInfo.boundingBox.maximumWorld;
}
if (includeDescendants) {
var descendants = this.getDescendants(false);
for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
var descendant = descendants_1[_i];
var childMesh = descendant;
//make sure we have the needed params to get mix and max
if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
continue;
}
childMesh.computeWorldMatrix(true);
var childBoundingInfo = childMesh.getBoundingInfo();
var boundingBox = childBoundingInfo.boundingBox;
var minBox = boundingBox.minimumWorld;
var maxBox = boundingBox.maximumWorld;
BABYLON.Tools.CheckExtends(minBox, min, max);
BABYLON.Tools.CheckExtends(maxBox, min, max);
}
}
return {
min: min,
max: max
};
};
/**
* Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype._updateBoundingInfo = function () {
this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
this._boundingInfo.update(this.worldMatrixFromCache);
this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
return this;
};
/**
* Update a mesh's children BoundingInfo objects only.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
if (!this.subMeshes) {
return this;
}
for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
var subMesh = this.subMeshes[subIndex];
if (!subMesh.IsGlobal) {
subMesh.updateBoundingInfo(matrix);
}
}
return this;
};
AbstractMesh.prototype._afterComputeWorldMatrix = function () {
// Bounding info
this._updateBoundingInfo();
};
/**
* Returns `true` if the mesh is within the frustum defined by the passed array of planes.
* A mesh is in the frustum if its bounding box intersects the frustum.
* Boolean returned.
*/
AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
};
/**
* Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
* A mesh is completely in the frustum if its bounding box it completely inside the frustum.
* Boolean returned.
*/
AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
;
};
/**
* True if the mesh intersects another mesh or a SolidParticle object.
* Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
* includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
* Returns a boolean.
*/
AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
if (precise === void 0) { precise = false; }
if (!this._boundingInfo || !mesh._boundingInfo) {
return false;
}
if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
return true;
}
if (includeDescendants) {
for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
var child = _a[_i];
if (child.intersectsMesh(mesh, precise, true)) {
return true;
}
}
}
return false;
};
/**
* Returns true if the passed point (Vector3) is inside the mesh bounding box.
* Returns a boolean.
*/
AbstractMesh.prototype.intersectsPoint = function (point) {
if (!this._boundingInfo) {
return false;
}
return this._boundingInfo.intersectsPoint(point);
};
AbstractMesh.prototype.getPhysicsImpostor = function () {
return this.physicsImpostor;
};
AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
if (camera === void 0) { camera = null; }
if (!camera) {
camera = this.getScene().activeCamera;
}
return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
};
/**
* Returns the distance from the mesh to the active camera.
* Returns a float.
*/
AbstractMesh.prototype.getDistanceToCamera = function (camera) {
if (camera === void 0) { camera = null; }
if (!camera) {
camera = this.getScene().activeCamera;
}
return this.absolutePosition.subtract(camera.position).length();
};
AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
if (!this.physicsImpostor) {
return this;
}
this.physicsImpostor.applyImpulse(force, contactPoint);
return this;
};
AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
return this;
}
this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
mainPivot: pivot1,
connectedPivot: pivot2,
nativeParams: options
});
return this;
};
Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
// Collisions
/**
* Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
* Default `false`.
*/
get: function () {
return this._checkCollisions;
},
set: function (collisionEnabled) {
this._checkCollisions = collisionEnabled;
if (this.getScene().workerCollisions) {
this.getScene().collisionCoordinator.onMeshUpdated(this);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "collider", {
/**
* Gets Collider object used to compute collisions (not physics)
*/
get: function () {
return this._collider;
},
enumerable: true,
configurable: true
});
AbstractMesh.prototype.moveWithCollisions = function (displacement) {
var globalPosition = this.getAbsolutePosition();
globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
if (!this._collider) {
this._collider = new BABYLON.Collider();
}
this._collider._radius = this.ellipsoid;
this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
return this;
};
// Submeshes octree
/**
* This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
* Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
* Returns an Octree of submeshes.
*/
AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
if (maxCapacity === void 0) { maxCapacity = 64; }
if (maxDepth === void 0) { maxDepth = 2; }
if (!this._submeshesOctree) {
this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
}
this.computeWorldMatrix(true);
var boundingInfo = this.getBoundingInfo();
// Update octree
var bbox = boundingInfo.boundingBox;
this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
return this._submeshesOctree;
};
// Collisions
AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
this._generatePointsArray();
if (!this._positions) {
return this;
}
// Transformation
if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
subMesh._lastColliderTransformMatrix = transformMatrix.clone();
subMesh._lastColliderWorldVertices = [];
subMesh._trianglePlanes = [];
var start = subMesh.verticesStart;
var end = (subMesh.verticesStart + subMesh.verticesCount);
for (var i = start; i < end; i++) {
subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
}
}
// Collide
collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
if (collider.collisionFound) {
collider.collidedMesh = this;
}
return this;
};
AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
var subMeshes;
var len;
// Octrees
if (this._submeshesOctree && this.useOctreeForCollisions) {
var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
len = intersections.length;
subMeshes = intersections.data;
}
else {
subMeshes = this.subMeshes;
len = subMeshes.length;
}
for (var index = 0; index < len; index++) {
var subMesh = subMeshes[index];
// Bounding test
if (len > 1 && !subMesh._checkCollision(collider))
continue;
this._collideForSubMesh(subMesh, transformMatrix, collider);
}
return this;
};
AbstractMesh.prototype._checkCollision = function (collider) {
// Bounding box test
if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
return this;
// Transformation matrix
BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
return this;
};
// Picking
AbstractMesh.prototype._generatePointsArray = function () {
return false;
};
/**
* Checks if the passed Ray intersects with the mesh.
* Returns an object PickingInfo.
*/
AbstractMesh.prototype.intersects = function (ray, fastCheck) {
var pickingInfo = new BABYLON.PickingInfo();
if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
return pickingInfo;
}
if (!this._generatePointsArray()) {
return pickingInfo;
}
var intersectInfo = null;
// Octrees
var subMeshes;
var len;
if (this._submeshesOctree && this.useOctreeForPicking) {
var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
var intersections = this._submeshesOctree.intersectsRay(worldRay);
len = intersections.length;
subMeshes = intersections.data;
}
else {
subMeshes = this.subMeshes;
len = subMeshes.length;
}
for (var index = 0; index < len; index++) {
var subMesh = subMeshes[index];
// Bounding test
if (len > 1 && !subMesh.canIntersects(ray))
continue;
var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
if (currentIntersectInfo) {
if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
intersectInfo = currentIntersectInfo;
intersectInfo.subMeshId = index;
if (fastCheck) {
break;
}
}
}
}
if (intersectInfo) {
// Get picked point
var world = this.getWorldMatrix();
var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
var direction = ray.direction.clone();
direction = direction.scale(intersectInfo.distance);
var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
var pickedPoint = worldOrigin.add(worldDirection);
// Return result
pickingInfo.hit = true;
pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
pickingInfo.pickedPoint = pickedPoint;
pickingInfo.pickedMesh = this;
pickingInfo.bu = intersectInfo.bu || 0;
pickingInfo.bv = intersectInfo.bv || 0;
pickingInfo.faceId = intersectInfo.faceId;
pickingInfo.subMeshId = intersectInfo.subMeshId;
return pickingInfo;
}
return pickingInfo;
};
/**
* Clones the mesh, used by the class Mesh.
* Just returns `null` for an AbstractMesh.
*/
AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
return null;
};
/**
* Disposes all the mesh submeshes.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.releaseSubMeshes = function () {
if (this.subMeshes) {
while (this.subMeshes.length) {
this.subMeshes[0].dispose();
}
}
else {
this.subMeshes = new Array();
}
return this;
};
/**
* Disposes the AbstractMesh.
* By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
* Returns nothing.
*/
AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
var _this = this;
if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
var index;
// Action manager
if (this.actionManager) {
this.actionManager.dispose();
this.actionManager = null;
}
// Skeleton
this.skeleton = null;
// Physics
if (this.physicsImpostor) {
this.physicsImpostor.dispose();
}
// Intersections in progress
for (index = 0; index < this._intersectionsInProgress.length; index++) {
var other = this._intersectionsInProgress[index];
var pos = other._intersectionsInProgress.indexOf(this);
other._intersectionsInProgress.splice(pos, 1);
}
this._intersectionsInProgress = [];
// Lights
var lights = this.getScene().lights;
lights.forEach(function (light) {
var meshIndex = light.includedOnlyMeshes.indexOf(_this);
if (meshIndex !== -1) {
light.includedOnlyMeshes.splice(meshIndex, 1);
}
meshIndex = light.excludedMeshes.indexOf(_this);
if (meshIndex !== -1) {
light.excludedMeshes.splice(meshIndex, 1);
}
// Shadow generators
var generator = light.getShadowGenerator();
if (generator) {
var shadowMap = generator.getShadowMap();
if (shadowMap && shadowMap.renderList) {
meshIndex = shadowMap.renderList.indexOf(_this);
if (meshIndex !== -1) {
shadowMap.renderList.splice(meshIndex, 1);
}
}
}
});
// Edges
if (this._edgesRenderer) {
this._edgesRenderer.dispose();
this._edgesRenderer = null;
}
// SubMeshes
if (this.getClassName() !== "InstancedMesh") {
this.releaseSubMeshes();
}
// Octree
var sceneOctree = this.getScene().selectionOctree;
if (sceneOctree) {
var index = sceneOctree.dynamicContent.indexOf(this);
if (index !== -1) {
sceneOctree.dynamicContent.splice(index, 1);
}
}
// Query
var engine = this.getScene().getEngine();
if (this._occlusionQuery) {
this._isOcclusionQueryInProgress = false;
engine.deleteQuery(this._occlusionQuery);
this._occlusionQuery = null;
}
// Engine
engine.wipeCaches();
// Remove from scene
this.getScene().removeMesh(this);
if (disposeMaterialAndTextures) {
if (this.material) {
this.material.dispose(false, true);
}
}
if (!doNotRecurse) {
// Particles
for (index = 0; index < this.getScene().particleSystems.length; index++) {
if (this.getScene().particleSystems[index].emitter === this) {
this.getScene().particleSystems[index].dispose();
index--;
}
}
}
// facet data
if (this._facetDataEnabled) {
this.disableFacetData();
}
this.onAfterWorldMatrixUpdateObservable.clear();
this.onCollideObservable.clear();
this.onCollisionPositionChangeObservable.clear();
this._isDisposed = true;
_super.prototype.dispose.call(this, doNotRecurse);
};
/**
* Adds the passed mesh as a child to the current mesh.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.addChild = function (mesh) {
mesh.setParent(this);
return this;
};
/**
* Removes the passed mesh from the current mesh children list.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.removeChild = function (mesh) {
mesh.setParent(null);
return this;
};
// Facet data
/**
* Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype._initFacetData = function () {
if (!this._facetNormals) {
this._facetNormals = new Array();
}
if (!this._facetPositions) {
this._facetPositions = new Array();
}
if (!this._facetPartitioning) {
this._facetPartitioning = new Array();
}
this._facetNb = (this.getIndices().length / 3) | 0;
this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
for (var f = 0; f < this._facetNb; f++) {
this._facetNormals[f] = BABYLON.Vector3.Zero();
this._facetPositions[f] = BABYLON.Vector3.Zero();
}
this._facetDataEnabled = true;
return this;
};
/**
* Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
* This method can be called within the render loop.
* You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.updateFacetData = function () {
if (!this._facetDataEnabled) {
this._initFacetData();
}
var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
var indices = this.getIndices();
var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
var bInfo = this.getBoundingInfo();
if (this._facetDepthSort && !this._facetDepthSortEnabled) {
// init arrays, matrix and sort function on first call
this._facetDepthSortEnabled = true;
if (indices instanceof Uint16Array) {
this._depthSortedIndices = new Uint16Array(indices);
}
else if (indices instanceof Uint32Array) {
this._depthSortedIndices = new Uint32Array(indices);
}
else {
var needs32bits = false;
for (var i = 0; i < indices.length; i++) {
if (indices[i] > 65535) {
needs32bits = true;
break;
}
}
if (needs32bits) {
this._depthSortedIndices = new Uint32Array(indices);
}
else {
this._depthSortedIndices = new Uint16Array(indices);
}
}
this._facetDepthSortFunction = function (f1, f2) {
return (f2.sqDistance - f1.sqDistance);
};
if (!this._facetDepthSortFrom) {
var camera = this.getScene().activeCamera;
this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
}
this._depthSortedFacets = [];
for (var f = 0; f < this._facetNb; f++) {
var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
this._depthSortedFacets.push(depthSortedFacet);
}
this._invertedMatrix = BABYLON.Matrix.Identity();
this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
}
this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
this._subDiv.max = this._partitioningSubdivisions;
this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
// set the parameters for ComputeNormals()
this._facetParameters.facetNormals = this.getFacetLocalNormals();
this._facetParameters.facetPositions = this.getFacetLocalPositions();
this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
this._facetParameters.bInfo = bInfo;
this._facetParameters.bbSize = this._bbSize;
this._facetParameters.subDiv = this._subDiv;
this._facetParameters.ratio = this.partitioningBBoxRatio;
this._facetParameters.depthSort = this._facetDepthSort;
if (this._facetDepthSort && this._facetDepthSortEnabled) {
this.computeWorldMatrix(true);
this._worldMatrix.invertToRef(this._invertedMatrix);
BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
this._facetParameters.distanceTo = this._facetDepthSortOrigin;
}
this._facetParameters.depthSortedFacets = this._depthSortedFacets;
BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
if (this._facetDepthSort && this._facetDepthSortEnabled) {
this._depthSortedFacets.sort(this._facetDepthSortFunction);
var l = (this._depthSortedIndices.length / 3) | 0;
for (var f = 0; f < l; f++) {
var sind = this._depthSortedFacets[f].ind;
this._depthSortedIndices[f * 3] = indices[sind];
this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
}
this.updateIndices(this._depthSortedIndices);
}
return this;
};
/**
* Returns the facetLocalNormals array.
* The normals are expressed in the mesh local space.
*/
AbstractMesh.prototype.getFacetLocalNormals = function () {
if (!this._facetNormals) {
this.updateFacetData();
}
return this._facetNormals;
};
/**
* Returns the facetLocalPositions array.
* The facet positions are expressed in the mesh local space.
*/
AbstractMesh.prototype.getFacetLocalPositions = function () {
if (!this._facetPositions) {
this.updateFacetData();
}
return this._facetPositions;
};
/**
* Returns the facetLocalPartioning array.
*/
AbstractMesh.prototype.getFacetLocalPartitioning = function () {
if (!this._facetPartitioning) {
this.updateFacetData();
}
return this._facetPartitioning;
};
/**
* Returns the i-th facet position in the world system.
* This method allocates a new Vector3 per call.
*/
AbstractMesh.prototype.getFacetPosition = function (i) {
var pos = BABYLON.Vector3.Zero();
this.getFacetPositionToRef(i, pos);
return pos;
};
/**
* Sets the reference Vector3 with the i-th facet position in the world system.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
var localPos = (this.getFacetLocalPositions())[i];
var world = this.getWorldMatrix();
BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
return this;
};
/**
* Returns the i-th facet normal in the world system.
* This method allocates a new Vector3 per call.
*/
AbstractMesh.prototype.getFacetNormal = function (i) {
var norm = BABYLON.Vector3.Zero();
this.getFacetNormalToRef(i, norm);
return norm;
};
/**
* Sets the reference Vector3 with the i-th facet normal in the world system.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
var localNorm = (this.getFacetLocalNormals())[i];
BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
return this;
};
/**
* Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
*/
AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
var bInfo = this.getBoundingInfo();
var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
return null;
}
return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
};
/**
* Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
* If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
* If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
* If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
* If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
*/
AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
if (checkFace === void 0) { checkFace = false; }
if (facing === void 0) { facing = true; }
var world = this.getWorldMatrix();
var invMat = BABYLON.Tmp.Matrix[5];
world.invertToRef(invMat);
var invVect = BABYLON.Tmp.Vector3[8];
BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
if (projected) {
// tranform the local computed projected vector to world coordinates
BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
}
return closest;
};
/**
* Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
* If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
* If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
* If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
* If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
*/
AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
if (checkFace === void 0) { checkFace = false; }
if (facing === void 0) { facing = true; }
var closest = null;
var tmpx = 0.0;
var tmpy = 0.0;
var tmpz = 0.0;
var d = 0.0; // tmp dot facet normal * facet position
var t0 = 0.0;
var projx = 0.0;
var projy = 0.0;
var projz = 0.0;
// Get all the facets in the same partitioning block than (x, y, z)
var facetPositions = this.getFacetLocalPositions();
var facetNormals = this.getFacetLocalNormals();
var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
if (!facetsInBlock) {
return null;
}
// Get the closest facet to (x, y, z)
var shortest = Number.MAX_VALUE; // init distance vars
var tmpDistance = shortest;
var fib; // current facet in the block
var norm; // current facet normal
var p0; // current facet barycenter position
// loop on all the facets in the current partitioning block
for (var idx = 0; idx < facetsInBlock.length; idx++) {
fib = facetsInBlock[idx];
norm = facetNormals[fib];
p0 = facetPositions[fib];
d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
// compute (x,y,z) projection on the facet = (projx, projy, projz)
d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
projx = x + norm.x * t0;
projy = y + norm.y * t0;
projz = z + norm.z * t0;
tmpx = projx - x;
tmpy = projy - y;
tmpz = projz - z;
tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
if (tmpDistance < shortest) {
shortest = tmpDistance;
closest = fib;
if (projected) {
projected.x = projx;
projected.y = projy;
projected.z = projz;
}
}
}
}
return closest;
};
/**
* Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
*/
AbstractMesh.prototype.getFacetDataParameters = function () {
return this._facetParameters;
};
/**
* Disables the feature FacetData and frees the related memory.
* Returns the AbstractMesh.
*/
AbstractMesh.prototype.disableFacetData = function () {
if (this._facetDataEnabled) {
this._facetDataEnabled = false;
this._facetPositions = new Array();
this._facetNormals = new Array();
this._facetPartitioning = new Array();
this._facetParameters = null;
this._depthSortedIndices = new Uint32Array(0);
}
return this;
};
/**
* Updates the AbstractMesh indices array. Actually, used by the Mesh object.
* Returns the mesh.
*/
AbstractMesh.prototype.updateIndices = function (indices) {
return this;
};
/**
* The mesh Geometry. Actually used by the Mesh object.
* Returns a blank geometry object.
*/
/**
* Creates new normals data for the mesh.
* @param updatable.
*/
AbstractMesh.prototype.createNormals = function (updatable) {
var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
var indices = this.getIndices();
var normals;
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
}
else {
normals = [];
}
BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
};
/**
* Align the mesh with a normal.
* Returns the mesh.
*/
AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
if (!upDirection) {
upDirection = BABYLON.Axis.Y;
}
var axisX = BABYLON.Tmp.Vector3[0];
var axisZ = BABYLON.Tmp.Vector3[1];
BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
if (this.rotationQuaternion) {
BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
}
else {
BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
}
return this;
};
AbstractMesh.prototype.checkOcclusionQuery = function () {
var engine = this.getEngine();
if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
this._isOccluded = false;
return;
}
if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
if (isOcclusionQueryAvailable) {
var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
this._isOcclusionQueryInProgress = false;
this._occlusionInternalRetryCounter = 0;
this._isOccluded = occlusionQueryResult === 1 ? false : true;
}
else {
this._occlusionInternalRetryCounter++;
if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
this._isOcclusionQueryInProgress = false;
this._occlusionInternalRetryCounter = 0;
// if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
// if strict continue the last state of the object.
this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
}
else {
return;
}
}
}
var scene = this.getScene();
var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
if (!this._occlusionQuery) {
this._occlusionQuery = engine.createQuery();
}
engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
this._isOcclusionQueryInProgress = true;
};
AbstractMesh.OCCLUSION_TYPE_NONE = 0;
AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
return AbstractMesh;
}(BABYLON.TransformNode));
BABYLON.AbstractMesh = AbstractMesh;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.abstractMesh.js.map
var BABYLON;
(function (BABYLON) {
var Light = /** @class */ (function (_super) {
__extends(Light, _super);
/**
* Creates a Light object in the scene.
* Documentation : http://doc.babylonjs.com/tutorials/lights
*/
function Light(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
_this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
_this.intensity = 1.0;
_this.range = Number.MAX_VALUE;
/**
* Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
* of light.
*/
_this._photometricScale = 1.0;
_this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
_this._radius = 0.00001;
_this.renderPriority = 0;
/**
* Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
* the current shadow generator.
*/
_this.shadowEnabled = true;
_this._excludeWithLayerMask = 0;
_this._includeOnlyWithLayerMask = 0;
_this._lightmapMode = 0;
_this._excludedMeshesIds = new Array();
_this._includedOnlyMeshesIds = new Array();
_this.getScene().addLight(_this);
_this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
_this._buildUniformLayout();
_this.includedOnlyMeshes = new Array();
_this.excludedMeshes = new Array();
_this._resyncMeshes();
return _this;
}
Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
/**
* If every light affecting the material is in this lightmapMode,
* material.lightmapTexture adds or multiplies
* (depends on material.useLightmapAsShadowmap)
* after every other light calculations.
*/
get: function () {
return Light._LIGHTMAP_DEFAULT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
/**
* material.lightmapTexture as only diffuse lighting from this light
* adds pnly specular lighting from this light
* adds dynamic shadows
*/
get: function () {
return Light._LIGHTMAP_SPECULAR;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
/**
* material.lightmapTexture as only lighting
* no light calculation from this light
* only adds dynamic shadows from this light
*/
get: function () {
return Light._LIGHTMAP_SHADOWSONLY;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
/**
* Each light type uses the default quantity according to its type:
* point/spot lights use luminous intensity
* directional lights use illuminance
*/
get: function () {
return Light._INTENSITYMODE_AUTOMATIC;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
/**
* lumen (lm)
*/
get: function () {
return Light._INTENSITYMODE_LUMINOUSPOWER;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
/**
* candela (lm/sr)
*/
get: function () {
return Light._INTENSITYMODE_LUMINOUSINTENSITY;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
/**
* lux (lm/m^2)
*/
get: function () {
return Light._INTENSITYMODE_ILLUMINANCE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
/**
* nit (cd/m^2)
*/
get: function () {
return Light._INTENSITYMODE_LUMINANCE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
/**
* Light type const id of the point light.
*/
get: function () {
return Light._LIGHTTYPEID_POINTLIGHT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
/**
* Light type const id of the directional light.
*/
get: function () {
return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
/**
* Light type const id of the spot light.
*/
get: function () {
return Light._LIGHTTYPEID_SPOTLIGHT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
/**
* Light type const id of the hemispheric light.
*/
get: function () {
return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light.prototype, "intensityMode", {
/**
* Gets the photometric scale used to interpret the intensity.
* This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
*/
get: function () {
return this._intensityMode;
},
/**
* Sets the photometric scale used to interpret the intensity.
* This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
*/
set: function (value) {
this._intensityMode = value;
this._computePhotometricScale();
},
enumerable: true,
configurable: true
});
;
;
Object.defineProperty(Light.prototype, "radius", {
/**
* Gets the light radius used by PBR Materials to simulate soft area lights.
*/
get: function () {
return this._radius;
},
/**
* sets the light radius used by PBR Materials to simulate soft area lights.
*/
set: function (value) {
this._radius = value;
this._computePhotometricScale();
},
enumerable: true,
configurable: true
});
;
;
Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
get: function () {
return this._includedOnlyMeshes;
},
set: function (value) {
this._includedOnlyMeshes = value;
this._hookArrayForIncludedOnly(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light.prototype, "excludedMeshes", {
get: function () {
return this._excludedMeshes;
},
set: function (value) {
this._excludedMeshes = value;
this._hookArrayForExcluded(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
get: function () {
return this._excludeWithLayerMask;
},
set: function (value) {
this._excludeWithLayerMask = value;
this._resyncMeshes();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
get: function () {
return this._includeOnlyWithLayerMask;
},
set: function (value) {
this._includeOnlyWithLayerMask = value;
this._resyncMeshes();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light.prototype, "lightmapMode", {
get: function () {
return this._lightmapMode;
},
set: function (value) {
if (this._lightmapMode === value) {
return;
}
this._lightmapMode = value;
this._markMeshesAsLightDirty();
},
enumerable: true,
configurable: true
});
Light.prototype._buildUniformLayout = function () {
// Overridden
};
/**
* Returns the string "Light".
*/
Light.prototype.getClassName = function () {
return "Light";
};
/**
* @param {boolean} fullDetails - support for multiple levels of logging within scene loading
*/
Light.prototype.toString = function (fullDetails) {
var ret = "Name: " + this.name;
ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
if (this.animations) {
for (var i = 0; i < this.animations.length; i++) {
ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
}
}
if (fullDetails) {
}
return ret;
};
/**
* Set the enabled state of this node.
* @param {boolean} value - the new enabled state
* @see isEnabled
*/
Light.prototype.setEnabled = function (value) {
_super.prototype.setEnabled.call(this, value);
this._resyncMeshes();
};
/**
* Returns the Light associated shadow generator.
*/
Light.prototype.getShadowGenerator = function () {
return this._shadowGenerator;
};
/**
* Returns a Vector3, the absolute light position in the World.
*/
Light.prototype.getAbsolutePosition = function () {
return BABYLON.Vector3.Zero();
};
Light.prototype.transferToEffect = function (effect, lightIndex) {
};
Light.prototype._getWorldMatrix = function () {
return BABYLON.Matrix.Identity();
};
/**
* Boolean : True if the light will affect the passed mesh.
*/
Light.prototype.canAffectMesh = function (mesh) {
if (!mesh) {
return true;
}
if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
return false;
}
if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
return false;
}
if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
return false;
}
if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
return false;
}
return true;
};
/**
* Returns the light World matrix.
*/
Light.prototype.getWorldMatrix = function () {
this._currentRenderId = this.getScene().getRenderId();
var worldMatrix = this._getWorldMatrix();
if (this.parent && this.parent.getWorldMatrix) {
if (!this._parentedWorldMatrix) {
this._parentedWorldMatrix = BABYLON.Matrix.Identity();
}
worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
this._markSyncedWithParent();
return this._parentedWorldMatrix;
}
return worldMatrix;
};
/**
* Sort function to order lights for rendering.
* @param a First Light object to compare to second.
* @param b Second Light object to compare first.
* @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
*/
Light.compareLightsPriority = function (a, b) {
//shadow-casting lights have priority over non-shadow-casting lights
//the renderPrioirty is a secondary sort criterion
if (a.shadowEnabled !== b.shadowEnabled) {
return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
}
return b.renderPriority - a.renderPriority;
};
/**
* Disposes the light.
*/
Light.prototype.dispose = function () {
if (this._shadowGenerator) {
this._shadowGenerator.dispose();
this._shadowGenerator = null;
}
// Animations
this.getScene().stopAnimation(this);
// Remove from meshes
for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
var mesh = _a[_i];
mesh._removeLightSource(this);
}
this._uniformBuffer.dispose();
// Remove from scene
this.getScene().removeLight(this);
_super.prototype.dispose.call(this);
};
/**
* Returns the light type ID (integer).
*/
Light.prototype.getTypeID = function () {
return 0;
};
/**
* Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
*/
Light.prototype.getScaledIntensity = function () {
return this._photometricScale * this.intensity;
};
/**
* Returns a new Light object, named "name", from the current one.
*/
Light.prototype.clone = function (name) {
var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
if (!constructor) {
return null;
}
return BABYLON.SerializationHelper.Clone(constructor, this);
};
/**
* Serializes the current light into a Serialization object.
* Returns the serialized object.
*/
Light.prototype.serialize = function () {
var serializationObject = BABYLON.SerializationHelper.Serialize(this);
// Type
serializationObject.type = this.getTypeID();
// Parent
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
// Inclusion / exclusions
if (this.excludedMeshes.length > 0) {
serializationObject.excludedMeshesIds = [];
this.excludedMeshes.forEach(function (mesh) {
serializationObject.excludedMeshesIds.push(mesh.id);
});
}
if (this.includedOnlyMeshes.length > 0) {
serializationObject.includedOnlyMeshesIds = [];
this.includedOnlyMeshes.forEach(function (mesh) {
serializationObject.includedOnlyMeshesIds.push(mesh.id);
});
}
// Animations
BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
serializationObject.ranges = this.serializeAnimationRanges();
return serializationObject;
};
/**
* Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
* This new light is named "name" and added to the passed scene.
*/
Light.GetConstructorFromName = function (type, name, scene) {
switch (type) {
case 0:
return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
case 1:
return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
case 2:
return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
case 3:
return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
}
return null;
};
/**
* Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
*/
Light.Parse = function (parsedLight, scene) {
var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
if (!constructor) {
return null;
}
var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
// Inclusion / exclusions
if (parsedLight.excludedMeshesIds) {
light._excludedMeshesIds = parsedLight.excludedMeshesIds;
}
if (parsedLight.includedOnlyMeshesIds) {
light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
}
// Parent
if (parsedLight.parentId) {
light._waitingParentId = parsedLight.parentId;
}
// Animations
if (parsedLight.animations) {
for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
var parsedAnimation = parsedLight.animations[animationIndex];
light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
}
BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
}
if (parsedLight.autoAnimate) {
scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
}
return light;
};
Light.prototype._hookArrayForExcluded = function (array) {
var _this = this;
var oldPush = array.push;
array.push = function () {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i] = arguments[_i];
}
var result = oldPush.apply(array, items);
for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
var item = items_1[_a];
item._resyncLighSource(_this);
}
return result;
};
var oldSplice = array.splice;
array.splice = function (index, deleteCount) {
var deleted = oldSplice.apply(array, [index, deleteCount]);
for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
var item = deleted_1[_i];
item._resyncLighSource(_this);
}
return deleted;
};
for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
var item = array_1[_i];
item._resyncLighSource(this);
}
};
Light.prototype._hookArrayForIncludedOnly = function (array) {
var _this = this;
var oldPush = array.push;
array.push = function () {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i] = arguments[_i];
}
var result = oldPush.apply(array, items);
_this._resyncMeshes();
return result;
};
var oldSplice = array.splice;
array.splice = function (index, deleteCount) {
var deleted = oldSplice.apply(array, [index, deleteCount]);
_this._resyncMeshes();
return deleted;
};
this._resyncMeshes();
};
Light.prototype._resyncMeshes = function () {
for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
var mesh = _a[_i];
mesh._resyncLighSource(this);
}
};
Light.prototype._markMeshesAsLightDirty = function () {
for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
var mesh = _a[_i];
if (mesh._lightSources.indexOf(this) !== -1) {
mesh._markSubMeshesAsLightDirty();
}
}
};
/**
* Recomputes the cached photometric scale if needed.
*/
Light.prototype._computePhotometricScale = function () {
this._photometricScale = this._getPhotometricScale();
this.getScene().resetCachedMaterial();
};
/**
* Returns the Photometric Scale according to the light type and intensity mode.
*/
Light.prototype._getPhotometricScale = function () {
var photometricScale = 0.0;
var lightTypeID = this.getTypeID();
//get photometric mode
var photometricMode = this.intensityMode;
if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
}
else {
photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
}
}
//compute photometric scale
switch (lightTypeID) {
case Light.LIGHTTYPEID_POINTLIGHT:
case Light.LIGHTTYPEID_SPOTLIGHT:
switch (photometricMode) {
case Light.INTENSITYMODE_LUMINOUSPOWER:
photometricScale = 1.0 / (4.0 * Math.PI);
break;
case Light.INTENSITYMODE_LUMINOUSINTENSITY:
photometricScale = 1.0;
break;
case Light.INTENSITYMODE_LUMINANCE:
photometricScale = this.radius * this.radius;
break;
}
break;
case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
switch (photometricMode) {
case Light.INTENSITYMODE_ILLUMINANCE:
photometricScale = 1.0;
break;
case Light.INTENSITYMODE_LUMINANCE:
// When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
// For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
var apexAngleRadians = this.radius;
// Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
apexAngleRadians = Math.max(apexAngleRadians, 0.001);
var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
photometricScale = solidAngle;
break;
}
break;
case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
// No fall off in hemisperic light.
photometricScale = 1.0;
break;
}
return photometricScale;
};
Light.prototype._reorderLightsInScene = function () {
var scene = this.getScene();
if (this._renderPriority != 0) {
scene.requireLightSorting = true;
}
this.getScene().sortLightsByPriority();
};
//lightmapMode Consts
Light._LIGHTMAP_DEFAULT = 0;
Light._LIGHTMAP_SPECULAR = 1;
Light._LIGHTMAP_SHADOWSONLY = 2;
// Intensity Mode Consts
Light._INTENSITYMODE_AUTOMATIC = 0;
Light._INTENSITYMODE_LUMINOUSPOWER = 1;
Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
Light._INTENSITYMODE_ILLUMINANCE = 3;
Light._INTENSITYMODE_LUMINANCE = 4;
// Light types ids const.
Light._LIGHTTYPEID_POINTLIGHT = 0;
Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
Light._LIGHTTYPEID_SPOTLIGHT = 2;
Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
__decorate([
BABYLON.serializeAsColor3()
], Light.prototype, "diffuse", void 0);
__decorate([
BABYLON.serializeAsColor3()
], Light.prototype, "specular", void 0);
__decorate([
BABYLON.serialize()
], Light.prototype, "intensity", void 0);
__decorate([
BABYLON.serialize()
], Light.prototype, "range", void 0);
__decorate([
BABYLON.serialize()
], Light.prototype, "intensityMode", null);
__decorate([
BABYLON.serialize()
], Light.prototype, "radius", null);
__decorate([
BABYLON.serialize()
], Light.prototype, "_renderPriority", void 0);
__decorate([
BABYLON.expandToProperty("_reorderLightsInScene")
], Light.prototype, "renderPriority", void 0);
__decorate([
BABYLON.serialize()
], Light.prototype, "shadowEnabled", void 0);
__decorate([
BABYLON.serialize("excludeWithLayerMask")
], Light.prototype, "_excludeWithLayerMask", void 0);
__decorate([
BABYLON.serialize("includeOnlyWithLayerMask")
], Light.prototype, "_includeOnlyWithLayerMask", void 0);
__decorate([
BABYLON.serialize("lightmapMode")
], Light.prototype, "_lightmapMode", void 0);
return Light;
}(BABYLON.Node));
BABYLON.Light = Light;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.light.js.map
var BABYLON;
(function (BABYLON) {
var Camera = /** @class */ (function (_super) {
__extends(Camera, _super);
function Camera(name, position, scene) {
var _this = _super.call(this, name, scene) || this;
_this.upVector = BABYLON.Vector3.Up();
_this.orthoLeft = null;
_this.orthoRight = null;
_this.orthoBottom = null;
_this.orthoTop = null;
_this.fov = 0.8;
_this.minZ = 1;
_this.maxZ = 10000.0;
_this.inertia = 0.9;
_this.mode = Camera.PERSPECTIVE_CAMERA;
_this.isIntermediate = false;
_this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
_this.layerMask = 0x0FFFFFFF;
_this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
// Camera rig members
_this.cameraRigMode = Camera.RIG_MODE_NONE;
_this._rigCameras = new Array();
_this._webvrViewMatrix = BABYLON.Matrix.Identity();
_this._skipRendering = false;
_this.customRenderTargets = new Array();
// Observables
_this.onViewMatrixChangedObservable = new BABYLON.Observable();
_this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
_this.onAfterCheckInputsObservable = new BABYLON.Observable();
_this.onRestoreStateObservable = new BABYLON.Observable();
// Cache
_this._computedViewMatrix = BABYLON.Matrix.Identity();
_this._projectionMatrix = new BABYLON.Matrix();
_this._doNotComputeProjectionMatrix = false;
_this._postProcesses = new Array();
_this._transformMatrix = BABYLON.Matrix.Zero();
_this._activeMeshes = new BABYLON.SmartArray(256);
_this._globalPosition = BABYLON.Vector3.Zero();
_this._refreshFrustumPlanes = true;
_this.getScene().addCamera(_this);
if (!_this.getScene().activeCamera) {
_this.getScene().activeCamera = _this;
}
_this.position = position;
return _this;
}
Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
get: function () {
return Camera._PERSPECTIVE_CAMERA;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
get: function () {
return Camera._ORTHOGRAPHIC_CAMERA;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
get: function () {
return Camera._FOVMODE_VERTICAL_FIXED;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
get: function () {
return Camera._FOVMODE_HORIZONTAL_FIXED;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera, "RIG_MODE_NONE", {
get: function () {
return Camera._RIG_MODE_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
get: function () {
return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
get: function () {
return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
get: function () {
return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
get: function () {
return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera, "RIG_MODE_VR", {
get: function () {
return Camera._RIG_MODE_VR;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
get: function () {
return Camera._RIG_MODE_WEBVR;
},
enumerable: true,
configurable: true
});
/**
* Store current camera state (fov, position, etc..)
*/
Camera.prototype.storeState = function () {
this._stateStored = true;
this._storedFov = this.fov;
return this;
};
/**
* Restores the camera state values if it has been stored. You must call storeState() first
*/
Camera.prototype._restoreStateValues = function () {
if (!this._stateStored) {
return false;
}
this.fov = this._storedFov;
return true;
};
/**
* Restored camera state. You must call storeState() first
*/
Camera.prototype.restoreState = function () {
if (this._restoreStateValues()) {
this.onRestoreStateObservable.notifyObservers(this);
return true;
}
return false;
};
Camera.prototype.getClassName = function () {
return "Camera";
};
/**
* @param {boolean} fullDetails - support for multiple levels of logging within scene loading
*/
Camera.prototype.toString = function (fullDetails) {
var ret = "Name: " + this.name;
ret += ", type: " + this.getClassName();
if (this.animations) {
for (var i = 0; i < this.animations.length; i++) {
ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
}
}
if (fullDetails) {
}
return ret;
};
Object.defineProperty(Camera.prototype, "globalPosition", {
get: function () {
return this._globalPosition;
},
enumerable: true,
configurable: true
});
Camera.prototype.getActiveMeshes = function () {
return this._activeMeshes;
};
Camera.prototype.isActiveMesh = function (mesh) {
return (this._activeMeshes.indexOf(mesh) !== -1);
};
//Cache
Camera.prototype._initCache = function () {
_super.prototype._initCache.call(this);
this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.mode = undefined;
this._cache.minZ = undefined;
this._cache.maxZ = undefined;
this._cache.fov = undefined;
this._cache.fovMode = undefined;
this._cache.aspectRatio = undefined;
this._cache.orthoLeft = undefined;
this._cache.orthoRight = undefined;
this._cache.orthoBottom = undefined;
this._cache.orthoTop = undefined;
this._cache.renderWidth = undefined;
this._cache.renderHeight = undefined;
};
Camera.prototype._updateCache = function (ignoreParentClass) {
if (!ignoreParentClass) {
_super.prototype._updateCache.call(this);
}
this._cache.position.copyFrom(this.position);
this._cache.upVector.copyFrom(this.upVector);
};
// Synchronized
Camera.prototype._isSynchronized = function () {
return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
};
Camera.prototype._isSynchronizedViewMatrix = function () {
if (!_super.prototype._isSynchronized.call(this))
return false;
return this._cache.position.equals(this.position)
&& this._cache.upVector.equals(this.upVector)
&& this.isSynchronizedWithParent();
};
Camera.prototype._isSynchronizedProjectionMatrix = function () {
var check = this._cache.mode === this.mode
&& this._cache.minZ === this.minZ
&& this._cache.maxZ === this.maxZ;
if (!check) {
return false;
}
var engine = this.getEngine();
if (this.mode === Camera.PERSPECTIVE_CAMERA) {
check = this._cache.fov === this.fov
&& this._cache.fovMode === this.fovMode
&& this._cache.aspectRatio === engine.getAspectRatio(this);
}
else {
check = this._cache.orthoLeft === this.orthoLeft
&& this._cache.orthoRight === this.orthoRight
&& this._cache.orthoBottom === this.orthoBottom
&& this._cache.orthoTop === this.orthoTop
&& this._cache.renderWidth === engine.getRenderWidth()
&& this._cache.renderHeight === engine.getRenderHeight();
}
return check;
};
// Controls
Camera.prototype.attachControl = function (element, noPreventDefault) {
};
Camera.prototype.detachControl = function (element) {
};
Camera.prototype.update = function () {
this._checkInputs();
if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
this._updateRigCameras();
}
};
Camera.prototype._checkInputs = function () {
this.onAfterCheckInputsObservable.notifyObservers(this);
};
Object.defineProperty(Camera.prototype, "rigCameras", {
get: function () {
return this._rigCameras;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera.prototype, "rigPostProcess", {
get: function () {
return this._rigPostProcess;
},
enumerable: true,
configurable: true
});
Camera.prototype._cascadePostProcessesToRigCams = function () {
// invalidate framebuffer
if (this._postProcesses.length > 0) {
this._postProcesses[0].markTextureDirty();
}
// glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
for (var i = 0, len = this._rigCameras.length; i < len; i++) {
var cam = this._rigCameras[i];
var rigPostProcess = cam._rigPostProcess;
// for VR rig, there does not have to be a post process
if (rigPostProcess) {
var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
if (isPass) {
// any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
cam.isIntermediate = this._postProcesses.length === 0;
}
cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
rigPostProcess.markTextureDirty();
}
else {
cam._postProcesses = this._postProcesses.slice(0);
}
}
};
Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
if (insertAt === void 0) { insertAt = null; }
if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
return 0;
}
if (insertAt == null || insertAt < 0) {
this._postProcesses.push(postProcess);
}
else {
this._postProcesses.splice(insertAt, 0, postProcess);
}
this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
return this._postProcesses.indexOf(postProcess);
};
Camera.prototype.detachPostProcess = function (postProcess) {
var idx = this._postProcesses.indexOf(postProcess);
if (idx !== -1) {
this._postProcesses.splice(idx, 1);
}
this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
};
Camera.prototype.getWorldMatrix = function () {
if (!this._worldMatrix) {
this._worldMatrix = BABYLON.Matrix.Identity();
}
var viewMatrix = this.getViewMatrix();
viewMatrix.invertToRef(this._worldMatrix);
return this._worldMatrix;
};
Camera.prototype._getViewMatrix = function () {
return BABYLON.Matrix.Identity();
};
Camera.prototype.getViewMatrix = function (force) {
if (!force && this._isSynchronizedViewMatrix()) {
return this._computedViewMatrix;
}
this.updateCache();
this._computedViewMatrix = this._getViewMatrix();
this._currentRenderId = this.getScene().getRenderId();
this._refreshFrustumPlanes = true;
if (!this.parent || !this.parent.getWorldMatrix) {
this._globalPosition.copyFrom(this.position);
}
else {
if (!this._worldMatrix) {
this._worldMatrix = BABYLON.Matrix.Identity();
}
this._computedViewMatrix.invertToRef(this._worldMatrix);
this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
this._computedViewMatrix.invert();
this._markSyncedWithParent();
}
if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
}
this.onViewMatrixChangedObservable.notifyObservers(this);
return this._computedViewMatrix;
};
Camera.prototype.freezeProjectionMatrix = function (projection) {
this._doNotComputeProjectionMatrix = true;
if (projection !== undefined) {
this._projectionMatrix = projection;
}
};
;
Camera.prototype.unfreezeProjectionMatrix = function () {
this._doNotComputeProjectionMatrix = false;
};
;
Camera.prototype.getProjectionMatrix = function (force) {
if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
return this._projectionMatrix;
}
// Cache
this._cache.mode = this.mode;
this._cache.minZ = this.minZ;
this._cache.maxZ = this.maxZ;
// Matrix
this._refreshFrustumPlanes = true;
var engine = this.getEngine();
var scene = this.getScene();
if (this.mode === Camera.PERSPECTIVE_CAMERA) {
this._cache.fov = this.fov;
this._cache.fovMode = this.fovMode;
this._cache.aspectRatio = engine.getAspectRatio(this);
if (this.minZ <= 0) {
this.minZ = 0.1;
}
if (scene.useRightHandedSystem) {
BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
}
else {
BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
}
}
else {
var halfWidth = engine.getRenderWidth() / 2.0;
var halfHeight = engine.getRenderHeight() / 2.0;
if (scene.useRightHandedSystem) {
BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
}
else {
BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
}
this._cache.orthoLeft = this.orthoLeft;
this._cache.orthoRight = this.orthoRight;
this._cache.orthoBottom = this.orthoBottom;
this._cache.orthoTop = this.orthoTop;
this._cache.renderWidth = engine.getRenderWidth();
this._cache.renderHeight = engine.getRenderHeight();
}
this.onProjectionMatrixChangedObservable.notifyObservers(this);
return this._projectionMatrix;
};
Camera.prototype.getTranformationMatrix = function () {
this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
return this._transformMatrix;
};
Camera.prototype.updateFrustumPlanes = function () {
if (!this._refreshFrustumPlanes) {
return;
}
this.getTranformationMatrix();
if (!this._frustumPlanes) {
this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
}
else {
BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
}
this._refreshFrustumPlanes = false;
};
Camera.prototype.isInFrustum = function (target) {
this.updateFrustumPlanes();
return target.isInFrustum(this._frustumPlanes);
};
Camera.prototype.isCompletelyInFrustum = function (target) {
this.updateFrustumPlanes();
return target.isCompletelyInFrustum(this._frustumPlanes);
};
Camera.prototype.getForwardRay = function (length, transform, origin) {
if (length === void 0) { length = 100; }
if (!transform) {
transform = this.getWorldMatrix();
}
if (!origin) {
origin = this.position;
}
var forward = new BABYLON.Vector3(0, 0, 1);
var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
var direction = BABYLON.Vector3.Normalize(forwardWorld);
return new BABYLON.Ray(origin, direction, length);
};
Camera.prototype.dispose = function () {
// Observables
this.onViewMatrixChangedObservable.clear();
this.onProjectionMatrixChangedObservable.clear();
this.onAfterCheckInputsObservable.clear();
this.onRestoreStateObservable.clear();
// Inputs
if (this.inputs) {
this.inputs.clear();
}
// Animations
this.getScene().stopAnimation(this);
// Remove from scene
this.getScene().removeCamera(this);
while (this._rigCameras.length > 0) {
var camera = this._rigCameras.pop();
if (camera) {
camera.dispose();
}
}
// Postprocesses
if (this._rigPostProcess) {
this._rigPostProcess.dispose(this);
this._rigPostProcess = null;
this._postProcesses = [];
}
else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
this._rigPostProcess = null;
this._postProcesses = [];
}
else {
var i = this._postProcesses.length;
while (--i >= 0) {
this._postProcesses[i].dispose(this);
}
}
// Render targets
var i = this.customRenderTargets.length;
while (--i >= 0) {
this.customRenderTargets[i].dispose();
}
this.customRenderTargets = [];
// Active Meshes
this._activeMeshes.dispose();
_super.prototype.dispose.call(this);
};
Object.defineProperty(Camera.prototype, "leftCamera", {
// ---- Camera rigs section ----
get: function () {
if (this._rigCameras.length < 1) {
return null;
}
return this._rigCameras[0];
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera.prototype, "rightCamera", {
get: function () {
if (this._rigCameras.length < 2) {
return null;
}
return this._rigCameras[1];
},
enumerable: true,
configurable: true
});
Camera.prototype.getLeftTarget = function () {
if (this._rigCameras.length < 1) {
return null;
}
return this._rigCameras[0].getTarget();
};
Camera.prototype.getRightTarget = function () {
if (this._rigCameras.length < 2) {
return null;
}
return this._rigCameras[1].getTarget();
};
Camera.prototype.setCameraRigMode = function (mode, rigParams) {
if (this.cameraRigMode === mode) {
return;
}
while (this._rigCameras.length > 0) {
var camera = this._rigCameras.pop();
if (camera) {
camera.dispose();
}
}
this.cameraRigMode = mode;
this._cameraRigParams = {};
//we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
//not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
// create the rig cameras, unless none
if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
var leftCamera = this.createRigCamera(this.name + "_L", 0);
var rightCamera = this.createRigCamera(this.name + "_R", 1);
if (leftCamera && rightCamera) {
this._rigCameras.push(leftCamera);
this._rigCameras.push(rightCamera);
}
}
switch (this.cameraRigMode) {
case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
break;
case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
break;
case Camera.RIG_MODE_VR:
var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
if (metrics.compensateDistortion) {
this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
}
break;
case Camera.RIG_MODE_WEBVR:
if (rigParams.vrDisplay) {
var leftEye = rigParams.vrDisplay.getEyeParameters('left');
var rightEye = rigParams.vrDisplay.getEyeParameters('right');
//Left eye
this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
this._rigCameras[0].setCameraRigParameter("left", true);
//leaving this for future reference
this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
this._rigCameras[0].parent = this;
this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
//Right eye
this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
this._rigCameras[1].parent = this;
this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
if (Camera.UseAlternateWebVRRendering) {
this._rigCameras[1]._skipRendering = true;
this._rigCameras[0]._alternateCamera = this._rigCameras[1];
}
}
break;
}
this._cascadePostProcessesToRigCams();
this.update();
};
Camera.prototype._getVRProjectionMatrix = function () {
BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
return this._projectionMatrix;
};
Camera.prototype._updateCameraRotationMatrix = function () {
//Here for WebVR
};
Camera.prototype._updateWebVRCameraRotationMatrix = function () {
//Here for WebVR
};
/**
* This function MUST be overwritten by the different WebVR cameras available.
* The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
*/
Camera.prototype._getWebVRProjectionMatrix = function () {
return BABYLON.Matrix.Identity();
};
/**
* This function MUST be overwritten by the different WebVR cameras available.
* The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
*/
Camera.prototype._getWebVRViewMatrix = function () {
return BABYLON.Matrix.Identity();
};
Camera.prototype.setCameraRigParameter = function (name, value) {
if (!this._cameraRigParams) {
this._cameraRigParams = {};
}
this._cameraRigParams[name] = value;
//provisionnally:
if (name === "interaxialDistance") {
this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
}
};
/**
* needs to be overridden by children so sub has required properties to be copied
*/
Camera.prototype.createRigCamera = function (name, cameraIndex) {
return null;
};
/**
* May need to be overridden by children
*/
Camera.prototype._updateRigCameras = function () {
for (var i = 0; i < this._rigCameras.length; i++) {
this._rigCameras[i].minZ = this.minZ;
this._rigCameras[i].maxZ = this.maxZ;
this._rigCameras[i].fov = this.fov;
}
// only update viewport when ANAGLYPH
if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
}
};
Camera.prototype._setupInputs = function () {
};
Camera.prototype.serialize = function () {
var serializationObject = BABYLON.SerializationHelper.Serialize(this);
// Type
serializationObject.type = this.getClassName();
// Parent
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
if (this.inputs) {
this.inputs.serialize(serializationObject);
}
// Animations
BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
serializationObject.ranges = this.serializeAnimationRanges();
return serializationObject;
};
Camera.prototype.clone = function (name) {
return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
};
Camera.prototype.getDirection = function (localAxis) {
var result = BABYLON.Vector3.Zero();
this.getDirectionToRef(localAxis, result);
return result;
};
Camera.prototype.getDirectionToRef = function (localAxis, result) {
BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
};
Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
if (interaxial_distance === void 0) { interaxial_distance = 0; }
if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
switch (type) {
case "ArcRotateCamera":
return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
case "DeviceOrientationCamera":
return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
case "FollowCamera":
return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
case "ArcFollowCamera":
return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
case "GamepadCamera":
return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
case "TouchCamera":
return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
case "VirtualJoysticksCamera":
return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
case "WebVRFreeCamera":
return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
case "WebVRGamepadCamera":
return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
case "VRDeviceOrientationFreeCamera":
return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
case "VRDeviceOrientationGamepadCamera":
return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
case "AnaglyphArcRotateCamera":
return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
case "AnaglyphFreeCamera":
return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
case "AnaglyphGamepadCamera":
return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
case "AnaglyphUniversalCamera":
return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
case "StereoscopicArcRotateCamera":
return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
case "StereoscopicFreeCamera":
return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
case "StereoscopicGamepadCamera":
return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
case "StereoscopicUniversalCamera":
return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
case "FreeCamera":// Forcing Universal here
return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
default:// Universal Camera is the default value
return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
}
};
Camera.prototype.computeWorldMatrix = function () {
return this.getWorldMatrix();
};
Camera.Parse = function (parsedCamera, scene) {
var type = parsedCamera.type;
var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
// Parent
if (parsedCamera.parentId) {
camera._waitingParentId = parsedCamera.parentId;
}
//If camera has an input manager, let it parse inputs settings
if (camera.inputs) {
camera.inputs.parse(parsedCamera);
camera._setupInputs();
}
if (camera.setPosition) {
camera.position.copyFromFloats(0, 0, 0);
camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
}
// Target
if (parsedCamera.target) {
if (camera.setTarget) {
camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
}
}
// Apply 3d rig, when found
if (parsedCamera.cameraRigMode) {
var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
}
// Animations
if (parsedCamera.animations) {
for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
var parsedAnimation = parsedCamera.animations[animationIndex];
camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
}
BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
}
if (parsedCamera.autoAnimate) {
scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
}
return camera;
};
// Statics
Camera._PERSPECTIVE_CAMERA = 0;
Camera._ORTHOGRAPHIC_CAMERA = 1;
Camera._FOVMODE_VERTICAL_FIXED = 0;
Camera._FOVMODE_HORIZONTAL_FIXED = 1;
Camera._RIG_MODE_NONE = 0;
Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
Camera._RIG_MODE_VR = 20;
Camera._RIG_MODE_WEBVR = 21;
Camera.ForceAttachControlToAlwaysPreventDefault = false;
Camera.UseAlternateWebVRRendering = false;
__decorate([
BABYLON.serializeAsVector3()
], Camera.prototype, "position", void 0);
__decorate([
BABYLON.serializeAsVector3()
], Camera.prototype, "upVector", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "orthoLeft", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "orthoRight", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "orthoBottom", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "orthoTop", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "fov", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "minZ", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "maxZ", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "inertia", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "mode", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "layerMask", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "fovMode", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "cameraRigMode", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "interaxialDistance", void 0);
__decorate([
BABYLON.serialize()
], Camera.prototype, "isStereoscopicSideBySide", void 0);
return Camera;
}(BABYLON.Node));
BABYLON.Camera = Camera;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.camera.js.map
var BABYLON;
(function (BABYLON) {
var RenderingManager = /** @class */ (function () {
function RenderingManager(scene) {
this._renderingGroups = new Array();
this._autoClearDepthStencil = {};
this._customOpaqueSortCompareFn = {};
this._customAlphaTestSortCompareFn = {};
this._customTransparentSortCompareFn = {};
this._renderinGroupInfo = null;
this._scene = scene;
for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
}
}
RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
if (depth === void 0) { depth = true; }
if (stencil === void 0) { stencil = true; }
if (this._depthStencilBufferAlreadyCleaned) {
return;
}
this._scene.getEngine().clear(null, false, depth, stencil);
this._depthStencilBufferAlreadyCleaned = true;
};
RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
// Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
var info = null;
if (observable) {
if (!this._renderinGroupInfo) {
this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
}
info = this._renderinGroupInfo;
info.scene = this._scene;
info.camera = this._scene.activeCamera;
}
// Dispatch sprites
if (renderSprites) {
for (var index = 0; index < this._scene.spriteManagers.length; index++) {
var manager = this._scene.spriteManagers[index];
this.dispatchSprites(manager);
}
}
// Render
for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
var renderingGroup = this._renderingGroups[index];
if (!renderingGroup && !observable)
continue;
var renderingGroupMask = 0;
// Fire PRECLEAR stage
if (observable && info) {
renderingGroupMask = Math.pow(2, index);
info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
info.renderingGroupId = index;
observable.notifyObservers(info, renderingGroupMask);
}
// Clear depth/stencil if needed
if (RenderingManager.AUTOCLEAR) {
var autoClear = this._autoClearDepthStencil[index];
if (autoClear && autoClear.autoClear) {
this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
}
}
if (observable && info) {
// Fire PREOPAQUE stage
info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
observable.notifyObservers(info, renderingGroupMask);
// Fire PRETRANSPARENT stage
info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
observable.notifyObservers(info, renderingGroupMask);
}
if (renderingGroup)
renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
// Fire POSTTRANSPARENT stage
if (observable && info) {
info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
observable.notifyObservers(info, renderingGroupMask);
}
}
};
RenderingManager.prototype.reset = function () {
for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
var renderingGroup = this._renderingGroups[index];
if (renderingGroup) {
renderingGroup.prepare();
}
}
};
RenderingManager.prototype.dispose = function () {
for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
var renderingGroup = this._renderingGroups[index];
if (renderingGroup) {
renderingGroup.dispose();
}
}
this._renderingGroups.length = 0;
};
RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
if (!this._renderingGroups[renderingGroupId]) {
this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
}
};
RenderingManager.prototype.dispatchSprites = function (spriteManager) {
var renderingGroupId = spriteManager.renderingGroupId || 0;
this._prepareRenderingGroup(renderingGroupId);
this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
};
RenderingManager.prototype.dispatchParticles = function (particleSystem) {
var renderingGroupId = particleSystem.renderingGroupId || 0;
this._prepareRenderingGroup(renderingGroupId);
this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
};
RenderingManager.prototype.dispatch = function (subMesh) {
var mesh = subMesh.getMesh();
var renderingGroupId = mesh.renderingGroupId || 0;
this._prepareRenderingGroup(renderingGroupId);
this._renderingGroups[renderingGroupId].dispatch(subMesh);
};
/**
* Overrides the default sort function applied in the renderging group to prepare the meshes.
* This allowed control for front to back rendering or reversly depending of the special needs.
*
* @param renderingGroupId The rendering group id corresponding to its index
* @param opaqueSortCompareFn The opaque queue comparison function use to sort.
* @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
* @param transparentSortCompareFn The transparent queue comparison function use to sort.
*/
RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
if (this._renderingGroups[renderingGroupId]) {
var group = this._renderingGroups[renderingGroupId];
group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
}
};
/**
* Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
*
* @param renderingGroupId The rendering group id corresponding to its index
* @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
* @param depth Automatically clears depth between groups if true and autoClear is true.
* @param stencil Automatically clears stencil between groups if true and autoClear is true.
*/
RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
if (depth === void 0) { depth = true; }
if (stencil === void 0) { stencil = true; }
this._autoClearDepthStencil[renderingGroupId] = {
autoClear: autoClearDepthStencil,
depth: depth,
stencil: stencil
};
};
/**
* The max id used for rendering groups (not included)
*/
RenderingManager.MAX_RENDERINGGROUPS = 4;
/**
* The min id used for rendering groups (included)
*/
RenderingManager.MIN_RENDERINGGROUPS = 0;
/**
* Used to globally prevent autoclearing scenes.
*/
RenderingManager.AUTOCLEAR = true;
return RenderingManager;
}());
BABYLON.RenderingManager = RenderingManager;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.renderingManager.js.map
var BABYLON;
(function (BABYLON) {
var RenderingGroup = /** @class */ (function () {
/**
* Creates a new rendering group.
* @param index The rendering group index
* @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
* @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
* @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
*/
function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
this.index = index;
this._opaqueSubMeshes = new BABYLON.SmartArray(256);
this._transparentSubMeshes = new BABYLON.SmartArray(256);
this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
this._particleSystems = new BABYLON.SmartArray(256);
this._spriteManagers = new BABYLON.SmartArray(256);
this._edgesRenderers = new BABYLON.SmartArray(16);
this._scene = scene;
this.opaqueSortCompareFn = opaqueSortCompareFn;
this.alphaTestSortCompareFn = alphaTestSortCompareFn;
this.transparentSortCompareFn = transparentSortCompareFn;
}
Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
/**
* Set the opaque sort comparison function.
* If null the sub meshes will be render in the order they were created
*/
set: function (value) {
this._opaqueSortCompareFn = value;
if (value) {
this._renderOpaque = this.renderOpaqueSorted;
}
else {
this._renderOpaque = RenderingGroup.renderUnsorted;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
/**
* Set the alpha test sort comparison function.
* If null the sub meshes will be render in the order they were created
*/
set: function (value) {
this._alphaTestSortCompareFn = value;
if (value) {
this._renderAlphaTest = this.renderAlphaTestSorted;
}
else {
this._renderAlphaTest = RenderingGroup.renderUnsorted;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
/**
* Set the transparent sort comparison function.
* If null the sub meshes will be render in the order they were created
*/
set: function (value) {
if (value) {
this._transparentSortCompareFn = value;
}
else {
this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
}
this._renderTransparent = this.renderTransparentSorted;
},
enumerable: true,
configurable: true
});
/**
* Render all the sub meshes contained in the group.
* @param customRenderFunction Used to override the default render behaviour of the group.
* @returns true if rendered some submeshes.
*/
RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
if (customRenderFunction) {
customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
return;
}
var engine = this._scene.getEngine();
// Depth only
if (this._depthOnlySubMeshes.length !== 0) {
engine.setAlphaTesting(true);
engine.setColorWrite(false);
this._renderAlphaTest(this._depthOnlySubMeshes);
engine.setAlphaTesting(false);
engine.setColorWrite(true);
}
// Opaque
if (this._opaqueSubMeshes.length !== 0) {
this._renderOpaque(this._opaqueSubMeshes);
}
// Alpha test
if (this._alphaTestSubMeshes.length !== 0) {
engine.setAlphaTesting(true);
this._renderAlphaTest(this._alphaTestSubMeshes);
engine.setAlphaTesting(false);
}
var stencilState = engine.getStencilBuffer();
engine.setStencilBuffer(false);
// Sprites
if (renderSprites) {
this._renderSprites();
}
// Particles
if (renderParticles) {
this._renderParticles(activeMeshes);
}
if (this.onBeforeTransparentRendering) {
this.onBeforeTransparentRendering();
}
// Transparent
if (this._transparentSubMeshes.length !== 0) {
this._renderTransparent(this._transparentSubMeshes);
engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
}
// Set back stencil to false in case it changes before the edge renderer.
engine.setStencilBuffer(false);
// Edges
for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
this._edgesRenderers.data[edgesRendererIndex].render();
}
// Restore Stencil state.
engine.setStencilBuffer(stencilState);
};
/**
* Renders the opaque submeshes in the order from the opaqueSortCompareFn.
* @param subMeshes The submeshes to render
*/
RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
};
/**
* Renders the opaque submeshes in the order from the alphatestSortCompareFn.
* @param subMeshes The submeshes to render
*/
RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
};
/**
* Renders the opaque submeshes in the order from the transparentSortCompareFn.
* @param subMeshes The submeshes to render
*/
RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
};
/**
* Renders the submeshes in a specified order.
* @param subMeshes The submeshes to sort before render
* @param sortCompareFn The comparison function use to sort
* @param cameraPosition The camera position use to preprocess the submeshes to help sorting
* @param transparent Specifies to activate blending if true
*/
RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
var subIndex = 0;
var subMesh;
var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
for (; subIndex < subMeshes.length; subIndex++) {
subMesh = subMeshes.data[subIndex];
subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
}
var sortedArray = subMeshes.data.slice(0, subMeshes.length);
if (sortCompareFn) {
sortedArray.sort(sortCompareFn);
}
for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
subMesh = sortedArray[subIndex];
if (transparent) {
var material = subMesh.getMaterial();
if (material && material.needDepthPrePass) {
var engine = material.getScene().getEngine();
engine.setColorWrite(false);
engine.setAlphaTesting(true);
engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
subMesh.render(false);
engine.setAlphaTesting(false);
engine.setColorWrite(true);
}
}
subMesh.render(transparent);
}
};
/**
* Renders the submeshes in the order they were dispatched (no sort applied).
* @param subMeshes The submeshes to render
*/
RenderingGroup.renderUnsorted = function (subMeshes) {
for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
var submesh = subMeshes.data[subIndex];
submesh.render(false);
}
};
/**
* Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
* are rendered back to front if in the same alpha index.
*
* @param a The first submesh
* @param b The second submesh
* @returns The result of the comparison
*/
RenderingGroup.defaultTransparentSortCompare = function (a, b) {
// Alpha index first
if (a._alphaIndex > b._alphaIndex) {
return 1;
}
if (a._alphaIndex < b._alphaIndex) {
return -1;
}
// Then distance to camera
return RenderingGroup.backToFrontSortCompare(a, b);
};
/**
* Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
* are rendered back to front.
*
* @param a The first submesh
* @param b The second submesh
* @returns The result of the comparison
*/
RenderingGroup.backToFrontSortCompare = function (a, b) {
// Then distance to camera
if (a._distanceToCamera < b._distanceToCamera) {
return 1;
}
if (a._distanceToCamera > b._distanceToCamera) {
return -1;
}
return 0;
};
/**
* Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
* are rendered front to back (prevent overdraw).
*
* @param a The first submesh
* @param b The second submesh
* @returns The result of the comparison
*/
RenderingGroup.frontToBackSortCompare = function (a, b) {
// Then distance to camera
if (a._distanceToCamera < b._distanceToCamera) {
return -1;
}
if (a._distanceToCamera > b._distanceToCamera) {
return 1;
}
return 0;
};
/**
* Resets the different lists of submeshes to prepare a new frame.
*/
RenderingGroup.prototype.prepare = function () {
this._opaqueSubMeshes.reset();
this._transparentSubMeshes.reset();
this._alphaTestSubMeshes.reset();
this._depthOnlySubMeshes.reset();
this._particleSystems.reset();
this._spriteManagers.reset();
this._edgesRenderers.reset();
};
RenderingGroup.prototype.dispose = function () {
this._opaqueSubMeshes.dispose();
this._transparentSubMeshes.dispose();
this._alphaTestSubMeshes.dispose();
this._depthOnlySubMeshes.dispose();
this._particleSystems.dispose();
this._spriteManagers.dispose();
this._edgesRenderers.dispose();
};
/**
* Inserts the submesh in its correct queue depending on its material.
* @param subMesh The submesh to dispatch
*/
RenderingGroup.prototype.dispatch = function (subMesh) {
var material = subMesh.getMaterial();
var mesh = subMesh.getMesh();
if (!material) {
return;
}
if (material.needAlphaBlendingForMesh(mesh)) {
this._transparentSubMeshes.push(subMesh);
}
else if (material.needAlphaTesting()) {
if (material.needDepthPrePass) {
this._depthOnlySubMeshes.push(subMesh);
}
this._alphaTestSubMeshes.push(subMesh);
}
else {
if (material.needDepthPrePass) {
this._depthOnlySubMeshes.push(subMesh);
}
this._opaqueSubMeshes.push(subMesh); // Opaque
}
if (mesh._edgesRenderer) {
this._edgesRenderers.push(mesh._edgesRenderer);
}
};
RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
this._spriteManagers.push(spriteManager);
};
RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
this._particleSystems.push(particleSystem);
};
RenderingGroup.prototype._renderParticles = function (activeMeshes) {
if (this._particleSystems.length === 0) {
return;
}
// Particles
var activeCamera = this._scene.activeCamera;
this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
continue;
}
var emitter = particleSystem.emitter;
if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
this._scene._activeParticles.addCount(particleSystem.render(), false);
}
}
this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
};
RenderingGroup.prototype._renderSprites = function () {
if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
return;
}
// Sprites
var activeCamera = this._scene.activeCamera;
this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
for (var id = 0; id < this._spriteManagers.length; id++) {
var spriteManager = this._spriteManagers.data[id];
if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
spriteManager.render();
}
}
this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
};
return RenderingGroup;
}());
BABYLON.RenderingGroup = RenderingGroup;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.renderingGroup.js.map
var BABYLON;
(function (BABYLON) {
var ClickInfo = /** @class */ (function () {
function ClickInfo() {
this._singleClick = false;
this._doubleClick = false;
this._hasSwiped = false;
this._ignore = false;
}
Object.defineProperty(ClickInfo.prototype, "singleClick", {
get: function () {
return this._singleClick;
},
set: function (b) {
this._singleClick = b;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ClickInfo.prototype, "doubleClick", {
get: function () {
return this._doubleClick;
},
set: function (b) {
this._doubleClick = b;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
get: function () {
return this._hasSwiped;
},
set: function (b) {
this._hasSwiped = b;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ClickInfo.prototype, "ignore", {
get: function () {
return this._ignore;
},
set: function (b) {
this._ignore = b;
},
enumerable: true,
configurable: true
});
return ClickInfo;
}());
/**
* This class is used by the onRenderingGroupObservable
*/
var RenderingGroupInfo = /** @class */ (function () {
function RenderingGroupInfo() {
}
/**
* Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
* This stage will be fired no matter what
*/
RenderingGroupInfo.STAGE_PRECLEAR = 1;
/**
* Called before opaque object are rendered.
* This stage will be fired only if there's 3D Opaque content to render
*/
RenderingGroupInfo.STAGE_PREOPAQUE = 2;
/**
* Called after the opaque objects are rendered and before the transparent ones
* This stage will be fired only if there's 3D transparent content to render
*/
RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
/**
* Called after the transparent object are rendered, last hook of the renderingGroup phase
* This stage will be fired no matter what
*/
RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
return RenderingGroupInfo;
}());
BABYLON.RenderingGroupInfo = RenderingGroupInfo;
/**
* Represents a scene to be rendered by the engine.
* @see http://doc.babylonjs.com/page.php?p=21911
*/
var Scene = /** @class */ (function () {
/**
* @constructor
* @param {BABYLON.Engine} engine - the engine to be used to render this scene.
*/
function Scene(engine) {
// Members
this.autoClear = true;
this.autoClearDepthAndStencil = true;
this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
this.ambientColor = new BABYLON.Color3(0, 0, 0);
this.forceWireframe = false;
this._forcePointsCloud = false;
this.forceShowBoundingBoxes = false;
this.animationsEnabled = true;
this.useConstantAnimationDeltaTime = false;
this.constantlyUpdateMeshUnderPointer = false;
this.hoverCursor = "pointer";
this.defaultCursor = "";
/**
* This is used to call preventDefault() on pointer down
* in order to block unwanted artifacts like system double clicks
*/
this.preventDefaultOnPointerDown = true;
// Metadata
this.metadata = null;
/**
* An event triggered when the scene is disposed.
* @type {BABYLON.Observable}
*/
this.onDisposeObservable = new BABYLON.Observable();
/**
* An event triggered before rendering the scene (right after animations and physics)
* @type {BABYLON.Observable}
*/
this.onBeforeRenderObservable = new BABYLON.Observable();
/**
* An event triggered after rendering the scene
* @type {BABYLON.Observable}
*/
this.onAfterRenderObservable = new BABYLON.Observable();
/**
* An event triggered before animating the scene
* @type {BABYLON.Observable}
*/
this.onBeforeAnimationsObservable = new BABYLON.Observable();
/**
* An event triggered after animations processing
* @type {BABYLON.Observable}
*/
this.onAfterAnimationsObservable = new BABYLON.Observable();
/**
* An event triggered before draw calls are ready to be sent
* @type {BABYLON.Observable}
*/
this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
/**
* An event triggered after draw calls have been sent
* @type {BABYLON.Observable}
*/
this.onAfterDrawPhaseObservable = new BABYLON.Observable();
/**
* An event triggered when physic simulation is about to be run
* @type {BABYLON.Observable}
*/
this.onBeforePhysicsObservable = new BABYLON.Observable();
/**
* An event triggered when physic simulation has been done
* @type {BABYLON.Observable}
*/
this.onAfterPhysicsObservable = new BABYLON.Observable();
/**
* An event triggered when the scene is ready
* @type {BABYLON.Observable}
*/
this.onReadyObservable = new BABYLON.Observable();
/**
* An event triggered before rendering a camera
* @type {BABYLON.Observable}
*/
this.onBeforeCameraRenderObservable = new BABYLON.Observable();
/**
* An event triggered after rendering a camera
* @type {BABYLON.Observable}
*/
this.onAfterCameraRenderObservable = new BABYLON.Observable();
/**
* An event triggered when active meshes evaluation is about to start
* @type {BABYLON.Observable}
*/
this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
/**
* An event triggered when active meshes evaluation is done
* @type {BABYLON.Observable}
*/
this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
/**
* An event triggered when particles rendering is about to start
* Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
* @type {BABYLON.Observable}
*/
this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
/**
* An event triggered when particles rendering is done
* Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
* @type {BABYLON.Observable}
*/
this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
/**
* An event triggered when sprites rendering is about to start
* Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
* @type {BABYLON.Observable}
*/
this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
/**
* An event triggered when sprites rendering is done
* Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
* @type {BABYLON.Observable}
*/
this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
/**
* An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
* @type {BABYLON.Observable}
*/
this.onDataLoadedObservable = new BABYLON.Observable();
/**
* An event triggered when a camera is created
* @type {BABYLON.Observable}
*/
this.onNewCameraAddedObservable = new BABYLON.Observable();
/**
* An event triggered when a camera is removed
* @type {BABYLON.Observable}
*/
this.onCameraRemovedObservable = new BABYLON.Observable();
/**
* An event triggered when a light is created
* @type {BABYLON.Observable}
*/
this.onNewLightAddedObservable = new BABYLON.Observable();
/**
* An event triggered when a light is removed
* @type {BABYLON.Observable}
*/
this.onLightRemovedObservable = new BABYLON.Observable();
/**
* An event triggered when a geometry is created
* @type {BABYLON.Observable}
*/
this.onNewGeometryAddedObservable = new BABYLON.Observable();
/**
* An event triggered when a geometry is removed
* @type {BABYLON.Observable}
*/
this.onGeometryRemovedObservable = new BABYLON.Observable();
/**
* An event triggered when a transform node is created
* @type {BABYLON.Observable}
*/
this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
/**
* An event triggered when a transform node is removed
* @type {BABYLON.Observable}
*/
this.onTransformNodeRemovedObservable = new BABYLON.Observable();
/**
* An event triggered when a mesh is created
* @type {BABYLON.Observable}
*/
this.onNewMeshAddedObservable = new BABYLON.Observable();
/**
* An event triggered when a mesh is removed
* @type {BABYLON.Observable}
*/
this.onMeshRemovedObservable = new BABYLON.Observable();
/**
* An event triggered when render targets are about to be rendered
* Can happen multiple times per frame.
* @type {BABYLON.Observable}
*/
this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
/**
* An event triggered when render targets were rendered.
* Can happen multiple times per frame.
* @type {BABYLON.Observable}
*/
this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
/**
* An event triggered before calculating deterministic simulation step
* @type {BABYLON.Observable}
*/
this.onBeforeStepObservable = new BABYLON.Observable();
/**
* An event triggered after calculating deterministic simulation step
* @type {BABYLON.Observable}
*/
this.onAfterStepObservable = new BABYLON.Observable();
/**
* This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
* The RenderinGroupInfo class contains all the information about the context in which the observable is called
* If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
*/
this.onRenderingGroupObservable = new BABYLON.Observable();
// Animations
this.animations = [];
/**
* This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
* You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
*/
this.onPrePointerObservable = new BABYLON.Observable();
/**
* Observable event triggered each time an input event is received from the rendering canvas
*/
this.onPointerObservable = new BABYLON.Observable();
this._meshPickProceed = false;
this._currentPickResult = null;
this._previousPickResult = null;
this._totalPointersPressed = 0;
this._doubleClickOccured = false;
/** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
this.cameraToUseForPointers = null;
this._startingPointerPosition = new BABYLON.Vector2(0, 0);
this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
this._startingPointerTime = 0;
this._previousStartingPointerTime = 0;
// Deterministic lockstep
this._timeAccumulator = 0;
this._currentStepId = 0;
this._currentInternalStep = 0;
// Keyboard
/**
* This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
* You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
*/
this.onPreKeyboardObservable = new BABYLON.Observable();
/**
* Observable event triggered each time an keyboard event is received from the hosting window
*/
this.onKeyboardObservable = new BABYLON.Observable();
// Coordinate system
/**
* use right-handed coordinate system on this scene.
* @type {boolean}
*/
this._useRightHandedSystem = false;
// Fog
this._fogEnabled = true;
this._fogMode = Scene.FOGMODE_NONE;
this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
this.fogDensity = 0.1;
this.fogStart = 0;
this.fogEnd = 1000.0;
// Lights
/**
* is shadow enabled on this scene.
* @type {boolean}
*/
this._shadowsEnabled = true;
/**
* is light enabled on this scene.
* @type {boolean}
*/
this._lightsEnabled = true;
/**
* All of the lights added to this scene.
* @see BABYLON.Light
* @type {BABYLON.Light[]}
*/
this.lights = new Array();
// Cameras
/** All of the cameras added to this scene. */
this.cameras = new Array();
/** All of the active cameras added to this scene. */
this.activeCameras = new Array();
// Meshes
/**
* All of the tranform nodes added to this scene.
* @see BABYLON.TransformNode
* @type {BABYLON.TransformNode[]}
*/
this.transformNodes = new Array();
/**
* All of the (abstract) meshes added to this scene.
* @see BABYLON.AbstractMesh
* @type {BABYLON.AbstractMesh[]}
*/
this.meshes = new Array();
/**
* All of the animation groups added to this scene.
* @see BABYLON.AnimationGroup
* @type {BABYLON.AnimationGroup[]}
*/
this.animationGroups = new Array();
// Geometries
this._geometries = new Array();
this.materials = new Array();
this.multiMaterials = new Array();
// Textures
this._texturesEnabled = true;
this.textures = new Array();
// Particles
this.particlesEnabled = true;
this.particleSystems = new Array();
// Sprites
this.spritesEnabled = true;
this.spriteManagers = new Array();
// Layers
this.layers = new Array();
this.highlightLayers = new Array();
// Skeletons
this._skeletonsEnabled = true;
this.skeletons = new Array();
// Morph targets
this.morphTargetManagers = new Array();
// Lens flares
this.lensFlaresEnabled = true;
this.lensFlareSystems = new Array();
// Collisions
this.collisionsEnabled = true;
/** Defines the gravity applied to this scene */
this.gravity = new BABYLON.Vector3(0, -9.807, 0);
// Postprocesses
this.postProcesses = new Array();
this.postProcessesEnabled = true;
// Customs render targets
this.renderTargetsEnabled = true;
this.dumpNextRenderTargets = false;
this.customRenderTargets = new Array();
// Imported meshes
this.importedMeshesFiles = new Array();
// Probes
this.probesEnabled = true;
this.reflectionProbes = new Array();
this._actionManagers = new Array();
this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
// Procedural textures
this.proceduralTexturesEnabled = true;
this._proceduralTextures = new Array();
this.soundTracks = new Array();
this._audioEnabled = true;
this._headphone = false;
// Performance counters
this._totalVertices = new BABYLON.PerfCounter();
this._activeIndices = new BABYLON.PerfCounter();
this._activeParticles = new BABYLON.PerfCounter();
this._activeBones = new BABYLON.PerfCounter();
this._animationTime = 0;
this.animationTimeScale = 1;
this._renderId = 0;
this._executeWhenReadyTimeoutId = -1;
this._intermediateRendering = false;
this._viewUpdateFlag = -1;
this._projectionUpdateFlag = -1;
this._alternateViewUpdateFlag = -1;
this._alternateProjectionUpdateFlag = -1;
this._toBeDisposed = new BABYLON.SmartArray(256);
this._pendingData = new Array();
this._isDisposed = false;
this._activeMeshes = new BABYLON.SmartArray(256);
this._processedMaterials = new BABYLON.SmartArray(256);
this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
this._activeParticleSystems = new BABYLON.SmartArray(256);
this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
this._activeAnimatables = new Array();
this._transformMatrix = BABYLON.Matrix.Zero();
this._useAlternateCameraConfiguration = false;
this._alternateRendering = false;
this.requireLightSorting = false;
this._activeMeshesFrozen = false;
this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
this._engine = engine || BABYLON.Engine.LastCreatedEngine;
this._engine.scenes.push(this);
this._uid = null;
this._renderingManager = new BABYLON.RenderingManager(this);
this.postProcessManager = new BABYLON.PostProcessManager(this);
if (BABYLON.OutlineRenderer) {
this._outlineRenderer = new BABYLON.OutlineRenderer(this);
}
if (BABYLON.Tools.IsWindowObjectExist()) {
this.attachControl();
}
//simplification queue
if (BABYLON.SimplificationQueue) {
this.simplificationQueue = new BABYLON.SimplificationQueue();
}
//collision coordinator initialization. For now legacy per default.
this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
// Uniform Buffer
this._createUbo();
// Default Image processing definition.
this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
}
Object.defineProperty(Scene, "FOGMODE_NONE", {
/** The fog is deactivated */
get: function () {
return Scene._FOGMODE_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene, "FOGMODE_EXP", {
/** The fog density is following an exponential function */
get: function () {
return Scene._FOGMODE_EXP;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene, "FOGMODE_EXP2", {
/** The fog density is following an exponential function faster than FOGMODE_EXP */
get: function () {
return Scene._FOGMODE_EXP2;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene, "FOGMODE_LINEAR", {
/** The fog density is following a linear function. */
get: function () {
return Scene._FOGMODE_LINEAR;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "environmentTexture", {
/**
* Texture used in all pbr material as the reflection texture.
* As in the majority of the scene they are the same (exception for multi room and so on),
* this is easier to reference from here than from all the materials.
*/
get: function () {
return this._environmentTexture;
},
/**
* Texture used in all pbr material as the reflection texture.
* As in the majority of the scene they are the same (exception for multi room and so on),
* this is easier to set here than in all the materials.
*/
set: function (value) {
if (this._environmentTexture === value) {
return;
}
this._environmentTexture = value;
this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
/**
* Default image processing configuration used either in the rendering
* Forward main pass or through the imageProcessingPostProcess if present.
* As in the majority of the scene they are the same (exception for multi camera),
* this is easier to reference from here than from all the materials and post process.
*
* No setter as we it is a shared configuration, you can set the values instead.
*/
get: function () {
return this._imageProcessingConfiguration;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "forcePointsCloud", {
get: function () {
return this._forcePointsCloud;
},
set: function (value) {
if (this._forcePointsCloud === value) {
return;
}
this._forcePointsCloud = value;
this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "onDispose", {
/** A function to be executed when this scene is disposed. */
set: function (callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "beforeRender", {
/** A function to be executed before rendering this scene */
set: function (callback) {
if (this._onBeforeRenderObserver) {
this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
}
if (callback) {
this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "afterRender", {
/** A function to be executed after rendering this scene */
set: function (callback) {
if (this._onAfterRenderObserver) {
this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
}
if (callback) {
this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "beforeCameraRender", {
set: function (callback) {
if (this._onBeforeCameraRenderObserver) {
this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
}
this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "afterCameraRender", {
set: function (callback) {
if (this._onAfterCameraRenderObserver) {
this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
}
this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "gamepadManager", {
get: function () {
if (!this._gamepadManager) {
this._gamepadManager = new BABYLON.GamepadManager(this);
}
return this._gamepadManager;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
get: function () {
return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
get: function () {
return this._useRightHandedSystem;
},
set: function (value) {
if (this._useRightHandedSystem === value) {
return;
}
this._useRightHandedSystem = value;
this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Scene.prototype.setStepId = function (newStepId) {
this._currentStepId = newStepId;
};
;
Scene.prototype.getStepId = function () {
return this._currentStepId;
};
;
Scene.prototype.getInternalStep = function () {
return this._currentInternalStep;
};
;
Object.defineProperty(Scene.prototype, "fogEnabled", {
get: function () {
return this._fogEnabled;
},
/**
* is fog enabled on this scene.
*/
set: function (value) {
if (this._fogEnabled === value) {
return;
}
this._fogEnabled = value;
this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "fogMode", {
get: function () {
return this._fogMode;
},
set: function (value) {
if (this._fogMode === value) {
return;
}
this._fogMode = value;
this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "shadowsEnabled", {
get: function () {
return this._shadowsEnabled;
},
set: function (value) {
if (this._shadowsEnabled === value) {
return;
}
this._shadowsEnabled = value;
this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "lightsEnabled", {
get: function () {
return this._lightsEnabled;
},
set: function (value) {
if (this._lightsEnabled === value) {
return;
}
this._lightsEnabled = value;
this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "defaultMaterial", {
/** The default material used on meshes when no material is affected */
get: function () {
if (!this._defaultMaterial) {
this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
}
return this._defaultMaterial;
},
/** The default material used on meshes when no material is affected */
set: function (value) {
this._defaultMaterial = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "texturesEnabled", {
get: function () {
return this._texturesEnabled;
},
set: function (value) {
if (this._texturesEnabled === value) {
return;
}
this._texturesEnabled = value;
this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
get: function () {
return this._skeletonsEnabled;
},
set: function (value) {
if (this._skeletonsEnabled === value) {
return;
}
this._skeletonsEnabled = value;
this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
get: function () {
if (!this._postProcessRenderPipelineManager) {
this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
}
return this._postProcessRenderPipelineManager;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "mainSoundTrack", {
get: function () {
if (!this._mainSoundTrack) {
this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
}
return this._mainSoundTrack;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
get: function () {
return this._alternateRendering;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "frustumPlanes", {
get: function () {
return this._frustumPlanes;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "debugLayer", {
// Properties
get: function () {
if (!this._debugLayer) {
this._debugLayer = new BABYLON.DebugLayer(this);
}
return this._debugLayer;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "workerCollisions", {
get: function () {
return this._workerCollisions;
},
set: function (enabled) {
if (!BABYLON.CollisionCoordinatorLegacy) {
return;
}
enabled = (enabled && !!Worker);
this._workerCollisions = enabled;
if (this.collisionCoordinator) {
this.collisionCoordinator.destroy();
}
this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
this.collisionCoordinator.init(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "selectionOctree", {
get: function () {
return this._selectionOctree;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "meshUnderPointer", {
/**
* The mesh that is currently under the pointer.
* @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
*/
get: function () {
return this._pointerOverMesh;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "pointerX", {
/**
* Current on-screen X position of the pointer
* @return {number} X position of the pointer
*/
get: function () {
return this._pointerX;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene.prototype, "pointerY", {
/**
* Current on-screen Y position of the pointer
* @return {number} Y position of the pointer
*/
get: function () {
return this._pointerY;
},
enumerable: true,
configurable: true
});
Scene.prototype.getCachedMaterial = function () {
return this._cachedMaterial;
};
Scene.prototype.getCachedEffect = function () {
return this._cachedEffect;
};
Scene.prototype.getCachedVisibility = function () {
return this._cachedVisibility;
};
Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
if (visibility === void 0) { visibility = 1; }
return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
};
Scene.prototype.getBoundingBoxRenderer = function () {
if (!this._boundingBoxRenderer) {
this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
}
return this._boundingBoxRenderer;
};
Scene.prototype.getOutlineRenderer = function () {
return this._outlineRenderer;
};
Scene.prototype.getEngine = function () {
return this._engine;
};
Scene.prototype.getTotalVertices = function () {
return this._totalVertices.current;
};
Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
get: function () {
return this._totalVertices;
},
enumerable: true,
configurable: true
});
Scene.prototype.getActiveIndices = function () {
return this._activeIndices.current;
};
Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
get: function () {
return this._activeIndices;
},
enumerable: true,
configurable: true
});
Scene.prototype.getActiveParticles = function () {
return this._activeParticles.current;
};
Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
get: function () {
return this._activeParticles;
},
enumerable: true,
configurable: true
});
Scene.prototype.getActiveBones = function () {
return this._activeBones.current;
};
Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
get: function () {
return this._activeBones;
},
enumerable: true,
configurable: true
});
// Stats
Scene.prototype.getInterFramePerfCounter = function () {
BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
get: function () {
BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene.prototype.getLastFrameDuration = function () {
BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
get: function () {
BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene.prototype.getEvaluateActiveMeshesDuration = function () {
BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
get: function () {
BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene.prototype.getActiveMeshes = function () {
return this._activeMeshes;
};
Scene.prototype.getRenderTargetsDuration = function () {
BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Scene.prototype.getRenderDuration = function () {
BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
get: function () {
BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene.prototype.getParticlesDuration = function () {
BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
get: function () {
BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene.prototype.getSpritesDuration = function () {
BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
get: function () {
BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene.prototype.getAnimationRatio = function () {
return this._animationRatio;
};
Scene.prototype.getRenderId = function () {
return this._renderId;
};
Scene.prototype.incrementRenderId = function () {
this._renderId++;
};
Scene.prototype._updatePointerPosition = function (evt) {
var canvasRect = this._engine.getRenderingCanvasClientRect();
if (!canvasRect) {
return;
}
this._pointerX = evt.clientX - canvasRect.left;
this._pointerY = evt.clientY - canvasRect.top;
this._unTranslatedPointerX = this._pointerX;
this._unTranslatedPointerY = this._pointerY;
};
Scene.prototype._createUbo = function () {
this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
this._sceneUbo.addUniform("viewProjection", 16);
this._sceneUbo.addUniform("view", 16);
};
Scene.prototype._createAlternateUbo = function () {
this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
this._alternateSceneUbo.addUniform("viewProjection", 16);
this._alternateSceneUbo.addUniform("view", 16);
};
// Pointers handling
/**
* Use this method to simulate a pointer move on a mesh
* The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
*/
Scene.prototype.simulatePointerMove = function (pickResult) {
var evt = new PointerEvent("pointermove");
return this._processPointerMove(pickResult, evt);
};
Scene.prototype._processPointerMove = function (pickResult, evt) {
var canvas = this._engine.getRenderingCanvas();
if (!canvas) {
return this;
}
if (pickResult && pickResult.hit && pickResult.pickedMesh) {
this.setPointerOverSprite(null);
this.setPointerOverMesh(pickResult.pickedMesh);
if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
if (this._pointerOverMesh.actionManager.hoverCursor) {
canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
}
else {
canvas.style.cursor = this.hoverCursor;
}
}
else {
canvas.style.cursor = this.defaultCursor;
}
}
else {
this.setPointerOverMesh(null);
// Sprites
pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
if (pickResult && pickResult.hit && pickResult.pickedSprite) {
this.setPointerOverSprite(pickResult.pickedSprite);
if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
}
else {
canvas.style.cursor = this.hoverCursor;
}
}
else {
this.setPointerOverSprite(null);
// Restore pointer
canvas.style.cursor = this.defaultCursor;
}
}
if (pickResult) {
if (this.onPointerMove) {
this.onPointerMove(evt, pickResult);
}
if (this.onPointerObservable.hasObservers()) {
var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
var pi = new BABYLON.PointerInfo(type, evt, pickResult);
this.onPointerObservable.notifyObservers(pi, type);
}
}
return this;
};
/**
* Use this method to simulate a pointer down on a mesh
* The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
*/
Scene.prototype.simulatePointerDown = function (pickResult) {
var evt = new PointerEvent("pointerdown");
return this._processPointerDown(pickResult, evt);
};
Scene.prototype._processPointerDown = function (pickResult, evt) {
var _this = this;
if (pickResult && pickResult.hit && pickResult.pickedMesh) {
this._pickedDownMesh = pickResult.pickedMesh;
var actionManager = pickResult.pickedMesh.actionManager;
if (actionManager) {
if (actionManager.hasPickTriggers) {
actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
switch (evt.button) {
case 0:
actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
break;
case 1:
actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
break;
case 2:
actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
break;
}
}
if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
window.setTimeout(function () {
var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);
if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
if (_this._totalPointersPressed !== 0 &&
((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
(Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
_this._startingPointerTime = 0;
actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
}
}
}, Scene.LongPressDelay);
}
}
}
if (pickResult) {
if (this.onPointerDown) {
this.onPointerDown(evt, pickResult);
}
if (this.onPointerObservable.hasObservers()) {
var type = BABYLON.PointerEventTypes.POINTERDOWN;
var pi = new BABYLON.PointerInfo(type, evt, pickResult);
this.onPointerObservable.notifyObservers(pi, type);
}
}
return this;
};
/**
* Use this method to simulate a pointer up on a mesh
* The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
*/
Scene.prototype.simulatePointerUp = function (pickResult) {
var evt = new PointerEvent("pointerup");
var clickInfo = new ClickInfo();
clickInfo.singleClick = true;
clickInfo.ignore = true;
return this._processPointerUp(pickResult, evt, clickInfo);
};
Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
if (pickResult && pickResult && pickResult.pickedMesh) {
this._pickedUpMesh = pickResult.pickedMesh;
if (this._pickedDownMesh === this._pickedUpMesh) {
if (this.onPointerPick) {
this.onPointerPick(evt, pickResult);
}
if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
var type = BABYLON.PointerEventTypes.POINTERPICK;
var pi = new BABYLON.PointerInfo(type, evt, pickResult);
this.onPointerObservable.notifyObservers(pi, type);
}
}
if (pickResult.pickedMesh.actionManager) {
if (clickInfo.ignore) {
pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
}
if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
}
if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
}
}
}
if (this._pickedDownMesh &&
this._pickedDownMesh.actionManager &&
this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
this._pickedDownMesh !== this._pickedUpMesh) {
this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
}
if (this.onPointerUp) {
this.onPointerUp(evt, pickResult);
}
if (this.onPointerObservable.hasObservers()) {
if (!clickInfo.ignore) {
if (!clickInfo.hasSwiped) {
if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
var type = BABYLON.PointerEventTypes.POINTERTAP;
var pi = new BABYLON.PointerInfo(type, evt, pickResult);
this.onPointerObservable.notifyObservers(pi, type);
}
if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
var pi = new BABYLON.PointerInfo(type, evt, pickResult);
this.onPointerObservable.notifyObservers(pi, type);
}
}
}
else {
var type = BABYLON.PointerEventTypes.POINTERUP;
var pi = new BABYLON.PointerInfo(type, evt, pickResult);
this.onPointerObservable.notifyObservers(pi, type);
}
}
return this;
};
/**
* Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
* @param attachUp defines if you want to attach events to pointerup
* @param attachDown defines if you want to attach events to pointerdown
* @param attachMove defines if you want to attach events to pointermove
*/
Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
var _this = this;
if (attachUp === void 0) { attachUp = true; }
if (attachDown === void 0) { attachDown = true; }
if (attachMove === void 0) { attachMove = true; }
this._initActionManager = function (act, clickInfo) {
if (!_this._meshPickProceed) {
var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
_this._currentPickResult = pickResult;
if (pickResult) {
act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
}
_this._meshPickProceed = true;
}
return act;
};
this._delayedSimpleClick = function (btn, clickInfo, cb) {
// double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
btn !== _this._previousButtonPressed) {
_this._doubleClickOccured = false;
clickInfo.singleClick = true;
clickInfo.ignore = false;
cb(clickInfo, _this._currentPickResult);
}
};
this._initClickEvent = function (obs1, obs2, evt, cb) {
var clickInfo = new ClickInfo();
_this._currentPickResult = null;
var act = null;
var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
|| obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
|| obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
act = _this._initActionManager(act, clickInfo);
if (act)
checkPicking = act.hasPickTriggers;
}
if (checkPicking) {
var btn = evt.button;
clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
if (!clickInfo.hasSwiped) {
var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
if (!checkSingleClickImmediately) {
checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
!obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
act = _this._initActionManager(act, clickInfo);
if (act)
checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
}
}
if (checkSingleClickImmediately) {
// single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
btn !== _this._previousButtonPressed) {
clickInfo.singleClick = true;
cb(clickInfo, _this._currentPickResult);
}
}
else {
// wait that no double click has been raised during the double click delay
_this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
_this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
}
var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
act = _this._initActionManager(act, clickInfo);
if (act)
checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
}
if (checkDoubleClick) {
// two successive keys pressed are equal, double click delay is not over and double click has not just occurred
if (btn === _this._previousButtonPressed &&
new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
!_this._doubleClickOccured) {
// pointer has not moved for 2 clicks, it's a double click
if (!clickInfo.hasSwiped &&
Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
_this._previousStartingPointerTime = 0;
_this._doubleClickOccured = true;
clickInfo.doubleClick = true;
clickInfo.ignore = false;
if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
clearTimeout(_this._previousDelayedSimpleClickTimeout);
}
_this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
cb(clickInfo, _this._currentPickResult);
}
else {
_this._doubleClickOccured = false;
_this._previousStartingPointerTime = _this._startingPointerTime;
_this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
_this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
_this._previousButtonPressed = btn;
if (Scene.ExclusiveDoubleClickMode) {
if (_this._previousDelayedSimpleClickTimeout) {
clearTimeout(_this._previousDelayedSimpleClickTimeout);
}
_this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
cb(clickInfo, _this._previousPickResult);
}
else {
cb(clickInfo, _this._currentPickResult);
}
}
}
else {
_this._doubleClickOccured = false;
_this._previousStartingPointerTime = _this._startingPointerTime;
_this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
_this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
_this._previousButtonPressed = btn;
}
}
}
}
clickInfo.ignore = true;
cb(clickInfo, _this._currentPickResult);
};
this._spritePredicate = function (sprite) {
return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
};
this._onPointerMove = function (evt) {
_this._updatePointerPosition(evt);
// PreObservable support
if (_this.onPrePointerObservable.hasObservers()) {
var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
_this.onPrePointerObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return;
}
}
if (!_this.cameraToUseForPointers && !_this.activeCamera) {
return;
}
if (!_this.pointerMovePredicate) {
_this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
}
// Meshes
var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
_this._processPointerMove(pickResult, evt);
};
this._onPointerDown = function (evt) {
_this._totalPointersPressed++;
_this._pickedDownMesh = null;
_this._meshPickProceed = false;
_this._updatePointerPosition(evt);
if (_this.preventDefaultOnPointerDown && canvas) {
evt.preventDefault();
canvas.focus();
}
// PreObservable support
if (_this.onPrePointerObservable.hasObservers()) {
var type = BABYLON.PointerEventTypes.POINTERDOWN;
var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
_this.onPrePointerObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return;
}
}
if (!_this.cameraToUseForPointers && !_this.activeCamera) {
return;
}
_this._startingPointerPosition.x = _this._pointerX;
_this._startingPointerPosition.y = _this._pointerY;
_this._startingPointerTime = new Date().getTime();
if (!_this.pointerDownPredicate) {
_this.pointerDownPredicate = function (mesh) {
return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
};
}
// Meshes
_this._pickedDownMesh = null;
var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
_this._processPointerDown(pickResult, evt);
// Sprites
_this._pickedDownSprite = null;
if (_this.spriteManagers.length > 0) {
pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
if (pickResult && pickResult.hit && pickResult.pickedSprite) {
if (pickResult.pickedSprite.actionManager) {
_this._pickedDownSprite = pickResult.pickedSprite;
switch (evt.button) {
case 0:
pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
break;
case 1:
pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
break;
case 2:
pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
break;
}
if (pickResult.pickedSprite.actionManager) {
pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
}
}
}
}
};
this._onPointerUp = function (evt) {
if (_this._totalPointersPressed === 0) {
return; // So we need to test it the pointer down was pressed before.
}
_this._totalPointersPressed--;
_this._pickedUpMesh = null;
_this._meshPickProceed = false;
_this._updatePointerPosition(evt);
_this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
// PreObservable support
if (_this.onPrePointerObservable.hasObservers()) {
if (!clickInfo.ignore) {
if (!clickInfo.hasSwiped) {
if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
var type = BABYLON.PointerEventTypes.POINTERTAP;
var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
_this.onPrePointerObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return;
}
}
if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
_this.onPrePointerObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return;
}
}
}
}
else {
var type = BABYLON.PointerEventTypes.POINTERUP;
var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
_this.onPrePointerObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return;
}
}
}
if (!_this.cameraToUseForPointers && !_this.activeCamera) {
return;
}
if (!_this.pointerUpPredicate) {
_this.pointerUpPredicate = function (mesh) {
return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
};
}
// Meshes
if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
_this._initActionManager(null, clickInfo);
}
if (!pickResult) {
pickResult = _this._currentPickResult;
}
_this._processPointerUp(pickResult, evt, clickInfo);
// Sprites
if (_this.spriteManagers.length > 0) {
var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
if (spritePickResult) {
if (spritePickResult.hit && spritePickResult.pickedSprite) {
if (spritePickResult.pickedSprite.actionManager) {
spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
if (spritePickResult.pickedSprite.actionManager) {
if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
}
}
}
}
if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
_this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
}
}
}
_this._previousPickResult = _this._currentPickResult;
});
};
this._onKeyDown = function (evt) {
var type = BABYLON.KeyboardEventTypes.KEYDOWN;
if (_this.onPreKeyboardObservable.hasObservers()) {
var pi = new BABYLON.KeyboardInfoPre(type, evt);
_this.onPreKeyboardObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return;
}
}
if (_this.onKeyboardObservable.hasObservers()) {
var pi = new BABYLON.KeyboardInfo(type, evt);
_this.onKeyboardObservable.notifyObservers(pi, type);
}
if (_this.actionManager) {
_this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
}
};
this._onKeyUp = function (evt) {
var type = BABYLON.KeyboardEventTypes.KEYUP;
if (_this.onPreKeyboardObservable.hasObservers()) {
var pi = new BABYLON.KeyboardInfoPre(type, evt);
_this.onPreKeyboardObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return;
}
}
if (_this.onKeyboardObservable.hasObservers()) {
var pi = new BABYLON.KeyboardInfo(type, evt);
_this.onKeyboardObservable.notifyObservers(pi, type);
}
if (_this.actionManager) {
_this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
}
};
var engine = this.getEngine();
this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
if (!canvas) {
return;
}
canvas.addEventListener("keydown", _this._onKeyDown, false);
canvas.addEventListener("keyup", _this._onKeyUp, false);
});
this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
if (!canvas) {
return;
}
canvas.removeEventListener("keydown", _this._onKeyDown);
canvas.removeEventListener("keyup", _this._onKeyUp);
});
var eventPrefix = BABYLON.Tools.GetPointerPrefix();
var canvas = this._engine.getRenderingCanvas();
if (!canvas) {
return;
}
if (attachMove) {
canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
// Wheel
canvas.addEventListener('mousewheel', this._onPointerMove, false);
canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
}
if (attachDown) {
canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
}
if (attachUp) {
window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
}
canvas.tabIndex = 1;
};
Scene.prototype.detachControl = function () {
var engine = this.getEngine();
var eventPrefix = BABYLON.Tools.GetPointerPrefix();
var canvas = engine.getRenderingCanvas();
if (!canvas) {
return;
}
canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
window.removeEventListener(eventPrefix + "up", this._onPointerUp);
if (this._onCanvasBlurObserver) {
engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
}
if (this._onCanvasFocusObserver) {
engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
}
// Wheel
canvas.removeEventListener('mousewheel', this._onPointerMove);
canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
// Keyboard
canvas.removeEventListener("keydown", this._onKeyDown);
canvas.removeEventListener("keyup", this._onKeyUp);
// Observables
this.onKeyboardObservable.clear();
this.onPreKeyboardObservable.clear();
this.onPointerObservable.clear();
this.onPrePointerObservable.clear();
};
// Ready
Scene.prototype.isReady = function () {
if (this._isDisposed) {
return false;
}
if (this._pendingData.length > 0) {
return false;
}
var index;
// Geometries
for (index = 0; index < this._geometries.length; index++) {
var geometry = this._geometries[index];
if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
return false;
}
}
// Meshes
for (index = 0; index < this.meshes.length; index++) {
var mesh = this.meshes[index];
if (!mesh.isEnabled()) {
continue;
}
if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
continue;
}
if (!mesh.isReady()) {
return false;
}
var mat = mesh.material;
if (mat) {
if (!mat.isReady(mesh)) {
return false;
}
}
}
return true;
};
Scene.prototype.resetCachedMaterial = function () {
this._cachedMaterial = null;
this._cachedEffect = null;
this._cachedVisibility = null;
};
Scene.prototype.registerBeforeRender = function (func) {
this.onBeforeRenderObservable.add(func);
};
Scene.prototype.unregisterBeforeRender = function (func) {
this.onBeforeRenderObservable.removeCallback(func);
};
Scene.prototype.registerAfterRender = function (func) {
this.onAfterRenderObservable.add(func);
};
Scene.prototype.unregisterAfterRender = function (func) {
this.onAfterRenderObservable.removeCallback(func);
};
Scene.prototype._addPendingData = function (data) {
this._pendingData.push(data);
};
Scene.prototype._removePendingData = function (data) {
var wasLoading = this.isLoading;
var index = this._pendingData.indexOf(data);
if (index !== -1) {
this._pendingData.splice(index, 1);
}
if (wasLoading && !this.isLoading) {
this.onDataLoadedObservable.notifyObservers(this);
}
};
Scene.prototype.getWaitingItemsCount = function () {
return this._pendingData.length;
};
Object.defineProperty(Scene.prototype, "isLoading", {
get: function () {
return this._pendingData.length > 0;
},
enumerable: true,
configurable: true
});
/**
* Registers a function to be executed when the scene is ready.
* @param {Function} func - the function to be executed.
*/
Scene.prototype.executeWhenReady = function (func) {
var _this = this;
this.onReadyObservable.add(func);
if (this._executeWhenReadyTimeoutId !== -1) {
return;
}
this._executeWhenReadyTimeoutId = setTimeout(function () {
_this._checkIsReady();
}, 150);
};
Scene.prototype._checkIsReady = function () {
var _this = this;
if (this.isReady()) {
this.onReadyObservable.notifyObservers(this);
this.onReadyObservable.clear();
this._executeWhenReadyTimeoutId = -1;
return;
}
this._executeWhenReadyTimeoutId = setTimeout(function () {
_this._checkIsReady();
}, 150);
};
// Animations
/**
* Will start the animation sequence of a given target
* @param target - the target
* @param {number} from - from which frame should animation start
* @param {number} to - till which frame should animation run.
* @param {boolean} [loop] - should the animation loop
* @param {number} [speedRatio] - the speed in which to run the animation
* @param {Function} [onAnimationEnd] function to be executed when the animation ended.
* @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
* Returns {BABYLON.Animatable} the animatable object created for this animation
* See BABYLON.Animatable
*/
Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
if (speedRatio === void 0) { speedRatio = 1.0; }
if (from > to && speedRatio > 0) {
speedRatio *= -1;
}
this.stopAnimation(target);
if (!animatable) {
animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
}
// Local animations
if (target.animations) {
animatable.appendAnimations(target, target.animations);
}
// Children animations
if (target.getAnimatables) {
var animatables = target.getAnimatables();
for (var index = 0; index < animatables.length; index++) {
this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
}
}
animatable.reset();
return animatable;
};
Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
if (speedRatio === undefined) {
speedRatio = 1.0;
}
var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
return animatable;
};
Scene.prototype.getAnimatableByTarget = function (target) {
for (var index = 0; index < this._activeAnimatables.length; index++) {
if (this._activeAnimatables[index].target === target) {
return this._activeAnimatables[index];
}
}
return null;
};
Object.defineProperty(Scene.prototype, "Animatables", {
get: function () {
return this._activeAnimatables;
},
enumerable: true,
configurable: true
});
/**
* Will stop the animation of the given target
* @param target - the target
* @param animationName - the name of the animation to stop (all animations will be stopped is empty)
* @see beginAnimation
*/
Scene.prototype.stopAnimation = function (target, animationName) {
var animatable = this.getAnimatableByTarget(target);
if (animatable) {
animatable.stop(animationName);
}
};
/**
* Stops and removes all animations that have been applied to the scene
*/
Scene.prototype.stopAllAnimations = function () {
if (this._activeAnimatables) {
for (var i = 0; i < this._activeAnimatables.length; i++) {
this._activeAnimatables[i].stop();
}
this._activeAnimatables = [];
}
};
Scene.prototype._animate = function () {
if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
return;
}
// Getting time
var now = BABYLON.Tools.Now;
if (!this._animationTimeLast) {
if (this._pendingData.length > 0) {
return;
}
this._animationTimeLast = now;
}
var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
this._animationTime += deltaTime;
this._animationTimeLast = now;
for (var index = 0; index < this._activeAnimatables.length; index++) {
this._activeAnimatables[index]._animate(this._animationTime);
}
};
// Matrix
Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
this._useAlternateCameraConfiguration = active;
};
Scene.prototype.getViewMatrix = function () {
return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
};
Scene.prototype.getProjectionMatrix = function () {
return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
};
Scene.prototype.getTransformMatrix = function () {
return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
};
Scene.prototype.setTransformMatrix = function (view, projection) {
if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
return;
}
this._viewUpdateFlag = view.updateFlag;
this._projectionUpdateFlag = projection.updateFlag;
this._viewMatrix = view;
this._projectionMatrix = projection;
this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
// Update frustum
if (!this._frustumPlanes) {
this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
}
else {
BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
}
if (this.activeCamera && this.activeCamera._alternateCamera) {
var otherCamera = this.activeCamera._alternateCamera;
otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
}
if (this._sceneUbo.useUbo) {
this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
this._sceneUbo.updateMatrix("view", this._viewMatrix);
this._sceneUbo.update();
}
};
Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
return;
}
this._alternateViewUpdateFlag = view.updateFlag;
this._alternateProjectionUpdateFlag = projection.updateFlag;
this._alternateViewMatrix = view;
this._alternateProjectionMatrix = projection;
if (!this._alternateTransformMatrix) {
this._alternateTransformMatrix = BABYLON.Matrix.Zero();
}
this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
if (!this._alternateSceneUbo) {
this._createAlternateUbo();
}
if (this._alternateSceneUbo.useUbo) {
this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
this._alternateSceneUbo.update();
}
};
Scene.prototype.getSceneUniformBuffer = function () {
return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
};
// Methods
Scene.prototype.getUniqueId = function () {
var result = Scene._uniqueIdCounter;
Scene._uniqueIdCounter++;
return result;
};
Scene.prototype.addMesh = function (newMesh) {
this.meshes.push(newMesh);
//notify the collision coordinator
if (this.collisionCoordinator) {
this.collisionCoordinator.onMeshAdded(newMesh);
}
this.onNewMeshAddedObservable.notifyObservers(newMesh);
};
Scene.prototype.removeMesh = function (toRemove) {
var index = this.meshes.indexOf(toRemove);
if (index !== -1) {
// Remove from the scene if mesh found
this.meshes.splice(index, 1);
}
this.onMeshRemovedObservable.notifyObservers(toRemove);
return index;
};
Scene.prototype.addTransformNode = function (newTransformNode) {
this.transformNodes.push(newTransformNode);
this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
};
Scene.prototype.removeTransformNode = function (toRemove) {
var index = this.transformNodes.indexOf(toRemove);
if (index !== -1) {
// Remove from the scene if found
this.transformNodes.splice(index, 1);
}
this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
return index;
};
Scene.prototype.removeSkeleton = function (toRemove) {
var index = this.skeletons.indexOf(toRemove);
if (index !== -1) {
// Remove from the scene if found
this.skeletons.splice(index, 1);
}
return index;
};
Scene.prototype.removeMorphTargetManager = function (toRemove) {
var index = this.morphTargetManagers.indexOf(toRemove);
if (index !== -1) {
// Remove from the scene if found
this.morphTargetManagers.splice(index, 1);
}
return index;
};
Scene.prototype.removeLight = function (toRemove) {
var index = this.lights.indexOf(toRemove);
if (index !== -1) {
// Remove from the scene if mesh found
this.lights.splice(index, 1);
this.sortLightsByPriority();
}
this.onLightRemovedObservable.notifyObservers(toRemove);
return index;
};
Scene.prototype.removeCamera = function (toRemove) {
var index = this.cameras.indexOf(toRemove);
if (index !== -1) {
// Remove from the scene if mesh found
this.cameras.splice(index, 1);
}
// Remove from activeCameras
var index2 = this.activeCameras.indexOf(toRemove);
if (index2 !== -1) {
// Remove from the scene if mesh found
this.activeCameras.splice(index2, 1);
}
// Reset the activeCamera
if (this.activeCamera === toRemove) {
if (this.cameras.length > 0) {
this.activeCamera = this.cameras[0];
}
else {
this.activeCamera = null;
}
}
this.onCameraRemovedObservable.notifyObservers(toRemove);
return index;
};
Scene.prototype.addLight = function (newLight) {
this.lights.push(newLight);
this.sortLightsByPriority();
this.onNewLightAddedObservable.notifyObservers(newLight);
};
Scene.prototype.sortLightsByPriority = function () {
if (this.requireLightSorting) {
this.lights.sort(BABYLON.Light.compareLightsPriority);
}
};
Scene.prototype.addCamera = function (newCamera) {
this.cameras.push(newCamera);
this.onNewCameraAddedObservable.notifyObservers(newCamera);
};
/**
* Switch active camera
* @param {Camera} newCamera - new active camera
* @param {boolean} attachControl - call attachControl for the new active camera (default: true)
*/
Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
if (attachControl === void 0) { attachControl = true; }
var canvas = this._engine.getRenderingCanvas();
if (!canvas) {
return;
}
if (this.activeCamera) {
this.activeCamera.detachControl(canvas);
}
this.activeCamera = newCamera;
if (attachControl) {
newCamera.attachControl(canvas);
}
};
/**
* sets the active camera of the scene using its ID
* @param {string} id - the camera's ID
* @return {BABYLON.Camera|null} the new active camera or null if none found.
* @see activeCamera
*/
Scene.prototype.setActiveCameraByID = function (id) {
var camera = this.getCameraByID(id);
if (camera) {
this.activeCamera = camera;
return camera;
}
return null;
};
/**
* sets the active camera of the scene using its name
* @param {string} name - the camera's name
* @return {BABYLON.Camera|null} the new active camera or null if none found.
* @see activeCamera
*/
Scene.prototype.setActiveCameraByName = function (name) {
var camera = this.getCameraByName(name);
if (camera) {
this.activeCamera = camera;
return camera;
}
return null;
};
/**
* get an animation group using its name
* @param {string} the material's name
* @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
*/
Scene.prototype.getAnimationGroupByName = function (name) {
for (var index = 0; index < this.animationGroups.length; index++) {
if (this.animationGroups[index].name === name) {
return this.animationGroups[index];
}
}
return null;
};
/**
* get a material using its id
* @param {string} the material's ID
* @return {BABYLON.Material|null} the material or null if none found.
*/
Scene.prototype.getMaterialByID = function (id) {
for (var index = 0; index < this.materials.length; index++) {
if (this.materials[index].id === id) {
return this.materials[index];
}
}
return null;
};
/**
* get a material using its name
* @param {string} the material's name
* @return {BABYLON.Material|null} the material or null if none found.
*/
Scene.prototype.getMaterialByName = function (name) {
for (var index = 0; index < this.materials.length; index++) {
if (this.materials[index].name === name) {
return this.materials[index];
}
}
return null;
};
Scene.prototype.getLensFlareSystemByName = function (name) {
for (var index = 0; index < this.lensFlareSystems.length; index++) {
if (this.lensFlareSystems[index].name === name) {
return this.lensFlareSystems[index];
}
}
return null;
};
Scene.prototype.getLensFlareSystemByID = function (id) {
for (var index = 0; index < this.lensFlareSystems.length; index++) {
if (this.lensFlareSystems[index].id === id) {
return this.lensFlareSystems[index];
}
}
return null;
};
Scene.prototype.getCameraByID = function (id) {
for (var index = 0; index < this.cameras.length; index++) {
if (this.cameras[index].id === id) {
return this.cameras[index];
}
}
return null;
};
Scene.prototype.getCameraByUniqueID = function (uniqueId) {
for (var index = 0; index < this.cameras.length; index++) {
if (this.cameras[index].uniqueId === uniqueId) {
return this.cameras[index];
}
}
return null;
};
/**
* get a camera using its name
* @param {string} the camera's name
* @return {BABYLON.Camera|null} the camera or null if none found.
*/
Scene.prototype.getCameraByName = function (name) {
for (var index = 0; index < this.cameras.length; index++) {
if (this.cameras[index].name === name) {
return this.cameras[index];
}
}
return null;
};
/**
* get a bone using its id
* @param {string} the bone's id
* @return {BABYLON.Bone|null} the bone or null if not found
*/
Scene.prototype.getBoneByID = function (id) {
for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
var skeleton = this.skeletons[skeletonIndex];
for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
if (skeleton.bones[boneIndex].id === id) {
return skeleton.bones[boneIndex];
}
}
}
return null;
};
/**
* get a bone using its id
* @param {string} the bone's name
* @return {BABYLON.Bone|null} the bone or null if not found
*/
Scene.prototype.getBoneByName = function (name) {
for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
var skeleton = this.skeletons[skeletonIndex];
for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
if (skeleton.bones[boneIndex].name === name) {
return skeleton.bones[boneIndex];
}
}
}
return null;
};
/**
* get a light node using its name
* @param {string} the light's name
* @return {BABYLON.Light|null} the light or null if none found.
*/
Scene.prototype.getLightByName = function (name) {
for (var index = 0; index < this.lights.length; index++) {
if (this.lights[index].name === name) {
return this.lights[index];
}
}
return null;
};
/**
* get a light node using its ID
* @param {string} the light's id
* @return {BABYLON.Light|null} the light or null if none found.
*/
Scene.prototype.getLightByID = function (id) {
for (var index = 0; index < this.lights.length; index++) {
if (this.lights[index].id === id) {
return this.lights[index];
}
}
return null;
};
/**
* get a light node using its scene-generated unique ID
* @param {number} the light's unique id
* @return {BABYLON.Light|null} the light or null if none found.
*/
Scene.prototype.getLightByUniqueID = function (uniqueId) {
for (var index = 0; index < this.lights.length; index++) {
if (this.lights[index].uniqueId === uniqueId) {
return this.lights[index];
}
}
return null;
};
/**
* get a particle system by id
* @param id {number} the particle system id
* @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
*/
Scene.prototype.getParticleSystemByID = function (id) {
for (var index = 0; index < this.particleSystems.length; index++) {
if (this.particleSystems[index].id === id) {
return this.particleSystems[index];
}
}
return null;
};
/**
* get a geometry using its ID
* @param {string} the geometry's id
* @return {BABYLON.Geometry|null} the geometry or null if none found.
*/
Scene.prototype.getGeometryByID = function (id) {
for (var index = 0; index < this._geometries.length; index++) {
if (this._geometries[index].id === id) {
return this._geometries[index];
}
}
return null;
};
/**
* add a new geometry to this scene.
* @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
* @param {boolean} [force] - force addition, even if a geometry with this ID already exists
* @return {boolean} was the geometry added or not
*/
Scene.prototype.pushGeometry = function (geometry, force) {
if (!force && this.getGeometryByID(geometry.id)) {
return false;
}
this._geometries.push(geometry);
//notify the collision coordinator
if (this.collisionCoordinator) {
this.collisionCoordinator.onGeometryAdded(geometry);
}
this.onNewGeometryAddedObservable.notifyObservers(geometry);
return true;
};
/**
* Removes an existing geometry
* @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
* @return {boolean} was the geometry removed or not
*/
Scene.prototype.removeGeometry = function (geometry) {
var index = this._geometries.indexOf(geometry);
if (index > -1) {
this._geometries.splice(index, 1);
//notify the collision coordinator
if (this.collisionCoordinator) {
this.collisionCoordinator.onGeometryDeleted(geometry);
}
this.onGeometryRemovedObservable.notifyObservers(geometry);
return true;
}
return false;
};
Scene.prototype.getGeometries = function () {
return this._geometries;
};
/**
* Get the first added mesh found of a given ID
* @param {string} id - the id to search for
* @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
*/
Scene.prototype.getMeshByID = function (id) {
for (var index = 0; index < this.meshes.length; index++) {
if (this.meshes[index].id === id) {
return this.meshes[index];
}
}
return null;
};
Scene.prototype.getMeshesByID = function (id) {
return this.meshes.filter(function (m) {
return m.id === id;
});
};
/**
* Get the first added transform node found of a given ID
* @param {string} id - the id to search for
* @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
*/
Scene.prototype.getTransformNodeByID = function (id) {
for (var index = 0; index < this.transformNodes.length; index++) {
if (this.transformNodes[index].id === id) {
return this.transformNodes[index];
}
}
return null;
};
Scene.prototype.getTransformNodesByID = function (id) {
return this.transformNodes.filter(function (m) {
return m.id === id;
});
};
/**
* Get a mesh with its auto-generated unique id
* @param {number} uniqueId - the unique id to search for
* @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
*/
Scene.prototype.getMeshByUniqueID = function (uniqueId) {
for (var index = 0; index < this.meshes.length; index++) {
if (this.meshes[index].uniqueId === uniqueId) {
return this.meshes[index];
}
}
return null;
};
/**
* Get a the last added mesh found of a given ID
* @param {string} id - the id to search for
* @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
*/
Scene.prototype.getLastMeshByID = function (id) {
for (var index = this.meshes.length - 1; index >= 0; index--) {
if (this.meshes[index].id === id) {
return this.meshes[index];
}
}
return null;
};
/**
* Get a the last added node (Mesh, Camera, Light) found of a given ID
* @param {string} id - the id to search for
* @return {BABYLON.Node|null} the node found or null if not found at all.
*/
Scene.prototype.getLastEntryByID = function (id) {
var index;
for (index = this.meshes.length - 1; index >= 0; index--) {
if (this.meshes[index].id === id) {
return this.meshes[index];
}
}
for (index = this.transformNodes.length - 1; index >= 0; index--) {
if (this.transformNodes[index].id === id) {
return this.transformNodes[index];
}
}
for (index = this.cameras.length - 1; index >= 0; index--) {
if (this.cameras[index].id === id) {
return this.cameras[index];
}
}
for (index = this.lights.length - 1; index >= 0; index--) {
if (this.lights[index].id === id) {
return this.lights[index];
}
}
return null;
};
Scene.prototype.getNodeByID = function (id) {
var mesh = this.getMeshByID(id);
if (mesh) {
return mesh;
}
var light = this.getLightByID(id);
if (light) {
return light;
}
var camera = this.getCameraByID(id);
if (camera) {
return camera;
}
var bone = this.getBoneByID(id);
return bone;
};
Scene.prototype.getNodeByName = function (name) {
var mesh = this.getMeshByName(name);
if (mesh) {
return mesh;
}
var light = this.getLightByName(name);
if (light) {
return light;
}
var camera = this.getCameraByName(name);
if (camera) {
return camera;
}
var bone = this.getBoneByName(name);
return bone;
};
Scene.prototype.getMeshByName = function (name) {
for (var index = 0; index < this.meshes.length; index++) {
if (this.meshes[index].name === name) {
return this.meshes[index];
}
}
return null;
};
Scene.prototype.getTransformNodeByName = function (name) {
for (var index = 0; index < this.transformNodes.length; index++) {
if (this.transformNodes[index].name === name) {
return this.transformNodes[index];
}
}
return null;
};
Scene.prototype.getSoundByName = function (name) {
var index;
if (BABYLON.AudioEngine) {
for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
if (this.mainSoundTrack.soundCollection[index].name === name) {
return this.mainSoundTrack.soundCollection[index];
}
}
for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
return this.soundTracks[sdIndex].soundCollection[index];
}
}
}
}
return null;
};
Scene.prototype.getLastSkeletonByID = function (id) {
for (var index = this.skeletons.length - 1; index >= 0; index--) {
if (this.skeletons[index].id === id) {
return this.skeletons[index];
}
}
return null;
};
Scene.prototype.getSkeletonById = function (id) {
for (var index = 0; index < this.skeletons.length; index++) {
if (this.skeletons[index].id === id) {
return this.skeletons[index];
}
}
return null;
};
Scene.prototype.getSkeletonByName = function (name) {
for (var index = 0; index < this.skeletons.length; index++) {
if (this.skeletons[index].name === name) {
return this.skeletons[index];
}
}
return null;
};
Scene.prototype.getMorphTargetManagerById = function (id) {
for (var index = 0; index < this.morphTargetManagers.length; index++) {
if (this.morphTargetManagers[index].uniqueId === id) {
return this.morphTargetManagers[index];
}
}
return null;
};
Scene.prototype.isActiveMesh = function (mesh) {
return (this._activeMeshes.indexOf(mesh) !== -1);
};
/**
* Return a the first highlight layer of the scene with a given name.
* @param name The name of the highlight layer to look for.
* @return The highlight layer if found otherwise null.
*/
Scene.prototype.getHighlightLayerByName = function (name) {
for (var index = 0; index < this.highlightLayers.length; index++) {
if (this.highlightLayers[index].name === name) {
return this.highlightLayers[index];
}
}
return null;
};
Object.defineProperty(Scene.prototype, "uid", {
/**
* Return a unique id as a string which can serve as an identifier for the scene
*/
get: function () {
if (!this._uid) {
this._uid = BABYLON.Tools.RandomId();
}
return this._uid;
},
enumerable: true,
configurable: true
});
/**
* Add an externaly attached data from its key.
* This method call will fail and return false, if such key already exists.
* If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
* @param key the unique key that identifies the data
* @param data the data object to associate to the key for this Engine instance
* @return true if no such key were already present and the data was added successfully, false otherwise
*/
Scene.prototype.addExternalData = function (key, data) {
if (!this._externalData) {
this._externalData = new BABYLON.StringDictionary();
}
return this._externalData.add(key, data);
};
/**
* Get an externaly attached data from its key
* @param key the unique key that identifies the data
* @return the associated data, if present (can be null), or undefined if not present
*/
Scene.prototype.getExternalData = function (key) {
if (!this._externalData) {
return null;
}
return this._externalData.get(key);
};
/**
* Get an externaly attached data from its key, create it using a factory if it's not already present
* @param key the unique key that identifies the data
* @param factory the factory that will be called to create the instance if and only if it doesn't exists
* @return the associated data, can be null if the factory returned null.
*/
Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
if (!this._externalData) {
this._externalData = new BABYLON.StringDictionary();
}
return this._externalData.getOrAddWithFactory(key, factory);
};
/**
* Remove an externaly attached data from the Engine instance
* @param key the unique key that identifies the data
* @return true if the data was successfully removed, false if it doesn't exist
*/
Scene.prototype.removeExternalData = function (key) {
return this._externalData.remove(key);
};
Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
var material = subMesh.getMaterial();
if (mesh.showSubMeshesBoundingBox) {
var boundingInfo = subMesh.getBoundingInfo();
this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
}
if (material) {
// Render targets
if (material.getRenderTargetTextures) {
if (this._processedMaterials.indexOf(material) === -1) {
this._processedMaterials.push(material);
this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
}
}
// Dispatch
this._activeIndices.addCount(subMesh.indexCount, false);
this._renderingManager.dispatch(subMesh);
}
}
};
Scene.prototype._isInIntermediateRendering = function () {
return this._intermediateRendering;
};
/**
* Use this function to stop evaluating active meshes. The current list will be keep alive between frames
*/
Scene.prototype.freezeActiveMeshes = function () {
this._evaluateActiveMeshes();
this._activeMeshesFrozen = true;
return this;
};
/**
* Use this function to restart evaluating active meshes on every frame
*/
Scene.prototype.unfreezeActiveMeshes = function () {
this._activeMeshesFrozen = false;
return this;
};
Scene.prototype._evaluateActiveMeshes = function () {
if (this._activeMeshesFrozen && this._activeMeshes.length) {
return;
}
if (!this.activeCamera) {
return;
}
this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
this.activeCamera._activeMeshes.reset();
this._activeMeshes.reset();
this._renderingManager.reset();
this._processedMaterials.reset();
this._activeParticleSystems.reset();
this._activeSkeletons.reset();
this._softwareSkinnedMeshes.reset();
if (this._boundingBoxRenderer) {
this._boundingBoxRenderer.reset();
}
// Meshes
var meshes;
var len;
if (this._selectionOctree) {
var selection = this._selectionOctree.select(this._frustumPlanes);
meshes = selection.data;
len = selection.length;
}
else {
len = this.meshes.length;
meshes = this.meshes;
}
for (var meshIndex = 0; meshIndex < len; meshIndex++) {
var mesh = meshes[meshIndex];
if (mesh.isBlocked) {
continue;
}
this._totalVertices.addCount(mesh.getTotalVertices(), false);
if (!mesh.isReady() || !mesh.isEnabled()) {
continue;
}
mesh.computeWorldMatrix();
// Intersections
if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
this._meshesForIntersections.pushNoDuplicate(mesh);
}
// Switch to current LOD
var meshLOD = mesh.getLOD(this.activeCamera);
if (!meshLOD) {
continue;
}
mesh._preActivate();
if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
this._activeMeshes.push(mesh);
this.activeCamera._activeMeshes.push(mesh);
mesh._activate(this._renderId);
if (meshLOD !== mesh) {
meshLOD._activate(this._renderId);
}
this._activeMesh(mesh, meshLOD);
}
}
this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
// Particle systems
if (this.particlesEnabled) {
this.onBeforeParticlesRenderingObservable.notifyObservers(this);
for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
var particleSystem = this.particleSystems[particleIndex];
if (!particleSystem.isStarted() || !particleSystem.emitter) {
continue;
}
var emitter = particleSystem.emitter;
if (!emitter.position || emitter.isEnabled()) {
this._activeParticleSystems.push(particleSystem);
particleSystem.animate();
this._renderingManager.dispatchParticles(particleSystem);
}
}
this.onAfterParticlesRenderingObservable.notifyObservers(this);
}
};
Scene.prototype._activeMesh = function (sourceMesh, mesh) {
if (mesh.skeleton && this.skeletonsEnabled) {
if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
mesh.skeleton.prepare();
}
if (!mesh.computeBonesUsingShaders) {
this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
}
}
if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
var boundingInfo = sourceMesh.getBoundingInfo();
this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
}
if (mesh && mesh.subMeshes) {
// Submeshes Octrees
var len;
var subMeshes;
if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
len = intersections.length;
subMeshes = intersections.data;
}
else {
subMeshes = mesh.subMeshes;
len = subMeshes.length;
}
for (var subIndex = 0; subIndex < len; subIndex++) {
var subMesh = subMeshes[subIndex];
this._evaluateSubMesh(subMesh, mesh);
}
}
};
Scene.prototype.updateTransformMatrix = function (force) {
if (!this.activeCamera) {
return;
}
this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
};
Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
};
Scene.prototype._renderForCamera = function (camera) {
if (camera && camera._skipRendering) {
return;
}
var engine = this._engine;
this.activeCamera = camera;
if (!this.activeCamera)
throw new Error("Active camera not set");
BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
// Viewport
engine.setViewport(this.activeCamera.viewport);
// Camera
this.resetCachedMaterial();
this._renderId++;
this.activeCamera.update();
this.updateTransformMatrix();
if (camera._alternateCamera) {
this.updateAlternateTransformMatrix(camera._alternateCamera);
this._alternateRendering = true;
}
this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
// Meshes
this._evaluateActiveMeshes();
// Software skinning
for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
mesh.applySkeleton(mesh.skeleton);
}
// Render targets
this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
var needsRestoreFrameBuffer = false;
if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
}
if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
this._intermediateRendering = true;
BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
var renderTarget = this._renderTargets.data[renderIndex];
if (renderTarget._shouldRender()) {
this._renderId++;
var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
}
}
BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
this._intermediateRendering = false;
this._renderId++;
needsRestoreFrameBuffer = true; // Restore back buffer
}
// Render HighlightLayer Texture
var stencilState = this._engine.getStencilBuffer();
var renderhighlights = false;
if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
this._intermediateRendering = true;
for (var i = 0; i < this.highlightLayers.length; i++) {
var highlightLayer = this.highlightLayers[i];
if (highlightLayer.shouldRender() &&
(!highlightLayer.camera ||
(highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
(highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
renderhighlights = true;
var renderTarget = highlightLayer._mainTexture;
if (renderTarget._shouldRender()) {
this._renderId++;
renderTarget.render(false, false);
needsRestoreFrameBuffer = true;
}
}
}
this._intermediateRendering = false;
this._renderId++;
}
if (needsRestoreFrameBuffer) {
engine.restoreDefaultFramebuffer(); // Restore back buffer
}
this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
// Prepare Frame
this.postProcessManager._prepareFrame();
// Backgrounds
var layerIndex;
var layer;
if (this.layers.length) {
engine.setDepthBuffer(false);
for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
layer = this.layers[layerIndex];
if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
layer.render();
}
}
engine.setDepthBuffer(true);
}
// Activate HighlightLayer stencil
if (renderhighlights) {
this._engine.setStencilBuffer(true);
}
// Render
this.onBeforeDrawPhaseObservable.notifyObservers(this);
this._renderingManager.render(null, null, true, true);
this.onAfterDrawPhaseObservable.notifyObservers(this);
// Restore HighlightLayer stencil
if (renderhighlights) {
this._engine.setStencilBuffer(stencilState);
}
// Bounding boxes
if (this._boundingBoxRenderer) {
this._boundingBoxRenderer.render();
}
// Lens flares
if (this.lensFlaresEnabled) {
BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
lensFlareSystem.render();
}
}
BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
}
// Foregrounds
if (this.layers.length) {
engine.setDepthBuffer(false);
for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
layer = this.layers[layerIndex];
if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
layer.render();
}
}
engine.setDepthBuffer(true);
}
// Highlight Layer
if (renderhighlights) {
engine.setDepthBuffer(false);
for (var i = 0; i < this.highlightLayers.length; i++) {
if (this.highlightLayers[i].shouldRender()) {
this.highlightLayers[i].render();
}
}
engine.setDepthBuffer(true);
}
// Finalize frame
this.postProcessManager._finalizeFrame(camera.isIntermediate);
// Reset some special arrays
this._renderTargets.reset();
this._alternateRendering = false;
this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
};
Scene.prototype._processSubCameras = function (camera) {
if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
this._renderForCamera(camera);
return;
}
// Update camera
if (this.activeCamera) {
this.activeCamera.update();
}
// rig cameras
for (var index = 0; index < camera._rigCameras.length; index++) {
this._renderForCamera(camera._rigCameras[index]);
}
this.activeCamera = camera;
this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
};
Scene.prototype._checkIntersections = function () {
for (var index = 0; index < this._meshesForIntersections.length; index++) {
var sourceMesh = this._meshesForIntersections.data[index];
if (!sourceMesh.actionManager) {
continue;
}
for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
var action = sourceMesh.actionManager.actions[actionIndex];
if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
var parameters = action.getTriggerParameter();
var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
if (areIntersecting && currentIntersectionInProgress === -1) {
if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
sourceMesh._intersectionsInProgress.push(otherMesh);
}
else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
sourceMesh._intersectionsInProgress.push(otherMesh);
}
}
else if (!areIntersecting && currentIntersectionInProgress > -1) {
//They intersected, and now they don't.
//is this trigger an exit trigger? execute an event.
if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
}
//if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
}
}
}
}
}
};
Scene.prototype.render = function () {
if (this.isDisposed) {
return;
}
this._activeParticles.fetchNewFrame();
this._totalVertices.fetchNewFrame();
this._activeIndices.fetchNewFrame();
this._activeBones.fetchNewFrame();
this._meshesForIntersections.reset();
this.resetCachedMaterial();
this.onBeforeAnimationsObservable.notifyObservers(this);
// Actions
if (this.actionManager) {
this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
}
//Simplification Queue
if (this.simplificationQueue && !this.simplificationQueue.running) {
this.simplificationQueue.executeNext();
}
if (this._engine.isDeterministicLockStep()) {
var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
var defaultFPS = (60.0 / 1000.0);
var defaultFrameTime = 1000 / 60; // frame time in MS
if (this._physicsEngine) {
defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
}
var stepsTaken = 0;
var maxSubSteps = this._engine.getLockstepMaxSteps();
var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
internalSteps = Math.min(internalSteps, maxSubSteps);
do {
this.onBeforeStepObservable.notifyObservers(this);
// Animations
this._animationRatio = defaultFrameTime * defaultFPS;
this._animate();
this.onAfterAnimationsObservable.notifyObservers(this);
// Physics
if (this._physicsEngine) {
this.onBeforePhysicsObservable.notifyObservers(this);
this._physicsEngine._step(defaultFrameTime / 1000);
this.onAfterPhysicsObservable.notifyObservers(this);
}
this.onAfterStepObservable.notifyObservers(this);
this._currentStepId++;
stepsTaken++;
deltaTime -= defaultFrameTime;
} while (deltaTime > 0 && stepsTaken < internalSteps);
this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
}
else {
// Animations
var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
this._animationRatio = deltaTime * (60.0 / 1000.0);
this._animate();
this.onAfterAnimationsObservable.notifyObservers(this);
// Physics
if (this._physicsEngine) {
this.onBeforePhysicsObservable.notifyObservers(this);
this._physicsEngine._step(deltaTime / 1000.0);
this.onAfterPhysicsObservable.notifyObservers(this);
}
}
// update gamepad manager
if (this._gamepadManager && this._gamepadManager._isMonitoring) {
this._gamepadManager._checkGamepadsStatus();
}
// Before render
this.onBeforeRenderObservable.notifyObservers(this);
// Customs render targets
this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
var engine = this.getEngine();
var currentActiveCamera = this.activeCamera;
if (this.renderTargetsEnabled) {
BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
this._intermediateRendering = true;
for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
var renderTarget = this.customRenderTargets[customIndex];
if (renderTarget._shouldRender()) {
this._renderId++;
this.activeCamera = renderTarget.activeCamera || this.activeCamera;
if (!this.activeCamera)
throw new Error("Active camera not set");
// Viewport
engine.setViewport(this.activeCamera.viewport);
// Camera
this.updateTransformMatrix();
renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
}
}
BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
this._intermediateRendering = false;
this._renderId++;
}
// Restore back buffer
if (this.customRenderTargets.length > 0) {
engine.restoreDefaultFramebuffer();
}
this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
this.activeCamera = currentActiveCamera;
// Procedural textures
if (this.proceduralTexturesEnabled) {
BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
var proceduralTexture = this._proceduralTextures[proceduralIndex];
if (proceduralTexture._shouldRender()) {
proceduralTexture.render();
}
}
BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
}
// Clear
if (this.autoClearDepthAndStencil || this.autoClear) {
this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
}
// Shadows
if (this.shadowsEnabled) {
for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
var light = this.lights[lightIndex];
var shadowGenerator = light.getShadowGenerator();
if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
var shadowMap = (shadowGenerator.getShadowMap());
if (this.textures.indexOf(shadowMap) !== -1) {
this._renderTargets.push(shadowMap);
}
}
}
}
// Depth renderer
if (this._depthRenderer) {
this._renderTargets.push(this._depthRenderer.getDepthMap());
}
// Geometry renderer
if (this._geometryBufferRenderer) {
this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
}
// RenderPipeline
if (this._postProcessRenderPipelineManager) {
this._postProcessRenderPipelineManager.update();
}
// Multi-cameras?
if (this.activeCameras.length > 0) {
for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
if (cameraIndex > 0) {
this._engine.clear(null, false, true, true);
}
this._processSubCameras(this.activeCameras[cameraIndex]);
}
}
else {
if (!this.activeCamera) {
throw new Error("No camera defined");
}
this._processSubCameras(this.activeCamera);
}
// Intersection checks
this._checkIntersections();
// Update the audio listener attached to the camera
if (BABYLON.AudioEngine) {
this._updateAudioParameters();
}
// After render
if (this.afterRender) {
this.afterRender();
}
this.onAfterRenderObservable.notifyObservers(this);
// Cleaning
for (var index = 0; index < this._toBeDisposed.length; index++) {
var data = this._toBeDisposed.data[index];
if (data) {
data.dispose();
}
this._toBeDisposed[index] = null;
}
this._toBeDisposed.reset();
if (this.dumpNextRenderTargets) {
this.dumpNextRenderTargets = false;
}
this._activeBones.addCount(0, true);
this._activeIndices.addCount(0, true);
this._activeParticles.addCount(0, true);
};
Scene.prototype._updateAudioParameters = function () {
if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
return;
}
var listeningCamera;
var audioEngine = BABYLON.Engine.audioEngine;
if (this.activeCameras.length > 0) {
listeningCamera = this.activeCameras[0];
}
else {
listeningCamera = this.activeCamera;
}
if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
// for VR cameras
if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
listeningCamera = listeningCamera.rigCameras[0];
}
var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
cameraDirection.normalize();
// To avoid some errors on GearVR
if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
}
var i;
for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
var sound = this.mainSoundTrack.soundCollection[i];
if (sound.useCustomAttenuation) {
sound.updateDistanceFromListener();
}
}
for (i = 0; i < this.soundTracks.length; i++) {
for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
sound = this.soundTracks[i].soundCollection[j];
if (sound.useCustomAttenuation) {
sound.updateDistanceFromListener();
}
}
}
}
};
Object.defineProperty(Scene.prototype, "audioEnabled", {
// Audio
get: function () {
return this._audioEnabled;
},
set: function (value) {
this._audioEnabled = value;
if (BABYLON.AudioEngine) {
if (this._audioEnabled) {
this._enableAudio();
}
else {
this._disableAudio();
}
}
},
enumerable: true,
configurable: true
});
Scene.prototype._disableAudio = function () {
var i;
for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
this.mainSoundTrack.soundCollection[i].pause();
}
for (i = 0; i < this.soundTracks.length; i++) {
for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
this.soundTracks[i].soundCollection[j].pause();
}
}
};
Scene.prototype._enableAudio = function () {
var i;
for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
if (this.mainSoundTrack.soundCollection[i].isPaused) {
this.mainSoundTrack.soundCollection[i].play();
}
}
for (i = 0; i < this.soundTracks.length; i++) {
for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
if (this.soundTracks[i].soundCollection[j].isPaused) {
this.soundTracks[i].soundCollection[j].play();
}
}
}
};
Object.defineProperty(Scene.prototype, "headphone", {
get: function () {
return this._headphone;
},
set: function (value) {
this._headphone = value;
if (BABYLON.AudioEngine) {
if (this._headphone) {
this._switchAudioModeForHeadphones();
}
else {
this._switchAudioModeForNormalSpeakers();
}
}
},
enumerable: true,
configurable: true
});
Scene.prototype._switchAudioModeForHeadphones = function () {
this.mainSoundTrack.switchPanningModelToHRTF();
for (var i = 0; i < this.soundTracks.length; i++) {
this.soundTracks[i].switchPanningModelToHRTF();
}
};
Scene.prototype._switchAudioModeForNormalSpeakers = function () {
this.mainSoundTrack.switchPanningModelToEqualPower();
for (var i = 0; i < this.soundTracks.length; i++) {
this.soundTracks[i].switchPanningModelToEqualPower();
}
};
Scene.prototype.enableDepthRenderer = function () {
if (this._depthRenderer) {
return this._depthRenderer;
}
this._depthRenderer = new BABYLON.DepthRenderer(this);
return this._depthRenderer;
};
Scene.prototype.disableDepthRenderer = function () {
if (!this._depthRenderer) {
return;
}
this._depthRenderer.dispose();
this._depthRenderer = null;
};
Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
if (ratio === void 0) { ratio = 1; }
if (this._geometryBufferRenderer) {
return this._geometryBufferRenderer;
}
this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
if (!this._geometryBufferRenderer.isSupported) {
this._geometryBufferRenderer = null;
}
return this._geometryBufferRenderer;
};
Scene.prototype.disableGeometryBufferRenderer = function () {
if (!this._geometryBufferRenderer) {
return;
}
this._geometryBufferRenderer.dispose();
this._geometryBufferRenderer = null;
};
Scene.prototype.freezeMaterials = function () {
for (var i = 0; i < this.materials.length; i++) {
this.materials[i].freeze();
}
};
Scene.prototype.unfreezeMaterials = function () {
for (var i = 0; i < this.materials.length; i++) {
this.materials[i].unfreeze();
}
};
Scene.prototype.dispose = function () {
this.beforeRender = null;
this.afterRender = null;
this.skeletons = [];
this.morphTargetManagers = [];
this.animationGroups = [];
this.importedMeshesFiles = new Array();
this.stopAllAnimations();
this.resetCachedMaterial();
if (this._depthRenderer) {
this._depthRenderer.dispose();
}
if (this._gamepadManager) {
this._gamepadManager.dispose();
this._gamepadManager = null;
}
// Smart arrays
if (this.activeCamera) {
this.activeCamera._activeMeshes.dispose();
this.activeCamera = null;
}
this._activeMeshes.dispose();
this._renderingManager.dispose();
this._processedMaterials.dispose();
this._activeParticleSystems.dispose();
this._activeSkeletons.dispose();
this._softwareSkinnedMeshes.dispose();
this._renderTargets.dispose();
if (this._boundingBoxRenderer) {
this._boundingBoxRenderer.dispose();
}
this._meshesForIntersections.dispose();
this._toBeDisposed.dispose();
// Debug layer
if (this._debugLayer) {
this._debugLayer.hide();
}
// Events
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
this.onBeforeRenderObservable.clear();
this.onAfterRenderObservable.clear();
this.OnBeforeRenderTargetsRenderObservable.clear();
this.OnAfterRenderTargetsRenderObservable.clear();
this.onAfterStepObservable.clear();
this.onBeforeStepObservable.clear();
this.onBeforeActiveMeshesEvaluationObservable.clear();
this.onAfterActiveMeshesEvaluationObservable.clear();
this.onBeforeParticlesRenderingObservable.clear();
this.onAfterParticlesRenderingObservable.clear();
this.onBeforeSpritesRenderingObservable.clear();
this.onAfterSpritesRenderingObservable.clear();
this.onBeforeDrawPhaseObservable.clear();
this.onAfterDrawPhaseObservable.clear();
this.onBeforePhysicsObservable.clear();
this.onAfterPhysicsObservable.clear();
this.onBeforeAnimationsObservable.clear();
this.onAfterAnimationsObservable.clear();
this.onDataLoadedObservable.clear();
this.detachControl();
// Release sounds & sounds tracks
if (BABYLON.AudioEngine) {
this.disposeSounds();
}
// VR Helper
if (this.VRHelper) {
this.VRHelper.dispose();
}
// Detach cameras
var canvas = this._engine.getRenderingCanvas();
if (canvas) {
var index;
for (index = 0; index < this.cameras.length; index++) {
this.cameras[index].detachControl(canvas);
}
}
// Release lights
while (this.lights.length) {
this.lights[0].dispose();
}
// Release meshes
while (this.meshes.length) {
this.meshes[0].dispose(true);
}
while (this.transformNodes.length) {
this.removeTransformNode(this.transformNodes[0]);
}
// Release cameras
while (this.cameras.length) {
this.cameras[0].dispose();
}
// Release materials
if (this.defaultMaterial) {
this.defaultMaterial.dispose();
}
while (this.multiMaterials.length) {
this.multiMaterials[0].dispose();
}
while (this.materials.length) {
this.materials[0].dispose();
}
// Release particles
while (this.particleSystems.length) {
this.particleSystems[0].dispose();
}
// Release sprites
while (this.spriteManagers.length) {
this.spriteManagers[0].dispose();
}
// Release postProcesses
while (this.postProcesses.length) {
this.postProcesses[0].dispose();
}
// Release layers
while (this.layers.length) {
this.layers[0].dispose();
}
while (this.highlightLayers.length) {
this.highlightLayers[0].dispose();
}
// Release textures
while (this.textures.length) {
this.textures[0].dispose();
}
// Release UBO
this._sceneUbo.dispose();
if (this._alternateSceneUbo) {
this._alternateSceneUbo.dispose();
}
// Post-processes
this.postProcessManager.dispose();
if (this._postProcessRenderPipelineManager) {
this._postProcessRenderPipelineManager.dispose();
}
// Physics
if (this._physicsEngine) {
this.disablePhysicsEngine();
}
// Remove from engine
index = this._engine.scenes.indexOf(this);
if (index > -1) {
this._engine.scenes.splice(index, 1);
}
this._engine.wipeCaches(true);
this._isDisposed = true;
};
Object.defineProperty(Scene.prototype, "isDisposed", {
get: function () {
return this._isDisposed;
},
enumerable: true,
configurable: true
});
// Release sounds & sounds tracks
Scene.prototype.disposeSounds = function () {
if (!this._mainSoundTrack) {
return;
}
this.mainSoundTrack.dispose();
for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
this.soundTracks[scIndex].dispose();
}
};
// Octrees
Scene.prototype.getWorldExtends = function () {
var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
for (var index = 0; index < this.meshes.length; index++) {
var mesh = this.meshes[index];
if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
continue;
}
mesh.computeWorldMatrix(true);
var boundingInfo = mesh.getBoundingInfo();
var minBox = boundingInfo.boundingBox.minimumWorld;
var maxBox = boundingInfo.boundingBox.maximumWorld;
BABYLON.Tools.CheckExtends(minBox, min, max);
BABYLON.Tools.CheckExtends(maxBox, min, max);
}
return {
min: min,
max: max
};
};
Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
if (maxCapacity === void 0) { maxCapacity = 64; }
if (maxDepth === void 0) { maxDepth = 2; }
if (!this._selectionOctree) {
this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
}
var worldExtends = this.getWorldExtends();
// Update octree
this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
return this._selectionOctree;
};
// Picking
Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
if (cameraViewSpace === void 0) { cameraViewSpace = false; }
var result = BABYLON.Ray.Zero();
this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
return result;
};
Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
if (cameraViewSpace === void 0) { cameraViewSpace = false; }
var engine = this._engine;
if (!camera) {
if (!this.activeCamera)
throw new Error("Active camera not set");
camera = this.activeCamera;
}
var cameraViewport = camera.viewport;
var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
// Moving coordinates to local viewport world
x = x / this._engine.getHardwareScalingLevel() - viewport.x;
y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
return this;
};
Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
var result = BABYLON.Ray.Zero();
this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
return result;
};
Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
if (!BABYLON.PickingInfo) {
return this;
}
var engine = this._engine;
if (!camera) {
if (!this.activeCamera)
throw new Error("Active camera not set");
camera = this.activeCamera;
}
var cameraViewport = camera.viewport;
var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
var identity = BABYLON.Matrix.Identity();
// Moving coordinates to local viewport world
x = x / this._engine.getHardwareScalingLevel() - viewport.x;
y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
return this;
};
Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
if (!BABYLON.PickingInfo) {
return null;
}
var pickingInfo = null;
for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
var mesh = this.meshes[meshIndex];
if (predicate) {
if (!predicate(mesh)) {
continue;
}
}
else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
continue;
}
var world = mesh.getWorldMatrix();
var ray = rayFunction(world);
var result = mesh.intersects(ray, fastCheck);
if (!result || !result.hit)
continue;
if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
continue;
pickingInfo = result;
if (fastCheck) {
break;
}
}
return pickingInfo || new BABYLON.PickingInfo();
};
Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
if (!BABYLON.PickingInfo) {
return null;
}
var pickingInfos = new Array();
for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
var mesh = this.meshes[meshIndex];
if (predicate) {
if (!predicate(mesh)) {
continue;
}
}
else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
continue;
}
var world = mesh.getWorldMatrix();
var ray = rayFunction(world);
var result = mesh.intersects(ray, false);
if (!result || !result.hit)
continue;
pickingInfos.push(result);
}
return pickingInfos;
};
Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
if (!BABYLON.PickingInfo) {
return null;
}
var pickingInfo = null;
if (!camera) {
if (!this.activeCamera) {
return null;
}
camera = this.activeCamera;
}
if (this.spriteManagers.length > 0) {
for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
var spriteManager = this.spriteManagers[spriteIndex];
if (!spriteManager.isPickable) {
continue;
}
var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
if (!result || !result.hit)
continue;
if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
continue;
pickingInfo = result;
if (fastCheck) {
break;
}
}
}
return pickingInfo || new BABYLON.PickingInfo();
};
/** Launch a ray to try to pick a mesh in the scene
* @param x position on screen
* @param y position on screen
* @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
* @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
* @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
*/
Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
var _this = this;
if (!BABYLON.PickingInfo) {
return null;
}
return this._internalPick(function (world) {
_this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
return _this._tempPickingRay;
}, predicate, fastCheck);
};
/** Launch a ray to try to pick a sprite in the scene
* @param x position on screen
* @param y position on screen
* @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
* @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
* @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
*/
Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
};
/** Use the given ray to pick a mesh in the scene
* @param ray The ray to use to pick meshes
* @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
* @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
*/
Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
var _this = this;
return this._internalPick(function (world) {
if (!_this._pickWithRayInverseMatrix) {
_this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
}
world.invertToRef(_this._pickWithRayInverseMatrix);
if (!_this._cachedRayForTransform) {
_this._cachedRayForTransform = BABYLON.Ray.Zero();
}
BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
return _this._cachedRayForTransform;
}, predicate, fastCheck);
};
/**
* Launch a ray to try to pick a mesh in the scene
* @param x X position on screen
* @param y Y position on screen
* @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
* @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
*/
Scene.prototype.multiPick = function (x, y, predicate, camera) {
var _this = this;
return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
};
/**
* Launch a ray to try to pick a mesh in the scene
* @param ray Ray to use
* @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
*/
Scene.prototype.multiPickWithRay = function (ray, predicate) {
var _this = this;
return this._internalMultiPick(function (world) {
if (!_this._pickWithRayInverseMatrix) {
_this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
}
world.invertToRef(_this._pickWithRayInverseMatrix);
if (!_this._cachedRayForTransform) {
_this._cachedRayForTransform = BABYLON.Ray.Zero();
}
BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
return _this._cachedRayForTransform;
}, predicate);
};
Scene.prototype.setPointerOverMesh = function (mesh) {
if (this._pointerOverMesh === mesh) {
return;
}
if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
}
this._pointerOverMesh = mesh;
if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
}
};
Scene.prototype.getPointerOverMesh = function () {
return this._pointerOverMesh;
};
Scene.prototype.setPointerOverSprite = function (sprite) {
if (this._pointerOverSprite === sprite) {
return;
}
if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
}
this._pointerOverSprite = sprite;
if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
}
};
Scene.prototype.getPointerOverSprite = function () {
return this._pointerOverSprite;
};
// Physics
Scene.prototype.getPhysicsEngine = function () {
return this._physicsEngine;
};
/**
* Enables physics to the current scene
* @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
* @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
* @return {boolean} was the physics engine initialized
*/
Scene.prototype.enablePhysics = function (gravity, plugin) {
if (gravity === void 0) { gravity = null; }
if (this._physicsEngine) {
return true;
}
try {
this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
return true;
}
catch (e) {
BABYLON.Tools.Error(e.message);
return false;
}
};
Scene.prototype.disablePhysicsEngine = function () {
if (!this._physicsEngine) {
return;
}
this._physicsEngine.dispose();
this._physicsEngine = null;
};
Scene.prototype.isPhysicsEnabled = function () {
return this._physicsEngine !== undefined;
};
Scene.prototype.deleteCompoundImpostor = function (compound) {
var mesh = compound.parts[0].mesh;
if (mesh.physicsImpostor) {
mesh.physicsImpostor.dispose();
mesh.physicsImpostor = null;
}
};
// Misc.
Scene.prototype._rebuildGeometries = function () {
for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
var geometry = _a[_i];
geometry._rebuild();
}
for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
var mesh = _c[_b];
mesh._rebuild();
}
if (this.postProcessManager) {
this.postProcessManager._rebuild();
}
for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
var layer = _e[_d];
layer._rebuild();
}
for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
var highlightLayer = _g[_f];
highlightLayer._rebuild();
}
if (this._boundingBoxRenderer) {
this._boundingBoxRenderer._rebuild();
}
for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
var system = _j[_h];
system.rebuild();
}
if (this._postProcessRenderPipelineManager) {
this._postProcessRenderPipelineManager._rebuild();
}
};
Scene.prototype._rebuildTextures = function () {
for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
var texture = _a[_i];
texture._rebuild();
}
this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
};
Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
if (replace === void 0) { replace = false; }
if (attachCameraControls === void 0) { attachCameraControls = false; }
// Dispose existing camera or light in replace mode.
if (replace) {
if (this.activeCamera) {
this.activeCamera.dispose();
this.activeCamera = null;
}
if (this.lights) {
for (var i = 0; i < this.lights.length; i++) {
this.lights[i].dispose();
}
}
}
// Light
if (this.lights.length === 0) {
new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
}
// Camera
if (!this.activeCamera) {
var worldExtends = this.getWorldExtends();
var worldSize = worldExtends.max.subtract(worldExtends.min);
var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
var camera;
var radius = worldSize.length() * 1.5;
if (createArcRotateCamera) {
var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
arcRotateCamera.lowerRadiusLimit = radius * 0.01;
arcRotateCamera.wheelPrecision = 100 / radius;
camera = arcRotateCamera;
}
else {
var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
freeCamera.setTarget(worldCenter);
camera = freeCamera;
}
camera.minZ = radius * 0.01;
camera.maxZ = radius * 100;
camera.speed = radius * 0.2;
this.activeCamera = camera;
var canvas = this.getEngine().getRenderingCanvas();
if (attachCameraControls && canvas) {
camera.attachControl(canvas);
}
}
};
Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
if (pbr === void 0) { pbr = false; }
if (scale === void 0) { scale = 1000; }
if (blur === void 0) { blur = 0; }
if (environmentTexture) {
this.environmentTexture = environmentTexture;
}
if (!this.environmentTexture) {
BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
return null;
}
// Skybox
var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
if (pbr) {
var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
hdrSkyboxMaterial.backFaceCulling = false;
hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
if (hdrSkyboxMaterial.reflectionTexture) {
hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
}
hdrSkyboxMaterial.microSurface = 1.0 - blur;
hdrSkyboxMaterial.disableLighting = true;
hdrSkyboxMaterial.twoSidedLighting = true;
hdrSkybox.infiniteDistance = true;
hdrSkybox.material = hdrSkyboxMaterial;
}
else {
var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
skyboxMaterial.backFaceCulling = false;
skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
if (skyboxMaterial.reflectionTexture) {
skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
}
skyboxMaterial.disableLighting = true;
hdrSkybox.infiniteDistance = true;
hdrSkybox.material = skyboxMaterial;
}
return hdrSkybox;
};
Scene.prototype.createDefaultEnvironment = function (options) {
if (BABYLON.EnvironmentHelper) {
return new BABYLON.EnvironmentHelper(options, this);
}
return null;
};
Scene.prototype.createDefaultVRExperience = function (webVROptions) {
if (webVROptions === void 0) { webVROptions = {}; }
return new BABYLON.VRExperienceHelper(this, webVROptions);
};
// Tags
Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
if (tagsQuery === undefined) {
// returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
return list;
}
var listByTags = [];
forEach = forEach || (function (item) { return; });
for (var i in list) {
var item = list[i];
if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
listByTags.push(item);
forEach(item);
}
}
return listByTags;
};
Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
return this._getByTags(this.meshes, tagsQuery, forEach);
};
Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
return this._getByTags(this.cameras, tagsQuery, forEach);
};
Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
return this._getByTags(this.lights, tagsQuery, forEach);
};
Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
};
/**
* Overrides the default sort function applied in the renderging group to prepare the meshes.
* This allowed control for front to back rendering or reversly depending of the special needs.
*
* @param renderingGroupId The rendering group id corresponding to its index
* @param opaqueSortCompareFn The opaque queue comparison function use to sort.
* @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
* @param transparentSortCompareFn The transparent queue comparison function use to sort.
*/
Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
};
/**
* Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
*
* @param renderingGroupId The rendering group id corresponding to its index
* @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
* @param depth Automatically clears depth between groups if true and autoClear is true.
* @param stencil Automatically clears stencil between groups if true and autoClear is true.
*/
Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
if (depth === void 0) { depth = true; }
if (stencil === void 0) { stencil = true; }
this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
};
/**
* Will flag all materials as dirty to trigger new shader compilation
* @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
*/
Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
var material = _a[_i];
if (predicate && !predicate(material)) {
continue;
}
material.markAsDirty(flag);
}
};
// Statics
Scene._FOGMODE_NONE = 0;
Scene._FOGMODE_EXP = 1;
Scene._FOGMODE_EXP2 = 2;
Scene._FOGMODE_LINEAR = 3;
Scene._uniqueIdCounter = 0;
Scene.MinDeltaTime = 1.0;
Scene.MaxDeltaTime = 1000.0;
/** The distance in pixel that you have to move to prevent some events */
Scene.DragMovementThreshold = 10; // in pixels
/** Time in milliseconds to wait to raise long press events if button is still pressed */
Scene.LongPressDelay = 500; // in milliseconds
/** Time in milliseconds with two consecutive clicks will be considered as a double click */
Scene.DoubleClickDelay = 300; // in milliseconds
/** If you need to check double click without raising a single click at first click, enable this flag */
Scene.ExclusiveDoubleClickMode = false;
return Scene;
}());
BABYLON.Scene = Scene;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.scene.js.map
var BABYLON;
(function (BABYLON) {
var Buffer = /** @class */ (function () {
function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
if (instanced === void 0) { instanced = false; }
if (engine instanceof BABYLON.Mesh) {
this._engine = engine.getScene().getEngine();
}
else {
this._engine = engine;
}
this._updatable = updatable;
this._data = data;
this._strideSize = stride;
if (!postponeInternalCreation) {
this.create();
}
this._instanced = instanced;
this._instanceDivisor = instanced ? 1 : 0;
}
Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
// a lot of these parameters are ignored as they are overriden by the buffer
return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
};
// Properties
Buffer.prototype.isUpdatable = function () {
return this._updatable;
};
Buffer.prototype.getData = function () {
return this._data;
};
Buffer.prototype.getBuffer = function () {
return this._buffer;
};
Buffer.prototype.getStrideSize = function () {
return this._strideSize;
};
Buffer.prototype.getIsInstanced = function () {
return this._instanced;
};
Object.defineProperty(Buffer.prototype, "instanceDivisor", {
get: function () {
return this._instanceDivisor;
},
set: function (value) {
this._instanceDivisor = value;
if (value == 0) {
this._instanced = false;
}
else {
this._instanced = true;
}
},
enumerable: true,
configurable: true
});
// Methods
Buffer.prototype.create = function (data) {
if (data === void 0) { data = null; }
if (!data && this._buffer) {
return; // nothing to do
}
data = data || this._data;
if (!data) {
return;
}
if (!this._buffer) {
if (this._updatable) {
this._buffer = this._engine.createDynamicVertexBuffer(data);
this._data = data;
}
else {
this._buffer = this._engine.createVertexBuffer(data);
}
}
else if (this._updatable) {
this._engine.updateDynamicVertexBuffer(this._buffer, data);
this._data = data;
}
};
Buffer.prototype._rebuild = function () {
this._buffer = null;
this.create(this._data);
};
Buffer.prototype.update = function (data) {
this.create(data);
};
Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
if (!this._buffer) {
return;
}
if (this._updatable) {
this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
this._data = null;
}
};
Buffer.prototype.dispose = function () {
if (!this._buffer) {
return;
}
if (this._engine._releaseBuffer(this._buffer)) {
this._buffer = null;
}
};
return Buffer;
}());
BABYLON.Buffer = Buffer;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.buffer.js.map
var BABYLON;
(function (BABYLON) {
var VertexBuffer = /** @class */ (function () {
function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
if (!stride) {
// Deduce stride from kind
switch (kind) {
case VertexBuffer.PositionKind:
stride = 3;
break;
case VertexBuffer.NormalKind:
stride = 3;
break;
case VertexBuffer.UVKind:
case VertexBuffer.UV2Kind:
case VertexBuffer.UV3Kind:
case VertexBuffer.UV4Kind:
case VertexBuffer.UV5Kind:
case VertexBuffer.UV6Kind:
stride = 2;
break;
case VertexBuffer.TangentKind:
case VertexBuffer.ColorKind:
stride = 4;
break;
case VertexBuffer.MatricesIndicesKind:
case VertexBuffer.MatricesIndicesExtraKind:
stride = 4;
break;
case VertexBuffer.MatricesWeightsKind:
case VertexBuffer.MatricesWeightsExtraKind:
default:
stride = 4;
break;
}
}
if (data instanceof BABYLON.Buffer) {
if (!stride) {
stride = data.getStrideSize();
}
this._buffer = data;
this._ownsBuffer = false;
}
else {
this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
this._ownsBuffer = true;
}
this._stride = stride;
this._offset = offset ? offset : 0;
this._size = size ? size : stride;
this._kind = kind;
}
VertexBuffer.prototype._rebuild = function () {
if (!this._buffer) {
return;
}
this._buffer._rebuild();
};
/**
* Returns the kind of the VertexBuffer (string).
*/
VertexBuffer.prototype.getKind = function () {
return this._kind;
};
// Properties
/**
* Boolean : is the VertexBuffer updatable ?
*/
VertexBuffer.prototype.isUpdatable = function () {
return this._buffer.isUpdatable();
};
/**
* Returns an array of numbers or a Float32Array containing the VertexBuffer data.
*/
VertexBuffer.prototype.getData = function () {
return this._buffer.getData();
};
/**
* Returns the WebGLBuffer associated to the VertexBuffer.
*/
VertexBuffer.prototype.getBuffer = function () {
return this._buffer.getBuffer();
};
/**
* Returns the stride of the VertexBuffer (integer).
*/
VertexBuffer.prototype.getStrideSize = function () {
return this._stride;
};
/**
* Returns the offset (integer).
*/
VertexBuffer.prototype.getOffset = function () {
return this._offset;
};
/**
* Returns the VertexBuffer total size (integer).
*/
VertexBuffer.prototype.getSize = function () {
return this._size;
};
/**
* Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
*/
VertexBuffer.prototype.getIsInstanced = function () {
return this._buffer.getIsInstanced();
};
/**
* Returns the instancing divisor, zero for non-instanced (integer).
*/
VertexBuffer.prototype.getInstanceDivisor = function () {
return this._buffer.instanceDivisor;
};
// Methods
/**
* Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
* Returns the created WebGLBuffer.
*/
VertexBuffer.prototype.create = function (data) {
return this._buffer.create(data);
};
/**
* Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
* Returns the updated WebGLBuffer.
*/
VertexBuffer.prototype.update = function (data) {
return this._buffer.update(data);
};
/**
* Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
* Returns the directly updated WebGLBuffer.
*/
VertexBuffer.prototype.updateDirectly = function (data, offset) {
return this._buffer.updateDirectly(data, offset);
};
/**
* Disposes the VertexBuffer and the underlying WebGLBuffer.
*/
VertexBuffer.prototype.dispose = function () {
if (this._ownsBuffer) {
this._buffer.dispose();
}
};
Object.defineProperty(VertexBuffer, "PositionKind", {
get: function () {
return VertexBuffer._PositionKind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "NormalKind", {
get: function () {
return VertexBuffer._NormalKind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "TangentKind", {
get: function () {
return VertexBuffer._TangentKind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "UVKind", {
get: function () {
return VertexBuffer._UVKind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "UV2Kind", {
get: function () {
return VertexBuffer._UV2Kind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "UV3Kind", {
get: function () {
return VertexBuffer._UV3Kind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "UV4Kind", {
get: function () {
return VertexBuffer._UV4Kind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "UV5Kind", {
get: function () {
return VertexBuffer._UV5Kind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "UV6Kind", {
get: function () {
return VertexBuffer._UV6Kind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "ColorKind", {
get: function () {
return VertexBuffer._ColorKind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
get: function () {
return VertexBuffer._MatricesIndicesKind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
get: function () {
return VertexBuffer._MatricesWeightsKind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
get: function () {
return VertexBuffer._MatricesIndicesExtraKind;
},
enumerable: true,
configurable: true
});
Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
get: function () {
return VertexBuffer._MatricesWeightsExtraKind;
},
enumerable: true,
configurable: true
});
// Enums
VertexBuffer._PositionKind = "position";
VertexBuffer._NormalKind = "normal";
VertexBuffer._TangentKind = "tangent";
VertexBuffer._UVKind = "uv";
VertexBuffer._UV2Kind = "uv2";
VertexBuffer._UV3Kind = "uv3";
VertexBuffer._UV4Kind = "uv4";
VertexBuffer._UV5Kind = "uv5";
VertexBuffer._UV6Kind = "uv6";
VertexBuffer._ColorKind = "color";
VertexBuffer._MatricesIndicesKind = "matricesIndices";
VertexBuffer._MatricesWeightsKind = "matricesWeights";
VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
return VertexBuffer;
}());
BABYLON.VertexBuffer = VertexBuffer;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.vertexBuffer.js.map
var BABYLON;
(function (BABYLON) {
var InternalTexture = /** @class */ (function () {
function InternalTexture(engine, dataSource) {
this.onLoadedObservable = new BABYLON.Observable();
// Private
this._initialSlot = -1;
this._designatedSlot = -1;
this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
this._references = 1;
this._engine = engine;
this._dataSource = dataSource;
this._webGLTexture = engine._createTexture();
}
Object.defineProperty(InternalTexture.prototype, "dataSource", {
get: function () {
return this._dataSource;
},
enumerable: true,
configurable: true
});
InternalTexture.prototype.incrementReferences = function () {
this._references++;
};
InternalTexture.prototype.updateSize = function (width, height, depth) {
if (depth === void 0) { depth = 1; }
this.width = width;
this.height = height;
this.depth = depth;
this.baseWidth = width;
this.baseHeight = height;
this.baseDepth = depth;
this._size = width * height * depth;
};
InternalTexture.prototype._rebuild = function () {
var _this = this;
var proxy;
this.isReady = false;
this._cachedCoordinatesMode = null;
this._cachedWrapU = null;
this._cachedWrapV = null;
this._cachedAnisotropicFilteringLevel = null;
switch (this._dataSource) {
case InternalTexture.DATASOURCE_TEMP:
return;
case InternalTexture.DATASOURCE_URL:
proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
_this.isReady = true;
}, null, this._buffer, undefined, this.format);
proxy._swapAndDie(this);
return;
case InternalTexture.DATASOURCE_RAW:
proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
proxy._swapAndDie(this);
this.isReady = true;
return;
case InternalTexture.DATASOURCE_RAW3D:
proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
proxy._swapAndDie(this);
this.isReady = true;
return;
case InternalTexture.DATASOURCE_DYNAMIC:
proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
proxy._swapAndDie(this);
// The engine will make sure to update content so no need to flag it as isReady = true
return;
case InternalTexture.DATASOURCE_RENDERTARGET:
var options = new BABYLON.RenderTargetCreationOptions();
options.generateDepthBuffer = this._generateDepthBuffer;
options.generateMipMaps = this.generateMipMaps;
options.generateStencilBuffer = this._generateStencilBuffer;
options.samplingMode = this.samplingMode;
options.type = this.type;
if (this.isCube) {
proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
}
else {
var size = {
width: this.width,
height: this.height
};
proxy = this._engine.createRenderTargetTexture(size, options);
}
proxy._swapAndDie(this);
this.isReady = true;
return;
case InternalTexture.DATASOURCE_CUBE:
proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
_this.isReady = true;
}, null, this.format, this._extension);
proxy._swapAndDie(this);
return;
case InternalTexture.DATASOURCE_CUBERAW:
proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
proxy._swapAndDie(this);
this.isReady = true;
return;
case InternalTexture.DATASOURCE_CUBEPREFILTERED:
proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
if (proxy) {
proxy._swapAndDie(_this);
}
_this.isReady = true;
}, null, this.format, this._extension);
return;
}
};
InternalTexture.prototype._swapAndDie = function (target) {
target._webGLTexture = this._webGLTexture;
if (this._framebuffer) {
target._framebuffer = this._framebuffer;
}
if (this._depthStencilBuffer) {
target._depthStencilBuffer = this._depthStencilBuffer;
}
if (this._lodTextureHigh) {
if (target._lodTextureHigh) {
target._lodTextureHigh.dispose();
}
target._lodTextureHigh = this._lodTextureHigh;
}
if (this._lodTextureMid) {
if (target._lodTextureMid) {
target._lodTextureMid.dispose();
}
target._lodTextureMid = this._lodTextureMid;
}
if (this._lodTextureLow) {
if (target._lodTextureLow) {
target._lodTextureLow.dispose();
}
target._lodTextureLow = this._lodTextureLow;
}
var cache = this._engine.getLoadedTexturesCache();
var index = cache.indexOf(this);
if (index !== -1) {
cache.splice(index, 1);
}
};
InternalTexture.prototype.dispose = function () {
if (!this._webGLTexture) {
return;
}
this._references--;
if (this._references === 0) {
this._engine._releaseTexture(this);
this._webGLTexture = null;
}
};
InternalTexture.DATASOURCE_UNKNOWN = 0;
InternalTexture.DATASOURCE_URL = 1;
InternalTexture.DATASOURCE_TEMP = 2;
InternalTexture.DATASOURCE_RAW = 3;
InternalTexture.DATASOURCE_DYNAMIC = 4;
InternalTexture.DATASOURCE_RENDERTARGET = 5;
InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
InternalTexture.DATASOURCE_CUBE = 7;
InternalTexture.DATASOURCE_CUBERAW = 8;
InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
InternalTexture.DATASOURCE_RAW3D = 10;
return InternalTexture;
}());
BABYLON.InternalTexture = InternalTexture;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.internalTexture.js.map
var BABYLON;
(function (BABYLON) {
var BaseTexture = /** @class */ (function () {
function BaseTexture(scene) {
this._hasAlpha = false;
this.getAlphaFromRGB = false;
this.level = 1;
this.coordinatesIndex = 0;
this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
this.isCube = false;
this.is3D = false;
this.gammaSpace = true;
this.invertZ = false;
this.lodLevelInAlpha = false;
this.lodGenerationOffset = 0.0;
this.lodGenerationScale = 0.8;
this.isRenderTarget = false;
this.animations = new Array();
/**
* An event triggered when the texture is disposed.
* @type {BABYLON.Observable}
*/
this.onDisposeObservable = new BABYLON.Observable();
this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
this._scene = scene || BABYLON.Engine.LastCreatedScene;
if (this._scene) {
this._scene.textures.push(this);
}
this._uid = null;
}
Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
get: function () {
return this._hasAlpha;
},
set: function (value) {
if (this._hasAlpha === value) {
return;
}
this._hasAlpha = value;
if (this._scene) {
this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
get: function () {
return this._coordinatesMode;
},
set: function (value) {
if (this._coordinatesMode === value) {
return;
}
this._coordinatesMode = value;
if (this._scene) {
this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture.prototype, "uid", {
get: function () {
if (!this._uid) {
this._uid = BABYLON.Tools.RandomId();
}
return this._uid;
},
enumerable: true,
configurable: true
});
BaseTexture.prototype.toString = function () {
return this.name;
};
BaseTexture.prototype.getClassName = function () {
return "BaseTexture";
};
Object.defineProperty(BaseTexture.prototype, "onDispose", {
set: function (callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture.prototype, "isBlocking", {
get: function () {
return true;
},
enumerable: true,
configurable: true
});
BaseTexture.prototype.getScene = function () {
return this._scene;
};
BaseTexture.prototype.getTextureMatrix = function () {
return BABYLON.Matrix.IdentityReadOnly;
};
BaseTexture.prototype.getReflectionTextureMatrix = function () {
return BABYLON.Matrix.IdentityReadOnly;
};
BaseTexture.prototype.getInternalTexture = function () {
return this._texture;
};
BaseTexture.prototype.isReadyOrNotBlocking = function () {
return !this.isBlocking || this.isReady();
};
BaseTexture.prototype.isReady = function () {
if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
this.delayLoad();
return false;
}
if (this._texture) {
return this._texture.isReady;
}
return false;
};
BaseTexture.prototype.getSize = function () {
if (this._texture && this._texture.width) {
return new BABYLON.Size(this._texture.width, this._texture.height);
}
if (this._texture && this._texture._size) {
return new BABYLON.Size(this._texture._size, this._texture._size);
}
return BABYLON.Size.Zero();
};
BaseTexture.prototype.getBaseSize = function () {
if (!this.isReady() || !this._texture)
return BABYLON.Size.Zero();
if (this._texture._size) {
return new BABYLON.Size(this._texture._size, this._texture._size);
}
return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
};
BaseTexture.prototype.scale = function (ratio) {
};
Object.defineProperty(BaseTexture.prototype, "canRescale", {
get: function () {
return false;
},
enumerable: true,
configurable: true
});
BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
if (!this._scene) {
return null;
}
var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
for (var index = 0; index < texturesCache.length; index++) {
var texturesCacheEntry = texturesCache[index];
if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
if (!sampling || sampling === texturesCacheEntry.samplingMode) {
texturesCacheEntry.incrementReferences();
return texturesCacheEntry;
}
}
}
return null;
};
BaseTexture.prototype._rebuild = function () {
};
BaseTexture.prototype.delayLoad = function () {
};
BaseTexture.prototype.clone = function () {
return null;
};
Object.defineProperty(BaseTexture.prototype, "textureType", {
get: function () {
if (!this._texture) {
return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
}
return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture.prototype, "textureFormat", {
get: function () {
if (!this._texture) {
return BABYLON.Engine.TEXTUREFORMAT_RGBA;
}
return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
},
enumerable: true,
configurable: true
});
BaseTexture.prototype.readPixels = function (faceIndex) {
if (faceIndex === void 0) { faceIndex = 0; }
if (!this._texture) {
return null;
}
var size = this.getSize();
var scene = this.getScene();
if (!scene) {
return null;
}
var engine = scene.getEngine();
if (this._texture.isCube) {
return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
}
return engine._readTexturePixels(this._texture, size.width, size.height, -1);
};
BaseTexture.prototype.releaseInternalTexture = function () {
if (this._texture) {
this._texture.dispose();
this._texture = null;
}
};
Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
get: function () {
if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
return null;
}
if (!this._texture._sphericalPolynomial) {
this._texture._sphericalPolynomial =
BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
}
return this._texture._sphericalPolynomial;
},
set: function (value) {
if (this._texture) {
this._texture._sphericalPolynomial = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
get: function () {
if (this._texture) {
return this._texture._lodTextureHigh;
}
return null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
get: function () {
if (this._texture) {
return this._texture._lodTextureMid;
}
return null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
get: function () {
if (this._texture) {
return this._texture._lodTextureLow;
}
return null;
},
enumerable: true,
configurable: true
});
BaseTexture.prototype.dispose = function () {
if (!this._scene) {
return;
}
// Animations
this._scene.stopAnimation(this);
// Remove from scene
this._scene._removePendingData(this);
var index = this._scene.textures.indexOf(this);
if (index >= 0) {
this._scene.textures.splice(index, 1);
}
if (this._texture === undefined) {
return;
}
// Release
this.releaseInternalTexture();
// Callback
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
};
BaseTexture.prototype.serialize = function () {
if (!this.name) {
return null;
}
var serializationObject = BABYLON.SerializationHelper.Serialize(this);
// Animations
BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
return serializationObject;
};
BaseTexture.WhenAllReady = function (textures, callback) {
var numRemaining = textures.length;
if (numRemaining === 0) {
callback();
return;
}
var _loop_1 = function () {
texture = textures[i];
if (texture.isReady()) {
if (--numRemaining === 0) {
callback();
}
}
else {
onLoadObservable = texture.onLoadObservable;
var onLoadCallback_1 = function () {
onLoadObservable.removeCallback(onLoadCallback_1);
if (--numRemaining === 0) {
callback();
}
};
onLoadObservable.add(onLoadCallback_1);
}
};
var texture, onLoadObservable;
for (var i = 0; i < textures.length; i++) {
_loop_1();
}
};
BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "name", void 0);
__decorate([
BABYLON.serialize("hasAlpha")
], BaseTexture.prototype, "_hasAlpha", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "getAlphaFromRGB", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "level", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "coordinatesIndex", void 0);
__decorate([
BABYLON.serialize("coordinatesMode")
], BaseTexture.prototype, "_coordinatesMode", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "wrapU", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "wrapV", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "wrapR", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "isCube", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "is3D", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "gammaSpace", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "invertZ", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "lodLevelInAlpha", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "lodGenerationOffset", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "lodGenerationScale", void 0);
__decorate([
BABYLON.serialize()
], BaseTexture.prototype, "isRenderTarget", void 0);
return BaseTexture;
}());
BABYLON.BaseTexture = BaseTexture;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.baseTexture.js.map
var BABYLON;
(function (BABYLON) {
var Texture = /** @class */ (function (_super) {
__extends(Texture, _super);
function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
if (noMipmap === void 0) { noMipmap = false; }
if (invertY === void 0) { invertY = true; }
if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (buffer === void 0) { buffer = null; }
if (deleteBuffer === void 0) { deleteBuffer = false; }
var _this = _super.call(this, scene) || this;
_this.uOffset = 0;
_this.vOffset = 0;
_this.uScale = 1.0;
_this.vScale = 1.0;
_this.uAng = 0;
_this.vAng = 0;
_this.wAng = 0;
_this._isBlocking = true;
_this.name = url || "";
_this.url = url;
_this._noMipmap = noMipmap;
_this._invertY = invertY;
_this._samplingMode = samplingMode;
_this._buffer = buffer;
_this._deleteBuffer = deleteBuffer;
if (format) {
_this._format = format;
}
scene = _this.getScene();
if (!scene) {
return _this;
}
scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
var load = function () {
if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
_this.onLoadObservable.notifyObservers(_this);
}
if (onLoad) {
onLoad();
}
if (!_this.isBlocking && scene) {
scene.resetCachedMaterial();
}
};
if (!_this.url) {
_this._delayedOnLoad = load;
_this._delayedOnError = onError;
return _this;
}
_this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
if (!_this._texture) {
if (!scene.useDelayedTextureLoading) {
_this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
if (deleteBuffer) {
delete _this._buffer;
}
}
else {
_this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
_this._delayedOnLoad = load;
_this._delayedOnError = onError;
}
}
else {
if (_this._texture.isReady) {
BABYLON.Tools.SetImmediate(function () { return load(); });
}
else {
_this._texture.onLoadedObservable.add(load);
}
}
return _this;
}
Object.defineProperty(Texture.prototype, "noMipmap", {
get: function () {
return this._noMipmap;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Texture.prototype, "isBlocking", {
get: function () {
return this._isBlocking;
},
set: function (value) {
this._isBlocking = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Texture.prototype, "samplingMode", {
get: function () {
return this._samplingMode;
},
enumerable: true,
configurable: true
});
Texture.prototype.updateURL = function (url) {
this.url = url;
this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
this.delayLoad();
};
Texture.prototype.delayLoad = function () {
var _this = this;
if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
return;
}
var scene = this.getScene();
if (!scene) {
return;
}
this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
if (!this._texture) {
this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
if (this._deleteBuffer) {
delete this._buffer;
}
}
else {
if (this._texture.isReady) {
BABYLON.Tools.SetImmediate(function () {
if (!_this._delayedOnLoad) {
return;
}
_this._delayedOnLoad();
});
}
else {
if (this._delayedOnLoad) {
this._texture.onLoadedObservable.add(this._delayedOnLoad);
}
}
}
};
Texture.prototype.updateSamplingMode = function (samplingMode) {
if (!this._texture) {
return;
}
var scene = this.getScene();
if (!scene) {
return;
}
this._samplingMode = samplingMode;
scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
};
Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
x *= this.uScale;
y *= this.vScale;
x -= 0.5 * this.uScale;
y -= 0.5 * this.vScale;
z -= 0.5;
BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
t.x += 0.5 * this.uScale + this.uOffset;
t.y += 0.5 * this.vScale + this.vOffset;
t.z += 0.5;
};
Texture.prototype.getTextureMatrix = function () {
var _this = this;
if (this.uOffset === this._cachedUOffset &&
this.vOffset === this._cachedVOffset &&
this.uScale === this._cachedUScale &&
this.vScale === this._cachedVScale &&
this.uAng === this._cachedUAng &&
this.vAng === this._cachedVAng &&
this.wAng === this._cachedWAng) {
return this._cachedTextureMatrix;
}
this._cachedUOffset = this.uOffset;
this._cachedVOffset = this.vOffset;
this._cachedUScale = this.uScale;
this._cachedVScale = this.vScale;
this._cachedUAng = this.uAng;
this._cachedVAng = this.vAng;
this._cachedWAng = this.wAng;
if (!this._cachedTextureMatrix) {
this._cachedTextureMatrix = BABYLON.Matrix.Zero();
this._rowGenerationMatrix = new BABYLON.Matrix();
this._t0 = BABYLON.Vector3.Zero();
this._t1 = BABYLON.Vector3.Zero();
this._t2 = BABYLON.Vector3.Zero();
}
BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
this._t1.subtractInPlace(this._t0);
this._t2.subtractInPlace(this._t0);
BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
this._cachedTextureMatrix.m[0] = this._t1.x;
this._cachedTextureMatrix.m[1] = this._t1.y;
this._cachedTextureMatrix.m[2] = this._t1.z;
this._cachedTextureMatrix.m[4] = this._t2.x;
this._cachedTextureMatrix.m[5] = this._t2.y;
this._cachedTextureMatrix.m[6] = this._t2.z;
this._cachedTextureMatrix.m[8] = this._t0.x;
this._cachedTextureMatrix.m[9] = this._t0.y;
this._cachedTextureMatrix.m[10] = this._t0.z;
var scene = this.getScene();
if (!scene) {
return this._cachedTextureMatrix;
}
scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
return mat.hasTexture(_this);
});
return this._cachedTextureMatrix;
};
Texture.prototype.getReflectionTextureMatrix = function () {
var _this = this;
var scene = this.getScene();
if (!scene) {
return this._cachedTextureMatrix;
}
if (this.uOffset === this._cachedUOffset &&
this.vOffset === this._cachedVOffset &&
this.uScale === this._cachedUScale &&
this.vScale === this._cachedVScale &&
this.coordinatesMode === this._cachedCoordinatesMode) {
if (this.coordinatesMode === Texture.PROJECTION_MODE) {
if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
return this._cachedTextureMatrix;
}
}
else {
return this._cachedTextureMatrix;
}
}
if (!this._cachedTextureMatrix) {
this._cachedTextureMatrix = BABYLON.Matrix.Zero();
}
if (!this._projectionModeMatrix) {
this._projectionModeMatrix = BABYLON.Matrix.Zero();
}
this._cachedUOffset = this.uOffset;
this._cachedVOffset = this.vOffset;
this._cachedUScale = this.uScale;
this._cachedVScale = this.vScale;
this._cachedCoordinatesMode = this.coordinatesMode;
switch (this.coordinatesMode) {
case Texture.PLANAR_MODE:
BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
this._cachedTextureMatrix[0] = this.uScale;
this._cachedTextureMatrix[5] = this.vScale;
this._cachedTextureMatrix[12] = this.uOffset;
this._cachedTextureMatrix[13] = this.vOffset;
break;
case Texture.PROJECTION_MODE:
BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
this._projectionModeMatrix.m[0] = 0.5;
this._projectionModeMatrix.m[5] = -0.5;
this._projectionModeMatrix.m[10] = 0.0;
this._projectionModeMatrix.m[12] = 0.5;
this._projectionModeMatrix.m[13] = 0.5;
this._projectionModeMatrix.m[14] = 1.0;
this._projectionModeMatrix.m[15] = 1.0;
var projectionMatrix = scene.getProjectionMatrix();
this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
break;
default:
BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
break;
}
scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
return (mat.getActiveTextures().indexOf(_this) !== -1);
});
return this._cachedTextureMatrix;
};
Texture.prototype.clone = function () {
var _this = this;
return BABYLON.SerializationHelper.Clone(function () {
return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
}, this);
};
Object.defineProperty(Texture.prototype, "onLoadObservable", {
get: function () {
if (!this._onLoadObservable) {
this._onLoadObservable = new BABYLON.Observable();
}
return this._onLoadObservable;
},
enumerable: true,
configurable: true
});
Texture.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
serializationObject.base64String = this._buffer;
serializationObject.name = serializationObject.name.replace("data:", "");
}
return serializationObject;
};
Texture.prototype.getClassName = function () {
return "Texture";
};
Texture.prototype.dispose = function () {
_super.prototype.dispose.call(this);
if (this.onLoadObservable) {
this.onLoadObservable.clear();
this._onLoadObservable = null;
}
this._delayedOnLoad = null;
this._delayedOnError = null;
};
// Statics
Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
};
Texture.Parse = function (parsedTexture, scene, rootUrl) {
if (parsedTexture.customType) {
var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
// Update Sampling Mode
var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
}
}
return parsedCustomTexture;
}
if (parsedTexture.isCube) {
return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
}
if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
return null;
}
var texture = BABYLON.SerializationHelper.Parse(function () {
var generateMipMaps = true;
if (parsedTexture.noMipmap) {
generateMipMaps = false;
}
if (parsedTexture.mirrorPlane) {
var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
mirrorTexture._waitingRenderList = parsedTexture.renderList;
mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
return mirrorTexture;
}
else if (parsedTexture.isRenderTarget) {
var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
renderTargetTexture._waitingRenderList = parsedTexture.renderList;
return renderTargetTexture;
}
else {
var texture;
if (parsedTexture.base64String) {
texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
}
else {
texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
}
return texture;
}
}, parsedTexture, scene);
// Update Sampling Mode
if (parsedTexture.samplingMode) {
var sampling = parsedTexture.samplingMode;
if (texture._samplingMode !== sampling) {
texture.updateSamplingMode(sampling);
}
}
// Animations
if (parsedTexture.animations) {
for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
var parsedAnimation = parsedTexture.animations[animationIndex];
texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
}
}
return texture;
};
Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
if (deleteBuffer === void 0) { deleteBuffer = false; }
if (noMipmap === void 0) { noMipmap = false; }
if (invertY === void 0) { invertY = true; }
if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
if (name.substr(0, 5) !== "data:") {
name = "data:" + name;
}
return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
};
// Constants
Texture.NEAREST_SAMPLINGMODE = 1;
Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
Texture.BILINEAR_SAMPLINGMODE = 2;
Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
Texture.TRILINEAR_SAMPLINGMODE = 3;
Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
Texture.NEAREST_NEAREST_MIPNEAREST = 4;
Texture.NEAREST_LINEAR_MIPNEAREST = 5;
Texture.NEAREST_LINEAR_MIPLINEAR = 6;
Texture.NEAREST_LINEAR = 7;
Texture.NEAREST_NEAREST = 8;
Texture.LINEAR_NEAREST_MIPNEAREST = 9;
Texture.LINEAR_NEAREST_MIPLINEAR = 10;
Texture.LINEAR_LINEAR = 11;
Texture.LINEAR_NEAREST = 12;
Texture.EXPLICIT_MODE = 0;
Texture.SPHERICAL_MODE = 1;
Texture.PLANAR_MODE = 2;
Texture.CUBIC_MODE = 3;
Texture.PROJECTION_MODE = 4;
Texture.SKYBOX_MODE = 5;
Texture.INVCUBIC_MODE = 6;
Texture.EQUIRECTANGULAR_MODE = 7;
Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
Texture.CLAMP_ADDRESSMODE = 0;
Texture.WRAP_ADDRESSMODE = 1;
Texture.MIRROR_ADDRESSMODE = 2;
__decorate([
BABYLON.serialize()
], Texture.prototype, "url", void 0);
__decorate([
BABYLON.serialize()
], Texture.prototype, "uOffset", void 0);
__decorate([
BABYLON.serialize()
], Texture.prototype, "vOffset", void 0);
__decorate([
BABYLON.serialize()
], Texture.prototype, "uScale", void 0);
__decorate([
BABYLON.serialize()
], Texture.prototype, "vScale", void 0);
__decorate([
BABYLON.serialize()
], Texture.prototype, "uAng", void 0);
__decorate([
BABYLON.serialize()
], Texture.prototype, "vAng", void 0);
__decorate([
BABYLON.serialize()
], Texture.prototype, "wAng", void 0);
__decorate([
BABYLON.serialize()
], Texture.prototype, "isBlocking", null);
return Texture;
}(BABYLON.BaseTexture));
BABYLON.Texture = Texture;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.texture.js.map
var BABYLON;
(function (BABYLON) {
var _InstancesBatch = /** @class */ (function () {
function _InstancesBatch() {
this.mustReturn = false;
this.visibleInstances = new Array();
this.renderSelf = new Array();
}
return _InstancesBatch;
}());
BABYLON._InstancesBatch = _InstancesBatch;
var Mesh = /** @class */ (function (_super) {
__extends(Mesh, _super);
/**
* @constructor
* @param {string} name The value used by scene.getMeshByName() to do a lookup.
* @param {Scene} scene The scene to add this mesh to.
* @param {Node} parent The parent of this mesh, if it has one
* @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
* @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
* When false, achieved by calling a clone(), also passing False.
* This will make creation of children, recursive.
* @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
*/
function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
if (scene === void 0) { scene = null; }
if (parent === void 0) { parent = null; }
if (source === void 0) { source = null; }
if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
var _this = _super.call(this, name, scene) || this;
// Events
/**
* An event triggered before rendering the mesh
* @type {BABYLON.Observable}
*/
_this.onBeforeRenderObservable = new BABYLON.Observable();
/**
* An event triggered after rendering the mesh
* @type {BABYLON.Observable}
*/
_this.onAfterRenderObservable = new BABYLON.Observable();
/**
* An event triggered before drawing the mesh
* @type {BABYLON.Observable}
*/
_this.onBeforeDrawObservable = new BABYLON.Observable();
// Members
_this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
_this.instances = new Array();
_this._LODLevels = new Array();
_this._visibleInstances = {};
_this._renderIdForInstances = new Array();
_this._batchCache = new _InstancesBatch();
_this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
// Use by builder only to know what orientation were the mesh build in.
_this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
_this.overrideMaterialSideOrientation = null;
_this._areNormalsFrozen = false; // Will be used by ribbons mainly
// Will be used to save a source mesh reference, If any
_this._source = null;
scene = _this.getScene();
if (source) {
// Source mesh
_this._source = source;
// Geometry
if (source._geometry) {
source._geometry.applyToMesh(_this);
}
// Deep copy
BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
// Tags
if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
}
_this.metadata = source.metadata;
// Parent
_this.parent = source.parent;
// Pivot
_this.setPivotMatrix(source.getPivotMatrix());
_this.id = name + "." + source.id;
// Material
_this.material = source.material;
var index;
if (!doNotCloneChildren) {
// Children
var directDescendants = source.getDescendants(true);
for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
var child = directDescendants[index_1];
if (child.clone) {
child.clone(name + "." + child.name, _this);
}
}
}
// Physics clone
var physicsEngine = _this.getScene().getPhysicsEngine();
if (clonePhysicsImpostor && physicsEngine) {
var impostor = physicsEngine.getImpostorForPhysicsObject(source);
if (impostor) {
_this.physicsImpostor = impostor.clone(_this);
}
}
// Particles
for (index = 0; index < scene.particleSystems.length; index++) {
var system = scene.particleSystems[index];
if (system.emitter === source) {
system.clone(system.name, _this);
}
}
_this.computeWorldMatrix(true);
}
// Parent
if (parent !== null) {
_this.parent = parent;
}
return _this;
}
Object.defineProperty(Mesh, "FRONTSIDE", {
/**
* Mesh side orientation : usually the external or front surface
*/
get: function () {
return Mesh._FRONTSIDE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh, "BACKSIDE", {
/**
* Mesh side orientation : usually the internal or back surface
*/
get: function () {
return Mesh._BACKSIDE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh, "DOUBLESIDE", {
/**
* Mesh side orientation : both internal and external or front and back surfaces
*/
get: function () {
return Mesh._DOUBLESIDE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh, "DEFAULTSIDE", {
/**
* Mesh side orientation : by default, `FRONTSIDE`
*/
get: function () {
return Mesh._DEFAULTSIDE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh, "NO_CAP", {
/**
* Mesh cap setting : no cap
*/
get: function () {
return Mesh._NO_CAP;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh, "CAP_START", {
/**
* Mesh cap setting : one cap at the beginning of the mesh
*/
get: function () {
return Mesh._CAP_START;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh, "CAP_END", {
/**
* Mesh cap setting : one cap at the end of the mesh
*/
get: function () {
return Mesh._CAP_END;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh, "CAP_ALL", {
/**
* Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
*/
get: function () {
return Mesh._CAP_ALL;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
set: function (callback) {
if (this._onBeforeDrawObserver) {
this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
}
this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh.prototype, "morphTargetManager", {
get: function () {
return this._morphTargetManager;
},
set: function (value) {
if (this._morphTargetManager === value) {
return;
}
this._morphTargetManager = value;
this._syncGeometryWithMorphTargetManager();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh.prototype, "source", {
get: function () {
return this._source;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh.prototype, "isUnIndexed", {
get: function () {
return this._unIndexed;
},
set: function (value) {
if (this._unIndexed !== value) {
this._unIndexed = value;
this._markSubMeshesAsAttributesDirty();
}
},
enumerable: true,
configurable: true
});
// Methods
/**
* Returns the string "Mesh".
*/
Mesh.prototype.getClassName = function () {
return "Mesh";
};
/**
* Returns a string.
* @param {boolean} fullDetails - support for multiple levels of logging within scene loading
*/
Mesh.prototype.toString = function (fullDetails) {
var ret = _super.prototype.toString.call(this, fullDetails);
ret += ", n vertices: " + this.getTotalVertices();
ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
if (this.animations) {
for (var i = 0; i < this.animations.length; i++) {
ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
}
}
if (fullDetails) {
if (this._geometry) {
var ib = this.getIndices();
var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
if (vb && ib) {
ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
}
}
else {
ret += ", flat shading: UNKNOWN";
}
}
return ret;
};
Object.defineProperty(Mesh.prototype, "hasLODLevels", {
/**
* True if the mesh has some Levels Of Details (LOD).
* Returns a boolean.
*/
get: function () {
return this._LODLevels.length > 0;
},
enumerable: true,
configurable: true
});
Mesh.prototype._sortLODLevels = function () {
this._LODLevels.sort(function (a, b) {
if (a.distance < b.distance) {
return 1;
}
if (a.distance > b.distance) {
return -1;
}
return 0;
});
};
/**
* Add a mesh as LOD level triggered at the given distance.
* tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
* @param {number} distance The distance from the center of the object to show this level
* @param {Mesh} mesh The mesh to be added as LOD level
* @return {Mesh} This mesh (for chaining)
*/
Mesh.prototype.addLODLevel = function (distance, mesh) {
if (mesh && mesh._masterMesh) {
BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
return this;
}
var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
this._LODLevels.push(level);
if (mesh) {
mesh._masterMesh = this;
}
this._sortLODLevels();
return this;
};
/**
* Returns the LOD level mesh at the passed distance or null if not found.
* It is related to the method `addLODLevel(distance, mesh)`.
* tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
* Returns an object Mesh or `null`.
*/
Mesh.prototype.getLODLevelAtDistance = function (distance) {
for (var index = 0; index < this._LODLevels.length; index++) {
var level = this._LODLevels[index];
if (level.distance === distance) {
return level.mesh;
}
}
return null;
};
/**
* Remove a mesh from the LOD array
* tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
* @param {Mesh} mesh The mesh to be removed.
* @return {Mesh} This mesh (for chaining)
*/
Mesh.prototype.removeLODLevel = function (mesh) {
for (var index = 0; index < this._LODLevels.length; index++) {
if (this._LODLevels[index].mesh === mesh) {
this._LODLevels.splice(index, 1);
if (mesh) {
mesh._masterMesh = null;
}
}
}
this._sortLODLevels();
return this;
};
/**
* Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
* tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
*/
Mesh.prototype.getLOD = function (camera, boundingSphere) {
if (!this._LODLevels || this._LODLevels.length === 0) {
return this;
}
var bSphere;
if (boundingSphere) {
bSphere = boundingSphere;
}
else {
var boundingInfo = this.getBoundingInfo();
bSphere = boundingInfo.boundingSphere;
}
var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
if (this.onLODLevelSelection) {
this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
}
return this;
}
for (var index = 0; index < this._LODLevels.length; index++) {
var level = this._LODLevels[index];
if (level.distance < distanceToCamera) {
if (level.mesh) {
level.mesh._preActivate();
level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
}
if (this.onLODLevelSelection) {
this.onLODLevelSelection(distanceToCamera, this, level.mesh);
}
return level.mesh;
}
}
if (this.onLODLevelSelection) {
this.onLODLevelSelection(distanceToCamera, this, this);
}
return this;
};
Object.defineProperty(Mesh.prototype, "geometry", {
/**
* Returns the mesh internal Geometry object.
*/
get: function () {
return this._geometry;
},
enumerable: true,
configurable: true
});
/**
* Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
*/
Mesh.prototype.getTotalVertices = function () {
if (!this._geometry) {
return 0;
}
return this._geometry.getTotalVertices();
};
/**
* Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
* If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
* You can force the copy with forceCopy === true
* Returns null if the mesh has no geometry or no vertex buffer.
* Possible `kind` values :
* - BABYLON.VertexBuffer.PositionKind
* - BABYLON.VertexBuffer.UVKind
* - BABYLON.VertexBuffer.UV2Kind
* - BABYLON.VertexBuffer.UV3Kind
* - BABYLON.VertexBuffer.UV4Kind
* - BABYLON.VertexBuffer.UV5Kind
* - BABYLON.VertexBuffer.UV6Kind
* - BABYLON.VertexBuffer.ColorKind
* - BABYLON.VertexBuffer.MatricesIndicesKind
* - BABYLON.VertexBuffer.MatricesIndicesExtraKind
* - BABYLON.VertexBuffer.MatricesWeightsKind
* - BABYLON.VertexBuffer.MatricesWeightsExtraKind
*/
Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
if (!this._geometry) {
return null;
}
return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
};
/**
* Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
* Returns `null` if the mesh has no geometry.
* Possible `kind` values :
* - BABYLON.VertexBuffer.PositionKind
* - BABYLON.VertexBuffer.UVKind
* - BABYLON.VertexBuffer.UV2Kind
* - BABYLON.VertexBuffer.UV3Kind
* - BABYLON.VertexBuffer.UV4Kind
* - BABYLON.VertexBuffer.UV5Kind
* - BABYLON.VertexBuffer.UV6Kind
* - BABYLON.VertexBuffer.ColorKind
* - BABYLON.VertexBuffer.MatricesIndicesKind
* - BABYLON.VertexBuffer.MatricesIndicesExtraKind
* - BABYLON.VertexBuffer.MatricesWeightsKind
* - BABYLON.VertexBuffer.MatricesWeightsExtraKind
*/
Mesh.prototype.getVertexBuffer = function (kind) {
if (!this._geometry) {
return null;
}
return this._geometry.getVertexBuffer(kind);
};
/**
* Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
* Possible `kind` values :
* - BABYLON.VertexBuffer.PositionKind
* - BABYLON.VertexBuffer.UVKind
* - BABYLON.VertexBuffer.UV2Kind
* - BABYLON.VertexBuffer.UV3Kind
* - BABYLON.VertexBuffer.UV4Kind
* - BABYLON.VertexBuffer.UV5Kind
* - BABYLON.VertexBuffer.UV6Kind
* - BABYLON.VertexBuffer.ColorKind
* - BABYLON.VertexBuffer.MatricesIndicesKind
* - BABYLON.VertexBuffer.MatricesIndicesExtraKind
* - BABYLON.VertexBuffer.MatricesWeightsKind
* - BABYLON.VertexBuffer.MatricesWeightsExtraKind
*/
Mesh.prototype.isVerticesDataPresent = function (kind) {
if (!this._geometry) {
if (this._delayInfo) {
return this._delayInfo.indexOf(kind) !== -1;
}
return false;
}
return this._geometry.isVerticesDataPresent(kind);
};
/**
* Returns a boolean defining if the vertex data for the requested `kind` is updatable.
* Possible `kind` values :
* - BABYLON.VertexBuffer.PositionKind
* - BABYLON.VertexBuffer.UVKind
* - BABYLON.VertexBuffer.UV2Kind
* - BABYLON.VertexBuffer.UV3Kind
* - BABYLON.VertexBuffer.UV4Kind
* - BABYLON.VertexBuffer.UV5Kind
* - BABYLON.VertexBuffer.UV6Kind
* - BABYLON.VertexBuffer.ColorKind
* - BABYLON.VertexBuffer.MatricesIndicesKind
* - BABYLON.VertexBuffer.MatricesIndicesExtraKind
* - BABYLON.VertexBuffer.MatricesWeightsKind
* - BABYLON.VertexBuffer.MatricesWeightsExtraKind
*/
Mesh.prototype.isVertexBufferUpdatable = function (kind) {
if (!this._geometry) {
if (this._delayInfo) {
return this._delayInfo.indexOf(kind) !== -1;
}
return false;
}
return this._geometry.isVertexBufferUpdatable(kind);
};
/**
* Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
* Possible `kind` values :
* - BABYLON.VertexBuffer.PositionKind
* - BABYLON.VertexBuffer.UVKind
* - BABYLON.VertexBuffer.UV2Kind
* - BABYLON.VertexBuffer.UV3Kind
* - BABYLON.VertexBuffer.UV4Kind
* - BABYLON.VertexBuffer.UV5Kind
* - BABYLON.VertexBuffer.UV6Kind
* - BABYLON.VertexBuffer.ColorKind
* - BABYLON.VertexBuffer.MatricesIndicesKind
* - BABYLON.VertexBuffer.MatricesIndicesExtraKind
* - BABYLON.VertexBuffer.MatricesWeightsKind
* - BABYLON.VertexBuffer.MatricesWeightsExtraKind
*/
Mesh.prototype.getVerticesDataKinds = function () {
if (!this._geometry) {
var result = new Array();
if (this._delayInfo) {
this._delayInfo.forEach(function (kind, index, array) {
result.push(kind);
});
}
return result;
}
return this._geometry.getVerticesDataKinds();
};
/**
* Returns a positive integer : the total number of indices in this mesh geometry.
* Returns zero if the mesh has no geometry.
*/
Mesh.prototype.getTotalIndices = function () {
if (!this._geometry) {
return 0;
}
return this._geometry.getTotalIndices();
};
/**
* Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
* If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
* Returns an empty array if the mesh has no geometry.
*/
Mesh.prototype.getIndices = function (copyWhenShared) {
if (!this._geometry) {
return [];
}
return this._geometry.getIndices(copyWhenShared);
};
Object.defineProperty(Mesh.prototype, "isBlocked", {
get: function () {
return this._masterMesh !== null && this._masterMesh !== undefined;
},
enumerable: true,
configurable: true
});
/**
* Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
*/
Mesh.prototype.isReady = function () {
if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
return false;
}
return _super.prototype.isReady.call(this);
};
Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
/**
* Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
* This property is pertinent only for updatable parametric shapes.
*/
get: function () {
return this._areNormalsFrozen;
},
enumerable: true,
configurable: true
});
/**
* This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
* It has no effect at all on other shapes.
* It prevents the mesh normals from being recomputed on next `positions` array update.
* Returns the Mesh.
*/
Mesh.prototype.freezeNormals = function () {
this._areNormalsFrozen = true;
return this;
};
/**
* This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
* It has no effect at all on other shapes.
* It reactivates the mesh normals computation if it was previously frozen.
* Returns the Mesh.
*/
Mesh.prototype.unfreezeNormals = function () {
this._areNormalsFrozen = false;
return this;
};
Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
/**
* Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
*/
set: function (count) {
this._overridenInstanceCount = count;
},
enumerable: true,
configurable: true
});
// Methods
Mesh.prototype._preActivate = function () {
var sceneRenderId = this.getScene().getRenderId();
if (this._preActivateId === sceneRenderId) {
return this;
}
this._preActivateId = sceneRenderId;
this._visibleInstances = null;
return this;
};
Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
if (this._visibleInstances) {
this._visibleInstances.intermediateDefaultRenderId = renderId;
}
return this;
};
Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
if (!this._visibleInstances) {
this._visibleInstances = {};
this._visibleInstances.defaultRenderId = renderId;
this._visibleInstances.selfDefaultRenderId = this._renderId;
}
if (!this._visibleInstances[renderId]) {
this._visibleInstances[renderId] = new Array();
}
this._visibleInstances[renderId].push(instance);
return this;
};
/**
* This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
* This means the mesh underlying bounding box and sphere are recomputed.
* Returns the Mesh.
*/
Mesh.prototype.refreshBoundingInfo = function () {
return this._refreshBoundingInfo(false);
};
Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
if (this._boundingInfo && this._boundingInfo.isLocked) {
return this;
}
var data = this._getPositionData(applySkeleton);
if (data) {
var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
}
if (this.subMeshes) {
for (var index = 0; index < this.subMeshes.length; index++) {
this.subMeshes[index].refreshBoundingInfo();
}
}
this._updateBoundingInfo();
return this;
};
Mesh.prototype._getPositionData = function (applySkeleton) {
var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
if (data && applySkeleton && this.skeleton) {
data = data.slice();
var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
if (matricesWeightsData && matricesIndicesData) {
var needExtras = this.numBoneInfluencers > 4;
var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
var skeletonMatrices = this.skeleton.getTransformMatrices(this);
var tempVector = BABYLON.Tmp.Vector3[0];
var finalMatrix = BABYLON.Tmp.Matrix[0];
var tempMatrix = BABYLON.Tmp.Matrix[1];
var matWeightIdx = 0;
for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
finalMatrix.reset();
var inf;
var weight;
for (inf = 0; inf < 4; inf++) {
weight = matricesWeightsData[matWeightIdx + inf];
if (weight <= 0)
break;
BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
finalMatrix.addToSelf(tempMatrix);
}
if (needExtras) {
for (inf = 0; inf < 4; inf++) {
weight = matricesWeightsExtraData[matWeightIdx + inf];
if (weight <= 0)
break;
BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
finalMatrix.addToSelf(tempMatrix);
}
}
BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
tempVector.toArray(data, index);
}
}
}
return data;
};
Mesh.prototype._createGlobalSubMesh = function (force) {
var totalVertices = this.getTotalVertices();
if (!totalVertices || !this.getIndices()) {
return null;
}
// Check if we need to recreate the submeshes
if (this.subMeshes && this.subMeshes.length > 0) {
var ib = this.getIndices();
if (!ib) {
return null;
}
var totalIndices = ib.length;
var needToRecreate = false;
if (force) {
needToRecreate = true;
}
else {
for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
var submesh = _a[_i];
if (submesh.indexStart + submesh.indexCount >= totalIndices) {
needToRecreate = true;
break;
}
if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
needToRecreate = true;
break;
}
}
}
if (!needToRecreate) {
return this.subMeshes[0];
}
}
this.releaseSubMeshes();
return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
};
Mesh.prototype.subdivide = function (count) {
if (count < 1) {
return;
}
var totalIndices = this.getTotalIndices();
var subdivisionSize = (totalIndices / count) | 0;
var offset = 0;
// Ensure that subdivisionSize is a multiple of 3
while (subdivisionSize % 3 !== 0) {
subdivisionSize++;
}
this.releaseSubMeshes();
for (var index = 0; index < count; index++) {
if (offset >= totalIndices) {
break;
}
BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
offset += subdivisionSize;
}
this.synchronizeInstances();
};
/**
* Sets the vertex data of the mesh geometry for the requested `kind`.
* If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
* The `data` are either a numeric array either a Float32Array.
* The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
* The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
* Note that a new underlying VertexBuffer object is created each call.
* If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
*
* Possible `kind` values :
* - BABYLON.VertexBuffer.PositionKind
* - BABYLON.VertexBuffer.UVKind
* - BABYLON.VertexBuffer.UV2Kind
* - BABYLON.VertexBuffer.UV3Kind
* - BABYLON.VertexBuffer.UV4Kind
* - BABYLON.VertexBuffer.UV5Kind
* - BABYLON.VertexBuffer.UV6Kind
* - BABYLON.VertexBuffer.ColorKind
* - BABYLON.VertexBuffer.MatricesIndicesKind
* - BABYLON.VertexBuffer.MatricesIndicesExtraKind
* - BABYLON.VertexBuffer.MatricesWeightsKind
* - BABYLON.VertexBuffer.MatricesWeightsExtraKind
*
* Returns the Mesh.
*/
Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
if (updatable === void 0) { updatable = false; }
if (!this._geometry) {
var vertexData = new BABYLON.VertexData();
vertexData.set(data, kind);
var scene = this.getScene();
new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
}
else {
this._geometry.setVerticesData(kind, data, updatable, stride);
}
return this;
};
Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
if (updatable === void 0) { updatable = true; }
var vb = this.getVertexBuffer(kind);
if (!vb || vb.isUpdatable() === updatable) {
return;
}
this.setVerticesData(kind, this.getVerticesData(kind), updatable);
};
/**
* Sets the mesh VertexBuffer.
* Returns the Mesh.
*/
Mesh.prototype.setVerticesBuffer = function (buffer) {
if (!this._geometry) {
this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
}
this._geometry.setVerticesBuffer(buffer);
return this;
};
/**
* Updates the existing vertex data of the mesh geometry for the requested `kind`.
* If the mesh has no geometry, it is simply returned as it is.
* The `data` are either a numeric array either a Float32Array.
* No new underlying VertexBuffer object is created.
* If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
* If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
*
* Possible `kind` values :
* - BABYLON.VertexBuffer.PositionKind
* - BABYLON.VertexBuffer.UVKind
* - BABYLON.VertexBuffer.UV2Kind
* - BABYLON.VertexBuffer.UV3Kind
* - BABYLON.VertexBuffer.UV4Kind
* - BABYLON.VertexBuffer.UV5Kind
* - BABYLON.VertexBuffer.UV6Kind
* - BABYLON.VertexBuffer.ColorKind
* - BABYLON.VertexBuffer.MatricesIndicesKind
* - BABYLON.VertexBuffer.MatricesIndicesExtraKind
* - BABYLON.VertexBuffer.MatricesWeightsKind
* - BABYLON.VertexBuffer.MatricesWeightsExtraKind
*
* Returns the Mesh.
*/
Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
if (!this._geometry) {
return this;
}
if (!makeItUnique) {
this._geometry.updateVerticesData(kind, data, updateExtends);
}
else {
this.makeGeometryUnique();
this.updateVerticesData(kind, data, updateExtends, false);
}
return this;
};
/**
* This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
* tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
* The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
* The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
* Returns the Mesh.
*/
Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
if (computeNormals === void 0) { computeNormals = true; }
var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
if (!positions) {
return this;
}
positionFunction(positions);
this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
if (computeNormals) {
var indices = this.getIndices();
var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
if (!normals) {
return this;
}
BABYLON.VertexData.ComputeNormals(positions, indices, normals);
this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
}
return this;
};
/**
* Creates a un-shared specific occurence of the geometry for the mesh.
* Returns the Mesh.
*/
Mesh.prototype.makeGeometryUnique = function () {
if (!this._geometry) {
return this;
}
var oldGeometry = this._geometry;
var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
oldGeometry.releaseForMesh(this, true);
geometry.applyToMesh(this);
return this;
};
/**
* Sets the mesh indices.
* Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
* Type is Uint16Array by default unless the mesh has more than 65536 vertices.
* If the mesh has no geometry, a new Geometry object is created and set to the mesh.
* This method creates a new index buffer each call.
* Returns the Mesh.
*/
Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
if (totalVertices === void 0) { totalVertices = null; }
if (updatable === void 0) { updatable = false; }
if (!this._geometry) {
var vertexData = new BABYLON.VertexData();
vertexData.indices = indices;
var scene = this.getScene();
new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
}
else {
this._geometry.setIndices(indices, totalVertices, updatable);
}
return this;
};
/**
* Update the current index buffer
* Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
* Returns the Mesh.
*/
Mesh.prototype.updateIndices = function (indices, offset) {
if (!this._geometry) {
return this;
}
this._geometry.updateIndices(indices, offset);
return this;
};
/**
* Invert the geometry to move from a right handed system to a left handed one.
* Returns the Mesh.
*/
Mesh.prototype.toLeftHanded = function () {
if (!this._geometry) {
return this;
}
this._geometry.toLeftHanded();
return this;
};
Mesh.prototype._bind = function (subMesh, effect, fillMode) {
if (!this._geometry) {
return this;
}
var engine = this.getScene().getEngine();
// Wireframe
var indexToBind;
if (this._unIndexed) {
indexToBind = null;
}
else {
switch (fillMode) {
case BABYLON.Material.PointFillMode:
indexToBind = null;
break;
case BABYLON.Material.WireFrameFillMode:
indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
break;
default:
case BABYLON.Material.TriangleFillMode:
indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
break;
}
}
// VBOs
this._geometry._bind(effect, indexToBind);
return this;
};
Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
if (alternate === void 0) { alternate = false; }
if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
return this;
}
this.onBeforeDrawObservable.notifyObservers(this);
var scene = this.getScene();
var engine = scene.getEngine();
if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
// or triangles as points
engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
}
else if (fillMode == BABYLON.Material.WireFrameFillMode) {
// Triangles as wireframe
engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
}
else {
engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
}
if (scene._isAlternateRenderingEnabled && !alternate) {
var effect = subMesh.effect || this._effectiveMaterial.getEffect();
if (!effect || !scene.activeCamera) {
return this;
}
scene._switchToAlternateCameraConfiguration(true);
this._effectiveMaterial.bindView(effect);
this._effectiveMaterial.bindViewProjection(effect);
engine.setViewport(scene.activeCamera._alternateCamera.viewport);
this._draw(subMesh, fillMode, instancesCount, true);
engine.setViewport(scene.activeCamera.viewport);
scene._switchToAlternateCameraConfiguration(false);
this._effectiveMaterial.bindView(effect);
this._effectiveMaterial.bindViewProjection(effect);
}
return this;
};
/**
* Registers for this mesh a javascript function called just before the rendering process.
* This function is passed the current mesh.
* Return the Mesh.
*/
Mesh.prototype.registerBeforeRender = function (func) {
this.onBeforeRenderObservable.add(func);
return this;
};
/**
* Disposes a previously registered javascript function called before the rendering.
* This function is passed the current mesh.
* Returns the Mesh.
*/
Mesh.prototype.unregisterBeforeRender = function (func) {
this.onBeforeRenderObservable.removeCallback(func);
return this;
};
/**
* Registers for this mesh a javascript function called just after the rendering is complete.
* This function is passed the current mesh.
* Returns the Mesh.
*/
Mesh.prototype.registerAfterRender = function (func) {
this.onAfterRenderObservable.add(func);
return this;
};
/**
* Disposes a previously registered javascript function called after the rendering.
* This function is passed the current mesh.
* Return the Mesh.
*/
Mesh.prototype.unregisterAfterRender = function (func) {
this.onAfterRenderObservable.removeCallback(func);
return this;
};
Mesh.prototype._getInstancesRenderList = function (subMeshId) {
var scene = this.getScene();
this._batchCache.mustReturn = false;
this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
this._batchCache.visibleInstances[subMeshId] = null;
if (this._visibleInstances) {
var currentRenderId = scene.getRenderId();
var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
var selfRenderId = this._renderId;
if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
currentRenderId = Math.max(defaultRenderId, currentRenderId);
selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
}
var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
if (this._renderIdForInstances[subMeshId] === currentRenderId) {
this._batchCache.mustReturn = true;
return this._batchCache;
}
if (currentRenderId !== selfRenderId) {
this._batchCache.renderSelf[subMeshId] = false;
}
}
this._renderIdForInstances[subMeshId] = currentRenderId;
}
return this._batchCache;
};
Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
var visibleInstances = batch.visibleInstances[subMesh._id];
if (!visibleInstances) {
return this;
}
var matricesCount = visibleInstances.length + 1;
var bufferSize = matricesCount * 16 * 4;
var currentInstancesBufferSize = this._instancesBufferSize;
var instancesBuffer = this._instancesBuffer;
while (this._instancesBufferSize < bufferSize) {
this._instancesBufferSize *= 2;
}
if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
this._instancesData = new Float32Array(this._instancesBufferSize / 4);
}
var offset = 0;
var instancesCount = 0;
var world = this.getWorldMatrix();
if (batch.renderSelf[subMesh._id]) {
world.copyToArray(this._instancesData, offset);
offset += 16;
instancesCount++;
}
if (visibleInstances) {
for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
var instance = visibleInstances[instanceIndex];
instance.getWorldMatrix().copyToArray(this._instancesData, offset);
offset += 16;
instancesCount++;
}
}
if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
if (instancesBuffer) {
instancesBuffer.dispose();
}
instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
this._instancesBuffer = instancesBuffer;
this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
}
else {
instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
}
this._bind(subMesh, effect, fillMode);
this._draw(subMesh, fillMode, instancesCount);
engine.unbindInstanceAttributes();
return this;
};
Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
var scene = this.getScene();
var engine = scene.getEngine();
if (hardwareInstancedRendering) {
this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
}
else {
if (batch.renderSelf[subMesh._id]) {
// Draw
if (onBeforeDraw) {
onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
}
this._draw(subMesh, fillMode, this._overridenInstanceCount);
}
var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
if (visibleInstancesForSubMesh) {
for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
var instance = visibleInstancesForSubMesh[instanceIndex];
// World
var world = instance.getWorldMatrix();
if (onBeforeDraw) {
onBeforeDraw(true, world, effectiveMaterial);
}
// Draw
this._draw(subMesh, fillMode);
}
}
}
return this;
};
/**
* Triggers the draw call for the mesh.
* Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
* Returns the Mesh.
*/
Mesh.prototype.render = function (subMesh, enableAlphaMode) {
this.checkOcclusionQuery();
if (this._isOccluded) {
return this;
}
var scene = this.getScene();
// Managing instances
var batch = this._getInstancesRenderList(subMesh._id);
if (batch.mustReturn) {
return this;
}
// Checking geometry state
if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
return this;
}
this.onBeforeRenderObservable.notifyObservers(this);
var engine = scene.getEngine();
var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
// Material
var material = subMesh.getMaterial();
if (!material) {
return this;
}
this._effectiveMaterial = material;
if (this._effectiveMaterial.storeEffectOnSubMeshes) {
if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
return this;
}
}
else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
return this;
}
// Alpha mode
if (enableAlphaMode) {
engine.setAlphaMode(this._effectiveMaterial.alphaMode);
}
// Outline - step 1
var savedDepthWrite = engine.getDepthWrite();
if (this.renderOutline) {
engine.setDepthWrite(false);
scene.getOutlineRenderer().render(subMesh, batch);
engine.setDepthWrite(savedDepthWrite);
}
var effect;
if (this._effectiveMaterial.storeEffectOnSubMeshes) {
effect = subMesh.effect;
}
else {
effect = this._effectiveMaterial.getEffect();
}
if (!effect) {
return this;
}
var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
if (this._effectiveMaterial.forceDepthWrite) {
engine.setDepthWrite(true);
}
// Bind
var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
if (!hardwareInstancedRendering) {
this._bind(subMesh, effect, fillMode);
}
var world = this.getWorldMatrix();
if (this._effectiveMaterial.storeEffectOnSubMeshes) {
this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
}
else {
this._effectiveMaterial.bind(world, this);
}
if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
}
// Draw
this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
// Unbind
this._effectiveMaterial.unbind();
// Outline - step 2
if (this.renderOutline && savedDepthWrite) {
engine.setDepthWrite(true);
engine.setColorWrite(false);
scene.getOutlineRenderer().render(subMesh, batch);
engine.setColorWrite(true);
}
// Overlay
if (this.renderOverlay) {
var currentMode = engine.getAlphaMode();
engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
scene.getOutlineRenderer().render(subMesh, batch, true);
engine.setAlphaMode(currentMode);
}
this.onAfterRenderObservable.notifyObservers(this);
return this;
};
Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
if (isInstance && effectiveMaterial) {
effectiveMaterial.bindOnlyWorldMatrix(world);
}
};
/**
* Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
*/
Mesh.prototype.getEmittedParticleSystems = function () {
var results = new Array();
for (var index = 0; index < this.getScene().particleSystems.length; index++) {
var particleSystem = this.getScene().particleSystems[index];
if (particleSystem.emitter === this) {
results.push(particleSystem);
}
}
return results;
};
/**
* Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
*/
Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
var results = new Array();
var descendants = this.getDescendants();
descendants.push(this);
for (var index = 0; index < this.getScene().particleSystems.length; index++) {
var particleSystem = this.getScene().particleSystems[index];
var emitter = particleSystem.emitter;
if (emitter.position && descendants.indexOf(emitter) !== -1) {
results.push(particleSystem);
}
}
return results;
};
Mesh.prototype._checkDelayState = function () {
var scene = this.getScene();
if (this._geometry) {
this._geometry.load(scene);
}
else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
this._queueLoad(scene);
}
return this;
};
Mesh.prototype._queueLoad = function (scene) {
var _this = this;
scene._addPendingData(this);
var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
if (data instanceof ArrayBuffer) {
_this._delayLoadingFunction(data, _this);
}
else {
_this._delayLoadingFunction(JSON.parse(data), _this);
}
_this.instances.forEach(function (instance) {
instance._syncSubMeshes();
});
_this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
scene._removePendingData(_this);
}, function () { }, scene.database, getBinaryData);
return this;
};
/**
* Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
*/
Mesh.prototype.isInFrustum = function (frustumPlanes) {
if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
return false;
}
if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
return false;
}
this._checkDelayState();
return true;
};
/**
* Sets the mesh material by the material or multiMaterial `id` property.
* The material `id` is a string identifying the material or the multiMaterial.
* This method returns the Mesh.
*/
Mesh.prototype.setMaterialByID = function (id) {
var materials = this.getScene().materials;
var index;
for (index = materials.length - 1; index > -1; index--) {
if (materials[index].id === id) {
this.material = materials[index];
return this;
}
}
// Multi
var multiMaterials = this.getScene().multiMaterials;
for (index = multiMaterials.length - 1; index > -1; index--) {
if (multiMaterials[index].id === id) {
this.material = multiMaterials[index];
return this;
}
}
return this;
};
/**
* Returns as a new array populated with the mesh material and/or skeleton, if any.
*/
Mesh.prototype.getAnimatables = function () {
var results = new Array();
if (this.material) {
results.push(this.material);
}
if (this.skeleton) {
results.push(this.skeleton);
}
return results;
};
/**
* Modifies the mesh geometry according to the passed transformation matrix.
* This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
* The mesh normals are modified accordingly the same transformation.
* tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
* Note that, under the hood, this method sets a new VertexBuffer each call.
* Returns the Mesh.
*/
Mesh.prototype.bakeTransformIntoVertices = function (transform) {
// Position
if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
return this;
}
var submeshes = this.subMeshes.splice(0);
this._resetPointsArrayCache();
var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
var temp = new Array();
var index;
for (index = 0; index < data.length; index += 3) {
BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
}
this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
// Normals
if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
return this;
}
data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
temp = [];
for (index = 0; index < data.length; index += 3) {
BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
}
this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
// flip faces?
if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
this.flipFaces();
}
// Restore submeshes
this.releaseSubMeshes();
this.subMeshes = submeshes;
return this;
};
/**
* Modifies the mesh geometry according to its own current World Matrix.
* The mesh World Matrix is then reset.
* This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
* tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
* Note that, under the hood, this method sets a new VertexBuffer each call.
* Returns the Mesh.
*/
Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
this.scaling.copyFromFloats(1, 1, 1);
this.position.copyFromFloats(0, 0, 0);
this.rotation.copyFromFloats(0, 0, 0);
//only if quaternion is already set
if (this.rotationQuaternion) {
this.rotationQuaternion = BABYLON.Quaternion.Identity();
}
this._worldMatrix = BABYLON.Matrix.Identity();
return this;
};
Object.defineProperty(Mesh.prototype, "_positions", {
// Cache
get: function () {
if (this._geometry) {
return this._geometry._positions;
}
return null;
},
enumerable: true,
configurable: true
});
Mesh.prototype._resetPointsArrayCache = function () {
if (this._geometry) {
this._geometry._resetPointsArrayCache();
}
return this;
};
Mesh.prototype._generatePointsArray = function () {
if (this._geometry) {
return this._geometry._generatePointsArray();
}
return false;
};
/**
* Returns a new Mesh object generated from the current mesh properties.
* This method must not get confused with createInstance().
* The parameter `name` is a string, the name given to the new mesh.
* The optional parameter `newParent` can be any Node object (default `null`).
* The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
* The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
*/
Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
};
/**
* Disposes the Mesh.
* By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
* Returns nothing.
*/
Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
var _this = this;
if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
this.morphTargetManager = null;
if (this._geometry) {
this._geometry.releaseForMesh(this, true);
}
// Sources
var meshes = this.getScene().meshes;
meshes.forEach(function (abstractMesh) {
var mesh = abstractMesh;
if (mesh._source && mesh._source === _this) {
mesh._source = null;
}
});
this._source = null;
// Instances
if (this._instancesBuffer) {
this._instancesBuffer.dispose();
this._instancesBuffer = null;
}
while (this.instances.length) {
this.instances[0].dispose();
}
// Highlight layers.
var highlightLayers = this.getScene().highlightLayers;
for (var i = 0; i < highlightLayers.length; i++) {
var highlightLayer = highlightLayers[i];
if (highlightLayer) {
highlightLayer.removeMesh(this);
highlightLayer.removeExcludedMesh(this);
}
}
_super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
};
/**
* Modifies the mesh geometry according to a displacement map.
* A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
* The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
* This method returns nothing.
* The parameter `url` is a string, the URL from the image file is to be downloaded.
* The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
* The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
* The parameter `uvOffset` is an optional vector2 used to offset UV.
* The parameter `uvScale` is an optional vector2 used to scale UV.
*
* Returns the Mesh.
*/
Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
var _this = this;
var scene = this.getScene();
var onload = function (img) {
// Getting height map data
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var heightMapWidth = img.width;
var heightMapHeight = img.height;
canvas.width = heightMapWidth;
canvas.height = heightMapHeight;
context.drawImage(img, 0, 0);
// Create VertexData from map data
//Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
_this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
//execute success callback, if set
if (onSuccess) {
onSuccess(_this);
}
};
BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
return this;
};
/**
* Modifies the mesh geometry according to a displacementMap buffer.
* A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
* The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
* This method returns nothing.
* The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
* The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
* The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
* The parameter `uvOffset` is an optional vector2 used to offset UV.
* The parameter `uvScale` is an optional vector2 used to scale UV.
*
* Returns the Mesh.
*/
Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
|| !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
|| !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
return this;
}
var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
var position = BABYLON.Vector3.Zero();
var normal = BABYLON.Vector3.Zero();
var uv = BABYLON.Vector2.Zero();
uvOffset = uvOffset || BABYLON.Vector2.Zero();
uvScale = uvScale || new BABYLON.Vector2(1, 1);
for (var index = 0; index < positions.length; index += 3) {
BABYLON.Vector3.FromArrayToRef(positions, index, position);
BABYLON.Vector3.FromArrayToRef(normals, index, normal);
BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
// Compute height
var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
var pos = (u + v * heightMapWidth) * 4;
var r = buffer[pos] / 255.0;
var g = buffer[pos + 1] / 255.0;
var b = buffer[pos + 2] / 255.0;
var gradient = r * 0.3 + g * 0.59 + b * 0.11;
normal.normalize();
normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
position = position.add(normal);
position.toArray(positions, index);
}
BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
return this;
};
/**
* Modify the mesh to get a flat shading rendering.
* This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
* This method returns the Mesh.
* Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
*/
Mesh.prototype.convertToFlatShadedMesh = function () {
/// Update normals and vertices to get a flat shading rendering.
/// Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face
var kinds = this.getVerticesDataKinds();
var vbs = {};
var data = {};
var newdata = {};
var updatableNormals = false;
var kindIndex;
var kind;
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
var vertexBuffer = this.getVertexBuffer(kind);
if (kind === BABYLON.VertexBuffer.NormalKind) {
updatableNormals = vertexBuffer.isUpdatable();
kinds.splice(kindIndex, 1);
kindIndex--;
continue;
}
vbs[kind] = vertexBuffer;
data[kind] = vbs[kind].getData();
newdata[kind] = [];
}
// Save previous submeshes
var previousSubmeshes = this.subMeshes.slice(0);
var indices = this.getIndices();
var totalIndices = this.getTotalIndices();
// Generating unique vertices per face
var index;
for (index = 0; index < totalIndices; index++) {
var vertexIndex = indices[index];
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
var stride = vbs[kind].getStrideSize();
for (var offset = 0; offset < stride; offset++) {
newdata[kind].push(data[kind][vertexIndex * stride + offset]);
}
}
}
// Updating faces & normal
var normals = [];
var positions = newdata[BABYLON.VertexBuffer.PositionKind];
for (index = 0; index < totalIndices; index += 3) {
indices[index] = index;
indices[index + 1] = index + 1;
indices[index + 2] = index + 2;
var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
var p1p2 = p1.subtract(p2);
var p3p2 = p3.subtract(p2);
var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
// Store same normals for every vertex
for (var localIndex = 0; localIndex < 3; localIndex++) {
normals.push(normal.x);
normals.push(normal.y);
normals.push(normal.z);
}
}
this.setIndices(indices);
this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
// Updating vertex buffers
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
}
// Updating submeshes
this.releaseSubMeshes();
for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
var previousOne = previousSubmeshes[submeshIndex];
BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
}
this.synchronizeInstances();
return this;
};
/**
* This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
* In other words, more vertices, no more indices and a single bigger VBO.
* The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
* Returns the Mesh.
*/
Mesh.prototype.convertToUnIndexedMesh = function () {
/// Remove indices by unfolding faces into buffers
/// Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face
var kinds = this.getVerticesDataKinds();
var vbs = {};
var data = {};
var newdata = {};
var kindIndex;
var kind;
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
var vertexBuffer = this.getVertexBuffer(kind);
vbs[kind] = vertexBuffer;
data[kind] = vbs[kind].getData();
newdata[kind] = [];
}
// Save previous submeshes
var previousSubmeshes = this.subMeshes.slice(0);
var indices = this.getIndices();
var totalIndices = this.getTotalIndices();
// Generating unique vertices per face
var index;
for (index = 0; index < totalIndices; index++) {
var vertexIndex = indices[index];
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
var stride = vbs[kind].getStrideSize();
for (var offset = 0; offset < stride; offset++) {
newdata[kind].push(data[kind][vertexIndex * stride + offset]);
}
}
}
// Updating indices
for (index = 0; index < totalIndices; index += 3) {
indices[index] = index;
indices[index + 1] = index + 1;
indices[index + 2] = index + 2;
}
this.setIndices(indices);
// Updating vertex buffers
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
}
// Updating submeshes
this.releaseSubMeshes();
for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
var previousOne = previousSubmeshes[submeshIndex];
BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
}
this._unIndexed = true;
this.synchronizeInstances();
return this;
};
/**
* Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
* This method returns the Mesh.
* Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
*/
Mesh.prototype.flipFaces = function (flipNormals) {
if (flipNormals === void 0) { flipNormals = false; }
var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
var i;
if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
for (i = 0; i < vertex_data.normals.length; i++) {
vertex_data.normals[i] *= -1;
}
}
if (vertex_data.indices) {
var temp;
for (i = 0; i < vertex_data.indices.length; i += 3) {
// reassign indices
temp = vertex_data.indices[i + 1];
vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
vertex_data.indices[i + 2] = temp;
}
}
vertex_data.applyToMesh(this);
return this;
};
// Instances
/**
* Creates a new InstancedMesh object from the mesh model.
* An instance shares the same properties and the same material than its model.
* Only these properties of each instance can then be set individually :
* - position
* - rotation
* - rotationQuaternion
* - setPivotMatrix
* - scaling
* tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
* Warning : this method is not supported for Line mesh and LineSystem
*/
Mesh.prototype.createInstance = function (name) {
return new BABYLON.InstancedMesh(name, this);
};
/**
* Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
* After this call, all the mesh instances have the same submeshes than the current mesh.
* This method returns the Mesh.
*/
Mesh.prototype.synchronizeInstances = function () {
for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
var instance = this.instances[instanceIndex];
instance._syncSubMeshes();
}
return this;
};
/**
* Simplify the mesh according to the given array of settings.
* Function will return immediately and will simplify async. It returns the Mesh.
* @param settings a collection of simplification settings.
* @param parallelProcessing should all levels calculate parallel or one after the other.
* @param type the type of simplification to run.
* @param successCallback optional success callback to be called after the simplification finished processing all settings.
*/
Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
if (parallelProcessing === void 0) { parallelProcessing = true; }
if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
this.getScene().simplificationQueue.addTask({
settings: settings,
parallelProcessing: parallelProcessing,
mesh: this,
simplificationType: simplificationType,
successCallback: successCallback
});
return this;
};
/**
* Optimization of the mesh's indices, in case a mesh has duplicated vertices.
* The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
* This should be used together with the simplification to avoid disappearing triangles.
* Returns the Mesh.
* @param successCallback an optional success callback to be called after the optimization finished.
*/
Mesh.prototype.optimizeIndices = function (successCallback) {
var _this = this;
var indices = this.getIndices();
var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
if (!positions || !indices) {
return this;
}
var vectorPositions = new Array();
for (var pos = 0; pos < positions.length; pos = pos + 3) {
vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
}
var dupes = new Array();
BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
var realPos = vectorPositions.length - 1 - iteration;
var testedPosition = vectorPositions[realPos];
for (var j = 0; j < realPos; ++j) {
var againstPosition = vectorPositions[j];
if (testedPosition.equals(againstPosition)) {
dupes[realPos] = j;
break;
}
}
}, function () {
for (var i = 0; i < indices.length; ++i) {
indices[i] = dupes[indices[i]] || indices[i];
}
//indices are now reordered
var originalSubMeshes = _this.subMeshes.slice(0);
_this.setIndices(indices);
_this.subMeshes = originalSubMeshes;
if (successCallback) {
successCallback(_this);
}
});
return this;
};
Mesh.prototype.serialize = function (serializationObject) {
serializationObject.name = this.name;
serializationObject.id = this.id;
serializationObject.type = this.getClassName();
if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
serializationObject.tags = BABYLON.Tags.GetTags(this);
}
serializationObject.position = this.position.asArray();
if (this.rotationQuaternion) {
serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
}
else if (this.rotation) {
serializationObject.rotation = this.rotation.asArray();
}
serializationObject.scaling = this.scaling.asArray();
serializationObject.localMatrix = this.getPivotMatrix().asArray();
serializationObject.isEnabled = this.isEnabled();
serializationObject.isVisible = this.isVisible;
serializationObject.infiniteDistance = this.infiniteDistance;
serializationObject.pickable = this.isPickable;
serializationObject.receiveShadows = this.receiveShadows;
serializationObject.billboardMode = this.billboardMode;
serializationObject.visibility = this.visibility;
serializationObject.checkCollisions = this.checkCollisions;
serializationObject.isBlocker = this.isBlocker;
// Parent
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
// Geometry
serializationObject.isUnIndexed = this.isUnIndexed;
var geometry = this._geometry;
if (geometry) {
var geometryId = geometry.id;
serializationObject.geometryId = geometryId;
// SubMeshes
serializationObject.subMeshes = [];
for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
var subMesh = this.subMeshes[subIndex];
serializationObject.subMeshes.push({
materialIndex: subMesh.materialIndex,
verticesStart: subMesh.verticesStart,
verticesCount: subMesh.verticesCount,
indexStart: subMesh.indexStart,
indexCount: subMesh.indexCount
});
}
}
// Material
if (this.material) {
serializationObject.materialId = this.material.id;
}
else {
this.material = null;
}
// Morph targets
if (this.morphTargetManager) {
serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
}
// Skeleton
if (this.skeleton) {
serializationObject.skeletonId = this.skeleton.id;
}
// Physics
//TODO implement correct serialization for physics impostors.
var impostor = this.getPhysicsImpostor();
if (impostor) {
serializationObject.physicsMass = impostor.getParam("mass");
serializationObject.physicsFriction = impostor.getParam("friction");
serializationObject.physicsRestitution = impostor.getParam("mass");
serializationObject.physicsImpostor = impostor.type;
}
// Metadata
if (this.metadata) {
serializationObject.metadata = this.metadata;
}
// Instances
serializationObject.instances = [];
for (var index = 0; index < this.instances.length; index++) {
var instance = this.instances[index];
var serializationInstance = {
name: instance.name,
id: instance.id,
position: instance.position.asArray(),
scaling: instance.scaling.asArray()
};
if (instance.rotationQuaternion) {
serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
}
else if (instance.rotation) {
serializationInstance.rotation = instance.rotation.asArray();
}
serializationObject.instances.push(serializationInstance);
// Animations
BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
serializationInstance.ranges = instance.serializeAnimationRanges();
}
//
// Animations
BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
serializationObject.ranges = this.serializeAnimationRanges();
// Layer mask
serializationObject.layerMask = this.layerMask;
// Alpha
serializationObject.alphaIndex = this.alphaIndex;
serializationObject.hasVertexAlpha = this.hasVertexAlpha;
// Overlay
serializationObject.overlayAlpha = this.overlayAlpha;
serializationObject.overlayColor = this.overlayColor.asArray();
serializationObject.renderOverlay = this.renderOverlay;
// Fog
serializationObject.applyFog = this.applyFog;
// Action Manager
if (this.actionManager) {
serializationObject.actions = this.actionManager.serialize(this.name);
}
};
Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
if (!this.geometry) {
return;
}
this._markSubMeshesAsAttributesDirty();
var morphTargetManager = this._morphTargetManager;
if (morphTargetManager && morphTargetManager.vertexCount) {
if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
this.morphTargetManager = null;
return;
}
for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
var morphTarget = morphTargetManager.getActiveTarget(index);
var positions = morphTarget.getPositions();
if (!positions) {
BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
return;
}
this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
var normals = morphTarget.getNormals();
if (normals) {
this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
}
var tangents = morphTarget.getTangents();
if (tangents) {
this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
}
}
}
else {
var index = 0;
// Positions
while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
}
if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
}
index++;
}
}
};
// Statics
/**
* Returns a new Mesh object parsed from the source provided.
* The parameter `parsedMesh` is the source.
* The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
*/
Mesh.Parse = function (parsedMesh, scene, rootUrl) {
var mesh;
if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
}
else {
mesh = new Mesh(parsedMesh.name, scene);
}
mesh.id = parsedMesh.id;
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
}
mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
if (parsedMesh.metadata !== undefined) {
mesh.metadata = parsedMesh.metadata;
}
if (parsedMesh.rotationQuaternion) {
mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
}
else if (parsedMesh.rotation) {
mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
}
mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
if (parsedMesh.localMatrix) {
mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
}
else if (parsedMesh.pivotMatrix) {
mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
}
mesh.setEnabled(parsedMesh.isEnabled);
mesh.isVisible = parsedMesh.isVisible;
mesh.infiniteDistance = parsedMesh.infiniteDistance;
mesh.showBoundingBox = parsedMesh.showBoundingBox;
mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
if (parsedMesh.applyFog !== undefined) {
mesh.applyFog = parsedMesh.applyFog;
}
if (parsedMesh.pickable !== undefined) {
mesh.isPickable = parsedMesh.pickable;
}
if (parsedMesh.alphaIndex !== undefined) {
mesh.alphaIndex = parsedMesh.alphaIndex;
}
mesh.receiveShadows = parsedMesh.receiveShadows;
mesh.billboardMode = parsedMesh.billboardMode;
if (parsedMesh.visibility !== undefined) {
mesh.visibility = parsedMesh.visibility;
}
mesh.checkCollisions = parsedMesh.checkCollisions;
if (parsedMesh.isBlocker !== undefined) {
mesh.isBlocker = parsedMesh.isBlocker;
}
mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
// freezeWorldMatrix
if (parsedMesh.freezeWorldMatrix) {
mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
}
// Parent
if (parsedMesh.parentId) {
mesh._waitingParentId = parsedMesh.parentId;
}
// Actions
if (parsedMesh.actions !== undefined) {
mesh._waitingActions = parsedMesh.actions;
}
// Overlay
if (parsedMesh.overlayAlpha !== undefined) {
mesh.overlayAlpha = parsedMesh.overlayAlpha;
}
if (parsedMesh.overlayColor !== undefined) {
mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
}
if (parsedMesh.renderOverlay !== undefined) {
mesh.renderOverlay = parsedMesh.renderOverlay;
}
// Geometry
mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
if (parsedMesh.delayLoadingFile) {
mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
if (parsedMesh._binaryInfo) {
mesh._binaryInfo = parsedMesh._binaryInfo;
}
mesh._delayInfo = [];
if (parsedMesh.hasUVs) {
mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
}
if (parsedMesh.hasUVs2) {
mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
}
if (parsedMesh.hasUVs3) {
mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
}
if (parsedMesh.hasUVs4) {
mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
}
if (parsedMesh.hasUVs5) {
mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
}
if (parsedMesh.hasUVs6) {
mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
}
if (parsedMesh.hasColors) {
mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
}
if (parsedMesh.hasMatricesIndices) {
mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
}
if (parsedMesh.hasMatricesWeights) {
mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
}
mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
mesh._checkDelayState();
}
}
else {
BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
}
// Material
if (parsedMesh.materialId) {
mesh.setMaterialByID(parsedMesh.materialId);
}
else {
mesh.material = null;
}
// Morph targets
if (parsedMesh.morphTargetManagerId > -1) {
mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
}
// Skeleton
if (parsedMesh.skeletonId > -1) {
mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
if (parsedMesh.numBoneInfluencers) {
mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
}
}
// Animations
if (parsedMesh.animations) {
for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
var parsedAnimation = parsedMesh.animations[animationIndex];
mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
}
BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
}
if (parsedMesh.autoAnimate) {
scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
}
// Layer Mask
if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
}
else {
mesh.layerMask = 0x0FFFFFFF;
}
// Physics
if (parsedMesh.physicsImpostor) {
mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
mass: parsedMesh.physicsMass,
friction: parsedMesh.physicsFriction,
restitution: parsedMesh.physicsRestitution
}, scene);
}
// Instances
if (parsedMesh.instances) {
for (var index = 0; index < parsedMesh.instances.length; index++) {
var parsedInstance = parsedMesh.instances[index];
var instance = mesh.createInstance(parsedInstance.name);
if (parsedInstance.id) {
instance.id = parsedInstance.id;
}
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
}
instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
if (parsedInstance.parentId) {
instance._waitingParentId = parsedInstance.parentId;
}
if (parsedInstance.rotationQuaternion) {
instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
}
else if (parsedInstance.rotation) {
instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
}
instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
instance.checkCollisions = mesh.checkCollisions;
if (parsedMesh.animations) {
for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
parsedAnimation = parsedMesh.animations[animationIndex];
instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
}
BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
}
}
}
return mesh;
};
/**
* Creates a ribbon mesh.
* Please consider using the same method from the MeshBuilder class instead.
* The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
*
* Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
* The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
* The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
* The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
* The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
* It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
* The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
if (closeArray === void 0) { closeArray = false; }
if (updatable === void 0) { updatable = false; }
return BABYLON.MeshBuilder.CreateRibbon(name, {
pathArray: pathArray,
closeArray: closeArray,
closePath: closePath,
offset: offset,
updatable: updatable,
sideOrientation: sideOrientation,
instance: instance
}, scene);
};
/**
* Creates a plane polygonal mesh. By default, this is a disc.
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
* The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
if (scene === void 0) { scene = null; }
var options = {
radius: radius,
tessellation: tessellation,
sideOrientation: sideOrientation,
updatable: updatable
};
return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
};
/**
* Creates a box mesh.
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `size` sets the size (float) of each box side (default 1).
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
if (scene === void 0) { scene = null; }
var options = {
size: size,
sideOrientation: sideOrientation,
updatable: updatable
};
return BABYLON.MeshBuilder.CreateBox(name, options, scene);
};
/**
* Creates a sphere mesh.
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
* The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
var options = {
segments: segments,
diameterX: diameter,
diameterY: diameter,
diameterZ: diameter,
sideOrientation: sideOrientation,
updatable: updatable
};
return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
};
/**
* Creates a cylinder or a cone mesh.
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
* The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
* The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
* The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
* The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
if (scene !== undefined) {
sideOrientation = updatable || Mesh.DEFAULTSIDE;
updatable = scene;
}
scene = subdivisions;
subdivisions = 1;
}
var options = {
height: height,
diameterTop: diameterTop,
diameterBottom: diameterBottom,
tessellation: tessellation,
subdivisions: subdivisions,
sideOrientation: sideOrientation,
updatable: updatable
};
return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
};
// Torus (Code from SharpDX.org)
/**
* Creates a torus mesh.
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `diameter` sets the diameter size (float) of the torus (default 1).
* The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
* The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
var options = {
diameter: diameter,
thickness: thickness,
tessellation: tessellation,
sideOrientation: sideOrientation,
updatable: updatable
};
return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
};
/**
* Creates a torus knot mesh.
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
* The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
* The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
* The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
var options = {
radius: radius,
tube: tube,
radialSegments: radialSegments,
tubularSegments: tubularSegments,
p: p,
q: q,
sideOrientation: sideOrientation,
updatable: updatable
};
return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
};
/**
* Creates a line mesh.
* Please consider using the same method from the MeshBuilder class instead.
* A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
* Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
* The parameter `points` is an array successive Vector3.
* The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
* When updating an instance, remember that only point positions can change, not the number of points.
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateLines = function (name, points, scene, updatable, instance) {
if (scene === void 0) { scene = null; }
if (updatable === void 0) { updatable = false; }
if (instance === void 0) { instance = null; }
var options = {
points: points,
updatable: updatable,
instance: instance
};
return BABYLON.MeshBuilder.CreateLines(name, options, scene);
};
/**
* Creates a dashed line mesh.
* Please consider using the same method from the MeshBuilder class instead.
* A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
* Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
* The parameter `points` is an array successive Vector3.
* The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
* The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
* The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
* The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
* When updating an instance, remember that only point positions can change, not the number of points.
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
if (scene === void 0) { scene = null; }
var options = {
points: points,
dashSize: dashSize,
gapSize: gapSize,
dashNb: dashNb,
updatable: updatable,
instance: instance
};
return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
};
/**
* Creates a polygon mesh.
* Please consider using the same method from the MeshBuilder class instead.
* The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
* The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
* You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
* Remember you can only change the shape positions, not their number when updating a polygon.
*/
Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
var options = {
shape: shape,
holes: holes,
updatable: updatable,
sideOrientation: sideOrientation
};
return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
};
/**
* Creates an extruded polygon mesh, with depth in the Y direction.
* Please consider using the same method from the MeshBuilder class instead.
*/
Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
var options = {
shape: shape,
holes: holes,
depth: depth,
updatable: updatable,
sideOrientation: sideOrientation
};
return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
};
/**
* Creates an extruded shape mesh.
* The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
* Please consider using the same method from the MeshBuilder class instead.
*
* Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
* The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
* extruded along the Z axis.
* The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
* The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
* The parameter `scale` (float, default 1) is the value to scale the shape.
* The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
* The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
* Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
if (scene === void 0) { scene = null; }
var options = {
shape: shape,
path: path,
scale: scale,
rotation: rotation,
cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
sideOrientation: sideOrientation,
instance: instance,
updatable: updatable
};
return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
};
/**
* Creates an custom extruded shape mesh.
* The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
* Please consider using the same method from the MeshBuilder class instead.
*
* Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
* The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
* extruded along the Z axis.
* The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
* The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
* and the distance of this point from the begining of the path :
* ```javascript
* var rotationFunction = function(i, distance) {
* // do things
* return rotationValue; }
* ```
* It must returns a float value that will be the rotation in radians applied to the shape on each path point.
* The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
* and the distance of this point from the begining of the path :
* ```javascript
* var scaleFunction = function(i, distance) {
* // do things
* return scaleValue;}
* ```
* It must returns a float value that will be the scale value applied to the shape on each path point.
* The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
* The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
* The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
* The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
* Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
var options = {
shape: shape,
path: path,
scaleFunction: scaleFunction,
rotationFunction: rotationFunction,
ribbonCloseArray: ribbonCloseArray,
ribbonClosePath: ribbonClosePath,
cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
sideOrientation: sideOrientation,
instance: instance,
updatable: updatable
};
return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
};
/**
* Creates lathe mesh.
* The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
* rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
* The parameter `radius` (positive float, default 1) is the radius value of the lathe.
* The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
var options = {
shape: shape,
radius: radius,
tessellation: tessellation,
sideOrientation: sideOrientation,
updatable: updatable
};
return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
};
/**
* Creates a plane mesh.
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
var options = {
size: size,
width: size,
height: size,
sideOrientation: sideOrientation,
updatable: updatable
};
return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
};
/**
* Creates a ground mesh.
* Please consider using the same method from the MeshBuilder class instead.
* The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
* The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
var options = {
width: width,
height: height,
subdivisions: subdivisions,
updatable: updatable
};
return BABYLON.MeshBuilder.CreateGround(name, options, scene);
};
/**
* Creates a tiled ground mesh.
* Please consider using the same method from the MeshBuilder class instead.
* The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
* The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
* The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
* numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
* The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
* numbers of subdivisions on the ground width and height of each tile.
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
var options = {
xmin: xmin,
zmin: zmin,
xmax: xmax,
zmax: zmax,
subdivisions: subdivisions,
precision: precision,
updatable: updatable
};
return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
};
/**
* Creates a ground mesh from a height map.
* tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `url` sets the URL of the height map image resource.
* The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
* The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
* The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
* The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
* The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
* This function is passed the newly built mesh :
* ```javascript
* function(mesh) { // do things
* return; }
* ```
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
var options = {
width: width,
height: height,
subdivisions: subdivisions,
minHeight: minHeight,
maxHeight: maxHeight,
updatable: updatable,
onReady: onReady
};
return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
};
/**
* Creates a tube mesh.
* The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
* The parameter `radius` (positive float, default 1) sets the tube radius size.
* The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
* The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
* This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
* It must return a radius value (positive float) :
* ```javascript
* var radiusFunction = function(i, distance) {
* // do things
* return radius; }
* ```
* The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
* The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
var options = {
path: path,
radius: radius,
tessellation: tessellation,
radiusFunction: radiusFunction,
arc: 1,
cap: cap,
updatable: updatable,
sideOrientation: sideOrientation,
instance: instance
};
return BABYLON.MeshBuilder.CreateTube(name, options, scene);
};
/**
* Creates a polyhedron mesh.
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
* to choose the wanted type.
* The parameter `size` (positive float, default 1) sets the polygon size.
* You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
* You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
* A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
* You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
* To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
* The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreatePolyhedron = function (name, options, scene) {
return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
};
/**
* Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
* Please consider using the same method from the MeshBuilder class instead.
* The parameter `radius` sets the radius size (float) of the icosphere (default 1).
* You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
* The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
* The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
* You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
* Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
*/
Mesh.CreateIcoSphere = function (name, options, scene) {
return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
};
/**
* Creates a decal mesh.
* Please consider using the same method from the MeshBuilder class instead.
* A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
* The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
* The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
* The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
* The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
*/
Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
var options = {
position: position,
normal: normal,
size: size,
angle: angle
};
return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
};
// Skeletons
/**
* @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
*/
Mesh.prototype.setPositionsForCPUSkinning = function () {
if (!this._sourcePositions) {
var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
if (!source) {
return this._sourcePositions;
}
this._sourcePositions = new Float32Array(source);
if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
}
}
return this._sourcePositions;
};
/**
* @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
*/
Mesh.prototype.setNormalsForCPUSkinning = function () {
if (!this._sourceNormals) {
var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
if (!source) {
return this._sourceNormals;
}
this._sourceNormals = new Float32Array(source);
if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
}
}
return this._sourceNormals;
};
/**
* Updates the vertex buffer by applying transformation from the bones.
* Returns the Mesh.
*
* @param {skeleton} skeleton to apply
*/
Mesh.prototype.applySkeleton = function (skeleton) {
if (!this.geometry) {
return this;
}
if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
return this;
}
this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
return this;
}
if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
return this;
}
if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
return this;
}
if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
return this;
}
if (!this._sourcePositions) {
var submeshes = this.subMeshes.slice();
this.setPositionsForCPUSkinning();
this.subMeshes = submeshes;
}
if (!this._sourceNormals) {
this.setNormalsForCPUSkinning();
}
// positionsData checks for not being Float32Array will only pass at most once
var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
if (!positionsData) {
return this;
}
if (!(positionsData instanceof Float32Array)) {
positionsData = new Float32Array(positionsData);
}
// normalsData checks for not being Float32Array will only pass at most once
var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
if (!normalsData) {
return this;
}
if (!(normalsData instanceof Float32Array)) {
normalsData = new Float32Array(normalsData);
}
var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
if (!matricesWeightsData || !matricesIndicesData) {
return this;
}
var needExtras = this.numBoneInfluencers > 4;
var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
var skeletonMatrices = skeleton.getTransformMatrices(this);
var tempVector3 = BABYLON.Vector3.Zero();
var finalMatrix = new BABYLON.Matrix();
var tempMatrix = new BABYLON.Matrix();
var matWeightIdx = 0;
var inf;
for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
var weight;
for (inf = 0; inf < 4; inf++) {
weight = matricesWeightsData[matWeightIdx + inf];
if (weight > 0) {
BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
finalMatrix.addToSelf(tempMatrix);
}
else
break;
}
if (needExtras) {
for (inf = 0; inf < 4; inf++) {
weight = matricesWeightsExtraData[matWeightIdx + inf];
if (weight > 0) {
BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
finalMatrix.addToSelf(tempMatrix);
}
else
break;
}
}
BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
tempVector3.toArray(positionsData, index);
BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
tempVector3.toArray(normalsData, index);
finalMatrix.reset();
}
this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
return this;
};
// Tools
/**
* Returns an object `{min:` Vector3`, max:` Vector3`}`
* This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
*/
Mesh.MinMax = function (meshes) {
var minVector = null;
var maxVector = null;
meshes.forEach(function (mesh, index, array) {
var boundingInfo = mesh.getBoundingInfo();
var boundingBox = boundingInfo.boundingBox;
if (!minVector || !maxVector) {
minVector = boundingBox.minimumWorld;
maxVector = boundingBox.maximumWorld;
}
else {
minVector.MinimizeInPlace(boundingBox.minimumWorld);
maxVector.MaximizeInPlace(boundingBox.maximumWorld);
}
});
if (!minVector || !maxVector) {
return {
min: BABYLON.Vector3.Zero(),
max: BABYLON.Vector3.Zero()
};
}
return {
min: minVector,
max: maxVector
};
};
/**
* Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
*/
Mesh.Center = function (meshesOrMinMaxVector) {
var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
};
/**
* Merge the array of meshes into a single mesh for performance reasons.
* @param {Array} meshes - The vertices source. They should all be of the same material. Entries can empty
* @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
* @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
* @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
* @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
*/
Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
if (disposeSource === void 0) { disposeSource = true; }
var index;
if (!allow32BitsIndices) {
var totalVertices = 0;
// Counting vertices
for (index = 0; index < meshes.length; index++) {
if (meshes[index]) {
totalVertices += meshes[index].getTotalVertices();
if (totalVertices > 65536) {
BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
return null;
}
}
}
}
// Merge
var vertexData = null;
var otherVertexData;
var indiceArray = new Array();
var source = null;
for (index = 0; index < meshes.length; index++) {
if (meshes[index]) {
meshes[index].computeWorldMatrix(true);
otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
otherVertexData.transform(meshes[index].getWorldMatrix());
if (vertexData) {
vertexData.merge(otherVertexData);
}
else {
vertexData = otherVertexData;
source = meshes[index];
}
if (subdivideWithSubMeshes) {
indiceArray.push(meshes[index].getTotalIndices());
}
}
}
source = source;
if (!meshSubclass) {
meshSubclass = new Mesh(source.name + "_merged", source.getScene());
}
vertexData.applyToMesh(meshSubclass);
// Setting properties
meshSubclass.material = source.material;
meshSubclass.checkCollisions = source.checkCollisions;
// Cleaning
if (disposeSource) {
for (index = 0; index < meshes.length; index++) {
if (meshes[index]) {
meshes[index].dispose();
}
}
}
// Subdivide
if (subdivideWithSubMeshes) {
//-- Suppresions du submesh global
meshSubclass.releaseSubMeshes();
index = 0;
var offset = 0;
//-- aplique la subdivision en fonction du tableau d'indices
while (index < indiceArray.length) {
BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
offset += indiceArray[index];
index++;
}
}
return meshSubclass;
};
// Consts
Mesh._FRONTSIDE = 0;
Mesh._BACKSIDE = 1;
Mesh._DOUBLESIDE = 2;
Mesh._DEFAULTSIDE = 0;
Mesh._NO_CAP = 0;
Mesh._CAP_START = 1;
Mesh._CAP_END = 2;
Mesh._CAP_ALL = 3;
return Mesh;
}(BABYLON.AbstractMesh));
BABYLON.Mesh = Mesh;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.mesh.js.map
var BABYLON;
(function (BABYLON) {
var BaseSubMesh = /** @class */ (function () {
function BaseSubMesh() {
}
Object.defineProperty(BaseSubMesh.prototype, "effect", {
get: function () {
return this._materialEffect;
},
enumerable: true,
configurable: true
});
BaseSubMesh.prototype.setEffect = function (effect, defines) {
if (defines === void 0) { defines = null; }
if (this._materialEffect === effect) {
if (!effect) {
this._materialDefines = null;
}
return;
}
this._materialDefines = defines;
this._materialEffect = effect;
};
return BaseSubMesh;
}());
BABYLON.BaseSubMesh = BaseSubMesh;
var SubMesh = /** @class */ (function (_super) {
__extends(SubMesh, _super);
function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
if (createBoundingBox === void 0) { createBoundingBox = true; }
var _this = _super.call(this) || this;
_this.materialIndex = materialIndex;
_this.verticesStart = verticesStart;
_this.verticesCount = verticesCount;
_this.indexStart = indexStart;
_this.indexCount = indexCount;
_this._renderId = 0;
_this._mesh = mesh;
_this._renderingMesh = renderingMesh || mesh;
mesh.subMeshes.push(_this);
_this._trianglePlanes = [];
_this._id = mesh.subMeshes.length - 1;
if (createBoundingBox) {
_this.refreshBoundingInfo();
mesh.computeWorldMatrix(true);
}
return _this;
}
SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
if (createBoundingBox === void 0) { createBoundingBox = true; }
return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
};
Object.defineProperty(SubMesh.prototype, "IsGlobal", {
get: function () {
return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
},
enumerable: true,
configurable: true
});
/**
* Returns the submesh BoudingInfo object.
*/
SubMesh.prototype.getBoundingInfo = function () {
if (this.IsGlobal) {
return this._mesh.getBoundingInfo();
}
return this._boundingInfo;
};
/**
* Sets the submesh BoundingInfo.
* Return the SubMesh.
*/
SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
this._boundingInfo = boundingInfo;
return this;
};
/**
* Returns the mesh of the current submesh.
*/
SubMesh.prototype.getMesh = function () {
return this._mesh;
};
/**
* Returns the rendering mesh of the submesh.
*/
SubMesh.prototype.getRenderingMesh = function () {
return this._renderingMesh;
};
/**
* Returns the submesh material.
*/
SubMesh.prototype.getMaterial = function () {
var rootMaterial = this._renderingMesh.material;
if (rootMaterial && rootMaterial.getSubMaterial) {
var multiMaterial = rootMaterial;
var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
if (this._currentMaterial !== effectiveMaterial) {
this._currentMaterial = effectiveMaterial;
this._materialDefines = null;
}
return effectiveMaterial;
}
if (!rootMaterial) {
return this._mesh.getScene().defaultMaterial;
}
return rootMaterial;
};
// Methods
/**
* Sets a new updated BoundingInfo object to the submesh.
* Returns the SubMesh.
*/
SubMesh.prototype.refreshBoundingInfo = function () {
this._lastColliderWorldVertices = null;
if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
return this;
}
var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
if (!data) {
this._boundingInfo = this._mesh.getBoundingInfo();
return this;
}
var indices = this._renderingMesh.getIndices();
var extend;
//is this the only submesh?
if (this.indexStart === 0 && this.indexCount === indices.length) {
var boundingInfo = this._renderingMesh.getBoundingInfo();
//the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
}
else {
extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
}
this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
return this;
};
SubMesh.prototype._checkCollision = function (collider) {
var boundingInfo = this._renderingMesh.getBoundingInfo();
return boundingInfo._checkCollision(collider);
};
/**
* Updates the submesh BoundingInfo.
* Returns the Submesh.
*/
SubMesh.prototype.updateBoundingInfo = function (world) {
var boundingInfo = this.getBoundingInfo();
if (!boundingInfo) {
this.refreshBoundingInfo();
boundingInfo = this.getBoundingInfo();
}
boundingInfo.update(world);
return this;
};
/**
* True is the submesh bounding box intersects the frustum defined by the passed array of planes.
* Boolean returned.
*/
SubMesh.prototype.isInFrustum = function (frustumPlanes) {
var boundingInfo = this.getBoundingInfo();
if (!boundingInfo) {
return false;
}
return boundingInfo.isInFrustum(frustumPlanes);
};
/**
* True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
* Boolean returned.
*/
SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
var boundingInfo = this.getBoundingInfo();
if (!boundingInfo) {
return false;
}
return boundingInfo.isCompletelyInFrustum(frustumPlanes);
};
/**
* Renders the submesh.
* Returns it.
*/
SubMesh.prototype.render = function (enableAlphaMode) {
this._renderingMesh.render(this, enableAlphaMode);
return this;
};
/**
* Returns a new Index Buffer.
* Type returned : WebGLBuffer.
*/
SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
if (!this._linesIndexBuffer) {
var linesIndices = [];
for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
}
this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
this.linesIndexCount = linesIndices.length;
}
return this._linesIndexBuffer;
};
/**
* True is the passed Ray intersects the submesh bounding box.
* Boolean returned.
*/
SubMesh.prototype.canIntersects = function (ray) {
var boundingInfo = this.getBoundingInfo();
if (!boundingInfo) {
return false;
}
return ray.intersectsBox(boundingInfo.boundingBox);
};
/**
* Returns an object IntersectionInfo.
*/
SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
var intersectInfo = null;
// LineMesh first as it's also a Mesh...
if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
var lineMesh = this._mesh;
// Line test
for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
var p0 = positions[indices[index]];
var p1 = positions[indices[index + 1]];
var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
if (length < 0) {
continue;
}
if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
if (fastCheck) {
break;
}
}
}
}
else {
// Triangles test
for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
var p0 = positions[indices[index]];
var p1 = positions[indices[index + 1]];
var p2 = positions[indices[index + 2]];
var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
if (currentIntersectInfo) {
if (currentIntersectInfo.distance < 0) {
continue;
}
if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
intersectInfo = currentIntersectInfo;
intersectInfo.faceId = index / 3;
if (fastCheck) {
break;
}
}
}
}
}
return intersectInfo;
};
SubMesh.prototype._rebuild = function () {
if (this._linesIndexBuffer) {
this._linesIndexBuffer = null;
}
};
// Clone
/**
* Creates a new Submesh from the passed Mesh.
*/
SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
if (!this.IsGlobal) {
var boundingInfo = this.getBoundingInfo();
if (!boundingInfo) {
return result;
}
result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
}
return result;
};
// Dispose
/**
* Disposes the Submesh.
* Returns nothing.
*/
SubMesh.prototype.dispose = function () {
if (this._linesIndexBuffer) {
this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
this._linesIndexBuffer = null;
}
// Remove from mesh
var index = this._mesh.subMeshes.indexOf(this);
this._mesh.subMeshes.splice(index, 1);
};
// Statics
/**
* Creates a new Submesh from the passed parameters :
* - materialIndex (integer) : the index of the main mesh material.
* - startIndex (integer) : the index where to start the copy in the mesh indices array.
* - indexCount (integer) : the number of indices to copy then from the startIndex.
* - mesh (Mesh) : the main mesh to create the submesh from.
* - renderingMesh (optional Mesh) : rendering mesh.
*/
SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
var minVertexIndex = Number.MAX_VALUE;
var maxVertexIndex = -Number.MAX_VALUE;
renderingMesh = (renderingMesh || mesh);
var indices = renderingMesh.getIndices();
for (var index = startIndex; index < startIndex + indexCount; index++) {
var vertexIndex = indices[index];
if (vertexIndex < minVertexIndex)
minVertexIndex = vertexIndex;
if (vertexIndex > maxVertexIndex)
maxVertexIndex = vertexIndex;
}
return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
};
return SubMesh;
}(BaseSubMesh));
BABYLON.SubMesh = SubMesh;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.subMesh.js.map
var BABYLON;
(function (BABYLON) {
var EffectFallbacks = /** @class */ (function () {
function EffectFallbacks() {
this._defines = {};
this._currentRank = 32;
this._maxRank = -1;
}
EffectFallbacks.prototype.unBindMesh = function () {
this._mesh = null;
};
EffectFallbacks.prototype.addFallback = function (rank, define) {
if (!this._defines[rank]) {
if (rank < this._currentRank) {
this._currentRank = rank;
}
if (rank > this._maxRank) {
this._maxRank = rank;
}
this._defines[rank] = new Array();
}
this._defines[rank].push(define);
};
EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
this._mesh = mesh;
if (rank < this._currentRank) {
this._currentRank = rank;
}
if (rank > this._maxRank) {
this._maxRank = rank;
}
};
Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
get: function () {
return this._currentRank <= this._maxRank;
},
enumerable: true,
configurable: true
});
EffectFallbacks.prototype.reduce = function (currentDefines) {
// First we try to switch to CPU skinning
if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
this._mesh.computeBonesUsingShaders = false;
currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
var scene = this._mesh.getScene();
for (var index = 0; index < scene.meshes.length; index++) {
var otherMesh = scene.meshes[index];
if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
otherMesh.computeBonesUsingShaders = false;
}
}
}
else {
var currentFallbacks = this._defines[this._currentRank];
if (currentFallbacks) {
for (var index = 0; index < currentFallbacks.length; index++) {
currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
}
}
this._currentRank++;
}
return currentDefines;
};
return EffectFallbacks;
}());
BABYLON.EffectFallbacks = EffectFallbacks;
var EffectCreationOptions = /** @class */ (function () {
function EffectCreationOptions() {
}
return EffectCreationOptions;
}());
BABYLON.EffectCreationOptions = EffectCreationOptions;
var Effect = /** @class */ (function () {
function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
if (samplers === void 0) { samplers = null; }
if (defines === void 0) { defines = null; }
if (fallbacks === void 0) { fallbacks = null; }
if (onCompiled === void 0) { onCompiled = null; }
if (onError === void 0) { onError = null; }
var _this = this;
this.uniqueId = 0;
this.onCompileObservable = new BABYLON.Observable();
this.onErrorObservable = new BABYLON.Observable();
this.onBindObservable = new BABYLON.Observable();
this._uniformBuffersNames = {};
this._isReady = false;
this._compilationError = "";
this.name = baseName;
if (attributesNamesOrOptions.attributes) {
var options = attributesNamesOrOptions;
this._engine = uniformsNamesOrEngine;
this._attributesNames = options.attributes;
this._uniformsNames = options.uniformsNames.concat(options.samplers);
this._samplers = options.samplers;
this.defines = options.defines;
this.onError = options.onError;
this.onCompiled = options.onCompiled;
this._fallbacks = options.fallbacks;
this._indexParameters = options.indexParameters;
this._transformFeedbackVaryings = options.transformFeedbackVaryings;
if (options.uniformBuffersNames) {
for (var i = 0; i < options.uniformBuffersNames.length; i++) {
this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
}
}
}
else {
this._engine = engine;
this.defines = defines;
this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
this._samplers = samplers;
this._attributesNames = attributesNamesOrOptions;
this.onError = onError;
this.onCompiled = onCompiled;
this._indexParameters = indexParameters;
this._fallbacks = fallbacks;
}
this.uniqueId = Effect._uniqueIdSeed++;
var vertexSource;
var fragmentSource;
if (baseName.vertexElement) {
vertexSource = document.getElementById(baseName.vertexElement);
if (!vertexSource) {
vertexSource = baseName.vertexElement;
}
}
else {
vertexSource = baseName.vertex || baseName;
}
if (baseName.fragmentElement) {
fragmentSource = document.getElementById(baseName.fragmentElement);
if (!fragmentSource) {
fragmentSource = baseName.fragmentElement;
}
}
else {
fragmentSource = baseName.fragment || baseName;
}
this._loadVertexShader(vertexSource, function (vertexCode) {
_this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
_this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
_this._loadFragmentShader(fragmentSource, function (fragmentCode) {
_this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
_this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
if (baseName) {
var vertex = baseName.vertexElement || baseName.vertex || baseName;
var fragment = baseName.fragmentElement || baseName.fragment || baseName;
_this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
_this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
}
else {
_this._vertexSourceCode = migratedVertexCode;
_this._fragmentSourceCode = migratedFragmentCode;
}
_this._prepareEffect();
});
});
});
});
});
});
}
Object.defineProperty(Effect.prototype, "key", {
get: function () {
return this._key;
},
enumerable: true,
configurable: true
});
// Properties
Effect.prototype.isReady = function () {
return this._isReady;
};
Effect.prototype.getEngine = function () {
return this._engine;
};
Effect.prototype.getProgram = function () {
return this._program;
};
Effect.prototype.getAttributesNames = function () {
return this._attributesNames;
};
Effect.prototype.getAttributeLocation = function (index) {
return this._attributes[index];
};
Effect.prototype.getAttributeLocationByName = function (name) {
var index = this._attributesNames.indexOf(name);
return this._attributes[index];
};
Effect.prototype.getAttributesCount = function () {
return this._attributes.length;
};
Effect.prototype.getUniformIndex = function (uniformName) {
return this._uniformsNames.indexOf(uniformName);
};
Effect.prototype.getUniform = function (uniformName) {
return this._uniforms[this._uniformsNames.indexOf(uniformName)];
};
Effect.prototype.getSamplers = function () {
return this._samplers;
};
Effect.prototype.getCompilationError = function () {
return this._compilationError;
};
// Methods
Effect.prototype.executeWhenCompiled = function (func) {
if (this.isReady()) {
func(this);
return;
}
this.onCompileObservable.add(function (effect) {
func(effect);
});
};
Effect.prototype._loadVertexShader = function (vertex, callback) {
if (BABYLON.Tools.IsWindowObjectExist()) {
// DOM element ?
if (vertex instanceof HTMLElement) {
var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
callback(vertexCode);
return;
}
}
// Base64 encoded ?
if (vertex.substr(0, 7) === "base64:") {
var vertexBinary = window.atob(vertex.substr(7));
callback(vertexBinary);
return;
}
// Is in local store ?
if (Effect.ShadersStore[vertex + "VertexShader"]) {
callback(Effect.ShadersStore[vertex + "VertexShader"]);
return;
}
var vertexShaderUrl;
if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
vertexShaderUrl = vertex;
}
else {
vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
}
// Vertex shader
BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
};
Effect.prototype._loadFragmentShader = function (fragment, callback) {
if (BABYLON.Tools.IsWindowObjectExist()) {
// DOM element ?
if (fragment instanceof HTMLElement) {
var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
callback(fragmentCode);
return;
}
}
// Base64 encoded ?
if (fragment.substr(0, 7) === "base64:") {
var fragmentBinary = window.atob(fragment.substr(7));
callback(fragmentBinary);
return;
}
// Is in local store ?
if (Effect.ShadersStore[fragment + "PixelShader"]) {
callback(Effect.ShadersStore[fragment + "PixelShader"]);
return;
}
if (Effect.ShadersStore[fragment + "FragmentShader"]) {
callback(Effect.ShadersStore[fragment + "FragmentShader"]);
return;
}
var fragmentShaderUrl;
if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
fragmentShaderUrl = fragment;
}
else {
fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
}
// Fragment shader
BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
};
Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
// Rebuild shaders source code
var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
var prefix = shaderVersion + (defines ? defines + "\n" : "");
vertexCode = prefix + vertexCode;
fragmentCode = prefix + fragmentCode;
// Number lines of shaders source code
var i = 2;
var regex = /\n/gm;
var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
i = 2;
var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
// Dump shaders name and formatted source code
if (this.name.vertexElement) {
BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
}
else if (this.name.vertex) {
BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
}
else {
BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
}
};
;
Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
var preparedSourceCode = this._processPrecision(sourceCode);
if (this._engine.webGLVersion == 1) {
callback(preparedSourceCode);
return;
}
// Already converted
if (preparedSourceCode.indexOf("#version 3") !== -1) {
callback(preparedSourceCode.replace("#version 300 es", ""));
return;
}
var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
// Remove extensions
// #extension GL_OES_standard_derivatives : enable
// #extension GL_EXT_shader_texture_lod : enable
// #extension GL_EXT_frag_depth : enable
// #extension GL_EXT_draw_buffers : require
var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
var result = preparedSourceCode.replace(regex, "");
// Migrate to GLSL v300
result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
result = result.replace(/attribute[ \t]/g, "in ");
result = result.replace(/[ \t]attribute/g, " in");
if (isFragment) {
result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
result = result.replace(/texture2D\s*\(/g, "texture(");
result = result.replace(/textureCube\s*\(/g, "texture(");
result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
result = result.replace(/gl_FragColor/g, "glFragColor");
result = result.replace(/gl_FragData/g, "glFragData");
result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
}
callback(result);
};
Effect.prototype._processIncludes = function (sourceCode, callback) {
var _this = this;
var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
var match = regex.exec(sourceCode);
var returnValue = new String(sourceCode);
while (match != null) {
var includeFile = match[1];
// Uniform declaration
if (includeFile.indexOf("__decl__") !== -1) {
includeFile = includeFile.replace(/__decl__/, "");
if (this._engine.supportsUniformBuffers) {
includeFile = includeFile.replace(/Vertex/, "Ubo");
includeFile = includeFile.replace(/Fragment/, "Ubo");
}
includeFile = includeFile + "Declaration";
}
if (Effect.IncludesShadersStore[includeFile]) {
// Substitution
var includeContent = Effect.IncludesShadersStore[includeFile];
if (match[2]) {
var splits = match[3].split(",");
for (var index = 0; index < splits.length; index += 2) {
var source = new RegExp(splits[index], "g");
var dest = splits[index + 1];
includeContent = includeContent.replace(source, dest);
}
}
if (match[4]) {
var indexString = match[5];
if (indexString.indexOf("..") !== -1) {
var indexSplits = indexString.split("..");
var minIndex = parseInt(indexSplits[0]);
var maxIndex = parseInt(indexSplits[1]);
var sourceIncludeContent = includeContent.slice(0);
includeContent = "";
if (isNaN(maxIndex)) {
maxIndex = this._indexParameters[indexSplits[1]];
}
for (var i = minIndex; i < maxIndex; i++) {
if (!this._engine.supportsUniformBuffers) {
// Ubo replacement
sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
return p1 + "{X}";
});
}
includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
}
}
else {
if (!this._engine.supportsUniformBuffers) {
// Ubo replacement
includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
return p1 + "{X}";
});
}
includeContent = includeContent.replace(/\{X\}/g, indexString);
}
}
// Replace
returnValue = returnValue.replace(match[0], includeContent);
}
else {
var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
Effect.IncludesShadersStore[includeFile] = fileContent;
_this._processIncludes(returnValue, callback);
});
return;
}
match = regex.exec(sourceCode);
}
callback(returnValue);
};
Effect.prototype._processPrecision = function (source) {
if (source.indexOf("precision highp float") === -1) {
if (!this._engine.getCaps().highPrecisionShaderSupported) {
source = "precision mediump float;\n" + source;
}
else {
source = "precision highp float;\n" + source;
}
}
else {
if (!this._engine.getCaps().highPrecisionShaderSupported) {
source = source.replace("precision highp float", "precision mediump float");
}
}
return source;
};
Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
var _this = this;
this._isReady = false;
this._vertexSourceCodeOverride = vertexSourceCode;
this._fragmentSourceCodeOverride = fragmentSourceCode;
this.onError = function (effect, error) {
if (onError) {
onError(error);
}
};
this.onCompiled = function () {
var scenes = _this.getEngine().scenes;
for (var i = 0; i < scenes.length; i++) {
scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
}
if (onCompiled) {
onCompiled(_this._program);
}
};
this._fallbacks = null;
this._prepareEffect();
};
Effect.prototype._prepareEffect = function () {
var attributesNames = this._attributesNames;
var defines = this.defines;
var fallbacks = this._fallbacks;
this._valueCache = {};
var previousProgram = this._program;
try {
var engine = this._engine;
if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
}
else {
this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
}
this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
if (engine.supportsUniformBuffers) {
for (var name in this._uniformBuffersNames) {
this.bindUniformBlock(name, this._uniformBuffersNames[name]);
}
}
this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
this._attributes = engine.getAttributes(this._program, attributesNames);
var index;
for (index = 0; index < this._samplers.length; index++) {
var sampler = this.getUniform(this._samplers[index]);
if (sampler == null) {
this._samplers.splice(index, 1);
index--;
}
}
engine.bindSamplers(this);
this._compilationError = "";
this._isReady = true;
if (this.onCompiled) {
this.onCompiled(this);
}
this.onCompileObservable.notifyObservers(this);
this.onCompileObservable.clear();
// Unbind mesh reference in fallbacks
if (this._fallbacks) {
this._fallbacks.unBindMesh();
}
if (previousProgram) {
this.getEngine()._deleteProgram(previousProgram);
}
}
catch (e) {
this._compilationError = e.message;
// Let's go through fallbacks then
BABYLON.Tools.Error("Unable to compile effect:");
BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
return " " + uniform;
}));
BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
return " " + attribute;
}));
this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
BABYLON.Tools.Error("Error: " + this._compilationError);
if (previousProgram) {
this._program = previousProgram;
this._isReady = true;
if (this.onError) {
this.onError(this, this._compilationError);
}
this.onErrorObservable.notifyObservers(this);
}
if (fallbacks && fallbacks.isMoreFallbacks) {
BABYLON.Tools.Error("Trying next fallback.");
this.defines = fallbacks.reduce(this.defines);
this._prepareEffect();
}
else {
if (this.onError) {
this.onError(this, this._compilationError);
}
this.onErrorObservable.notifyObservers(this);
this.onErrorObservable.clear();
// Unbind mesh reference in fallbacks
if (this._fallbacks) {
this._fallbacks.unBindMesh();
}
}
}
};
Object.defineProperty(Effect.prototype, "isSupported", {
get: function () {
return this._compilationError === "";
},
enumerable: true,
configurable: true
});
Effect.prototype._bindTexture = function (channel, texture) {
this._engine._bindTexture(this._samplers.indexOf(channel), texture);
};
Effect.prototype.setTexture = function (channel, texture) {
this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
};
Effect.prototype.setTextureArray = function (channel, textures) {
if (this._samplers.indexOf(channel + "Ex") === -1) {
var initialPos = this._samplers.indexOf(channel);
for (var index = 1; index < textures.length; index++) {
this._samplers.splice(initialPos + index, 0, channel + "Ex");
}
}
this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
};
Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
};
Effect.prototype._cacheMatrix = function (uniformName, matrix) {
var cache = this._valueCache[uniformName];
var flag = matrix.updateFlag;
if (cache !== undefined && cache === flag) {
return false;
}
this._valueCache[uniformName] = flag;
return true;
};
Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
var cache = this._valueCache[uniformName];
if (!cache) {
cache = [x, y];
this._valueCache[uniformName] = cache;
return true;
}
var changed = false;
if (cache[0] !== x) {
cache[0] = x;
changed = true;
}
if (cache[1] !== y) {
cache[1] = y;
changed = true;
}
return changed;
};
Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
var cache = this._valueCache[uniformName];
if (!cache) {
cache = [x, y, z];
this._valueCache[uniformName] = cache;
return true;
}
var changed = false;
if (cache[0] !== x) {
cache[0] = x;
changed = true;
}
if (cache[1] !== y) {
cache[1] = y;
changed = true;
}
if (cache[2] !== z) {
cache[2] = z;
changed = true;
}
return changed;
};
Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
var cache = this._valueCache[uniformName];
if (!cache) {
cache = [x, y, z, w];
this._valueCache[uniformName] = cache;
return true;
}
var changed = false;
if (cache[0] !== x) {
cache[0] = x;
changed = true;
}
if (cache[1] !== y) {
cache[1] = y;
changed = true;
}
if (cache[2] !== z) {
cache[2] = z;
changed = true;
}
if (cache[3] !== w) {
cache[3] = w;
changed = true;
}
return changed;
};
Effect.prototype.bindUniformBuffer = function (buffer, name) {
var bufferName = this._uniformBuffersNames[name];
if (Effect._baseCache[bufferName] === buffer) {
return;
}
Effect._baseCache[bufferName] = buffer;
this._engine.bindUniformBufferBase(buffer, bufferName);
};
Effect.prototype.bindUniformBlock = function (blockName, index) {
this._engine.bindUniformBlock(this._program, blockName, index);
};
Effect.prototype.setIntArray = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setIntArray(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setIntArray2 = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setIntArray2(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setIntArray3 = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setIntArray3(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setIntArray4 = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setIntArray4(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setFloatArray = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setFloatArray(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setFloatArray2 = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setFloatArray2(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setFloatArray3 = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setFloatArray3(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setFloatArray4 = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setFloatArray4(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setArray = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setArray(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setArray2 = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setArray2(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setArray3 = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setArray3(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setArray4 = function (uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setArray4(this.getUniform(uniformName), array);
return this;
};
Effect.prototype.setMatrices = function (uniformName, matrices) {
if (!matrices) {
return this;
}
this._valueCache[uniformName] = null;
this._engine.setMatrices(this.getUniform(uniformName), matrices);
return this;
};
Effect.prototype.setMatrix = function (uniformName, matrix) {
if (this._cacheMatrix(uniformName, matrix)) {
this._engine.setMatrix(this.getUniform(uniformName), matrix);
}
return this;
};
Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
this._valueCache[uniformName] = null;
this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
return this;
};
Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
this._valueCache[uniformName] = null;
this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
return this;
};
Effect.prototype.setFloat = function (uniformName, value) {
var cache = this._valueCache[uniformName];
if (cache !== undefined && cache === value)
return this;
this._valueCache[uniformName] = value;
this._engine.setFloat(this.getUniform(uniformName), value);
return this;
};
Effect.prototype.setBool = function (uniformName, bool) {
var cache = this._valueCache[uniformName];
if (cache !== undefined && cache === bool)
return this;
this._valueCache[uniformName] = bool;
this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
return this;
};
Effect.prototype.setVector2 = function (uniformName, vector2) {
if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
}
return this;
};
Effect.prototype.setFloat2 = function (uniformName, x, y) {
if (this._cacheFloat2(uniformName, x, y)) {
this._engine.setFloat2(this.getUniform(uniformName), x, y);
}
return this;
};
Effect.prototype.setVector3 = function (uniformName, vector3) {
if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
}
return this;
};
Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
if (this._cacheFloat3(uniformName, x, y, z)) {
this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
}
return this;
};
Effect.prototype.setVector4 = function (uniformName, vector4) {
if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
}
return this;
};
Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
if (this._cacheFloat4(uniformName, x, y, z, w)) {
this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
}
return this;
};
Effect.prototype.setColor3 = function (uniformName, color3) {
if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
this._engine.setColor3(this.getUniform(uniformName), color3);
}
return this;
};
Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
}
return this;
};
Effect.ResetCache = function () {
Effect._baseCache = {};
};
Effect._uniqueIdSeed = 0;
Effect._baseCache = {};
// Statics
Effect.ShadersStore = {};
Effect.IncludesShadersStore = {};
return Effect;
}());
BABYLON.Effect = Effect;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.effect.js.map
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var BABYLON;
(function (BABYLON) {
var MaterialDefines = /** @class */ (function () {
function MaterialDefines() {
this._isDirty = true;
this._areLightsDirty = true;
this._areAttributesDirty = true;
this._areTexturesDirty = true;
this._areFresnelDirty = true;
this._areMiscDirty = true;
this._areImageProcessingDirty = true;
this._normals = false;
this._uvs = false;
this._needNormals = false;
this._needUVs = false;
}
Object.defineProperty(MaterialDefines.prototype, "isDirty", {
get: function () {
return this._isDirty;
},
enumerable: true,
configurable: true
});
MaterialDefines.prototype.markAsProcessed = function () {
this._isDirty = false;
this._areAttributesDirty = false;
this._areTexturesDirty = false;
this._areFresnelDirty = false;
this._areLightsDirty = false;
this._areMiscDirty = false;
this._areImageProcessingDirty = false;
};
MaterialDefines.prototype.markAsUnprocessed = function () {
this._isDirty = true;
};
MaterialDefines.prototype.markAllAsDirty = function () {
this._areTexturesDirty = true;
this._areAttributesDirty = true;
this._areLightsDirty = true;
this._areFresnelDirty = true;
this._areMiscDirty = true;
this._areImageProcessingDirty = true;
this._isDirty = true;
};
MaterialDefines.prototype.markAsImageProcessingDirty = function () {
this._areImageProcessingDirty = true;
this._isDirty = true;
};
MaterialDefines.prototype.markAsLightDirty = function () {
this._areLightsDirty = true;
this._isDirty = true;
};
MaterialDefines.prototype.markAsAttributesDirty = function () {
this._areAttributesDirty = true;
this._isDirty = true;
};
MaterialDefines.prototype.markAsTexturesDirty = function () {
this._areTexturesDirty = true;
this._isDirty = true;
};
MaterialDefines.prototype.markAsFresnelDirty = function () {
this._areFresnelDirty = true;
this._isDirty = true;
};
MaterialDefines.prototype.markAsMiscDirty = function () {
this._areMiscDirty = true;
this._isDirty = true;
};
MaterialDefines.prototype.rebuild = function () {
if (this._keys) {
delete this._keys;
}
this._keys = [];
for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
var key = _a[_i];
if (key[0] === "_") {
continue;
}
this._keys.push(key);
}
};
MaterialDefines.prototype.isEqual = function (other) {
if (this._keys.length !== other._keys.length) {
return false;
}
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
if (this[prop] !== other[prop]) {
return false;
}
}
return true;
};
MaterialDefines.prototype.cloneTo = function (other) {
if (this._keys.length !== other._keys.length) {
other._keys = this._keys.slice(0);
}
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
other[prop] = this[prop];
}
};
MaterialDefines.prototype.reset = function () {
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
if (typeof (this[prop]) === "number") {
this[prop] = 0;
}
else {
this[prop] = false;
}
}
};
MaterialDefines.prototype.toString = function () {
var result = "";
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
var value = this[prop];
if (typeof (value) === "number") {
result += "#define " + prop + " " + this[prop] + "\n";
}
else if (value) {
result += "#define " + prop + "\n";
}
}
return result;
};
return MaterialDefines;
}());
BABYLON.MaterialDefines = MaterialDefines;
var Material = /** @class */ (function () {
function Material(name, scene, doNotAdd) {
this.checkReadyOnEveryCall = false;
this.checkReadyOnlyOnce = false;
this.state = "";
this.alpha = 1.0;
this._backFaceCulling = true;
this.doNotSerialize = false;
this.storeEffectOnSubMeshes = false;
/**
* An event triggered when the material is disposed.
* @type {BABYLON.Observable}
*/
this.onDisposeObservable = new BABYLON.Observable();
/**
* An event triggered when the material is bound.
* @type {BABYLON.Observable}
*/
this.onBindObservable = new BABYLON.Observable();
/**
* An event triggered when the material is unbound.
* @type {BABYLON.Observable}
*/
this.onUnBindObservable = new BABYLON.Observable();
this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
this._needDepthPrePass = false;
this.disableDepthWrite = false;
this.forceDepthWrite = false;
this.separateCullingPass = false;
this._fogEnabled = true;
this.pointSize = 1.0;
this.zOffset = 0;
this._wasPreviouslyReady = false;
this._fillMode = Material.TriangleFillMode;
this.name = name;
this.id = name || BABYLON.Tools.RandomId();
this._scene = scene || BABYLON.Engine.LastCreatedScene;
if (this._scene.useRightHandedSystem) {
this.sideOrientation = Material.ClockWiseSideOrientation;
}
else {
this.sideOrientation = Material.CounterClockWiseSideOrientation;
}
this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
if (!doNotAdd) {
this._scene.materials.push(this);
}
}
Object.defineProperty(Material, "TriangleFillMode", {
get: function () {
return Material._TriangleFillMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "WireFrameFillMode", {
get: function () {
return Material._WireFrameFillMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "PointFillMode", {
get: function () {
return Material._PointFillMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "PointListDrawMode", {
get: function () {
return Material._PointListDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "LineListDrawMode", {
get: function () {
return Material._LineListDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "LineLoopDrawMode", {
get: function () {
return Material._LineLoopDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "LineStripDrawMode", {
get: function () {
return Material._LineStripDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "TriangleStripDrawMode", {
get: function () {
return Material._TriangleStripDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "TriangleFanDrawMode", {
get: function () {
return Material._TriangleFanDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "ClockWiseSideOrientation", {
get: function () {
return Material._ClockWiseSideOrientation;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
get: function () {
return Material._CounterClockWiseSideOrientation;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "TextureDirtyFlag", {
get: function () {
return Material._TextureDirtyFlag;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "LightDirtyFlag", {
get: function () {
return Material._LightDirtyFlag;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "FresnelDirtyFlag", {
get: function () {
return Material._FresnelDirtyFlag;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "AttributesDirtyFlag", {
get: function () {
return Material._AttributesDirtyFlag;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material, "MiscDirtyFlag", {
get: function () {
return Material._MiscDirtyFlag;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material.prototype, "backFaceCulling", {
get: function () {
return this._backFaceCulling;
},
set: function (value) {
if (this._backFaceCulling === value) {
return;
}
this._backFaceCulling = value;
this.markAsDirty(Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material.prototype, "onDispose", {
set: function (callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material.prototype, "onBind", {
set: function (callback) {
if (this._onBindObserver) {
this.onBindObservable.remove(this._onBindObserver);
}
this._onBindObserver = this.onBindObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material.prototype, "alphaMode", {
get: function () {
return this._alphaMode;
},
set: function (value) {
if (this._alphaMode === value) {
return;
}
this._alphaMode = value;
this.markAsDirty(Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material.prototype, "needDepthPrePass", {
get: function () {
return this._needDepthPrePass;
},
set: function (value) {
if (this._needDepthPrePass === value) {
return;
}
this._needDepthPrePass = value;
if (this._needDepthPrePass) {
this.checkReadyOnEveryCall = true;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material.prototype, "fogEnabled", {
get: function () {
return this._fogEnabled;
},
set: function (value) {
if (this._fogEnabled === value) {
return;
}
this._fogEnabled = value;
this.markAsDirty(Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material.prototype, "wireframe", {
get: function () {
return this._fillMode === Material.WireFrameFillMode;
},
set: function (value) {
this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material.prototype, "pointsCloud", {
get: function () {
return this._fillMode === Material.PointFillMode;
},
set: function (value) {
this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material.prototype, "fillMode", {
get: function () {
return this._fillMode;
},
set: function (value) {
if (this._fillMode === value) {
return;
}
this._fillMode = value;
this.markAsDirty(Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
/**
* @param {boolean} fullDetails - support for multiple levels of logging within scene loading
* subclasses should override adding information pertainent to themselves
*/
Material.prototype.toString = function (fullDetails) {
var ret = "Name: " + this.name;
if (fullDetails) {
}
return ret;
};
/**
* Child classes can use it to update shaders
*/
Material.prototype.getClassName = function () {
return "Material";
};
Object.defineProperty(Material.prototype, "isFrozen", {
get: function () {
return this.checkReadyOnlyOnce;
},
enumerable: true,
configurable: true
});
Material.prototype.freeze = function () {
this.checkReadyOnlyOnce = true;
};
Material.prototype.unfreeze = function () {
this.checkReadyOnlyOnce = false;
};
Material.prototype.isReady = function (mesh, useInstances) {
return true;
};
Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
return false;
};
Material.prototype.getEffect = function () {
return this._effect;
};
Material.prototype.getScene = function () {
return this._scene;
};
Material.prototype.needAlphaBlending = function () {
return (this.alpha < 1.0);
};
Material.prototype.needAlphaBlendingForMesh = function (mesh) {
return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
};
Material.prototype.needAlphaTesting = function () {
return false;
};
Material.prototype.getAlphaTestTexture = function () {
return null;
};
Material.prototype.markDirty = function () {
this._wasPreviouslyReady = false;
};
Material.prototype._preBind = function (effect, overrideOrientation) {
if (overrideOrientation === void 0) { overrideOrientation = null; }
var engine = this._scene.getEngine();
var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
var reverse = orientation === Material.ClockWiseSideOrientation;
engine.enableEffect(effect ? effect : this._effect);
engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
return reverse;
};
Material.prototype.bind = function (world, mesh) {
};
Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
};
Material.prototype.bindOnlyWorldMatrix = function (world) {
};
Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
sceneUbo.bindToEffect(effect, "Scene");
};
Material.prototype.bindView = function (effect) {
if (!this._useUBO) {
effect.setMatrix("view", this.getScene().getViewMatrix());
}
else {
this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
}
};
Material.prototype.bindViewProjection = function (effect) {
if (!this._useUBO) {
effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
}
else {
this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
}
};
Material.prototype._afterBind = function (mesh) {
this._scene._cachedMaterial = this;
if (mesh) {
this._scene._cachedVisibility = mesh.visibility;
}
else {
this._scene._cachedVisibility = 1;
}
if (mesh) {
this.onBindObservable.notifyObservers(mesh);
}
if (this.disableDepthWrite) {
var engine = this._scene.getEngine();
this._cachedDepthWriteState = engine.getDepthWrite();
engine.setDepthWrite(false);
}
};
Material.prototype.unbind = function () {
this.onUnBindObservable.notifyObservers(this);
if (this.disableDepthWrite) {
var engine = this._scene.getEngine();
engine.setDepthWrite(this._cachedDepthWriteState);
}
};
Material.prototype.getActiveTextures = function () {
return [];
};
Material.prototype.hasTexture = function (texture) {
return false;
};
Material.prototype.clone = function (name) {
return null;
};
Material.prototype.getBindedMeshes = function () {
var result = new Array();
for (var index = 0; index < this._scene.meshes.length; index++) {
var mesh = this._scene.meshes[index];
if (mesh.material === this) {
result.push(mesh);
}
}
return result;
};
/**
* Force shader compilation including textures ready check
*/
Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
var _this = this;
var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
var subMesh = new BABYLON.BaseSubMesh();
var scene = this.getScene();
var engine = scene.getEngine();
var checkReady = function () {
if (!_this._scene || !_this._scene.getEngine()) {
return;
}
if (subMesh._materialDefines) {
subMesh._materialDefines._renderId = -1;
}
var alphaTestState = engine.getAlphaTesting();
var clipPlaneState = scene.clipPlane;
engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
if (localOptions.clipPlane) {
scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
}
if (_this.storeEffectOnSubMeshes) {
if (_this.isReadyForSubMesh(mesh, subMesh)) {
if (onCompiled) {
onCompiled(_this);
}
}
else {
setTimeout(checkReady, 16);
}
}
else {
if (_this.isReady(mesh)) {
if (onCompiled) {
onCompiled(_this);
}
}
else {
setTimeout(checkReady, 16);
}
}
engine.setAlphaTesting(alphaTestState);
if (options && options.clipPlane) {
scene.clipPlane = clipPlaneState;
}
};
checkReady();
};
Material.prototype.markAsDirty = function (flag) {
if (flag & Material.TextureDirtyFlag) {
this._markAllSubMeshesAsTexturesDirty();
}
if (flag & Material.LightDirtyFlag) {
this._markAllSubMeshesAsLightsDirty();
}
if (flag & Material.FresnelDirtyFlag) {
this._markAllSubMeshesAsFresnelDirty();
}
if (flag & Material.AttributesDirtyFlag) {
this._markAllSubMeshesAsAttributesDirty();
}
if (flag & Material.MiscDirtyFlag) {
this._markAllSubMeshesAsMiscDirty();
}
this.getScene().resetCachedMaterial();
};
Material.prototype._markAllSubMeshesAsDirty = function (func) {
for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
var mesh = _a[_i];
if (!mesh.subMeshes) {
continue;
}
for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
var subMesh = _c[_b];
if (subMesh.getMaterial() !== this) {
continue;
}
if (!subMesh._materialDefines) {
continue;
}
func(subMesh._materialDefines);
}
}
};
Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
};
Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
};
Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
};
Material.prototype._markAllSubMeshesAsLightsDirty = function () {
this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
};
Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
};
Material.prototype._markAllSubMeshesAsMiscDirty = function () {
this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
};
Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
// Animations
this.getScene().stopAnimation(this);
// Remove from scene
var index = this._scene.materials.indexOf(this);
if (index >= 0) {
this._scene.materials.splice(index, 1);
}
// Remove from meshes
for (index = 0; index < this._scene.meshes.length; index++) {
var mesh = this._scene.meshes[index];
if (mesh.material === this) {
mesh.material = null;
if (mesh.geometry) {
var geometry = (mesh.geometry);
if (this.storeEffectOnSubMeshes) {
for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
geometry._releaseVertexArrayObject(subMesh._materialEffect);
if (forceDisposeEffect && subMesh._materialEffect) {
this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
}
}
}
else {
geometry._releaseVertexArrayObject(this._effect);
}
}
}
}
this._uniformBuffer.dispose();
// Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
if (forceDisposeEffect && this._effect) {
if (!this.storeEffectOnSubMeshes) {
this._scene.getEngine()._releaseEffect(this._effect);
}
this._effect = null;
}
// Callback
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
this.onBindObservable.clear();
this.onUnBindObservable.clear();
};
Material.prototype.serialize = function () {
return BABYLON.SerializationHelper.Serialize(this);
};
Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
multiMaterial.id = parsedMultiMaterial.id;
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
}
for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
var subMatId = parsedMultiMaterial.materials[matIndex];
if (subMatId) {
multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
}
else {
multiMaterial.subMaterials.push(null);
}
}
return multiMaterial;
};
Material.Parse = function (parsedMaterial, scene, rootUrl) {
if (!parsedMaterial.customType) {
return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
}
if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
if (!BABYLON.LegacyPBRMaterial) {
BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
return;
}
}
var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
return materialType.Parse(parsedMaterial, scene, rootUrl);
;
};
// Triangle views
Material._TriangleFillMode = 0;
Material._WireFrameFillMode = 1;
Material._PointFillMode = 2;
// Draw modes
Material._PointListDrawMode = 3;
Material._LineListDrawMode = 4;
Material._LineLoopDrawMode = 5;
Material._LineStripDrawMode = 6;
Material._TriangleStripDrawMode = 7;
Material._TriangleFanDrawMode = 8;
Material._ClockWiseSideOrientation = 0;
Material._CounterClockWiseSideOrientation = 1;
Material._TextureDirtyFlag = 1;
Material._LightDirtyFlag = 2;
Material._FresnelDirtyFlag = 4;
Material._AttributesDirtyFlag = 8;
Material._MiscDirtyFlag = 16;
__decorate([
BABYLON.serialize()
], Material.prototype, "id", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "name", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "checkReadyOnEveryCall", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "checkReadyOnlyOnce", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "state", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "alpha", void 0);
__decorate([
BABYLON.serialize("backFaceCulling")
], Material.prototype, "_backFaceCulling", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "sideOrientation", void 0);
__decorate([
BABYLON.serialize("alphaMode")
], Material.prototype, "_alphaMode", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "_needDepthPrePass", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "disableDepthWrite", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "forceDepthWrite", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "separateCullingPass", void 0);
__decorate([
BABYLON.serialize("fogEnabled")
], Material.prototype, "_fogEnabled", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "pointSize", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "zOffset", void 0);
__decorate([
BABYLON.serialize()
], Material.prototype, "wireframe", null);
__decorate([
BABYLON.serialize()
], Material.prototype, "pointsCloud", null);
__decorate([
BABYLON.serialize()
], Material.prototype, "fillMode", null);
return Material;
}());
BABYLON.Material = Material;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.material.js.map
var BABYLON;
(function (BABYLON) {
var UniformBuffer = /** @class */ (function () {
/**
* Uniform buffer objects.
*
* Handles blocks of uniform on the GPU.
*
* If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
*
* For more information, please refer to :
* https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
*/
function UniformBuffer(engine, data, dynamic) {
this._engine = engine;
this._noUBO = !engine.supportsUniformBuffers;
this._dynamic = dynamic;
this._data = data || [];
this._uniformLocations = {};
this._uniformSizes = {};
this._uniformLocationPointer = 0;
this._needSync = false;
if (this._noUBO) {
this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
this.updateFloat = this._updateFloatForEffect;
this.updateFloat2 = this._updateFloat2ForEffect;
this.updateFloat3 = this._updateFloat3ForEffect;
this.updateFloat4 = this._updateFloat4ForEffect;
this.updateMatrix = this._updateMatrixForEffect;
this.updateVector3 = this._updateVector3ForEffect;
this.updateVector4 = this._updateVector4ForEffect;
this.updateColor3 = this._updateColor3ForEffect;
this.updateColor4 = this._updateColor4ForEffect;
}
else {
this._engine._uniformBuffers.push(this);
this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
this.updateFloat = this._updateFloatForUniform;
this.updateFloat2 = this._updateFloat2ForUniform;
this.updateFloat3 = this._updateFloat3ForUniform;
this.updateFloat4 = this._updateFloat4ForUniform;
this.updateMatrix = this._updateMatrixForUniform;
this.updateVector3 = this._updateVector3ForUniform;
this.updateVector4 = this._updateVector4ForUniform;
this.updateColor3 = this._updateColor3ForUniform;
this.updateColor4 = this._updateColor4ForUniform;
}
}
Object.defineProperty(UniformBuffer.prototype, "useUbo", {
// Properties
/**
* Indicates if the buffer is using the WebGL2 UBO implementation,
* or just falling back on setUniformXXX calls.
*/
get: function () {
return !this._noUBO;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UniformBuffer.prototype, "isSync", {
/**
* Indicates if the WebGL underlying uniform buffer is in sync
* with the javascript cache data.
*/
get: function () {
return !this._needSync;
},
enumerable: true,
configurable: true
});
/**
* Indicates if the WebGL underlying uniform buffer is dynamic.
* Also, a dynamic UniformBuffer will disable cache verification and always
* update the underlying WebGL uniform buffer to the GPU.
*/
UniformBuffer.prototype.isDynamic = function () {
return this._dynamic !== undefined;
};
/**
* The data cache on JS side.
*/
UniformBuffer.prototype.getData = function () {
return this._bufferData;
};
/**
* The underlying WebGL Uniform buffer.
*/
UniformBuffer.prototype.getBuffer = function () {
return this._buffer;
};
/**
* std140 layout specifies how to align data within an UBO structure.
* See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
* for specs.
*/
UniformBuffer.prototype._fillAlignment = function (size) {
// This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
// and 4x4 matrices
// TODO : change if other types are used
var alignment;
if (size <= 2) {
alignment = size;
}
else {
alignment = 4;
}
if ((this._uniformLocationPointer % alignment) !== 0) {
var oldPointer = this._uniformLocationPointer;
this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
var diff = this._uniformLocationPointer - oldPointer;
for (var i = 0; i < diff; i++) {
this._data.push(0);
}
}
};
/**
* Adds an uniform in the buffer.
* Warning : the subsequents calls of this function must be in the same order as declared in the shader
* for the layout to be correct !
* @param {string} name Name of the uniform, as used in the uniform block in the shader.
* @param {number|number[]} size Data size, or data directly.
*/
UniformBuffer.prototype.addUniform = function (name, size) {
if (this._noUBO) {
return;
}
if (this._uniformLocations[name] !== undefined) {
// Already existing uniform
return;
}
// This function must be called in the order of the shader layout !
// size can be the size of the uniform, or data directly
var data;
if (size instanceof Array) {
data = size;
size = data.length;
}
else {
size = size;
data = [];
// Fill with zeros
for (var i = 0; i < size; i++) {
data.push(0);
}
}
this._fillAlignment(size);
this._uniformSizes[name] = size;
this._uniformLocations[name] = this._uniformLocationPointer;
this._uniformLocationPointer += size;
for (var i = 0; i < size; i++) {
this._data.push(data[i]);
}
this._needSync = true;
};
/**
* Wrapper for addUniform.
* @param {string} name Name of the uniform, as used in the uniform block in the shader.
* @param {Matrix} mat A 4x4 matrix.
*/
UniformBuffer.prototype.addMatrix = function (name, mat) {
this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
};
/**
* Wrapper for addUniform.
* @param {string} name Name of the uniform, as used in the uniform block in the shader.
* @param {number} x
* @param {number} y
*/
UniformBuffer.prototype.addFloat2 = function (name, x, y) {
var temp = [x, y];
this.addUniform(name, temp);
};
/**
* Wrapper for addUniform.
* @param {string} name Name of the uniform, as used in the uniform block in the shader.
* @param {number} x
* @param {number} y
* @param {number} z
*/
UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
var temp = [x, y, z];
this.addUniform(name, temp);
};
/**
* Wrapper for addUniform.
* @param {string} name Name of the uniform, as used in the uniform block in the shader.
* @param {Color3} color
*/
UniformBuffer.prototype.addColor3 = function (name, color) {
var temp = new Array();
color.toArray(temp);
this.addUniform(name, temp);
};
/**
* Wrapper for addUniform.
* @param {string} name Name of the uniform, as used in the uniform block in the shader.
* @param {Color3} color
* @param {number} alpha
*/
UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
var temp = new Array();
color.toArray(temp);
temp.push(alpha);
this.addUniform(name, temp);
};
/**
* Wrapper for addUniform.
* @param {string} name Name of the uniform, as used in the uniform block in the shader.
* @param {Vector3} vector
*/
UniformBuffer.prototype.addVector3 = function (name, vector) {
var temp = new Array();
vector.toArray(temp);
this.addUniform(name, temp);
};
/**
* Wrapper for addUniform.
* @param {string} name Name of the uniform, as used in the uniform block in the shader.
*/
UniformBuffer.prototype.addMatrix3x3 = function (name) {
this.addUniform(name, 12);
};
/**
* Wrapper for addUniform.
* @param {string} name Name of the uniform, as used in the uniform block in the shader.
*/
UniformBuffer.prototype.addMatrix2x2 = function (name) {
this.addUniform(name, 8);
};
/**
* Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
*/
UniformBuffer.prototype.create = function () {
if (this._noUBO) {
return;
}
if (this._buffer) {
return; // nothing to do
}
// See spec, alignment must be filled as a vec4
this._fillAlignment(4);
this._bufferData = new Float32Array(this._data);
this._rebuild();
this._needSync = true;
};
UniformBuffer.prototype._rebuild = function () {
if (this._noUBO) {
return;
}
if (this._dynamic) {
this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
}
else {
this._buffer = this._engine.createUniformBuffer(this._bufferData);
}
};
/**
* Updates the WebGL Uniform Buffer on the GPU.
* If the `dynamic` flag is set to true, no cache comparison is done.
* Otherwise, the buffer will be updated only if the cache differs.
*/
UniformBuffer.prototype.update = function () {
if (!this._buffer) {
this.create();
return;
}
if (!this._dynamic && !this._needSync) {
return;
}
this._engine.updateUniformBuffer(this._buffer, this._bufferData);
this._needSync = false;
};
/**
* Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
* @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
* @param {number[]|Float32Array} data Flattened data
* @param {number} size Size of the data.
*/
UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
var location = this._uniformLocations[uniformName];
if (location === undefined) {
if (this._buffer) {
// Cannot add an uniform if the buffer is already created
BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
return;
}
this.addUniform(uniformName, size);
location = this._uniformLocations[uniformName];
}
if (!this._buffer) {
this.create();
}
if (!this._dynamic) {
// Cache for static uniform buffers
var changed = false;
for (var i = 0; i < size; i++) {
if (this._bufferData[location + i] !== data[i]) {
changed = true;
this._bufferData[location + i] = data[i];
}
}
this._needSync = this._needSync || changed;
}
else {
// No cache for dynamic
for (var i = 0; i < size; i++) {
this._bufferData[location + i] = data[i];
}
}
};
// Update methods
UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
// To match std140, matrix must be realigned
for (var i = 0; i < 3; i++) {
UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
}
this.updateUniform(name, UniformBuffer._tempBuffer, 12);
};
UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
this._currentEffect.setMatrix3x3(name, matrix);
};
UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
this._currentEffect.setMatrix2x2(name, matrix);
};
UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
// To match std140, matrix must be realigned
for (var i = 0; i < 2; i++) {
UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
}
this.updateUniform(name, UniformBuffer._tempBuffer, 8);
};
UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
this._currentEffect.setFloat(name, x);
};
UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
UniformBuffer._tempBuffer[0] = x;
this.updateUniform(name, UniformBuffer._tempBuffer, 1);
};
UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
if (suffix === void 0) { suffix = ""; }
this._currentEffect.setFloat2(name + suffix, x, y);
};
UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
if (suffix === void 0) { suffix = ""; }
UniformBuffer._tempBuffer[0] = x;
UniformBuffer._tempBuffer[1] = y;
this.updateUniform(name, UniformBuffer._tempBuffer, 2);
};
UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
if (suffix === void 0) { suffix = ""; }
this._currentEffect.setFloat3(name + suffix, x, y, z);
};
UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
if (suffix === void 0) { suffix = ""; }
UniformBuffer._tempBuffer[0] = x;
UniformBuffer._tempBuffer[1] = y;
UniformBuffer._tempBuffer[2] = z;
this.updateUniform(name, UniformBuffer._tempBuffer, 3);
};
UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
if (suffix === void 0) { suffix = ""; }
this._currentEffect.setFloat4(name + suffix, x, y, z, w);
};
UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
if (suffix === void 0) { suffix = ""; }
UniformBuffer._tempBuffer[0] = x;
UniformBuffer._tempBuffer[1] = y;
UniformBuffer._tempBuffer[2] = z;
UniformBuffer._tempBuffer[3] = w;
this.updateUniform(name, UniformBuffer._tempBuffer, 4);
};
UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
this._currentEffect.setMatrix(name, mat);
};
UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
this.updateUniform(name, mat.toArray(), 16);
};
UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
this._currentEffect.setVector3(name, vector);
};
UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
vector.toArray(UniformBuffer._tempBuffer);
this.updateUniform(name, UniformBuffer._tempBuffer, 3);
};
UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
this._currentEffect.setVector4(name, vector);
};
UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
vector.toArray(UniformBuffer._tempBuffer);
this.updateUniform(name, UniformBuffer._tempBuffer, 4);
};
UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
if (suffix === void 0) { suffix = ""; }
this._currentEffect.setColor3(name + suffix, color);
};
UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
if (suffix === void 0) { suffix = ""; }
color.toArray(UniformBuffer._tempBuffer);
this.updateUniform(name, UniformBuffer._tempBuffer, 3);
};
UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
if (suffix === void 0) { suffix = ""; }
this._currentEffect.setColor4(name + suffix, color, alpha);
};
UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
if (suffix === void 0) { suffix = ""; }
color.toArray(UniformBuffer._tempBuffer);
UniformBuffer._tempBuffer[3] = alpha;
this.updateUniform(name, UniformBuffer._tempBuffer, 4);
};
/**
* Sets a sampler uniform on the effect.
* @param {string} name Name of the sampler.
* @param {Texture} texture
*/
UniformBuffer.prototype.setTexture = function (name, texture) {
this._currentEffect.setTexture(name, texture);
};
/**
* Directly updates the value of the uniform in the cache AND on the GPU.
* @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
* @param {number[]|Float32Array} data Flattened data
*/
UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
this.updateUniform(uniformName, data, data.length);
this.update();
};
/**
* Binds this uniform buffer to an effect.
* @param {Effect} effect
* @param {string} name Name of the uniform block in the shader.
*/
UniformBuffer.prototype.bindToEffect = function (effect, name) {
this._currentEffect = effect;
if (this._noUBO || !this._buffer) {
return;
}
effect.bindUniformBuffer(this._buffer, name);
};
/**
* Disposes the uniform buffer.
*/
UniformBuffer.prototype.dispose = function () {
if (this._noUBO) {
return;
}
var index = this._engine._uniformBuffers.indexOf(this);
if (index !== -1) {
this._engine._uniformBuffers.splice(index, 1);
}
if (!this._buffer) {
return;
}
if (this._engine._releaseBuffer(this._buffer)) {
this._buffer = null;
}
};
// Pool for avoiding memory leaks
UniformBuffer._MAX_UNIFORM_SIZE = 256;
UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
return UniformBuffer;
}());
BABYLON.UniformBuffer = UniformBuffer;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.uniformBuffer.js.map
var BABYLON;
(function (BABYLON) {
var VertexData = /** @class */ (function () {
function VertexData() {
}
VertexData.prototype.set = function (data, kind) {
switch (kind) {
case BABYLON.VertexBuffer.PositionKind:
this.positions = data;
break;
case BABYLON.VertexBuffer.NormalKind:
this.normals = data;
break;
case BABYLON.VertexBuffer.TangentKind:
this.tangents = data;
break;
case BABYLON.VertexBuffer.UVKind:
this.uvs = data;
break;
case BABYLON.VertexBuffer.UV2Kind:
this.uvs2 = data;
break;
case BABYLON.VertexBuffer.UV3Kind:
this.uvs3 = data;
break;
case BABYLON.VertexBuffer.UV4Kind:
this.uvs4 = data;
break;
case BABYLON.VertexBuffer.UV5Kind:
this.uvs5 = data;
break;
case BABYLON.VertexBuffer.UV6Kind:
this.uvs6 = data;
break;
case BABYLON.VertexBuffer.ColorKind:
this.colors = data;
break;
case BABYLON.VertexBuffer.MatricesIndicesKind:
this.matricesIndices = data;
break;
case BABYLON.VertexBuffer.MatricesWeightsKind:
this.matricesWeights = data;
break;
case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
this.matricesIndicesExtra = data;
break;
case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
this.matricesWeightsExtra = data;
break;
}
};
/**
* Associates the vertexData to the passed Mesh.
* Sets it as updatable or not (default `false`).
* Returns the VertexData.
*/
VertexData.prototype.applyToMesh = function (mesh, updatable) {
this._applyTo(mesh, updatable);
return this;
};
/**
* Associates the vertexData to the passed Geometry.
* Sets it as updatable or not (default `false`).
* Returns the VertexData.
*/
VertexData.prototype.applyToGeometry = function (geometry, updatable) {
this._applyTo(geometry, updatable);
return this;
};
/**
* Updates the associated mesh.
* Returns the VertexData.
*/
VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
this._update(mesh);
return this;
};
/**
* Updates the associated geometry.
* Returns the VertexData.
*/
VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
this._update(geometry);
return this;
};
VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
if (updatable === void 0) { updatable = false; }
if (this.positions) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
}
if (this.normals) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
}
if (this.tangents) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
}
if (this.uvs) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
}
if (this.uvs2) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
}
if (this.uvs3) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
}
if (this.uvs4) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
}
if (this.uvs5) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
}
if (this.uvs6) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
}
if (this.colors) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
}
if (this.matricesIndices) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
}
if (this.matricesWeights) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
}
if (this.matricesIndicesExtra) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
}
if (this.matricesWeightsExtra) {
meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
}
if (this.indices) {
meshOrGeometry.setIndices(this.indices, null, updatable);
}
return this;
};
VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
if (this.positions) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
}
if (this.normals) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
}
if (this.tangents) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
}
if (this.uvs) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
}
if (this.uvs2) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
}
if (this.uvs3) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
}
if (this.uvs4) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
}
if (this.uvs5) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
}
if (this.uvs6) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
}
if (this.colors) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
}
if (this.matricesIndices) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
}
if (this.matricesWeights) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
}
if (this.matricesIndicesExtra) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
}
if (this.matricesWeightsExtra) {
meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
}
if (this.indices) {
meshOrGeometry.setIndices(this.indices, null);
}
return this;
};
/**
* Transforms each position and each normal of the vertexData according to the passed Matrix.
* Returns the VertexData.
*/
VertexData.prototype.transform = function (matrix) {
var transformed = BABYLON.Vector3.Zero();
var index;
if (this.positions) {
var position = BABYLON.Vector3.Zero();
for (index = 0; index < this.positions.length; index += 3) {
BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
this.positions[index] = transformed.x;
this.positions[index + 1] = transformed.y;
this.positions[index + 2] = transformed.z;
}
}
if (this.normals) {
var normal = BABYLON.Vector3.Zero();
for (index = 0; index < this.normals.length; index += 3) {
BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
this.normals[index] = transformed.x;
this.normals[index + 1] = transformed.y;
this.normals[index + 2] = transformed.z;
}
}
if (this.tangents) {
var tangent = BABYLON.Vector4.Zero();
var tangentTransformed = BABYLON.Vector4.Zero();
for (index = 0; index < this.tangents.length; index += 4) {
BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
this.tangents[index] = tangentTransformed.x;
this.tangents[index + 1] = tangentTransformed.y;
this.tangents[index + 2] = tangentTransformed.z;
this.tangents[index + 3] = tangentTransformed.w;
}
}
return this;
};
/**
* Merges the passed VertexData into the current one.
* Returns the modified VertexData.
*/
VertexData.prototype.merge = function (other, options) {
options = options || {};
if (other.indices) {
if (!this.indices) {
this.indices = [];
}
var offset = this.positions ? this.positions.length / 3 : 0;
for (var index = 0; index < other.indices.length; index++) {
//TODO check type - if Int32Array | Uint32Array | Uint16Array!
this.indices.push(other.indices[index] + offset);
}
}
this.positions = this._mergeElement(this.positions, other.positions);
if (!this.positions) {
return this;
}
var count = this.positions.length / 3;
this.normals = this._mergeElement(this.normals, other.normals, count * 3);
this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
return this;
};
VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
if (length === void 0) { length = 0; }
if (defaultValue === void 0) { defaultValue = 0; }
if (!other && !source) {
return null;
}
if (!other) {
var padding = new Float32Array(source.length);
padding.fill(defaultValue);
return this._mergeElement(source, padding, length);
}
if (!source) {
if (length === 0 || length === other.length) {
return other;
}
var padding = new Float32Array(length - other.length);
padding.fill(defaultValue);
return this._mergeElement(padding, other, length);
}
var len = other.length + source.length;
var isSrcTypedArray = source instanceof Float32Array;
var isOthTypedArray = other instanceof Float32Array;
// use non-loop method when the source is Float32Array
if (isSrcTypedArray) {
var ret32 = new Float32Array(len);
ret32.set(source);
ret32.set(other, source.length);
return ret32;
// source is number[], when other is also use concat
}
else if (!isOthTypedArray) {
return source.concat(other);
// source is a number[], but other is a Float32Array, loop required
}
else {
var ret = source.slice(0); // copy source to a separate array
for (var i = 0, len = other.length; i < len; i++) {
ret.push(other[i]);
}
return ret;
}
};
/**
* Serializes the VertexData.
* Returns a serialized object.
*/
VertexData.prototype.serialize = function () {
var serializationObject = this.serialize();
if (this.positions) {
serializationObject.positions = this.positions;
}
if (this.normals) {
serializationObject.normals = this.normals;
}
if (this.tangents) {
serializationObject.tangents = this.tangents;
}
if (this.uvs) {
serializationObject.uvs = this.uvs;
}
if (this.uvs2) {
serializationObject.uvs2 = this.uvs2;
}
if (this.uvs3) {
serializationObject.uvs3 = this.uvs3;
}
if (this.uvs4) {
serializationObject.uvs4 = this.uvs4;
}
if (this.uvs5) {
serializationObject.uvs5 = this.uvs5;
}
if (this.uvs6) {
serializationObject.uvs6 = this.uvs6;
}
if (this.colors) {
serializationObject.colors = this.colors;
}
if (this.matricesIndices) {
serializationObject.matricesIndices = this.matricesIndices;
serializationObject.matricesIndices._isExpanded = true;
}
if (this.matricesWeights) {
serializationObject.matricesWeights = this.matricesWeights;
}
if (this.matricesIndicesExtra) {
serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
serializationObject.matricesIndicesExtra._isExpanded = true;
}
if (this.matricesWeightsExtra) {
serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
}
serializationObject.indices = this.indices;
return serializationObject;
};
// Statics
/**
* Returns the object VertexData associated to the passed mesh.
*/
VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
};
/**
* Returns the object VertexData associated to the passed geometry.
*/
VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
};
VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
var result = new VertexData();
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
}
result.indices = meshOrGeometry.getIndices(copyWhenShared);
return result;
};
/**
* Creates the vertexData of the Ribbon.
*/
VertexData.CreateRibbon = function (options) {
var pathArray = options.pathArray;
var closeArray = options.closeArray || false;
var closePath = options.closePath || false;
var invertUV = options.invertUV || false;
var defaultOffset = Math.floor(pathArray[0].length / 2);
var offset = options.offset || defaultOffset;
offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
var customUV = options.uvs;
var customColors = options.colors;
var positions = [];
var indices = [];
var normals = [];
var uvs = [];
var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
var minlg; // minimal length among all paths from pathArray
var lg = []; // array of path lengths : nb of vertex per path
var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
var p; // path iterator
var i; // point iterator
var j; // point iterator
// if single path in pathArray
if (pathArray.length < 2) {
var ar1 = [];
var ar2 = [];
for (i = 0; i < pathArray[0].length - offset; i++) {
ar1.push(pathArray[0][i]);
ar2.push(pathArray[0][i + offset]);
}
pathArray = [ar1, ar2];
}
// positions and horizontal distances (u)
var idc = 0;
var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
var path;
var l;
minlg = pathArray[0].length;
var vectlg;
var dist;
for (p = 0; p < pathArray.length; p++) {
uTotalDistance[p] = 0;
us[p] = [0];
path = pathArray[p];
l = path.length;
minlg = (minlg < l) ? minlg : l;
j = 0;
while (j < l) {
positions.push(path[j].x, path[j].y, path[j].z);
if (j > 0) {
vectlg = path[j].subtract(path[j - 1]).length();
dist = vectlg + uTotalDistance[p];
us[p].push(dist);
uTotalDistance[p] = dist;
}
j++;
}
if (closePath) {
j--;
positions.push(path[0].x, path[0].y, path[0].z);
vectlg = path[j].subtract(path[0]).length();
dist = vectlg + uTotalDistance[p];
us[p].push(dist);
uTotalDistance[p] = dist;
}
lg[p] = l + closePathCorr;
idx[p] = idc;
idc += (l + closePathCorr);
}
// vertical distances (v)
var path1;
var path2;
var vertex1 = null;
var vertex2 = null;
for (i = 0; i < minlg + closePathCorr; i++) {
vTotalDistance[i] = 0;
vs[i] = [0];
for (p = 0; p < pathArray.length - 1; p++) {
path1 = pathArray[p];
path2 = pathArray[p + 1];
if (i === minlg) {
vertex1 = path1[0];
vertex2 = path2[0];
}
else {
vertex1 = path1[i];
vertex2 = path2[i];
}
vectlg = vertex2.subtract(vertex1).length();
dist = vectlg + vTotalDistance[i];
vs[i].push(dist);
vTotalDistance[i] = dist;
}
if (closeArray && vertex2 && vertex1) {
path1 = pathArray[p];
path2 = pathArray[0];
if (i === minlg) {
vertex2 = path2[0];
}
vectlg = vertex2.subtract(vertex1).length();
dist = vectlg + vTotalDistance[i];
vTotalDistance[i] = dist;
}
}
// uvs
var u;
var v;
if (customUV) {
for (p = 0; p < customUV.length; p++) {
uvs.push(customUV[p].x, customUV[p].y);
}
}
else {
for (p = 0; p < pathArray.length; p++) {
for (i = 0; i < minlg + closePathCorr; i++) {
u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
if (invertUV) {
uvs.push(v, u);
}
else {
uvs.push(u, v);
}
}
}
}
// indices
p = 0; // path index
var pi = 0; // positions array index
var l1 = lg[p] - 1; // path1 length
var l2 = lg[p + 1] - 1; // path2 length
var min = (l1 < l2) ? l1 : l2; // current path stop index
var shft = idx[1] - idx[0]; // shift
var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
while (pi <= min && p < path1nb) {
// draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
indices.push(pi, pi + shft, pi + 1);
indices.push(pi + shft + 1, pi + 1, pi + shft);
pi += 1;
if (pi === min) {
p++;
if (p === lg.length - 1) {
shft = idx[0] - idx[p];
l1 = lg[p] - 1;
l2 = lg[0] - 1;
}
else {
shft = idx[p + 1] - idx[p];
l1 = lg[p] - 1;
l2 = lg[p + 1] - 1;
}
pi = idx[p];
min = (l1 < l2) ? l1 + pi : l2 + pi;
}
}
// normals
VertexData.ComputeNormals(positions, indices, normals);
if (closePath) {
var indexFirst = 0;
var indexLast = 0;
for (p = 0; p < pathArray.length; p++) {
indexFirst = idx[p] * 3;
if (p + 1 < pathArray.length) {
indexLast = (idx[p + 1] - 1) * 3;
}
else {
indexLast = normals.length - 3;
}
normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
normals[indexLast] = normals[indexFirst];
normals[indexLast + 1] = normals[indexFirst + 1];
normals[indexLast + 2] = normals[indexFirst + 2];
}
}
// sides
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
// Colors
var colors = null;
if (customColors) {
colors = new Float32Array(customColors.length * 4);
for (var c = 0; c < customColors.length; c++) {
colors[c * 4] = customColors[c].r;
colors[c * 4 + 1] = customColors[c].g;
colors[c * 4 + 2] = customColors[c].b;
colors[c * 4 + 3] = customColors[c].a;
}
}
// Result
var vertexData = new VertexData();
var positions32 = new Float32Array(positions);
var normals32 = new Float32Array(normals);
var uvs32 = new Float32Array(uvs);
vertexData.indices = indices;
vertexData.positions = positions32;
vertexData.normals = normals32;
vertexData.uvs = uvs32;
if (colors) {
vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
}
if (closePath) {
vertexData._idx = idx;
}
return vertexData;
};
/**
* Creates the VertexData of the Box.
*/
VertexData.CreateBox = function (options) {
var normalsSource = [
new BABYLON.Vector3(0, 0, 1),
new BABYLON.Vector3(0, 0, -1),
new BABYLON.Vector3(1, 0, 0),
new BABYLON.Vector3(-1, 0, 0),
new BABYLON.Vector3(0, 1, 0),
new BABYLON.Vector3(0, -1, 0)
];
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
var width = options.width || options.size || 1;
var height = options.height || options.size || 1;
var depth = options.depth || options.size || 1;
var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
var faceUV = options.faceUV || new Array(6);
var faceColors = options.faceColors;
var colors = [];
// default face colors and UV if undefined
for (var f = 0; f < 6; f++) {
if (faceUV[f] === undefined) {
faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
}
if (faceColors && faceColors[f] === undefined) {
faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
}
}
var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
// Create each face in turn.
for (var index = 0; index < normalsSource.length; index++) {
var normal = normalsSource[index];
// Get two vectors perpendicular to the face normal and to each other.
var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
var side2 = BABYLON.Vector3.Cross(normal, side1);
// Six indices (two triangles) per face.
var verticesLength = positions.length / 3;
indices.push(verticesLength);
indices.push(verticesLength + 1);
indices.push(verticesLength + 2);
indices.push(verticesLength);
indices.push(verticesLength + 2);
indices.push(verticesLength + 3);
// Four vertices per face.
var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(faceUV[index].z, faceUV[index].w);
if (faceColors) {
colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
}
vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(faceUV[index].x, faceUV[index].w);
if (faceColors) {
colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
}
vertex = normal.add(side1).add(side2).multiply(scaleVector);
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(faceUV[index].x, faceUV[index].y);
if (faceColors) {
colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
}
vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(faceUV[index].z, faceUV[index].y);
if (faceColors) {
colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
}
}
// sides
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
// Result
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
if (faceColors) {
var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
vertexData.colors = totalColors;
}
return vertexData;
};
/**
* Creates the VertexData of the Sphere.
*/
VertexData.CreateSphere = function (options) {
var segments = options.segments || 32;
var diameterX = options.diameterX || options.diameter || 1;
var diameterY = options.diameterY || options.diameter || 1;
var diameterZ = options.diameterZ || options.diameter || 1;
var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
var totalZRotationSteps = 2 + segments;
var totalYRotationSteps = 2 * totalZRotationSteps;
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
var normalizedZ = zRotationStep / totalZRotationSteps;
var angleZ = normalizedZ * Math.PI * slice;
for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
var normalizedY = yRotationStep / totalYRotationSteps;
var angleY = normalizedY * Math.PI * 2 * arc;
var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
var rotationY = BABYLON.Matrix.RotationY(angleY);
var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
var vertex = complete.multiply(radius);
var normal = complete.divide(radius).normalize();
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(normalizedY, normalizedZ);
}
if (zRotationStep > 0) {
var verticesCount = positions.length / 3;
for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
indices.push((firstIndex));
indices.push((firstIndex + 1));
indices.push(firstIndex + totalYRotationSteps + 1);
indices.push((firstIndex + totalYRotationSteps + 1));
indices.push((firstIndex + 1));
indices.push((firstIndex + totalYRotationSteps + 2));
}
}
}
// Sides
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
// Result
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
/**
* Creates the VertexData of the Cylinder or Cone.
*/
VertexData.CreateCylinder = function (options) {
var height = options.height || 2;
var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
var tessellation = options.tessellation || 24;
var subdivisions = options.subdivisions || 1;
var hasRings = options.hasRings ? true : false;
var enclose = options.enclose ? true : false;
var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
var faceUV = options.faceUV || new Array(3);
var faceColors = options.faceColors;
// default face colors and UV if undefined
var quadNb = (arc !== 1 && enclose) ? 2 : 0;
var ringNb = (hasRings) ? subdivisions : 1;
var surfaceNb = 2 + (1 + quadNb) * ringNb;
var f;
for (f = 0; f < surfaceNb; f++) {
if (faceColors && faceColors[f] === undefined) {
faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
}
}
for (f = 0; f < surfaceNb; f++) {
if (faceUV && faceUV[f] === undefined) {
faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
}
}
var indices = new Array();
var positions = new Array();
var normals = new Array();
var uvs = new Array();
var colors = new Array();
var angle_step = Math.PI * 2 * arc / tessellation;
var angle;
var h;
var radius;
var tan = (diameterBottom - diameterTop) / 2 / height;
var ringVertex = BABYLON.Vector3.Zero();
var ringNormal = BABYLON.Vector3.Zero();
var ringFirstVertex = BABYLON.Vector3.Zero();
var ringFirstNormal = BABYLON.Vector3.Zero();
var quadNormal = BABYLON.Vector3.Zero();
var Y = BABYLON.Axis.Y;
// positions, normals, uvs
var i;
var j;
var r;
var ringIdx = 1;
var s = 1; // surface index
var cs = 0;
var v = 0;
for (i = 0; i <= subdivisions; i++) {
h = i / subdivisions;
radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
for (r = 0; r < ringIdx; r++) {
if (hasRings) {
s += r;
}
if (enclose) {
s += 2 * r;
}
for (j = 0; j <= tessellation; j++) {
angle = j * angle_step;
// position
ringVertex.x = Math.cos(-angle) * radius;
ringVertex.y = -height / 2 + h * height;
ringVertex.z = Math.sin(-angle) * radius;
// normal
if (diameterTop === 0 && i === subdivisions) {
// if no top cap, reuse former normals
ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
}
else {
ringNormal.x = ringVertex.x;
ringNormal.z = ringVertex.z;
ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
ringNormal.normalize();
}
// keep first ring vertex values for enclose
if (j === 0) {
ringFirstVertex.copyFrom(ringVertex);
ringFirstNormal.copyFrom(ringNormal);
}
positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
if (hasRings) {
v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
}
else {
v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
}
uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
if (faceColors) {
colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
}
}
// if enclose, add four vertices and their dedicated normals
if (arc !== 1 && enclose) {
positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
positions.push(0, ringVertex.y, 0);
positions.push(0, ringVertex.y, 0);
positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
quadNormal.normalize();
normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
quadNormal.normalize();
normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
if (hasRings) {
v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
}
else {
v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
}
uvs.push(faceUV[s + 1].x, v);
uvs.push(faceUV[s + 1].z, v);
if (hasRings) {
v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
}
else {
v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
}
uvs.push(faceUV[s + 2].x, v);
uvs.push(faceUV[s + 2].z, v);
if (faceColors) {
colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
}
}
if (cs !== s) {
cs = s;
}
}
}
// indices
var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
var s;
i = 0;
for (s = 0; s < subdivisions; s++) {
var i0 = 0;
var i1 = 0;
var i2 = 0;
var i3 = 0;
for (j = 0; j < tessellation; j++) {
i0 = i * (e + 1) + j;
i1 = (i + 1) * (e + 1) + j;
i2 = i * (e + 1) + (j + 1);
i3 = (i + 1) * (e + 1) + (j + 1);
indices.push(i0, i1, i2);
indices.push(i3, i2, i1);
}
if (arc !== 1 && enclose) {
indices.push(i0 + 2, i1 + 2, i2 + 2);
indices.push(i3 + 2, i2 + 2, i1 + 2);
indices.push(i0 + 4, i1 + 4, i2 + 4);
indices.push(i3 + 4, i2 + 4, i1 + 4);
}
i = (hasRings) ? (i + 2) : (i + 1);
}
// Caps
var createCylinderCap = function (isTop) {
var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
if (radius === 0) {
return;
}
// Cap positions, normals & uvs
var angle;
var circleVector;
var i;
var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
var c = null;
if (faceColors) {
c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
}
// cap center
var vbase = positions.length / 3;
var offset = isTop ? height / 2 : -height / 2;
var center = new BABYLON.Vector3(0, offset, 0);
positions.push(center.x, center.y, center.z);
normals.push(0, isTop ? 1 : -1, 0);
uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
if (c) {
colors.push(c.r, c.g, c.b, c.a);
}
var textureScale = new BABYLON.Vector2(0.5, 0.5);
for (i = 0; i <= tessellation; i++) {
angle = Math.PI * 2 * i * arc / tessellation;
var cos = Math.cos(-angle);
var sin = Math.sin(-angle);
circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
positions.push(circleVector.x, circleVector.y, circleVector.z);
normals.push(0, isTop ? 1 : -1, 0);
uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
if (c) {
colors.push(c.r, c.g, c.b, c.a);
}
}
// Cap indices
for (i = 0; i < tessellation; i++) {
if (!isTop) {
indices.push(vbase);
indices.push(vbase + (i + 1));
indices.push(vbase + (i + 2));
}
else {
indices.push(vbase);
indices.push(vbase + (i + 2));
indices.push(vbase + (i + 1));
}
}
};
// add caps to geometry
createCylinderCap(false);
createCylinderCap(true);
// Sides
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
if (faceColors) {
vertexData.colors = colors;
}
return vertexData;
};
/**
* Creates the VertexData of the Torus.
*/
VertexData.CreateTorus = function (options) {
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
var diameter = options.diameter || 1;
var thickness = options.thickness || 0.5;
var tessellation = options.tessellation || 16;
var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
var stride = tessellation + 1;
for (var i = 0; i <= tessellation; i++) {
var u = i / tessellation;
var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
for (var j = 0; j <= tessellation; j++) {
var v = 1 - j / tessellation;
var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
var dx = Math.cos(innerAngle);
var dy = Math.sin(innerAngle);
// Create a vertex.
var normal = new BABYLON.Vector3(dx, dy, 0);
var position = normal.scale(thickness / 2);
var textureCoordinate = new BABYLON.Vector2(u, v);
position = BABYLON.Vector3.TransformCoordinates(position, transform);
normal = BABYLON.Vector3.TransformNormal(normal, transform);
positions.push(position.x, position.y, position.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(textureCoordinate.x, textureCoordinate.y);
// And create indices for two triangles.
var nextI = (i + 1) % stride;
var nextJ = (j + 1) % stride;
indices.push(i * stride + j);
indices.push(i * stride + nextJ);
indices.push(nextI * stride + j);
indices.push(i * stride + nextJ);
indices.push(nextI * stride + nextJ);
indices.push(nextI * stride + j);
}
}
// Sides
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
// Result
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
/**
* Creates the VertexData of the LineSystem.
*/
VertexData.CreateLineSystem = function (options) {
var indices = [];
var positions = [];
var lines = options.lines;
var colors = options.colors;
var vertexColors = [];
var idx = 0;
for (var l = 0; l < lines.length; l++) {
var points = lines[l];
for (var index = 0; index < points.length; index++) {
positions.push(points[index].x, points[index].y, points[index].z);
if (colors) {
var color = colors[l];
vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
}
if (index > 0) {
indices.push(idx - 1);
indices.push(idx);
}
idx++;
}
}
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
if (colors) {
vertexData.colors = vertexColors;
}
return vertexData;
};
/**
* Create the VertexData of the DashedLines.
*/
VertexData.CreateDashedLines = function (options) {
var dashSize = options.dashSize || 3;
var gapSize = options.gapSize || 1;
var dashNb = options.dashNb || 200;
var points = options.points;
var positions = new Array();
var indices = new Array();
var curvect = BABYLON.Vector3.Zero();
var lg = 0;
var nb = 0;
var shft = 0;
var dashshft = 0;
var curshft = 0;
var idx = 0;
var i = 0;
for (i = 0; i < points.length - 1; i++) {
points[i + 1].subtractToRef(points[i], curvect);
lg += curvect.length();
}
shft = lg / dashNb;
dashshft = dashSize * shft / (dashSize + gapSize);
for (i = 0; i < points.length - 1; i++) {
points[i + 1].subtractToRef(points[i], curvect);
nb = Math.floor(curvect.length() / shft);
curvect.normalize();
for (var j = 0; j < nb; j++) {
curshft = shft * j;
positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
indices.push(idx, idx + 1);
idx += 2;
}
}
// Result
var vertexData = new VertexData();
vertexData.positions = positions;
vertexData.indices = indices;
return vertexData;
};
/**
* Creates the VertexData of the Ground.
*/
VertexData.CreateGround = function (options) {
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
var row, col;
var width = options.width || 1;
var height = options.height || 1;
var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
for (row = 0; row <= subdivisionsY; row++) {
for (col = 0; col <= subdivisionsX; col++) {
var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
var normal = new BABYLON.Vector3(0, 1.0, 0);
positions.push(position.x, position.y, position.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
}
}
for (row = 0; row < subdivisionsY; row++) {
for (col = 0; col < subdivisionsX; col++) {
indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
indices.push(col + 1 + row * (subdivisionsX + 1));
indices.push(col + row * (subdivisionsX + 1));
indices.push(col + (row + 1) * (subdivisionsX + 1));
indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
indices.push(col + row * (subdivisionsX + 1));
}
}
// Result
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
/**
* Creates the VertexData of the TiledGround.
*/
VertexData.CreateTiledGround = function (options) {
var xmin = options.xmin || -1.0;
var zmin = options.zmin || -1.0;
var xmax = options.xmax || 1.0;
var zmax = options.zmax || 1.0;
var subdivisions = options.subdivisions || { w: 1, h: 1 };
var precision = options.precision || { w: 1, h: 1 };
var indices = new Array();
var positions = new Array();
var normals = new Array();
var uvs = new Array();
var row, col, tileRow, tileCol;
subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
precision.w = (precision.w < 1) ? 1 : precision.w;
precision.h = (precision.h < 1) ? 1 : precision.h;
var tileSize = {
'w': (xmax - xmin) / subdivisions.w,
'h': (zmax - zmin) / subdivisions.h
};
function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
// Indices
var base = positions.length / 3;
var rowLength = precision.w + 1;
for (row = 0; row < precision.h; row++) {
for (col = 0; col < precision.w; col++) {
var square = [
base + col + row * rowLength,
base + (col + 1) + row * rowLength,
base + (col + 1) + (row + 1) * rowLength,
base + col + (row + 1) * rowLength
];
indices.push(square[1]);
indices.push(square[2]);
indices.push(square[3]);
indices.push(square[0]);
indices.push(square[1]);
indices.push(square[3]);
}
}
// Position, normals and uvs
var position = BABYLON.Vector3.Zero();
var normal = new BABYLON.Vector3(0, 1.0, 0);
for (row = 0; row <= precision.h; row++) {
position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
for (col = 0; col <= precision.w; col++) {
position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
position.y = 0;
positions.push(position.x, position.y, position.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(col / precision.w, row / precision.h);
}
}
}
for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
}
}
// Result
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
/**
* Creates the VertexData of the Ground designed from a heightmap.
*/
VertexData.CreateGroundFromHeightMap = function (options) {
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
var row, col;
var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
// Vertices
for (row = 0; row <= options.subdivisions; row++) {
for (col = 0; col <= options.subdivisions; col++) {
var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
// Compute height
var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
var r = options.buffer[pos] / 255.0;
var g = options.buffer[pos + 1] / 255.0;
var b = options.buffer[pos + 2] / 255.0;
var gradient = r * filter.r + g * filter.g + b * filter.b;
position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
// Add vertex
positions.push(position.x, position.y, position.z);
normals.push(0, 0, 0);
uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
}
}
// Indices
for (row = 0; row < options.subdivisions; row++) {
for (col = 0; col < options.subdivisions; col++) {
indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
indices.push(col + 1 + row * (options.subdivisions + 1));
indices.push(col + row * (options.subdivisions + 1));
indices.push(col + (row + 1) * (options.subdivisions + 1));
indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
indices.push(col + row * (options.subdivisions + 1));
}
}
// Normals
VertexData.ComputeNormals(positions, indices, normals);
// Result
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
/**
* Creates the VertexData of the Plane.
*/
VertexData.CreatePlane = function (options) {
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
var width = options.width || options.size || 1;
var height = options.height || options.size || 1;
var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
// Vertices
var halfWidth = width / 2.0;
var halfHeight = height / 2.0;
positions.push(-halfWidth, -halfHeight, 0);
normals.push(0, 0, -1.0);
uvs.push(0.0, 0.0);
positions.push(halfWidth, -halfHeight, 0);
normals.push(0, 0, -1.0);
uvs.push(1.0, 0.0);
positions.push(halfWidth, halfHeight, 0);
normals.push(0, 0, -1.0);
uvs.push(1.0, 1.0);
positions.push(-halfWidth, halfHeight, 0);
normals.push(0, 0, -1.0);
uvs.push(0.0, 1.0);
// Indices
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
// Sides
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
// Result
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
/**
* Creates the VertexData of the Disc or regular Polygon.
*/
VertexData.CreateDisc = function (options) {
var positions = new Array();
var indices = new Array();
var normals = new Array();
var uvs = new Array();
var radius = options.radius || 0.5;
var tessellation = options.tessellation || 64;
var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
// positions and uvs
positions.push(0, 0, 0); // disc center first
uvs.push(0.5, 0.5);
var theta = Math.PI * 2 * arc;
var step = theta / tessellation;
for (var a = 0; a < theta; a += step) {
var x = Math.cos(a);
var y = Math.sin(a);
var u = (x + 1) / 2;
var v = (1 - y) / 2;
positions.push(radius * x, radius * y, 0);
uvs.push(u, v);
}
if (arc === 1) {
positions.push(positions[3], positions[4], positions[5]); // close the circle
uvs.push(uvs[2], uvs[3]);
}
//indices
var vertexNb = positions.length / 3;
for (var i = 1; i < vertexNb - 1; i++) {
indices.push(i + 1, 0, i);
}
// result
VertexData.ComputeNormals(positions, indices, normals);
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
/**
* Re-creates the VertexData of the Polygon for sideOrientation.
*/
VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
var faceUV = fUV || new Array(3);
var faceColors = fColors;
var colors = [];
// default face colors and UV if undefined
for (var f = 0; f < 3; f++) {
if (faceUV[f] === undefined) {
faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
}
if (faceColors && faceColors[f] === undefined) {
faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
}
}
var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
var indices = polygon.getIndices();
// set face colours and textures
var idx = 0;
var face = 0;
for (var index = 0; index < normals.length; index += 3) {
//Edge Face no. 1
if (Math.abs(normals[index + 1]) < 0.001) {
face = 1;
}
//Top Face no. 0
if (Math.abs(normals[index + 1] - 1) < 0.001) {
face = 0;
}
//Bottom Face no. 2
if (Math.abs(normals[index + 1] + 1) < 0.001) {
face = 2;
}
idx = index / 3;
uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
if (faceColors) {
colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
}
}
// sides
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
// Result
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
if (faceColors) {
var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
vertexData.colors = totalColors;
}
return vertexData;
};
/**
* Creates the VertexData of the IcoSphere.
*/
VertexData.CreateIcoSphere = function (options) {
var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
var radius = options.radius || 1;
var flat = (options.flat === undefined) ? true : options.flat;
var subdivisions = options.subdivisions || 4;
var radiusX = options.radiusX || radius;
var radiusY = options.radiusY || radius;
var radiusZ = options.radiusZ || radius;
var t = (1 + Math.sqrt(5)) / 2;
// 12 vertex x,y,z
var ico_vertices = [
-1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
];
// index of 3 vertex makes a face of icopshere
var ico_indices = [
0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
];
// vertex for uv have aliased position, not for UV
var vertices_unalias_id = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
// vertex alias
0,
2,
3,
3,
3,
4,
7,
8,
9,
9,
10,
11 // 23: B + 12
];
// uv as integer step (not pixels !)
var ico_vertexuv = [
5, 1, 3, 1, 6, 4, 0, 0,
5, 3, 4, 2, 2, 2, 4, 0,
2, 0, 1, 1, 6, 0, 6, 2,
// vertex alias (for same vertex on different faces)
0, 4,
3, 3,
4, 4,
3, 1,
4, 2,
4, 4,
0, 2,
1, 1,
2, 2,
3, 3,
1, 3,
2, 4 // 23: B + 12
];
// Vertices[0, 1, ...9, A, B] : position on UV plane
// '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
// First island of uv mapping
// v = 4h 3+ 2
// v = 3h 9+ 4
// v = 2h 9+ 5 B
// v = 1h 9 1 0
// v = 0h 3 8 7 A
// u = 0 1 2 3 4 5 6 *a
// Second island of uv mapping
// v = 4h 0+ B+ 4+
// v = 3h A+ 2+
// v = 2h 7+ 6 3+
// v = 1h 8+ 3+
// v = 0h
// u = 0 1 2 3 4 5 6 *a
// Face layout on texture UV mapping
// ============
// \ 4 /\ 16 / ======
// \ / \ / /\ 11 /
// \/ 7 \/ / \ /
// ======= / 10 \/
// /\ 17 /\ =======
// / \ / \ \ 15 /\
// / 8 \/ 12 \ \ / \
// ============ \/ 6 \
// \ 18 /\ ============
// \ / \ \ 5 /\ 0 /
// \/ 13 \ \ / \ /
// ======= \/ 1 \/
// =============
// /\ 19 /\ 2 /\
// / \ / \ / \
// / 14 \/ 9 \/ 3 \
// ===================
// uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
var ustep = 138 / 1024;
var vstep = 239 / 1024;
var uoffset = 60 / 1024;
var voffset = 26 / 1024;
// Second island should have margin, not to touch the first island
// avoid any borderline artefact in pixel rounding
var island_u_offset = -40 / 1024;
var island_v_offset = +20 / 1024;
// face is either island 0 or 1 :
// second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
var island = [
0, 0, 0, 0, 1,
0, 0, 1, 1, 0,
0, 0, 1, 1, 0,
0, 1, 1, 1, 0 // 15 - 19
];
var indices = new Array();
var positions = new Array();
var normals = new Array();
var uvs = new Array();
var current_indice = 0;
// prepare array of 3 vector (empty) (to be worked in place, shared for each face)
var face_vertex_pos = new Array(3);
var face_vertex_uv = new Array(3);
var v012;
for (v012 = 0; v012 < 3; v012++) {
face_vertex_pos[v012] = BABYLON.Vector3.Zero();
face_vertex_uv[v012] = BABYLON.Vector2.Zero();
}
// create all with normals
for (var face = 0; face < 20; face++) {
// 3 vertex per face
for (v012 = 0; v012 < 3; v012++) {
// look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
var v_id = ico_indices[3 * face + v012];
// vertex have 3D position (x,y,z)
face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
// Normalize to get normal, then scale to radius
face_vertex_pos[v012].normalize().scaleInPlace(radius);
// uv Coordinates from vertex ID
face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
}
// Subdivide the face (interpolate pos, norm, uv)
// - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
// - norm is linear interpolation of vertex corner normal
// (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
// - uv is linear interpolation
//
// Topology is as below for sub-divide by 2
// vertex shown as v0,v1,v2
// interp index is i1 to progress in range [v0,v1[
// interp index is i2 to progress in range [v0,v2[
// face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
// and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
//
//
// i2 v2
// ^ ^
// / / \
// / / \
// / / \
// / / (0,1) \
// / #---------\
// / / \ (0,0)'/ \
// / / \ / \
// / / \ / \
// / / (0,0) \ / (1,0) \
// / #---------#---------\
// v0 v1
//
// --------------------> i1
//
// interp of (i1,i2):
// along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
// along i1 : lerp(x0,x1, i1/(S-i2))
//
// centroid of triangle is needed to get help normal computation
// (c1,c2) are used for centroid location
var interp_vertex = function (i1, i2, c1, c2) {
// vertex is interpolated from
// - face_vertex_pos[0..2]
// - face_vertex_uv[0..2]
var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
pos_interp.normalize();
var vertex_normal;
if (flat) {
// in flat mode, recalculate normal as face centroid normal
var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
}
else {
// in smooth mode, recalculate normal from each single vertex position
vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
}
// Vertex normal need correction due to X,Y,Z radius scaling
vertex_normal.x /= radiusX;
vertex_normal.y /= radiusY;
vertex_normal.z /= radiusZ;
vertex_normal.normalize();
var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
uvs.push(uv_interp.x, uv_interp.y);
// push each vertex has member of a face
// Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
indices.push(current_indice);
current_indice++;
};
for (var i2 = 0; i2 < subdivisions; i2++) {
for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
// face : (i1,i2) for /\ :
// interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
if (i1 + i2 + 1 < subdivisions) {
// face : (i1,i2)' for \/ :
// interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
}
}
}
}
// Sides
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
// Result
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
// inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
/**
* Creates the VertexData of the Polyhedron.
*/
VertexData.CreatePolyhedron = function (options) {
// provided polyhedron types :
// 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
// 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
var polyhedra = [];
polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
polyhedra[2] = {
vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
};
polyhedra[3] = {
vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
};
polyhedra[4] = {
vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
};
polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
polyhedra[14] = {
vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
};
var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
var size = options.size;
var sizeX = options.sizeX || size || 1;
var sizeY = options.sizeY || size || 1;
var sizeZ = options.sizeZ || size || 1;
var data = options.custom || polyhedra[type];
var nbfaces = data.face.length;
var faceUV = options.faceUV || new Array(nbfaces);
var faceColors = options.faceColors;
var flat = (options.flat === undefined) ? true : options.flat;
var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
var positions = new Array();
var indices = new Array();
var normals = new Array();
var uvs = new Array();
var colors = new Array();
var index = 0;
var faceIdx = 0; // face cursor in the array "indexes"
var indexes = new Array();
var i = 0;
var f = 0;
var u, v, ang, x, y, tmp;
// default face colors and UV if undefined
if (flat) {
for (f = 0; f < nbfaces; f++) {
if (faceColors && faceColors[f] === undefined) {
faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
}
if (faceUV && faceUV[f] === undefined) {
faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
}
}
}
if (!flat) {
for (i = 0; i < data.vertex.length; i++) {
positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
uvs.push(0, 0);
}
for (f = 0; f < nbfaces; f++) {
for (i = 0; i < data.face[f].length - 2; i++) {
indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
}
}
}
else {
for (f = 0; f < nbfaces; f++) {
var fl = data.face[f].length; // number of vertices of the current face
ang = 2 * Math.PI / fl;
x = 0.5 * Math.tan(ang / 2);
y = 0.5;
// positions, uvs, colors
for (i = 0; i < fl; i++) {
// positions
positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
indexes.push(index);
index++;
// uvs
u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
uvs.push(u, v);
tmp = x * Math.cos(ang) - y * Math.sin(ang);
y = x * Math.sin(ang) + y * Math.cos(ang);
x = tmp;
// colors
if (faceColors) {
colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
}
}
// indices from indexes
for (i = 0; i < fl - 2; i++) {
indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
}
faceIdx += fl;
}
}
VertexData.ComputeNormals(positions, indices, normals);
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData();
vertexData.positions = positions;
vertexData.indices = indices;
vertexData.normals = normals;
vertexData.uvs = uvs;
if (faceColors && flat) {
vertexData.colors = colors;
}
return vertexData;
};
// based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
/**
* Creates the VertexData of the Torus Knot.
*/
VertexData.CreateTorusKnot = function (options) {
var indices = new Array();
var positions = new Array();
var normals = new Array();
var uvs = new Array();
var radius = options.radius || 2;
var tube = options.tube || 0.5;
var radialSegments = options.radialSegments || 32;
var tubularSegments = options.tubularSegments || 32;
var p = options.p || 2;
var q = options.q || 3;
var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
// Helper
var getPos = function (angle) {
var cu = Math.cos(angle);
var su = Math.sin(angle);
var quOverP = q / p * angle;
var cs = Math.cos(quOverP);
var tx = radius * (2 + cs) * 0.5 * cu;
var ty = radius * (2 + cs) * su * 0.5;
var tz = radius * Math.sin(quOverP) * 0.5;
return new BABYLON.Vector3(tx, ty, tz);
};
// Vertices
var i;
var j;
for (i = 0; i <= radialSegments; i++) {
var modI = i % radialSegments;
var u = modI / radialSegments * 2 * p * Math.PI;
var p1 = getPos(u);
var p2 = getPos(u + 0.01);
var tang = p2.subtract(p1);
var n = p2.add(p1);
var bitan = BABYLON.Vector3.Cross(tang, n);
n = BABYLON.Vector3.Cross(bitan, tang);
bitan.normalize();
n.normalize();
for (j = 0; j < tubularSegments; j++) {
var modJ = j % tubularSegments;
var v = modJ / tubularSegments * 2 * Math.PI;
var cx = -tube * Math.cos(v);
var cy = tube * Math.sin(v);
positions.push(p1.x + cx * n.x + cy * bitan.x);
positions.push(p1.y + cx * n.y + cy * bitan.y);
positions.push(p1.z + cx * n.z + cy * bitan.z);
uvs.push(i / radialSegments);
uvs.push(j / tubularSegments);
}
}
for (i = 0; i < radialSegments; i++) {
for (j = 0; j < tubularSegments; j++) {
var jNext = (j + 1) % tubularSegments;
var a = i * tubularSegments + j;
var b = (i + 1) * tubularSegments + j;
var c = (i + 1) * tubularSegments + jNext;
var d = i * tubularSegments + jNext;
indices.push(d);
indices.push(b);
indices.push(a);
indices.push(d);
indices.push(c);
indices.push(b);
}
}
// Normals
VertexData.ComputeNormals(positions, indices, normals);
// Sides
VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
// Result
var vertexData = new VertexData();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
// Tools
/**
* @param {any} - positions (number[] or Float32Array)
* @param {any} - indices (number[] or Uint16Array)
* @param {any} - normals (number[] or Float32Array)
* options (optional) :
* facetPositions : optional array of facet positions (vector3)
* facetNormals : optional array of facet normals (vector3)
* facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
* subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
* ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
* bbSize : optional bounding box size data, required for facetPartitioning computation
* bInfo : optional bounding info, required for facetPartitioning computation
* useRightHandedSystem: optional boolean to for right handed system computation
* depthSort : optional boolean to enable the facet depth sort computation
* distanceTo : optional Vector3 to compute the facet depth from this location
* depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
*/
VertexData.ComputeNormals = function (positions, indices, normals, options) {
// temporary scalar variables
var index = 0; // facet index
var p1p2x = 0.0; // p1p2 vector x coordinate
var p1p2y = 0.0; // p1p2 vector y coordinate
var p1p2z = 0.0; // p1p2 vector z coordinate
var p3p2x = 0.0; // p3p2 vector x coordinate
var p3p2y = 0.0; // p3p2 vector y coordinate
var p3p2z = 0.0; // p3p2 vector z coordinate
var faceNormalx = 0.0; // facet normal x coordinate
var faceNormaly = 0.0; // facet normal y coordinate
var faceNormalz = 0.0; // facet normal z coordinate
var length = 0.0; // facet normal length before normalization
var v1x = 0; // vector1 x index in the positions array
var v1y = 0; // vector1 y index in the positions array
var v1z = 0; // vector1 z index in the positions array
var v2x = 0; // vector2 x index in the positions array
var v2y = 0; // vector2 y index in the positions array
var v2z = 0; // vector2 z index in the positions array
var v3x = 0; // vector3 x index in the positions array
var v3y = 0; // vector3 y index in the positions array
var v3z = 0; // vector3 z index in the positions array
var computeFacetNormals = false;
var computeFacetPositions = false;
var computeFacetPartitioning = false;
var computeDepthSort = false;
var faceNormalSign = 1;
var ratio = 0;
var distanceTo = null;
if (options) {
computeFacetNormals = (options.facetNormals) ? true : false;
computeFacetPositions = (options.facetPositions) ? true : false;
computeFacetPartitioning = (options.facetPartitioning) ? true : false;
faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
ratio = options.ratio || 0;
computeDepthSort = (options.depthSort) ? true : false;
distanceTo = (options.distanceTo);
if (computeDepthSort) {
if (distanceTo === undefined) {
distanceTo = BABYLON.Vector3.Zero();
}
var depthSortedFacets = options.depthSortedFacets;
}
}
// facetPartitioning reinit if needed
var xSubRatio = 0;
var ySubRatio = 0;
var zSubRatio = 0;
var subSq = 0;
if (computeFacetPartitioning && options && options.bbSize) {
var ox = 0; // X partitioning index for facet position
var oy = 0; // Y partinioning index for facet position
var oz = 0; // Z partinioning index for facet position
var b1x = 0; // X partitioning index for facet v1 vertex
var b1y = 0; // Y partitioning index for facet v1 vertex
var b1z = 0; // z partitioning index for facet v1 vertex
var b2x = 0; // X partitioning index for facet v2 vertex
var b2y = 0; // Y partitioning index for facet v2 vertex
var b2z = 0; // Z partitioning index for facet v2 vertex
var b3x = 0; // X partitioning index for facet v3 vertex
var b3y = 0; // Y partitioning index for facet v3 vertex
var b3z = 0; // Z partitioning index for facet v3 vertex
var block_idx_o = 0; // facet barycenter block index
var block_idx_v1 = 0; // v1 vertex block index
var block_idx_v2 = 0; // v2 vertex block index
var block_idx_v3 = 0; // v3 vertex block index
var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
subSq = options.subDiv.max * options.subDiv.max;
options.facetPartitioning.length = 0;
}
// reset the normals
for (index = 0; index < positions.length; index++) {
normals[index] = 0.0;
}
// Loop : 1 indice triplet = 1 facet
var nbFaces = (indices.length / 3) | 0;
for (index = 0; index < nbFaces; index++) {
// get the indexes of the coordinates of each vertex of the facet
v1x = indices[index * 3] * 3;
v1y = v1x + 1;
v1z = v1x + 2;
v2x = indices[index * 3 + 1] * 3;
v2y = v2x + 1;
v2z = v2x + 2;
v3x = indices[index * 3 + 2] * 3;
v3y = v3x + 1;
v3z = v3x + 2;
p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
p1p2y = positions[v1y] - positions[v2y];
p1p2z = positions[v1z] - positions[v2z];
p3p2x = positions[v3x] - positions[v2x];
p3p2y = positions[v3y] - positions[v2y];
p3p2z = positions[v3z] - positions[v2z];
// compute the face normal with the cross product
faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
// normalize this normal and store it in the array facetData
length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
length = (length === 0) ? 1.0 : length;
faceNormalx /= length;
faceNormaly /= length;
faceNormalz /= length;
if (computeFacetNormals && options) {
options.facetNormals[index].x = faceNormalx;
options.facetNormals[index].y = faceNormaly;
options.facetNormals[index].z = faceNormalz;
}
if (computeFacetPositions && options) {
// compute and the facet barycenter coordinates in the array facetPositions
options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
}
if (computeFacetPartitioning && options) {
// store the facet indexes in arrays in the main facetPartitioning array :
// compute each facet vertex (+ facet barycenter) index in the partiniong array
ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
// push each facet index in each block containing the vertex
options.facetPartitioning[block_idx_v1].push(index);
if (block_idx_v2 != block_idx_v1) {
options.facetPartitioning[block_idx_v2].push(index);
}
if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
options.facetPartitioning[block_idx_v3].push(index);
}
if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
options.facetPartitioning[block_idx_o].push(index);
}
}
if (computeDepthSort && options && options.facetPositions) {
var dsf = depthSortedFacets[index];
dsf.ind = index * 3;
dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
}
// compute the normals anyway
normals[v1x] += faceNormalx; // accumulate all the normals per face
normals[v1y] += faceNormaly;
normals[v1z] += faceNormalz;
normals[v2x] += faceNormalx;
normals[v2y] += faceNormaly;
normals[v2z] += faceNormalz;
normals[v3x] += faceNormalx;
normals[v3y] += faceNormaly;
normals[v3z] += faceNormalz;
}
// last normalization of each normal
for (index = 0; index < normals.length / 3; index++) {
faceNormalx = normals[index * 3];
faceNormaly = normals[index * 3 + 1];
faceNormalz = normals[index * 3 + 2];
length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
length = (length === 0) ? 1.0 : length;
faceNormalx /= length;
faceNormaly /= length;
faceNormalz /= length;
normals[index * 3] = faceNormalx;
normals[index * 3 + 1] = faceNormaly;
normals[index * 3 + 2] = faceNormalz;
}
};
VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
var li = indices.length;
var ln = normals.length;
var i;
var n;
sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
switch (sideOrientation) {
case BABYLON.Mesh.FRONTSIDE:
// nothing changed
break;
case BABYLON.Mesh.BACKSIDE:
var tmp;
// indices
for (i = 0; i < li; i += 3) {
tmp = indices[i];
indices[i] = indices[i + 2];
indices[i + 2] = tmp;
}
// normals
for (n = 0; n < ln; n++) {
normals[n] = -normals[n];
}
break;
case BABYLON.Mesh.DOUBLESIDE:
// positions
var lp = positions.length;
var l = lp / 3;
for (var p = 0; p < lp; p++) {
positions[lp + p] = positions[p];
}
// indices
for (i = 0; i < li; i += 3) {
indices[i + li] = indices[i + 2] + l;
indices[i + 1 + li] = indices[i + 1] + l;
indices[i + 2 + li] = indices[i] + l;
}
// normals
for (n = 0; n < ln; n++) {
normals[ln + n] = -normals[n];
}
// uvs
var lu = uvs.length;
var u = 0;
for (u = 0; u < lu; u++) {
uvs[u + lu] = uvs[u];
}
frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
u = 0;
for (i = 0; i < lu / 2; i++) {
uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
u += 2;
}
break;
}
};
/**
* Creates a new VertexData from the imported parameters.
*/
VertexData.ImportVertexData = function (parsedVertexData, geometry) {
var vertexData = new VertexData();
// positions
var positions = parsedVertexData.positions;
if (positions) {
vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
}
// normals
var normals = parsedVertexData.normals;
if (normals) {
vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
}
// tangents
var tangents = parsedVertexData.tangents;
if (tangents) {
vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
}
// uvs
var uvs = parsedVertexData.uvs;
if (uvs) {
vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
}
// uv2s
var uv2s = parsedVertexData.uv2s;
if (uv2s) {
vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
}
// uv3s
var uv3s = parsedVertexData.uv3s;
if (uv3s) {
vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
}
// uv4s
var uv4s = parsedVertexData.uv4s;
if (uv4s) {
vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
}
// uv5s
var uv5s = parsedVertexData.uv5s;
if (uv5s) {
vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
}
// uv6s
var uv6s = parsedVertexData.uv6s;
if (uv6s) {
vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
}
// colors
var colors = parsedVertexData.colors;
if (colors) {
vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
}
// matricesIndices
var matricesIndices = parsedVertexData.matricesIndices;
if (matricesIndices) {
vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
}
// matricesWeights
var matricesWeights = parsedVertexData.matricesWeights;
if (matricesWeights) {
vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
}
// indices
var indices = parsedVertexData.indices;
if (indices) {
vertexData.indices = indices;
}
geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
};
return VertexData;
}());
BABYLON.VertexData = VertexData;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.mesh.vertexData.js.map
var BABYLON;
(function (BABYLON) {
var Geometry = /** @class */ (function () {
function Geometry(id, scene, vertexData, updatable, mesh) {
if (updatable === void 0) { updatable = false; }
if (mesh === void 0) { mesh = null; }
this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
this._totalVertices = 0;
this._isDisposed = false;
this._indexBufferIsUpdatable = false;
this.id = id;
this._engine = scene.getEngine();
this._meshes = [];
this._scene = scene;
//Init vertex buffer cache
this._vertexBuffers = {};
this._indices = [];
this._updatable = updatable;
// vertexData
if (vertexData) {
this.setAllVerticesData(vertexData, updatable);
}
else {
this._totalVertices = 0;
this._indices = [];
}
if (this._engine.getCaps().vertexArrayObject) {
this._vertexArrayObjects = {};
}
// applyToMesh
if (mesh) {
if (mesh.getClassName() === "LinesMesh") {
this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
this.updateExtend();
}
this.applyToMesh(mesh);
mesh.computeWorldMatrix(true);
}
}
Object.defineProperty(Geometry.prototype, "boundingBias", {
/**
* The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
* @returns The Bias Vector
*/
get: function () {
return this._boundingBias;
},
set: function (value) {
if (this._boundingBias && this._boundingBias.equals(value)) {
return;
}
this._boundingBias = value.clone();
this.updateBoundingInfo(true, null);
},
enumerable: true,
configurable: true
});
Geometry.CreateGeometryForMesh = function (mesh) {
var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
geometry.applyToMesh(mesh);
return geometry;
};
Object.defineProperty(Geometry.prototype, "extend", {
get: function () {
return this._extend;
},
enumerable: true,
configurable: true
});
Geometry.prototype.getScene = function () {
return this._scene;
};
Geometry.prototype.getEngine = function () {
return this._engine;
};
Geometry.prototype.isReady = function () {
return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
};
Object.defineProperty(Geometry.prototype, "doNotSerialize", {
get: function () {
for (var index = 0; index < this._meshes.length; index++) {
if (!this._meshes[index].doNotSerialize) {
return false;
}
}
return true;
},
enumerable: true,
configurable: true
});
Geometry.prototype._rebuild = function () {
if (this._vertexArrayObjects) {
this._vertexArrayObjects = {};
}
// Index buffer
if (this._meshes.length !== 0 && this._indices) {
this._indexBuffer = this._engine.createIndexBuffer(this._indices);
}
// Vertex buffers
for (var key in this._vertexBuffers) {
var vertexBuffer = this._vertexBuffers[key];
vertexBuffer._rebuild();
}
};
Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
vertexData.applyToGeometry(this, updatable);
this.notifyUpdate();
};
Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
if (updatable === void 0) { updatable = false; }
var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
this.setVerticesBuffer(buffer);
};
Geometry.prototype.removeVerticesData = function (kind) {
if (this._vertexBuffers[kind]) {
this._vertexBuffers[kind].dispose();
delete this._vertexBuffers[kind];
}
};
Geometry.prototype.setVerticesBuffer = function (buffer) {
var kind = buffer.getKind();
if (this._vertexBuffers[kind]) {
this._vertexBuffers[kind].dispose();
}
this._vertexBuffers[kind] = buffer;
if (kind === BABYLON.VertexBuffer.PositionKind) {
var data = buffer.getData();
var stride = buffer.getStrideSize();
this._totalVertices = data.length / stride;
this.updateExtend(data, stride);
this._resetPointsArrayCache();
var meshes = this._meshes;
var numOfMeshes = meshes.length;
for (var index = 0; index < numOfMeshes; index++) {
var mesh = meshes[index];
mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
mesh._createGlobalSubMesh(false);
mesh.computeWorldMatrix(true);
}
}
this.notifyUpdate(kind);
if (this._vertexArrayObjects) {
this._disposeVertexArrayObjects();
this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
}
};
Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
var vertexBuffer = this.getVertexBuffer(kind);
if (!vertexBuffer) {
return;
}
vertexBuffer.updateDirectly(data, offset);
this.notifyUpdate(kind);
};
Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
if (updateExtends === void 0) { updateExtends = false; }
var vertexBuffer = this.getVertexBuffer(kind);
if (!vertexBuffer) {
return;
}
vertexBuffer.update(data);
if (kind === BABYLON.VertexBuffer.PositionKind) {
var stride = vertexBuffer.getStrideSize();
this._totalVertices = data.length / stride;
this.updateBoundingInfo(updateExtends, data);
}
this.notifyUpdate(kind);
};
Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
if (updateExtends) {
this.updateExtend(data);
}
var meshes = this._meshes;
var numOfMeshes = meshes.length;
this._resetPointsArrayCache();
for (var index = 0; index < numOfMeshes; index++) {
var mesh = meshes[index];
if (updateExtends) {
mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
var subMesh = mesh.subMeshes[subIndex];
subMesh.refreshBoundingInfo();
}
}
}
};
Geometry.prototype._bind = function (effect, indexToBind) {
if (!effect) {
return;
}
if (indexToBind === undefined) {
indexToBind = this._indexBuffer;
}
var vbs = this.getVertexBuffers();
if (!vbs) {
return;
}
if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
this._engine.bindBuffers(vbs, indexToBind, effect);
return;
}
// Using VAO
if (!this._vertexArrayObjects[effect.key]) {
this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
}
this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
};
Geometry.prototype.getTotalVertices = function () {
if (!this.isReady()) {
return 0;
}
return this._totalVertices;
};
Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
var vertexBuffer = this.getVertexBuffer(kind);
if (!vertexBuffer) {
return null;
}
var orig = vertexBuffer.getData();
if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
return orig;
}
else {
var len = orig.length;
var copy = [];
for (var i = 0; i < len; i++) {
copy.push(orig[i]);
}
return copy;
}
};
/**
* Returns a boolean defining if the vertex data for the requested `kind` is updatable.
* Possible `kind` values :
* - BABYLON.VertexBuffer.PositionKind
* - BABYLON.VertexBuffer.UVKind
* - BABYLON.VertexBuffer.UV2Kind
* - BABYLON.VertexBuffer.UV3Kind
* - BABYLON.VertexBuffer.UV4Kind
* - BABYLON.VertexBuffer.UV5Kind
* - BABYLON.VertexBuffer.UV6Kind
* - BABYLON.VertexBuffer.ColorKind
* - BABYLON.VertexBuffer.MatricesIndicesKind
* - BABYLON.VertexBuffer.MatricesIndicesExtraKind
* - BABYLON.VertexBuffer.MatricesWeightsKind
* - BABYLON.VertexBuffer.MatricesWeightsExtraKind
*/
Geometry.prototype.isVertexBufferUpdatable = function (kind) {
var vb = this._vertexBuffers[kind];
if (!vb) {
return false;
}
return vb.isUpdatable();
};
Geometry.prototype.getVertexBuffer = function (kind) {
if (!this.isReady()) {
return null;
}
return this._vertexBuffers[kind];
};
Geometry.prototype.getVertexBuffers = function () {
if (!this.isReady()) {
return null;
}
return this._vertexBuffers;
};
Geometry.prototype.isVerticesDataPresent = function (kind) {
if (!this._vertexBuffers) {
if (this._delayInfo) {
return this._delayInfo.indexOf(kind) !== -1;
}
return false;
}
return this._vertexBuffers[kind] !== undefined;
};
Geometry.prototype.getVerticesDataKinds = function () {
var result = [];
var kind;
if (!this._vertexBuffers && this._delayInfo) {
for (kind in this._delayInfo) {
result.push(kind);
}
}
else {
for (kind in this._vertexBuffers) {
result.push(kind);
}
}
return result;
};
Geometry.prototype.updateIndices = function (indices, offset) {
if (!this._indexBuffer) {
return;
}
if (!this._indexBufferIsUpdatable) {
this.setIndices(indices, null, true);
}
else {
this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
}
};
Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
if (totalVertices === void 0) { totalVertices = null; }
if (updatable === void 0) { updatable = false; }
if (this._indexBuffer) {
this._engine._releaseBuffer(this._indexBuffer);
}
this._disposeVertexArrayObjects();
this._indices = indices;
this._indexBufferIsUpdatable = updatable;
if (this._meshes.length !== 0 && this._indices) {
this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
}
if (totalVertices != undefined) {
this._totalVertices = totalVertices;
}
var meshes = this._meshes;
var numOfMeshes = meshes.length;
for (var index = 0; index < numOfMeshes; index++) {
meshes[index]._createGlobalSubMesh(true);
}
this.notifyUpdate();
};
Geometry.prototype.getTotalIndices = function () {
if (!this.isReady()) {
return 0;
}
return this._indices.length;
};
Geometry.prototype.getIndices = function (copyWhenShared) {
if (!this.isReady()) {
return null;
}
var orig = this._indices;
if (!copyWhenShared || this._meshes.length === 1) {
return orig;
}
else {
var len = orig.length;
var copy = [];
for (var i = 0; i < len; i++) {
copy.push(orig[i]);
}
return copy;
}
};
Geometry.prototype.getIndexBuffer = function () {
if (!this.isReady()) {
return null;
}
return this._indexBuffer;
};
Geometry.prototype._releaseVertexArrayObject = function (effect) {
if (effect === void 0) { effect = null; }
if (!effect || !this._vertexArrayObjects) {
return;
}
if (this._vertexArrayObjects[effect.key]) {
this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
delete this._vertexArrayObjects[effect.key];
}
};
Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
var meshes = this._meshes;
var index = meshes.indexOf(mesh);
if (index === -1) {
return;
}
meshes.splice(index, 1);
mesh._geometry = null;
if (meshes.length === 0 && shouldDispose) {
this.dispose();
}
};
Geometry.prototype.applyToMesh = function (mesh) {
if (mesh._geometry === this) {
return;
}
var previousGeometry = mesh._geometry;
if (previousGeometry) {
previousGeometry.releaseForMesh(mesh);
}
var meshes = this._meshes;
// must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
mesh._geometry = this;
this._scene.pushGeometry(this);
meshes.push(mesh);
if (this.isReady()) {
this._applyToMesh(mesh);
}
else {
mesh._boundingInfo = this._boundingInfo;
}
};
Geometry.prototype.updateExtend = function (data, stride) {
if (data === void 0) { data = null; }
if (!data) {
data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
}
this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
};
Geometry.prototype._applyToMesh = function (mesh) {
var numOfMeshes = this._meshes.length;
// vertexBuffers
for (var kind in this._vertexBuffers) {
if (numOfMeshes === 1) {
this._vertexBuffers[kind].create();
}
var buffer = this._vertexBuffers[kind].getBuffer();
if (buffer)
buffer.references = numOfMeshes;
if (kind === BABYLON.VertexBuffer.PositionKind) {
if (!this._extend) {
this.updateExtend(this._vertexBuffers[kind].getData());
}
mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
mesh._createGlobalSubMesh(false);
//bounding info was just created again, world matrix should be applied again.
mesh._updateBoundingInfo();
}
}
// indexBuffer
if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
this._indexBuffer = this._engine.createIndexBuffer(this._indices);
}
if (this._indexBuffer) {
this._indexBuffer.references = numOfMeshes;
}
};
Geometry.prototype.notifyUpdate = function (kind) {
if (this.onGeometryUpdated) {
this.onGeometryUpdated(this, kind);
}
for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
var mesh = _a[_i];
mesh._markSubMeshesAsAttributesDirty();
}
};
Geometry.prototype.load = function (scene, onLoaded) {
if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
return;
}
if (this.isReady()) {
if (onLoaded) {
onLoaded();
}
return;
}
this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
this._queueLoad(scene, onLoaded);
};
Geometry.prototype._queueLoad = function (scene, onLoaded) {
var _this = this;
if (!this.delayLoadingFile) {
return;
}
scene._addPendingData(this);
BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
if (!_this._delayLoadingFunction) {
return;
}
_this._delayLoadingFunction(JSON.parse(data), _this);
_this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
_this._delayInfo = [];
scene._removePendingData(_this);
var meshes = _this._meshes;
var numOfMeshes = meshes.length;
for (var index = 0; index < numOfMeshes; index++) {
_this._applyToMesh(meshes[index]);
}
if (onLoaded) {
onLoaded();
}
}, function () { }, scene.database);
};
/**
* Invert the geometry to move from a right handed system to a left handed one.
*/
Geometry.prototype.toLeftHanded = function () {
// Flip faces
var tIndices = this.getIndices(false);
if (tIndices != null && tIndices.length > 0) {
for (var i = 0; i < tIndices.length; i += 3) {
var tTemp = tIndices[i + 0];
tIndices[i + 0] = tIndices[i + 2];
tIndices[i + 2] = tTemp;
}
this.setIndices(tIndices);
}
// Negate position.z
var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
if (tPositions != null && tPositions.length > 0) {
for (var i = 0; i < tPositions.length; i += 3) {
tPositions[i + 2] = -tPositions[i + 2];
}
this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
}
// Negate normal.z
var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
if (tNormals != null && tNormals.length > 0) {
for (var i = 0; i < tNormals.length; i += 3) {
tNormals[i + 2] = -tNormals[i + 2];
}
this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
}
};
// Cache
Geometry.prototype._resetPointsArrayCache = function () {
this._positions = null;
};
Geometry.prototype._generatePointsArray = function () {
if (this._positions)
return true;
this._positions = [];
var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
if (!data) {
return false;
}
for (var index = 0; index < data.length; index += 3) {
this._positions.push(BABYLON.Vector3.FromArray(data, index));
}
return true;
};
Geometry.prototype.isDisposed = function () {
return this._isDisposed;
};
Geometry.prototype._disposeVertexArrayObjects = function () {
if (this._vertexArrayObjects) {
for (var kind in this._vertexArrayObjects) {
this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
}
this._vertexArrayObjects = {};
}
};
Geometry.prototype.dispose = function () {
var meshes = this._meshes;
var numOfMeshes = meshes.length;
var index;
for (index = 0; index < numOfMeshes; index++) {
this.releaseForMesh(meshes[index]);
}
this._meshes = [];
this._disposeVertexArrayObjects();
for (var kind in this._vertexBuffers) {
this._vertexBuffers[kind].dispose();
}
this._vertexBuffers = {};
this._totalVertices = 0;
if (this._indexBuffer) {
this._engine._releaseBuffer(this._indexBuffer);
}
this._indexBuffer = null;
this._indices = [];
this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
this.delayLoadingFile = null;
this._delayLoadingFunction = null;
this._delayInfo = [];
this._boundingInfo = null;
this._scene.removeGeometry(this);
this._isDisposed = true;
};
Geometry.prototype.copy = function (id) {
var vertexData = new BABYLON.VertexData();
vertexData.indices = [];
var indices = this.getIndices();
if (indices) {
for (var index = 0; index < indices.length; index++) {
vertexData.indices.push(indices[index]);
}
}
var updatable = false;
var stopChecking = false;
var kind;
for (kind in this._vertexBuffers) {
// using slice() to make a copy of the array and not just reference it
var data = this.getVerticesData(kind);
if (data instanceof Float32Array) {
vertexData.set(new Float32Array(data), kind);
}
else {
vertexData.set(data.slice(0), kind);
}
if (!stopChecking) {
var vb = this.getVertexBuffer(kind);
if (vb) {
updatable = vb.isUpdatable();
stopChecking = !updatable;
}
}
}
var geometry = new Geometry(id, this._scene, vertexData, updatable);
geometry.delayLoadState = this.delayLoadState;
geometry.delayLoadingFile = this.delayLoadingFile;
geometry._delayLoadingFunction = this._delayLoadingFunction;
for (kind in this._delayInfo) {
geometry._delayInfo = geometry._delayInfo || [];
geometry._delayInfo.push(kind);
}
// Bounding info
geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
return geometry;
};
Geometry.prototype.serialize = function () {
var serializationObject = {};
serializationObject.id = this.id;
serializationObject.updatable = this._updatable;
if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
serializationObject.tags = BABYLON.Tags.GetTags(this);
}
return serializationObject;
};
Geometry.prototype.toNumberArray = function (origin) {
if (Array.isArray(origin)) {
return origin;
}
else {
return Array.prototype.slice.call(origin);
}
};
Geometry.prototype.serializeVerticeData = function () {
var serializationObject = this.serialize();
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
serializationObject.positions._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
serializationObject.normals._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
serializationObject.uvs._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
serializationObject.uv2s._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
serializationObject.uv3s._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
serializationObject.uv4s._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
serializationObject.uv5s._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
serializationObject.uv6s._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
serializationObject.colors._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
serializationObject.matricesIndices._isExpanded = true;
if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
serializationObject.matricesIndices._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
serializationObject.matricesWeights._updatable = true;
}
}
serializationObject.indices = this.toNumberArray(this.getIndices());
return serializationObject;
};
// Statics
Geometry.ExtractFromMesh = function (mesh, id) {
var geometry = mesh._geometry;
if (!geometry) {
return null;
}
return geometry.copy(id);
};
/**
* You should now use Tools.RandomId(), this method is still here for legacy reasons.
* Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
* Be aware Math.random() could cause collisions, but:
* "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
*/
Geometry.RandomId = function () {
return BABYLON.Tools.RandomId();
};
Geometry.ImportGeometry = function (parsedGeometry, mesh) {
var scene = mesh.getScene();
// Geometry
var geometryId = parsedGeometry.geometryId;
if (geometryId) {
var geometry = scene.getGeometryByID(geometryId);
if (geometry) {
geometry.applyToMesh(mesh);
}
}
else if (parsedGeometry instanceof ArrayBuffer) {
var binaryInfo = mesh._binaryInfo;
if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
}
if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
}
if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
}
if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
}
if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
}
if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
}
if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
}
if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
}
if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
}
if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
}
if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
}
if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
mesh.setIndices(indicesData, null);
}
if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
mesh.subMeshes = [];
for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
var materialIndex = subMeshesData[(i * 5) + 0];
var verticesStart = subMeshesData[(i * 5) + 1];
var verticesCount = subMeshesData[(i * 5) + 2];
var indexStart = subMeshesData[(i * 5) + 3];
var indexCount = subMeshesData[(i * 5) + 4];
BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
}
}
}
else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
if (parsedGeometry.uvs) {
mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
}
if (parsedGeometry.uvs2) {
mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
}
if (parsedGeometry.uvs3) {
mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
}
if (parsedGeometry.uvs4) {
mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
}
if (parsedGeometry.uvs5) {
mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
}
if (parsedGeometry.uvs6) {
mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
}
if (parsedGeometry.colors) {
mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
}
if (parsedGeometry.matricesIndices) {
if (!parsedGeometry.matricesIndices._isExpanded) {
var floatIndices = [];
for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
var matricesIndex = parsedGeometry.matricesIndices[i];
floatIndices.push(matricesIndex & 0x000000FF);
floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
floatIndices.push(matricesIndex >> 24);
}
mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
}
else {
delete parsedGeometry.matricesIndices._isExpanded;
mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
}
}
if (parsedGeometry.matricesIndicesExtra) {
if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
var floatIndices = [];
for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
floatIndices.push(matricesIndex & 0x000000FF);
floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
floatIndices.push(matricesIndex >> 24);
}
mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
}
else {
delete parsedGeometry.matricesIndices._isExpanded;
mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
}
}
if (parsedGeometry.matricesWeights) {
Geometry._CleanMatricesWeights(parsedGeometry, mesh);
mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
}
if (parsedGeometry.matricesWeightsExtra) {
mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
}
mesh.setIndices(parsedGeometry.indices, null);
}
// SubMeshes
if (parsedGeometry.subMeshes) {
mesh.subMeshes = [];
for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
}
}
// Flat shading
if (mesh._shouldGenerateFlatShading) {
mesh.convertToFlatShadedMesh();
delete mesh._shouldGenerateFlatShading;
}
// Update
mesh.computeWorldMatrix(true);
// Octree
if (scene['_selectionOctree']) {
scene['_selectionOctree'].addMesh(mesh);
}
};
Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
var epsilon = 1e-3;
if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
return;
}
var noInfluenceBoneIndex = 0.0;
if (parsedGeometry.skeletonId > -1) {
var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
if (!skeleton) {
return;
}
noInfluenceBoneIndex = skeleton.bones.length;
}
else {
return;
}
var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
var matricesWeights = parsedGeometry.matricesWeights;
var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
var influencers = parsedGeometry.numBoneInfluencer;
var size = matricesWeights.length;
for (var i = 0; i < size; i += 4) {
var weight = 0.0;
var firstZeroWeight = -1;
for (var j = 0; j < 4; j++) {
var w = matricesWeights[i + j];
weight += w;
if (w < epsilon && firstZeroWeight < 0) {
firstZeroWeight = j;
}
}
if (matricesWeightsExtra) {
for (var j = 0; j < 4; j++) {
var w = matricesWeightsExtra[i + j];
weight += w;
if (w < epsilon && firstZeroWeight < 0) {
firstZeroWeight = j + 4;
}
}
}
if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
firstZeroWeight = influencers - 1;
}
if (weight > epsilon) {
var mweight = 1.0 / weight;
for (var j = 0; j < 4; j++) {
matricesWeights[i + j] *= mweight;
}
if (matricesWeightsExtra) {
for (var j = 0; j < 4; j++) {
matricesWeightsExtra[i + j] *= mweight;
}
}
}
else {
if (firstZeroWeight >= 4) {
matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
}
else {
matricesWeights[i + firstZeroWeight] = 1.0 - weight;
matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
}
}
}
mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
if (parsedGeometry.matricesWeightsExtra) {
mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
}
};
Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
if (scene.getGeometryByID(parsedVertexData.id)) {
return null; // null since geometry could be something else than a box...
}
var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
}
if (parsedVertexData.delayLoadingFile) {
geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
geometry._delayInfo = [];
if (parsedVertexData.hasUVs) {
geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
}
if (parsedVertexData.hasUVs2) {
geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
}
if (parsedVertexData.hasUVs3) {
geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
}
if (parsedVertexData.hasUVs4) {
geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
}
if (parsedVertexData.hasUVs5) {
geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
}
if (parsedVertexData.hasUVs6) {
geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
}
if (parsedVertexData.hasColors) {
geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
}
if (parsedVertexData.hasMatricesIndices) {
geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
}
if (parsedVertexData.hasMatricesWeights) {
geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
}
geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
}
else {
BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
}
scene.pushGeometry(geometry, true);
return geometry;
};
return Geometry;
}());
BABYLON.Geometry = Geometry;
/////// Primitives //////////////////////////////////////////////
(function (Geometry) {
var Primitives;
(function (Primitives) {
/// Abstract class
var _Primitive = /** @class */ (function (_super) {
__extends(_Primitive, _super);
function _Primitive(id, scene, _canBeRegenerated, mesh) {
if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
if (mesh === void 0) { mesh = null; }
var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
_this._canBeRegenerated = _canBeRegenerated;
_this._beingRegenerated = true;
_this.regenerate();
_this._beingRegenerated = false;
return _this;
}
_Primitive.prototype.canBeRegenerated = function () {
return this._canBeRegenerated;
};
_Primitive.prototype.regenerate = function () {
if (!this._canBeRegenerated) {
return;
}
this._beingRegenerated = true;
this.setAllVerticesData(this._regenerateVertexData(), false);
this._beingRegenerated = false;
};
_Primitive.prototype.asNewGeometry = function (id) {
return _super.prototype.copy.call(this, id);
};
// overrides
_Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
if (!this._beingRegenerated) {
return;
}
_super.prototype.setAllVerticesData.call(this, vertexData, false);
};
_Primitive.prototype.setVerticesData = function (kind, data, updatable) {
if (!this._beingRegenerated) {
return;
}
_super.prototype.setVerticesData.call(this, kind, data, false);
};
// to override
// protected
_Primitive.prototype._regenerateVertexData = function () {
throw new Error("Abstract method");
};
_Primitive.prototype.copy = function (id) {
throw new Error("Must be overriden in sub-classes.");
};
_Primitive.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.canBeRegenerated = this.canBeRegenerated();
return serializationObject;
};
return _Primitive;
}(Geometry));
Primitives._Primitive = _Primitive;
var Ribbon = /** @class */ (function (_super) {
__extends(Ribbon, _super);
// Members
function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
_this.pathArray = pathArray;
_this.closeArray = closeArray;
_this.closePath = closePath;
_this.offset = offset;
_this.side = side;
return _this;
}
Ribbon.prototype._regenerateVertexData = function () {
return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
};
Ribbon.prototype.copy = function (id) {
return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
};
return Ribbon;
}(_Primitive));
Primitives.Ribbon = Ribbon;
var Box = /** @class */ (function (_super) {
__extends(Box, _super);
// Members
function Box(id, scene, size, canBeRegenerated, mesh, side) {
if (mesh === void 0) { mesh = null; }
if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
_this.size = size;
_this.side = side;
return _this;
}
Box.prototype._regenerateVertexData = function () {
return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
};
Box.prototype.copy = function (id) {
return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
};
Box.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.size = this.size;
return serializationObject;
};
Box.Parse = function (parsedBox, scene) {
if (scene.getGeometryByID(parsedBox.id)) {
return null; // null since geometry could be something else than a box...
}
var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
}
scene.pushGeometry(box, true);
return box;
};
return Box;
}(_Primitive));
Primitives.Box = Box;
var Sphere = /** @class */ (function (_super) {
__extends(Sphere, _super);
function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
if (mesh === void 0) { mesh = null; }
if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
_this.segments = segments;
_this.diameter = diameter;
_this.side = side;
return _this;
}
Sphere.prototype._regenerateVertexData = function () {
return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
};
Sphere.prototype.copy = function (id) {
return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
};
Sphere.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.segments = this.segments;
serializationObject.diameter = this.diameter;
return serializationObject;
};
Sphere.Parse = function (parsedSphere, scene) {
if (scene.getGeometryByID(parsedSphere.id)) {
return null; // null since geometry could be something else than a sphere...
}
var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
}
scene.pushGeometry(sphere, true);
return sphere;
};
return Sphere;
}(_Primitive));
Primitives.Sphere = Sphere;
var Disc = /** @class */ (function (_super) {
__extends(Disc, _super);
// Members
function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
if (mesh === void 0) { mesh = null; }
if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
_this.radius = radius;
_this.tessellation = tessellation;
_this.side = side;
return _this;
}
Disc.prototype._regenerateVertexData = function () {
return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
};
Disc.prototype.copy = function (id) {
return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
};
return Disc;
}(_Primitive));
Primitives.Disc = Disc;
var Cylinder = /** @class */ (function (_super) {
__extends(Cylinder, _super);
function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
if (subdivisions === void 0) { subdivisions = 1; }
if (mesh === void 0) { mesh = null; }
if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
_this.height = height;
_this.diameterTop = diameterTop;
_this.diameterBottom = diameterBottom;
_this.tessellation = tessellation;
_this.subdivisions = subdivisions;
_this.side = side;
return _this;
}
Cylinder.prototype._regenerateVertexData = function () {
return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
};
Cylinder.prototype.copy = function (id) {
return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
};
Cylinder.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.height = this.height;
serializationObject.diameterTop = this.diameterTop;
serializationObject.diameterBottom = this.diameterBottom;
serializationObject.tessellation = this.tessellation;
return serializationObject;
};
Cylinder.Parse = function (parsedCylinder, scene) {
if (scene.getGeometryByID(parsedCylinder.id)) {
return null; // null since geometry could be something else than a cylinder...
}
var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
}
scene.pushGeometry(cylinder, true);
return cylinder;
};
return Cylinder;
}(_Primitive));
Primitives.Cylinder = Cylinder;
var Torus = /** @class */ (function (_super) {
__extends(Torus, _super);
function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
if (mesh === void 0) { mesh = null; }
if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
_this.diameter = diameter;
_this.thickness = thickness;
_this.tessellation = tessellation;
_this.side = side;
return _this;
}
Torus.prototype._regenerateVertexData = function () {
return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
};
Torus.prototype.copy = function (id) {
return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
};
Torus.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.diameter = this.diameter;
serializationObject.thickness = this.thickness;
serializationObject.tessellation = this.tessellation;
return serializationObject;
};
Torus.Parse = function (parsedTorus, scene) {
if (scene.getGeometryByID(parsedTorus.id)) {
return null; // null since geometry could be something else than a torus...
}
var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
}
scene.pushGeometry(torus, true);
return torus;
};
return Torus;
}(_Primitive));
Primitives.Torus = Torus;
var Ground = /** @class */ (function (_super) {
__extends(Ground, _super);
function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
if (mesh === void 0) { mesh = null; }
var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
_this.width = width;
_this.height = height;
_this.subdivisions = subdivisions;
return _this;
}
Ground.prototype._regenerateVertexData = function () {
return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
};
Ground.prototype.copy = function (id) {
return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
};
Ground.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.width = this.width;
serializationObject.height = this.height;
serializationObject.subdivisions = this.subdivisions;
return serializationObject;
};
Ground.Parse = function (parsedGround, scene) {
if (scene.getGeometryByID(parsedGround.id)) {
return null; // null since geometry could be something else than a ground...
}
var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
}
scene.pushGeometry(ground, true);
return ground;
};
return Ground;
}(_Primitive));
Primitives.Ground = Ground;
var TiledGround = /** @class */ (function (_super) {
__extends(TiledGround, _super);
function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
if (mesh === void 0) { mesh = null; }
var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
_this.xmin = xmin;
_this.zmin = zmin;
_this.xmax = xmax;
_this.zmax = zmax;
_this.subdivisions = subdivisions;
_this.precision = precision;
return _this;
}
TiledGround.prototype._regenerateVertexData = function () {
return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
};
TiledGround.prototype.copy = function (id) {
return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
};
return TiledGround;
}(_Primitive));
Primitives.TiledGround = TiledGround;
var Plane = /** @class */ (function (_super) {
__extends(Plane, _super);
function Plane(id, scene, size, canBeRegenerated, mesh, side) {
if (mesh === void 0) { mesh = null; }
if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
_this.size = size;
_this.side = side;
return _this;
}
Plane.prototype._regenerateVertexData = function () {
return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
};
Plane.prototype.copy = function (id) {
return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
};
Plane.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.size = this.size;
return serializationObject;
};
Plane.Parse = function (parsedPlane, scene) {
if (scene.getGeometryByID(parsedPlane.id)) {
return null; // null since geometry could be something else than a ground...
}
var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
}
scene.pushGeometry(plane, true);
return plane;
};
return Plane;
}(_Primitive));
Primitives.Plane = Plane;
var TorusKnot = /** @class */ (function (_super) {
__extends(TorusKnot, _super);
function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
if (mesh === void 0) { mesh = null; }
if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
_this.radius = radius;
_this.tube = tube;
_this.radialSegments = radialSegments;
_this.tubularSegments = tubularSegments;
_this.p = p;
_this.q = q;
_this.side = side;
return _this;
}
TorusKnot.prototype._regenerateVertexData = function () {
return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
};
TorusKnot.prototype.copy = function (id) {
return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
};
TorusKnot.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.radius = this.radius;
serializationObject.tube = this.tube;
serializationObject.radialSegments = this.radialSegments;
serializationObject.tubularSegments = this.tubularSegments;
serializationObject.p = this.p;
serializationObject.q = this.q;
return serializationObject;
};
;
TorusKnot.Parse = function (parsedTorusKnot, scene) {
if (scene.getGeometryByID(parsedTorusKnot.id)) {
return null; // null since geometry could be something else than a ground...
}
var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
if (BABYLON.Tags) {
BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
}
scene.pushGeometry(torusKnot, true);
return torusKnot;
};
return TorusKnot;
}(_Primitive));
Primitives.TorusKnot = TorusKnot;
})(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
})(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.geometry.js.map
var BABYLON;
(function (BABYLON) {
var PostProcessManager = /** @class */ (function () {
function PostProcessManager(scene) {
this._vertexBuffers = {};
this._scene = scene;
}
PostProcessManager.prototype._prepareBuffers = function () {
if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
return;
}
// VBO
var vertices = [];
vertices.push(1, 1);
vertices.push(-1, 1);
vertices.push(-1, -1);
vertices.push(1, -1);
this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
this._buildIndexBuffer();
};
PostProcessManager.prototype._buildIndexBuffer = function () {
// Indices
var indices = [];
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
};
PostProcessManager.prototype._rebuild = function () {
var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
if (!vb) {
return;
}
vb._rebuild();
this._buildIndexBuffer();
};
// Methods
PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
if (sourceTexture === void 0) { sourceTexture = null; }
if (postProcesses === void 0) { postProcesses = null; }
var camera = this._scene.activeCamera;
if (!camera) {
return false;
}
var postProcesses = postProcesses || camera._postProcesses;
if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
return false;
}
postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
return true;
};
PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
if (targetTexture === void 0) { targetTexture = null; }
if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
var engine = this._scene.getEngine();
for (var index = 0; index < postProcesses.length; index++) {
if (index < postProcesses.length - 1) {
postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
}
else {
if (targetTexture) {
engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
}
else {
engine.restoreDefaultFramebuffer();
}
}
var pp = postProcesses[index];
var effect = pp.apply();
if (effect) {
pp.onBeforeRenderObservable.notifyObservers(effect);
// VBOs
this._prepareBuffers();
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
// Draw order
engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
pp.onAfterRenderObservable.notifyObservers(effect);
}
}
// Restore depth buffer
engine.setDepthBuffer(true);
engine.setDepthWrite(true);
};
PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
var camera = this._scene.activeCamera;
if (!camera) {
return;
}
postProcesses = postProcesses || camera._postProcesses;
if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
return;
}
var engine = this._scene.getEngine();
for (var index = 0, len = postProcesses.length; index < len; index++) {
if (index < len - 1) {
postProcesses[index + 1].activate(camera, targetTexture);
}
else {
if (targetTexture) {
engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
}
else {
engine.restoreDefaultFramebuffer();
}
}
if (doNotPresent) {
break;
}
var pp = postProcesses[index];
var effect = pp.apply();
if (effect) {
pp.onBeforeRenderObservable.notifyObservers(effect);
// VBOs
this._prepareBuffers();
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
// Draw order
engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
pp.onAfterRenderObservable.notifyObservers(effect);
}
}
// Restore states
engine.setDepthBuffer(true);
engine.setDepthWrite(true);
engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
};
PostProcessManager.prototype.dispose = function () {
var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
if (buffer) {
buffer.dispose();
this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
}
if (this._indexBuffer) {
this._scene.getEngine()._releaseBuffer(this._indexBuffer);
this._indexBuffer = null;
}
};
return PostProcessManager;
}());
BABYLON.PostProcessManager = PostProcessManager;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.postProcessManager.js.map
var BABYLON;
(function (BABYLON) {
/**
* Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
*/
var PerformanceMonitor = /** @class */ (function () {
/**
* constructor
* @param frameSampleSize The number of samples required to saturate the sliding window
*/
function PerformanceMonitor(frameSampleSize) {
if (frameSampleSize === void 0) { frameSampleSize = 30; }
this._enabled = true;
this._rollingFrameTime = new RollingAverage(frameSampleSize);
}
/**
* Samples current frame
* @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
*/
PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
if (!this._enabled)
return;
if (this._lastFrameTimeMs != null) {
var dt = timeMs - this._lastFrameTimeMs;
this._rollingFrameTime.add(dt);
}
this._lastFrameTimeMs = timeMs;
};
Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
/**
* Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
* @return Average frame time in milliseconds
*/
get: function () {
return this._rollingFrameTime.average;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
/**
* Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
* @return Frame time variance in milliseconds squared
*/
get: function () {
return this._rollingFrameTime.variance;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
/**
* Returns the frame time of the most recent frame
* @return Frame time in milliseconds
*/
get: function () {
return this._rollingFrameTime.history(0);
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
/**
* Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
* @return Framerate in frames per second
*/
get: function () {
return 1000.0 / this._rollingFrameTime.average;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
/**
* Returns the average framerate in frames per second using the most recent frame time
* @return Framerate in frames per second
*/
get: function () {
var history = this._rollingFrameTime.history(0);
if (history === 0) {
return 0;
}
return 1000.0 / history;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
/**
* Returns true if enough samples have been taken to completely fill the sliding window
* @return true if saturated
*/
get: function () {
return this._rollingFrameTime.isSaturated();
},
enumerable: true,
configurable: true
});
/**
* Enables contributions to the sliding window sample set
*/
PerformanceMonitor.prototype.enable = function () {
this._enabled = true;
};
/**
* Disables contributions to the sliding window sample set
* Samples will not be interpolated over the disabled period
*/
PerformanceMonitor.prototype.disable = function () {
this._enabled = false;
//clear last sample to avoid interpolating over the disabled period when next enabled
this._lastFrameTimeMs = null;
};
Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
/**
* Returns true if sampling is enabled
* @return true if enabled
*/
get: function () {
return this._enabled;
},
enumerable: true,
configurable: true
});
/**
* Resets performance monitor
*/
PerformanceMonitor.prototype.reset = function () {
//clear last sample to avoid interpolating over the disabled period when next enabled
this._lastFrameTimeMs = null;
//wipe record
this._rollingFrameTime.reset();
};
return PerformanceMonitor;
}());
BABYLON.PerformanceMonitor = PerformanceMonitor;
/**
* RollingAverage
*
* Utility to efficiently compute the rolling average and variance over a sliding window of samples
*/
var RollingAverage = /** @class */ (function () {
/**
* constructor
* @param length The number of samples required to saturate the sliding window
*/
function RollingAverage(length) {
this._samples = new Array(length);
this.reset();
}
/**
* Adds a sample to the sample set
* @param v The sample value
*/
RollingAverage.prototype.add = function (v) {
//http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
var delta;
//we need to check if we've already wrapped round
if (this.isSaturated()) {
//remove bottom of stack from mean
var bottomValue = this._samples[this._pos];
delta = bottomValue - this.average;
this.average -= delta / (this._sampleCount - 1);
this._m2 -= delta * (bottomValue - this.average);
}
else {
this._sampleCount++;
}
//add new value to mean
delta = v - this.average;
this.average += delta / (this._sampleCount);
this._m2 += delta * (v - this.average);
//set the new variance
this.variance = this._m2 / (this._sampleCount - 1);
this._samples[this._pos] = v;
this._pos++;
this._pos %= this._samples.length; //positive wrap around
};
/**
* Returns previously added values or null if outside of history or outside the sliding window domain
* @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
* @return Value previously recorded with add() or null if outside of range
*/
RollingAverage.prototype.history = function (i) {
if ((i >= this._sampleCount) || (i >= this._samples.length)) {
return 0;
}
var i0 = this._wrapPosition(this._pos - 1.0);
return this._samples[this._wrapPosition(i0 - i)];
};
/**
* Returns true if enough samples have been taken to completely fill the sliding window
* @return true if sample-set saturated
*/
RollingAverage.prototype.isSaturated = function () {
return this._sampleCount >= this._samples.length;
};
/**
* Resets the rolling average (equivalent to 0 samples taken so far)
*/
RollingAverage.prototype.reset = function () {
this.average = 0;
this.variance = 0;
this._sampleCount = 0;
this._pos = 0;
this._m2 = 0;
};
/**
* Wraps a value around the sample range boundaries
* @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
* @return Wrapped position in sample range
*/
RollingAverage.prototype._wrapPosition = function (i) {
var max = this._samples.length;
return ((i % max) + max) % max;
};
return RollingAverage;
}());
BABYLON.RollingAverage = RollingAverage;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.performanceMonitor.js.map
var BABYLON;
(function (BABYLON) {
/**
* This groups together the common properties used for image processing either in direct forward pass
* or through post processing effect depending on the use of the image processing pipeline in your scene
* or not.
*/
var ImageProcessingConfiguration = /** @class */ (function () {
function ImageProcessingConfiguration() {
/**
* Color curves setup used in the effect if colorCurvesEnabled is set to true
*/
this.colorCurves = new BABYLON.ColorCurves();
this._colorCurvesEnabled = false;
this._colorGradingEnabled = false;
this._colorGradingWithGreenDepth = true;
this._colorGradingBGR = true;
this._exposure = 1.0;
this._toneMappingEnabled = false;
this._contrast = 1.0;
/**
* Vignette stretch size.
*/
this.vignetteStretch = 0;
/**
* Vignette centre X Offset.
*/
this.vignetteCentreX = 0;
/**
* Vignette centre Y Offset.
*/
this.vignetteCentreY = 0;
/**
* Vignette weight or intensity of the vignette effect.
*/
this.vignetteWeight = 1.5;
/**
* Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
* if vignetteEnabled is set to true.
*/
this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
/**
* Camera field of view used by the Vignette effect.
*/
this.vignetteCameraFov = 0.5;
this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
this._vignetteEnabled = false;
this._applyByPostProcess = false;
this._isEnabled = true;
/**
* An event triggered when the configuration changes and requires Shader to Update some parameters.
* @type {BABYLON.Observable}
*/
this.onUpdateParameters = new BABYLON.Observable();
}
Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
/**
* Gets wether the color curves effect is enabled.
*/
get: function () {
return this._colorCurvesEnabled;
},
/**
* Sets wether the color curves effect is enabled.
*/
set: function (value) {
if (this._colorCurvesEnabled === value) {
return;
}
this._colorCurvesEnabled = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
/**
* Gets wether the color grading effect is enabled.
*/
get: function () {
return this._colorGradingEnabled;
},
/**
* Sets wether the color grading effect is enabled.
*/
set: function (value) {
if (this._colorGradingEnabled === value) {
return;
}
this._colorGradingEnabled = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
/**
* Gets wether the color grading effect is using a green depth for the 3d Texture.
*/
get: function () {
return this._colorGradingWithGreenDepth;
},
/**
* Sets wether the color grading effect is using a green depth for the 3d Texture.
*/
set: function (value) {
if (this._colorGradingWithGreenDepth === value) {
return;
}
this._colorGradingWithGreenDepth = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
/**
* Gets wether the color grading texture contains BGR values.
*/
get: function () {
return this._colorGradingBGR;
},
/**
* Sets wether the color grading texture contains BGR values.
*/
set: function (value) {
if (this._colorGradingBGR === value) {
return;
}
this._colorGradingBGR = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
/**
* Gets the Exposure used in the effect.
*/
get: function () {
return this._exposure;
},
/**
* Sets the Exposure used in the effect.
*/
set: function (value) {
if (this._exposure === value) {
return;
}
this._exposure = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
/**
* Gets wether the tone mapping effect is enabled.
*/
get: function () {
return this._toneMappingEnabled;
},
/**
* Sets wether the tone mapping effect is enabled.
*/
set: function (value) {
if (this._toneMappingEnabled === value) {
return;
}
this._toneMappingEnabled = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
/**
* Gets the contrast used in the effect.
*/
get: function () {
return this._contrast;
},
/**
* Sets the contrast used in the effect.
*/
set: function (value) {
if (this._contrast === value) {
return;
}
this._contrast = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
/**
* Gets the vignette blend mode allowing different kind of effect.
*/
get: function () {
return this._vignetteBlendMode;
},
/**
* Sets the vignette blend mode allowing different kind of effect.
*/
set: function (value) {
if (this._vignetteBlendMode === value) {
return;
}
this._vignetteBlendMode = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
/**
* Gets wether the vignette effect is enabled.
*/
get: function () {
return this._vignetteEnabled;
},
/**
* Sets wether the vignette effect is enabled.
*/
set: function (value) {
if (this._vignetteEnabled === value) {
return;
}
this._vignetteEnabled = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
/**
* Gets wether the image processing is applied through a post process or not.
*/
get: function () {
return this._applyByPostProcess;
},
/**
* Sets wether the image processing is applied through a post process or not.
*/
set: function (value) {
if (this._applyByPostProcess === value) {
return;
}
this._applyByPostProcess = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
/**
* Gets wether the image processing is enabled or not.
*/
get: function () {
return this._isEnabled;
},
/**
* Sets wether the image processing is enabled or not.
*/
set: function (value) {
if (this._isEnabled === value) {
return;
}
this._isEnabled = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
/**
* Method called each time the image processing information changes requires to recompile the effect.
*/
ImageProcessingConfiguration.prototype._updateParameters = function () {
this.onUpdateParameters.notifyObservers(this);
};
ImageProcessingConfiguration.prototype.getClassName = function () {
return "ImageProcessingConfiguration";
};
/**
* Prepare the list of uniforms associated with the Image Processing effects.
* @param uniformsList The list of uniforms used in the effect
* @param defines the list of defines currently in use
*/
ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
if (defines.EXPOSURE) {
uniforms.push("exposureLinear");
}
if (defines.CONTRAST) {
uniforms.push("contrast");
}
if (defines.COLORGRADING) {
uniforms.push("colorTransformSettings");
}
if (defines.VIGNETTE) {
uniforms.push("vInverseScreenSize");
uniforms.push("vignetteSettings1");
uniforms.push("vignetteSettings2");
}
if (defines.COLORCURVES) {
BABYLON.ColorCurves.PrepareUniforms(uniforms);
}
};
/**
* Prepare the list of samplers associated with the Image Processing effects.
* @param uniformsList The list of uniforms used in the effect
* @param defines the list of defines currently in use
*/
ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
if (defines.COLORGRADING) {
samplersList.push("txColorTransform");
}
};
/**
* Prepare the list of defines associated to the shader.
* @param defines the list of defines to complete
*/
ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
if (forPostProcess === void 0) { forPostProcess = false; }
if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
defines.VIGNETTE = false;
defines.TONEMAPPING = false;
defines.CONTRAST = false;
defines.EXPOSURE = false;
defines.COLORCURVES = false;
defines.COLORGRADING = false;
defines.COLORGRADING3D = false;
defines.IMAGEPROCESSING = false;
defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
return;
}
defines.VIGNETTE = this.vignetteEnabled;
defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
defines.TONEMAPPING = this.toneMappingEnabled;
defines.CONTRAST = (this.contrast !== 1.0);
defines.EXPOSURE = (this.exposure !== 1.0);
defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
if (defines.COLORGRADING) {
defines.COLORGRADING3D = this.colorGradingTexture.is3D;
}
else {
defines.COLORGRADING3D = false;
}
defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
};
/**
* Returns true if all the image processing information are ready.
*/
ImageProcessingConfiguration.prototype.isReady = function () {
// Color Grading texure can not be none blocking.
return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
};
/**
* Binds the image processing to the shader.
* @param effect The effect to bind to
*/
ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
if (aspectRatio === void 0) { aspectRatio = 1; }
// Color Curves
if (this._colorCurvesEnabled && this.colorCurves) {
BABYLON.ColorCurves.Bind(this.colorCurves, effect);
}
// Vignette
if (this._vignetteEnabled) {
var inverseWidth = 1 / effect.getEngine().getRenderWidth();
var inverseHeight = 1 / effect.getEngine().getRenderHeight();
effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
var vignetteScaleX = vignetteScaleY * aspectRatio;
var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
var vignettePower = -2.0 * this.vignetteWeight;
effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
}
// Exposure
effect.setFloat("exposureLinear", this.exposure);
// Contrast
effect.setFloat("contrast", this.contrast);
// Color transform settings
if (this.colorGradingTexture) {
effect.setTexture("txColorTransform", this.colorGradingTexture);
var textureSize = this.colorGradingTexture.getSize().height;
effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
0.5 / textureSize, // textureOffset
textureSize, // textureSize
this.colorGradingTexture.level // weight
);
}
};
/**
* Clones the current image processing instance.
* @return The cloned image processing
*/
ImageProcessingConfiguration.prototype.clone = function () {
return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
};
/**
* Serializes the current image processing instance to a json representation.
* @return a JSON representation
*/
ImageProcessingConfiguration.prototype.serialize = function () {
return BABYLON.SerializationHelper.Serialize(this);
};
/**
* Parses the image processing from a json representation.
* @param source the JSON source to parse
* @return The parsed image processing
*/
ImageProcessingConfiguration.Parse = function (source) {
return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
};
Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
/**
* Used to apply the vignette as a mix with the pixel color.
*/
get: function () {
return this._VIGNETTEMODE_MULTIPLY;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
/**
* Used to apply the vignette as a replacement of the pixel color.
*/
get: function () {
return this._VIGNETTEMODE_OPAQUE;
},
enumerable: true,
configurable: true
});
// Static constants associated to the image processing.
ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
__decorate([
BABYLON.serializeAsColorCurves()
], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
__decorate([
BABYLON.serializeAsTexture()
], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "_exposure", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "_contrast", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
__decorate([
BABYLON.serializeAsColor4()
], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
__decorate([
BABYLON.serialize()
], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
return ImageProcessingConfiguration;
}());
BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
var BABYLON;
(function (BABYLON) {
/**
* This represents a color grading texture. This acts as a lookup table LUT, useful during post process
* It can help converting any input color in a desired output one. This can then be used to create effects
* from sepia, black and white to sixties or futuristic rendering...
*
* The only supported format is currently 3dl.
* More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
*/
var ColorGradingTexture = /** @class */ (function (_super) {
__extends(ColorGradingTexture, _super);
/**
* Instantiates a ColorGradingTexture from the following parameters.
*
* @param url The location of the color gradind data (currently only supporting 3dl)
* @param scene The scene the texture will be used in
*/
function ColorGradingTexture(url, scene) {
var _this = _super.call(this, scene) || this;
if (!url) {
return _this;
}
_this._engine = scene.getEngine();
_this._textureMatrix = BABYLON.Matrix.Identity();
_this.name = url;
_this.url = url;
_this.hasAlpha = false;
_this.isCube = false;
_this.is3D = _this._engine.webGLVersion > 1;
_this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
_this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
_this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
_this.anisotropicFilteringLevel = 1;
_this._texture = _this._getFromCache(url, true);
if (!_this._texture) {
if (!scene.useDelayedTextureLoading) {
_this.loadTexture();
}
else {
_this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
}
}
return _this;
}
/**
* Returns the texture matrix used in most of the material.
* This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
*/
ColorGradingTexture.prototype.getTextureMatrix = function () {
return this._textureMatrix;
};
/**
* Occurs when the file being loaded is a .3dl LUT file.
*/
ColorGradingTexture.prototype.load3dlTexture = function () {
var engine = this._engine;
var texture;
if (engine.webGLVersion === 1) {
texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
}
else {
texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
}
this._texture = texture;
var callback = function (text) {
if (typeof text !== "string") {
return;
}
var data = null;
var tempData = null;
var line;
var lines = text.split('\n');
var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
var maxColor = 0;
for (var i = 0; i < lines.length; i++) {
line = lines[i];
if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
continue;
if (line.indexOf('#') === 0)
continue;
var words = line.split(" ");
if (size === 0) {
// Number of space + one
size = words.length;
data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
tempData = new Float32Array(size * size * size * 4);
continue;
}
if (size != 0) {
var r = Math.max(parseInt(words[0]), 0);
var g = Math.max(parseInt(words[1]), 0);
var b = Math.max(parseInt(words[2]), 0);
maxColor = Math.max(r, maxColor);
maxColor = Math.max(g, maxColor);
maxColor = Math.max(b, maxColor);
var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
if (tempData) {
tempData[pixelStorageIndex + 0] = r;
tempData[pixelStorageIndex + 1] = g;
tempData[pixelStorageIndex + 2] = b;
}
pixelIndexSlice++;
if (pixelIndexSlice % size == 0) {
pixelIndexH++;
pixelIndexSlice = 0;
if (pixelIndexH % size == 0) {
pixelIndexW++;
pixelIndexH = 0;
}
}
}
}
if (tempData && data) {
for (var i = 0; i < tempData.length; i++) {
if (i > 0 && (i + 1) % 4 === 0) {
data[i] = 255;
}
else {
var value = tempData[i];
data[i] = (value / maxColor * 255);
}
}
}
if (texture.is3D) {
texture.updateSize(size, size, size);
engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
}
else {
texture.updateSize(size * size, size);
engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
}
};
BABYLON.Tools.LoadFile(this.url, callback);
return this._texture;
};
/**
* Starts the loading process of the texture.
*/
ColorGradingTexture.prototype.loadTexture = function () {
if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
this.load3dlTexture();
}
};
/**
* Clones the color gradind texture.
*/
ColorGradingTexture.prototype.clone = function () {
var newTexture = new ColorGradingTexture(this.url, this.getScene());
// Base texture
newTexture.level = this.level;
return newTexture;
};
/**
* Called during delayed load for textures.
*/
ColorGradingTexture.prototype.delayLoad = function () {
if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
return;
}
this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
this._texture = this._getFromCache(this.url, true);
if (!this._texture) {
this.loadTexture();
}
};
/**
* Parses a color grading texture serialized by Babylon.
* @param parsedTexture The texture information being parsedTexture
* @param scene The scene to load the texture in
* @param rootUrl The root url of the data assets to load
* @return A color gradind texture
*/
ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
var texture = null;
if (parsedTexture.name && !parsedTexture.isRenderTarget) {
texture = new ColorGradingTexture(parsedTexture.name, scene);
texture.name = parsedTexture.name;
texture.level = parsedTexture.level;
}
return texture;
};
/**
* Serializes the LUT texture to json format.
*/
ColorGradingTexture.prototype.serialize = function () {
if (!this.name) {
return null;
}
var serializationObject = {};
serializationObject.name = this.name;
serializationObject.level = this.level;
serializationObject.customType = "BABYLON.ColorGradingTexture";
return serializationObject;
};
/**
* Empty line regex stored for GC.
*/
ColorGradingTexture._noneEmptyLineRegex = /\S+/;
return ColorGradingTexture;
}(BABYLON.BaseTexture));
BABYLON.ColorGradingTexture = ColorGradingTexture;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.colorGradingTexture.js.map
var BABYLON;
(function (BABYLON) {
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
var ColorCurves = /** @class */ (function () {
function ColorCurves() {
this._dirty = true;
this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
this._globalHue = 30;
this._globalDensity = 0;
this._globalSaturation = 0;
this._globalExposure = 0;
this._highlightsHue = 30;
this._highlightsDensity = 0;
this._highlightsSaturation = 0;
this._highlightsExposure = 0;
this._midtonesHue = 30;
this._midtonesDensity = 0;
this._midtonesSaturation = 0;
this._midtonesExposure = 0;
this._shadowsHue = 30;
this._shadowsDensity = 0;
this._shadowsSaturation = 0;
this._shadowsExposure = 0;
}
Object.defineProperty(ColorCurves.prototype, "globalHue", {
/**
* Gets the global Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
get: function () {
return this._globalHue;
},
/**
* Sets the global Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
set: function (value) {
this._globalHue = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "globalDensity", {
/**
* Gets the global Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
get: function () {
return this._globalDensity;
},
/**
* Sets the global Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
set: function (value) {
this._globalDensity = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
/**
* Gets the global Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
get: function () {
return this._globalSaturation;
},
/**
* Sets the global Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
set: function (value) {
this._globalSaturation = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
/**
* Gets the highlights Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
get: function () {
return this._highlightsHue;
},
/**
* Sets the highlights Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
set: function (value) {
this._highlightsHue = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
/**
* Gets the highlights Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
get: function () {
return this._highlightsDensity;
},
/**
* Sets the highlights Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
set: function (value) {
this._highlightsDensity = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
/**
* Gets the highlights Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
get: function () {
return this._highlightsSaturation;
},
/**
* Sets the highlights Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
set: function (value) {
this._highlightsSaturation = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
/**
* Gets the highlights Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
get: function () {
return this._highlightsExposure;
},
/**
* Sets the highlights Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
set: function (value) {
this._highlightsExposure = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
/**
* Gets the midtones Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
get: function () {
return this._midtonesHue;
},
/**
* Sets the midtones Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
set: function (value) {
this._midtonesHue = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
/**
* Gets the midtones Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
get: function () {
return this._midtonesDensity;
},
/**
* Sets the midtones Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
set: function (value) {
this._midtonesDensity = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
/**
* Gets the midtones Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
get: function () {
return this._midtonesSaturation;
},
/**
* Sets the midtones Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
set: function (value) {
this._midtonesSaturation = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
/**
* Gets the midtones Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
get: function () {
return this._midtonesExposure;
},
/**
* Sets the midtones Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
set: function (value) {
this._midtonesExposure = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
/**
* Gets the shadows Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
get: function () {
return this._shadowsHue;
},
/**
* Sets the shadows Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
set: function (value) {
this._shadowsHue = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
/**
* Gets the shadows Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
get: function () {
return this._shadowsDensity;
},
/**
* Sets the shadows Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
set: function (value) {
this._shadowsDensity = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
/**
* Gets the shadows Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
get: function () {
return this._shadowsSaturation;
},
/**
* Sets the shadows Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
set: function (value) {
this._shadowsSaturation = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
/**
* Gets the shadows Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
get: function () {
return this._shadowsExposure;
},
/**
* Sets the shadows Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
set: function (value) {
this._shadowsExposure = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
ColorCurves.prototype.getClassName = function () {
return "ColorCurves";
};
/**
* Binds the color curves to the shader.
* @param colorCurves The color curve to bind
* @param effect The effect to bind to
*/
ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
if (colorCurves._dirty) {
colorCurves._dirty = false;
// Fill in global info.
colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
// Compute highlights info.
colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
// Compute midtones info.
colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
// Compute shadows info.
colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
// Compute deltas (neutral is midtones).
colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
}
if (effect) {
effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
}
};
/**
* Prepare the list of uniforms associated with the ColorCurves effects.
* @param uniformsList The list of uniforms used in the effect
*/
ColorCurves.PrepareUniforms = function (uniformsList) {
uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
};
/**
* Returns color grading data based on a hue, density, saturation and exposure value.
* @param filterHue The hue of the color filter.
* @param filterDensity The density of the color filter.
* @param saturation The saturation.
* @param exposure The exposure.
* @param result The result data container.
*/
ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
if (hue == null) {
return;
}
hue = ColorCurves.clamp(hue, 0, 360);
density = ColorCurves.clamp(density, -100, 100);
saturation = ColorCurves.clamp(saturation, -100, 100);
exposure = ColorCurves.clamp(exposure, -100, 100);
// Remap the slider/config filter density with non-linear mapping and also scale by half
// so that the maximum filter density is only 50% control. This provides fine control
// for small values and reasonable range.
density = ColorCurves.applyColorGradingSliderNonlinear(density);
density *= 0.5;
exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
if (density < 0) {
density *= -1;
hue = (hue + 180) % 360;
}
ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
result.scaleToRef(2, result);
result.a = 1 + 0.01 * saturation;
};
/**
* Takes an input slider value and returns an adjusted value that provides extra control near the centre.
* @param value The input slider value in range [-100,100].
* @returns Adjusted value.
*/
ColorCurves.applyColorGradingSliderNonlinear = function (value) {
value /= 100;
var x = Math.abs(value);
x = Math.pow(x, 2);
if (value < 0) {
x *= -1;
}
x *= 100;
return x;
};
/**
* Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
* @param hue The hue (H) input.
* @param saturation The saturation (S) input.
* @param brightness The brightness (B) input.
* @result An RGBA color represented as Vector4.
*/
ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
var h = ColorCurves.clamp(hue, 0, 360);
var s = ColorCurves.clamp(saturation / 100, 0, 1);
var v = ColorCurves.clamp(brightness / 100, 0, 1);
if (s === 0) {
result.r = v;
result.g = v;
result.b = v;
}
else {
// sector 0 to 5
h /= 60;
var i = Math.floor(h);
// fractional part of h
var f = h - i;
var p = v * (1 - s);
var q = v * (1 - s * f);
var t = v * (1 - s * (1 - f));
switch (i) {
case 0:
result.r = v;
result.g = t;
result.b = p;
break;
case 1:
result.r = q;
result.g = v;
result.b = p;
break;
case 2:
result.r = p;
result.g = v;
result.b = t;
break;
case 3:
result.r = p;
result.g = q;
result.b = v;
break;
case 4:
result.r = t;
result.g = p;
result.b = v;
break;
default:// case 5:
result.r = v;
result.g = p;
result.b = q;
break;
}
}
result.a = 1;
};
/**
* Returns a value clamped between min and max
* @param value The value to clamp
* @param min The minimum of value
* @param max The maximum of value
* @returns The clamped value.
*/
ColorCurves.clamp = function (value, min, max) {
return Math.min(Math.max(value, min), max);
};
/**
* Clones the current color curve instance.
* @return The cloned curves
*/
ColorCurves.prototype.clone = function () {
return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
};
/**
* Serializes the current color curve instance to a json representation.
* @return a JSON representation
*/
ColorCurves.prototype.serialize = function () {
return BABYLON.SerializationHelper.Serialize(this);
};
/**
* Parses the color curve from a json representation.
* @param source the JSON source to parse
* @return The parsed curves
*/
ColorCurves.Parse = function (source) {
return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
};
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_globalHue", void 0);
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_globalDensity", void 0);
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_globalSaturation", void 0);
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_globalExposure", void 0);
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_highlightsHue", void 0);
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_highlightsDensity", void 0);
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_highlightsSaturation", void 0);
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_highlightsExposure", void 0);
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_midtonesHue", void 0);
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_midtonesDensity", void 0);
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_midtonesSaturation", void 0);
__decorate([
BABYLON.serialize()
], ColorCurves.prototype, "_midtonesExposure", void 0);
return ColorCurves;
}());
BABYLON.ColorCurves = ColorCurves;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.colorCurves.js.map
var BABYLON;
(function (BABYLON) {
var MaterialHelper = /** @class */ (function () {
function MaterialHelper() {
}
MaterialHelper.BindEyePosition = function (effect, scene) {
if (scene._forcedViewPosition) {
effect.setVector3("vEyePosition", scene._forcedViewPosition);
return;
}
effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
};
MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
defines._needUVs = true;
defines[key] = true;
if (texture.getTextureMatrix().isIdentity(true)) {
defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
if (texture.coordinatesIndex === 0) {
defines["MAINUV1"] = true;
}
else {
defines["MAINUV2"] = true;
}
}
else {
defines[key + "DIRECTUV"] = 0;
}
};
MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
var matrix = texture.getTextureMatrix();
if (!matrix.isIdentity(true)) {
uniformBuffer.updateMatrix(key + "Matrix", matrix);
}
};
MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
if (defines._areMiscDirty) {
defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
}
};
MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
if (forceAlphaTest === void 0) { forceAlphaTest = false; }
var changed = false;
if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
defines["CLIPPLANE"] = !defines["CLIPPLANE"];
changed = true;
}
if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
defines["ALPHATEST"] = !defines["ALPHATEST"];
changed = true;
}
if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
changed = true;
}
if (defines["INSTANCES"] !== useInstances) {
defines["INSTANCES"] = useInstances;
changed = true;
}
if (changed) {
defines.markAsUnprocessed();
}
};
MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
if (useMorphTargets === void 0) { useMorphTargets = false; }
if (useVertexAlpha === void 0) { useVertexAlpha = true; }
if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
return false;
}
defines._normals = defines._needNormals;
defines._uvs = defines._needUVs;
defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
defines["TANGENT"] = true;
}
if (defines._needUVs) {
defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
}
else {
defines["UV1"] = false;
defines["UV2"] = false;
}
if (useVertexColor) {
var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
defines["VERTEXCOLOR"] = hasVertexColors;
defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
}
if (useBones) {
if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
}
else {
defines["NUM_BONE_INFLUENCERS"] = 0;
defines["BonesPerMesh"] = 0;
}
}
if (useMorphTargets) {
var manager = mesh.morphTargetManager;
if (manager) {
defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
}
else {
defines["MORPHTARGETS_TANGENT"] = false;
defines["MORPHTARGETS_NORMAL"] = false;
defines["MORPHTARGETS"] = false;
defines["NUM_MORPH_INFLUENCERS"] = 0;
}
}
return true;
};
MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
if (disableLighting === void 0) { disableLighting = false; }
if (!defines._areLightsDirty) {
return defines._needNormals;
}
var lightIndex = 0;
var needNormals = false;
var needRebuild = false;
var lightmapMode = false;
var shadowEnabled = false;
var specularEnabled = false;
if (scene.lightsEnabled && !disableLighting) {
for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
var light = _a[_i];
needNormals = true;
if (defines["LIGHT" + lightIndex] === undefined) {
needRebuild = true;
}
defines["LIGHT" + lightIndex] = true;
defines["SPOTLIGHT" + lightIndex] = false;
defines["HEMILIGHT" + lightIndex] = false;
defines["POINTLIGHT" + lightIndex] = false;
defines["DIRLIGHT" + lightIndex] = false;
var type;
if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
type = "SPOTLIGHT" + lightIndex;
}
else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
type = "HEMILIGHT" + lightIndex;
}
else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
type = "POINTLIGHT" + lightIndex;
}
else {
type = "DIRLIGHT" + lightIndex;
}
defines[type] = true;
// Specular
if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
specularEnabled = true;
}
// Shadows
defines["SHADOW" + lightIndex] = false;
defines["SHADOWPCF" + lightIndex] = false;
defines["SHADOWESM" + lightIndex] = false;
defines["SHADOWCUBE" + lightIndex] = false;
if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
var shadowGenerator = light.getShadowGenerator();
if (shadowGenerator) {
shadowEnabled = true;
shadowGenerator.prepareDefines(defines, lightIndex);
}
}
if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
lightmapMode = true;
defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
}
else {
defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
}
lightIndex++;
if (lightIndex === maxSimultaneousLights)
break;
}
}
defines["SPECULARTERM"] = specularEnabled;
defines["SHADOWS"] = shadowEnabled;
// Resetting all other lights if any
for (var index = lightIndex; index < maxSimultaneousLights; index++) {
if (defines["LIGHT" + index] !== undefined) {
defines["LIGHT" + index] = false;
defines["HEMILIGHT" + lightIndex] = false;
defines["POINTLIGHT" + lightIndex] = false;
defines["DIRLIGHT" + lightIndex] = false;
defines["SPOTLIGHT" + lightIndex] = false;
defines["SHADOW" + lightIndex] = false;
}
}
var caps = scene.getEngine().getCaps();
if (defines["SHADOWFLOAT"] === undefined) {
needRebuild = true;
}
defines["SHADOWFLOAT"] = shadowEnabled &&
((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
(caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
defines["LIGHTMAPEXCLUDED"] = lightmapMode;
if (needRebuild) {
defines.rebuild();
}
return needNormals;
};
MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
var uniformsList;
var uniformBuffersList = null;
if (uniformsListOrOptions.uniformsNames) {
var options = uniformsListOrOptions;
uniformsList = options.uniformsNames;
uniformBuffersList = options.uniformBuffersNames;
samplersList = options.samplers;
defines = options.defines;
maxSimultaneousLights = options.maxSimultaneousLights;
}
else {
uniformsList = uniformsListOrOptions;
if (!samplersList) {
samplersList = [];
}
}
for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
if (!defines["LIGHT" + lightIndex]) {
break;
}
uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
if (uniformBuffersList) {
uniformBuffersList.push("Light" + lightIndex);
}
samplersList.push("shadowSampler" + lightIndex);
}
if (defines["NUM_MORPH_INFLUENCERS"]) {
uniformsList.push("morphTargetInfluences");
}
};
MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
if (rank === void 0) { rank = 0; }
var lightFallbackRank = 0;
for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
if (!defines["LIGHT" + lightIndex]) {
break;
}
if (lightIndex > 0) {
lightFallbackRank = rank + lightIndex;
fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
}
if (!defines["SHADOWS"]) {
if (defines["SHADOW" + lightIndex]) {
fallbacks.addFallback(rank, "SHADOW" + lightIndex);
}
if (defines["SHADOWPCF" + lightIndex]) {
fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
}
if (defines["SHADOWESM" + lightIndex]) {
fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
}
}
}
return lightFallbackRank++;
};
MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
var influencers = defines["NUM_MORPH_INFLUENCERS"];
if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
var manager = mesh.morphTargetManager;
var normal = manager && manager.supportsNormals && defines["NORMAL"];
var tangent = manager && manager.supportsTangents && defines["TANGENT"];
for (var index = 0; index < influencers; index++) {
attribs.push(BABYLON.VertexBuffer.PositionKind + index);
if (normal) {
attribs.push(BABYLON.VertexBuffer.NormalKind + index);
}
if (tangent) {
attribs.push(BABYLON.VertexBuffer.TangentKind + index);
}
if (attribs.length > maxAttributesCount) {
BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
}
}
}
};
MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
if (defines["NUM_BONE_INFLUENCERS"] > 0) {
fallbacks.addCPUSkinningFallback(0, mesh);
attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
if (defines["NUM_BONE_INFLUENCERS"] > 4) {
attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
}
}
};
MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
if (defines["INSTANCES"]) {
attribs.push("world0");
attribs.push("world1");
attribs.push("world2");
attribs.push("world3");
}
};
// Bindings
MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
if (light.shadowEnabled && mesh.receiveShadows) {
var shadowGenerator = light.getShadowGenerator();
if (shadowGenerator) {
shadowGenerator.bindShadowLight(lightIndex, effect);
}
}
};
MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
light.transferToEffect(effect, lightIndex + "");
};
MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
var lightIndex = 0;
for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
var light = _a[_i];
var scaledIntensity = light.getScaledIntensity();
light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
MaterialHelper.BindLightProperties(light, effect, lightIndex);
light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
if (defines["SPECULARTERM"]) {
light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
}
// Shadows
if (scene.shadowsEnabled) {
this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
}
light._uniformBuffer.update();
lightIndex++;
if (lightIndex === maxSimultaneousLights)
break;
}
};
MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
effect.setColor3("vFogColor", scene.fogColor);
}
};
MaterialHelper.BindBonesParameters = function (mesh, effect) {
if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
var matrices = mesh.skeleton.getTransformMatrices(mesh);
if (matrices && effect) {
effect.setMatrices("mBones", matrices);
}
}
};
MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
var manager = abstractMesh.morphTargetManager;
if (!abstractMesh || !manager) {
return;
}
effect.setFloatArray("morphTargetInfluences", manager.influences);
};
MaterialHelper.BindLogDepth = function (defines, effect, scene) {
if (defines["LOGARITHMICDEPTH"]) {
effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
}
};
MaterialHelper.BindClipPlane = function (effect, scene) {
if (scene.clipPlane) {
var clipPlane = scene.clipPlane;
effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
}
};
return MaterialHelper;
}());
BABYLON.MaterialHelper = MaterialHelper;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.materialHelper.js.map
var BABYLON;
(function (BABYLON) {
var PushMaterial = /** @class */ (function (_super) {
__extends(PushMaterial, _super);
function PushMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this.storeEffectOnSubMeshes = true;
return _this;
}
PushMaterial.prototype.getEffect = function () {
return this._activeEffect;
};
PushMaterial.prototype.isReady = function (mesh, useInstances) {
if (!mesh) {
return false;
}
if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
return true;
}
return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
};
PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
this._activeEffect.setMatrix("world", world);
};
PushMaterial.prototype.bind = function (world, mesh) {
if (!mesh) {
return;
}
this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
};
PushMaterial.prototype._afterBind = function (mesh, effect) {
if (effect === void 0) { effect = null; }
_super.prototype._afterBind.call(this, mesh);
this.getScene()._cachedEffect = effect;
};
PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
if (visibility === void 0) { visibility = 1; }
return scene.isCachedMaterialInvalid(this, effect, visibility);
};
return PushMaterial;
}(BABYLON.Material));
BABYLON.PushMaterial = PushMaterial;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.pushMaterial.js.map
var BABYLON;
(function (BABYLON) {
var StandardMaterialDefines = /** @class */ (function (_super) {
__extends(StandardMaterialDefines, _super);
function StandardMaterialDefines() {
var _this = _super.call(this) || this;
_this.MAINUV1 = false;
_this.MAINUV2 = false;
_this.DIFFUSE = false;
_this.DIFFUSEDIRECTUV = 0;
_this.AMBIENT = false;
_this.AMBIENTDIRECTUV = 0;
_this.OPACITY = false;
_this.OPACITYDIRECTUV = 0;
_this.OPACITYRGB = false;
_this.REFLECTION = false;
_this.EMISSIVE = false;
_this.EMISSIVEDIRECTUV = 0;
_this.SPECULAR = false;
_this.SPECULARDIRECTUV = 0;
_this.BUMP = false;
_this.BUMPDIRECTUV = 0;
_this.PARALLAX = false;
_this.PARALLAXOCCLUSION = false;
_this.SPECULAROVERALPHA = false;
_this.CLIPPLANE = false;
_this.ALPHATEST = false;
_this.DEPTHPREPASS = false;
_this.ALPHAFROMDIFFUSE = false;
_this.POINTSIZE = false;
_this.FOG = false;
_this.SPECULARTERM = false;
_this.DIFFUSEFRESNEL = false;
_this.OPACITYFRESNEL = false;
_this.REFLECTIONFRESNEL = false;
_this.REFRACTIONFRESNEL = false;
_this.EMISSIVEFRESNEL = false;
_this.FRESNEL = false;
_this.NORMAL = false;
_this.UV1 = false;
_this.UV2 = false;
_this.VERTEXCOLOR = false;
_this.VERTEXALPHA = false;
_this.NUM_BONE_INFLUENCERS = 0;
_this.BonesPerMesh = 0;
_this.INSTANCES = false;
_this.GLOSSINESS = false;
_this.ROUGHNESS = false;
_this.EMISSIVEASILLUMINATION = false;
_this.LINKEMISSIVEWITHDIFFUSE = false;
_this.REFLECTIONFRESNELFROMSPECULAR = false;
_this.LIGHTMAP = false;
_this.LIGHTMAPDIRECTUV = 0;
_this.USELIGHTMAPASSHADOWMAP = false;
_this.REFLECTIONMAP_3D = false;
_this.REFLECTIONMAP_SPHERICAL = false;
_this.REFLECTIONMAP_PLANAR = false;
_this.REFLECTIONMAP_CUBIC = false;
_this.REFLECTIONMAP_PROJECTION = false;
_this.REFLECTIONMAP_SKYBOX = false;
_this.REFLECTIONMAP_EXPLICIT = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
_this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
_this.INVERTCUBICMAP = false;
_this.LOGARITHMICDEPTH = false;
_this.REFRACTION = false;
_this.REFRACTIONMAP_3D = false;
_this.REFLECTIONOVERALPHA = false;
_this.TWOSIDEDLIGHTING = false;
_this.SHADOWFLOAT = false;
_this.MORPHTARGETS = false;
_this.MORPHTARGETS_NORMAL = false;
_this.MORPHTARGETS_TANGENT = false;
_this.NUM_MORPH_INFLUENCERS = 0;
_this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
_this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
_this.IMAGEPROCESSING = false;
_this.VIGNETTE = false;
_this.VIGNETTEBLENDMODEMULTIPLY = false;
_this.VIGNETTEBLENDMODEOPAQUE = false;
_this.TONEMAPPING = false;
_this.CONTRAST = false;
_this.COLORCURVES = false;
_this.COLORGRADING = false;
_this.COLORGRADING3D = false;
_this.SAMPLER3DGREENDEPTH = false;
_this.SAMPLER3DBGRMAP = false;
_this.IMAGEPROCESSINGPOSTPROCESS = false;
_this.EXPOSURE = false;
_this.rebuild();
return _this;
}
StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
var modes = [
"REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
"REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
"REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
];
for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
var mode = modes_1[_i];
this[mode] = (mode === modeToEnable);
}
};
return StandardMaterialDefines;
}(BABYLON.MaterialDefines));
BABYLON.StandardMaterialDefines = StandardMaterialDefines;
var StandardMaterial = /** @class */ (function (_super) {
__extends(StandardMaterial, _super);
function StandardMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this.ambientColor = new BABYLON.Color3(0, 0, 0);
_this.diffuseColor = new BABYLON.Color3(1, 1, 1);
_this.specularColor = new BABYLON.Color3(1, 1, 1);
_this.emissiveColor = new BABYLON.Color3(0, 0, 0);
_this.specularPower = 64;
_this._useAlphaFromDiffuseTexture = false;
_this._useEmissiveAsIllumination = false;
_this._linkEmissiveWithDiffuse = false;
_this._useSpecularOverAlpha = false;
_this._useReflectionOverAlpha = false;
_this._disableLighting = false;
_this._useParallax = false;
_this._useParallaxOcclusion = false;
_this.parallaxScaleBias = 0.05;
_this._roughness = 0;
_this.indexOfRefraction = 0.98;
_this.invertRefractionY = true;
_this._useLightmapAsShadowmap = false;
_this._useReflectionFresnelFromSpecular = false;
_this._useGlossinessFromSpecularMapAlpha = false;
_this._maxSimultaneousLights = 4;
/**
* If sets to true, x component of normal map value will invert (x = 1.0 - x).
*/
_this._invertNormalMapX = false;
/**
* If sets to true, y component of normal map value will invert (y = 1.0 - y).
*/
_this._invertNormalMapY = false;
/**
* If sets to true and backfaceCulling is false, normals will be flipped on the backside.
*/
_this._twoSidedLighting = false;
_this._renderTargets = new BABYLON.SmartArray(16);
_this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
_this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
// Setup the default processing configuration to the scene.
_this._attachImageProcessingConfiguration(null);
_this.getRenderTargetTextures = function () {
_this._renderTargets.reset();
if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
_this._renderTargets.push(_this._reflectionTexture);
}
if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
_this._renderTargets.push(_this._refractionTexture);
}
return _this._renderTargets;
};
return _this;
}
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
/**
* Gets the image processing configuration used either in this material.
*/
get: function () {
return this._imageProcessingConfiguration;
},
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
set: function (value) {
this._attachImageProcessingConfiguration(value);
// Ensure the effect will be rebuilt.
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: true,
configurable: true
});
/**
* Attaches a new image processing configuration to the Standard Material.
* @param configuration
*/
StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
var _this = this;
if (configuration === this._imageProcessingConfiguration) {
return;
}
// Detaches observer.
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
// Pick the scene configuration if needed.
if (!configuration) {
this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
}
else {
this._imageProcessingConfiguration = configuration;
}
// Attaches observer.
this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
_this._markAllSubMeshesAsImageProcessingDirty();
});
};
Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
/**
* Gets wether the color curves effect is enabled.
*/
get: function () {
return this.imageProcessingConfiguration.colorCurvesEnabled;
},
/**
* Sets wether the color curves effect is enabled.
*/
set: function (value) {
this.imageProcessingConfiguration.colorCurvesEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
/**
* Gets wether the color grading effect is enabled.
*/
get: function () {
return this.imageProcessingConfiguration.colorGradingEnabled;
},
/**
* Gets wether the color grading effect is enabled.
*/
set: function (value) {
this.imageProcessingConfiguration.colorGradingEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
/**
* Gets wether tonemapping is enabled or not.
*/
get: function () {
return this._imageProcessingConfiguration.toneMappingEnabled;
},
/**
* Sets wether tonemapping is enabled or not
*/
set: function (value) {
this._imageProcessingConfiguration.toneMappingEnabled = value;
},
enumerable: true,
configurable: true
});
;
;
Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
get: function () {
return this._imageProcessingConfiguration.exposure;
},
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
set: function (value) {
this._imageProcessingConfiguration.exposure = value;
},
enumerable: true,
configurable: true
});
;
;
Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
/**
* Gets The camera contrast used on this material.
*/
get: function () {
return this._imageProcessingConfiguration.contrast;
},
/**
* Sets The camera contrast used on this material.
*/
set: function (value) {
this._imageProcessingConfiguration.contrast = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
/**
* Gets the Color Grading 2D Lookup Texture.
*/
get: function () {
return this._imageProcessingConfiguration.colorGradingTexture;
},
/**
* Sets the Color Grading 2D Lookup Texture.
*/
set: function (value) {
this._imageProcessingConfiguration.colorGradingTexture = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
get: function () {
return this._imageProcessingConfiguration.colorCurves;
},
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
set: function (value) {
this._imageProcessingConfiguration.colorCurves = value;
},
enumerable: true,
configurable: true
});
StandardMaterial.prototype.getClassName = function () {
return "StandardMaterial";
};
Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
get: function () {
return this._useLogarithmicDepth;
},
set: function (value) {
this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
this._markAllSubMeshesAsMiscDirty();
},
enumerable: true,
configurable: true
});
StandardMaterial.prototype.needAlphaBlending = function () {
return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
};
StandardMaterial.prototype.needAlphaTesting = function () {
return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
};
StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
};
StandardMaterial.prototype.getAlphaTestTexture = function () {
return this._diffuseTexture;
};
/**
* Child classes can use it to update shaders
*/
StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
if (useInstances === void 0) { useInstances = false; }
if (subMesh.effect && this.isFrozen) {
if (this._wasPreviouslyReady && subMesh.effect) {
return true;
}
}
if (!subMesh._materialDefines) {
subMesh._materialDefines = new StandardMaterialDefines();
}
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!this.checkReadyOnEveryCall && subMesh.effect) {
if (defines._renderId === scene.getRenderId()) {
return true;
}
}
var engine = scene.getEngine();
// Lights
defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
// Textures
if (defines._areTexturesDirty) {
defines._needUVs = false;
defines.MAINUV1 = false;
defines.MAINUV2 = false;
if (scene.texturesEnabled) {
if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
if (!this._diffuseTexture.isReadyOrNotBlocking()) {
return false;
}
else {
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
}
}
else {
defines.DIFFUSE = false;
}
if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
if (!this._ambientTexture.isReadyOrNotBlocking()) {
return false;
}
else {
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
}
}
else {
defines.AMBIENT = false;
}
if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
if (!this._opacityTexture.isReadyOrNotBlocking()) {
return false;
}
else {
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
}
}
else {
defines.OPACITY = false;
}
if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
if (!this._reflectionTexture.isReadyOrNotBlocking()) {
return false;
}
else {
defines._needNormals = true;
defines.REFLECTION = true;
defines.ROUGHNESS = (this._roughness > 0);
defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
switch (this._reflectionTexture.coordinatesMode) {
case BABYLON.Texture.CUBIC_MODE:
case BABYLON.Texture.INVCUBIC_MODE:
defines.setReflectionMode("REFLECTIONMAP_CUBIC");
break;
case BABYLON.Texture.EXPLICIT_MODE:
defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
break;
case BABYLON.Texture.PLANAR_MODE:
defines.setReflectionMode("REFLECTIONMAP_PLANAR");
break;
case BABYLON.Texture.PROJECTION_MODE:
defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
break;
case BABYLON.Texture.SKYBOX_MODE:
defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
break;
case BABYLON.Texture.SPHERICAL_MODE:
defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
break;
case BABYLON.Texture.EQUIRECTANGULAR_MODE:
defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
break;
case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
break;
case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
break;
}
}
}
else {
defines.REFLECTION = false;
}
if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
if (!this._emissiveTexture.isReadyOrNotBlocking()) {
return false;
}
else {
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
}
}
else {
defines.EMISSIVE = false;
}
if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
if (!this._lightmapTexture.isReadyOrNotBlocking()) {
return false;
}
else {
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
}
}
else {
defines.LIGHTMAP = false;
}
if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
if (!this._specularTexture.isReadyOrNotBlocking()) {
return false;
}
else {
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
}
}
else {
defines.SPECULAR = false;
}
if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
// Bump texure can not be not blocking.
if (!this._bumpTexture.isReady()) {
return false;
}
else {
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
defines.PARALLAX = this._useParallax;
defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
}
}
else {
defines.BUMP = false;
}
if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
if (!this._refractionTexture.isReadyOrNotBlocking()) {
return false;
}
else {
defines._needUVs = true;
defines.REFRACTION = true;
defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
}
}
else {
defines.REFRACTION = false;
}
defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
}
else {
defines.DIFFUSE = false;
defines.AMBIENT = false;
defines.OPACITY = false;
defines.REFLECTION = false;
defines.EMISSIVE = false;
defines.LIGHTMAP = false;
defines.BUMP = false;
defines.REFRACTION = false;
}
defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
}
if (defines._areImageProcessingDirty) {
if (!this._imageProcessingConfiguration.isReady()) {
return false;
}
this._imageProcessingConfiguration.prepareDefines(defines);
}
if (defines._areFresnelDirty) {
if (StandardMaterial.FresnelEnabled) {
// Fresnel
if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
this._emissiveFresnelParameters || this._refractionFresnelParameters ||
this._reflectionFresnelParameters) {
defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
defines._needNormals = true;
defines.FRESNEL = true;
}
}
else {
defines.FRESNEL = false;
}
}
// Misc.
BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
// Attribs
BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
// Values that need to be evaluated on every frame
BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
// Get correct effect
if (defines.isDirty) {
defines.markAsProcessed();
scene.resetCachedMaterial();
// Fallbacks
var fallbacks = new BABYLON.EffectFallbacks();
if (defines.REFLECTION) {
fallbacks.addFallback(0, "REFLECTION");
}
if (defines.SPECULAR) {
fallbacks.addFallback(0, "SPECULAR");
}
if (defines.BUMP) {
fallbacks.addFallback(0, "BUMP");
}
if (defines.PARALLAX) {
fallbacks.addFallback(1, "PARALLAX");
}
if (defines.PARALLAXOCCLUSION) {
fallbacks.addFallback(0, "PARALLAXOCCLUSION");
}
if (defines.SPECULAROVERALPHA) {
fallbacks.addFallback(0, "SPECULAROVERALPHA");
}
if (defines.FOG) {
fallbacks.addFallback(1, "FOG");
}
if (defines.POINTSIZE) {
fallbacks.addFallback(0, "POINTSIZE");
}
if (defines.LOGARITHMICDEPTH) {
fallbacks.addFallback(0, "LOGARITHMICDEPTH");
}
BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
if (defines.SPECULARTERM) {
fallbacks.addFallback(0, "SPECULARTERM");
}
if (defines.DIFFUSEFRESNEL) {
fallbacks.addFallback(1, "DIFFUSEFRESNEL");
}
if (defines.OPACITYFRESNEL) {
fallbacks.addFallback(2, "OPACITYFRESNEL");
}
if (defines.REFLECTIONFRESNEL) {
fallbacks.addFallback(3, "REFLECTIONFRESNEL");
}
if (defines.EMISSIVEFRESNEL) {
fallbacks.addFallback(4, "EMISSIVEFRESNEL");
}
if (defines.FRESNEL) {
fallbacks.addFallback(4, "FRESNEL");
}
//Attributes
var attribs = [BABYLON.VertexBuffer.PositionKind];
if (defines.NORMAL) {
attribs.push(BABYLON.VertexBuffer.NormalKind);
}
if (defines.UV1) {
attribs.push(BABYLON.VertexBuffer.UVKind);
}
if (defines.UV2) {
attribs.push(BABYLON.VertexBuffer.UV2Kind);
}
if (defines.VERTEXCOLOR) {
attribs.push(BABYLON.VertexBuffer.ColorKind);
}
BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
var shaderName = "default";
var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
"vFogInfos", "vFogColor", "pointSize",
"vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
"mBones",
"vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
"diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
"logarithmicDepthConstant", "vTangentSpaceParams"
];
var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
var uniformBuffers = ["Material", "Scene"];
BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: defines,
maxSimultaneousLights: this._maxSimultaneousLights
});
if (this.customShaderNameResolve) {
shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
}
var join = defines.toString();
subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
attributes: attribs,
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: join,
fallbacks: fallbacks,
onCompiled: this.onCompiled,
onError: this.onError,
indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
}, engine), defines);
this.buildUniformLayout();
}
if (!subMesh.effect || !subMesh.effect.isReady()) {
return false;
}
defines._renderId = scene.getRenderId();
this._wasPreviouslyReady = true;
return true;
};
StandardMaterial.prototype.buildUniformLayout = function () {
// Order is important !
this._uniformBuffer.addUniform("diffuseLeftColor", 4);
this._uniformBuffer.addUniform("diffuseRightColor", 4);
this._uniformBuffer.addUniform("opacityParts", 4);
this._uniformBuffer.addUniform("reflectionLeftColor", 4);
this._uniformBuffer.addUniform("reflectionRightColor", 4);
this._uniformBuffer.addUniform("refractionLeftColor", 4);
this._uniformBuffer.addUniform("refractionRightColor", 4);
this._uniformBuffer.addUniform("emissiveLeftColor", 4);
this._uniformBuffer.addUniform("emissiveRightColor", 4);
this._uniformBuffer.addUniform("vDiffuseInfos", 2);
this._uniformBuffer.addUniform("vAmbientInfos", 2);
this._uniformBuffer.addUniform("vOpacityInfos", 2);
this._uniformBuffer.addUniform("vReflectionInfos", 2);
this._uniformBuffer.addUniform("vEmissiveInfos", 2);
this._uniformBuffer.addUniform("vLightmapInfos", 2);
this._uniformBuffer.addUniform("vSpecularInfos", 2);
this._uniformBuffer.addUniform("vBumpInfos", 3);
this._uniformBuffer.addUniform("diffuseMatrix", 16);
this._uniformBuffer.addUniform("ambientMatrix", 16);
this._uniformBuffer.addUniform("opacityMatrix", 16);
this._uniformBuffer.addUniform("reflectionMatrix", 16);
this._uniformBuffer.addUniform("emissiveMatrix", 16);
this._uniformBuffer.addUniform("lightmapMatrix", 16);
this._uniformBuffer.addUniform("specularMatrix", 16);
this._uniformBuffer.addUniform("bumpMatrix", 16);
this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
this._uniformBuffer.addUniform("refractionMatrix", 16);
this._uniformBuffer.addUniform("vRefractionInfos", 4);
this._uniformBuffer.addUniform("vSpecularColor", 4);
this._uniformBuffer.addUniform("vEmissiveColor", 3);
this._uniformBuffer.addUniform("vDiffuseColor", 4);
this._uniformBuffer.addUniform("pointSize", 1);
this._uniformBuffer.create();
};
StandardMaterial.prototype.unbind = function () {
if (this._activeEffect) {
if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
this._activeEffect.setTexture("reflection2DSampler", null);
}
if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
this._activeEffect.setTexture("refraction2DSampler", null);
}
}
_super.prototype.unbind.call(this);
};
StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!defines) {
return;
}
var effect = subMesh.effect;
if (!effect) {
return;
}
this._activeEffect = effect;
// Matrices
this.bindOnlyWorldMatrix(world);
var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
// Bones
BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
if (mustRebind) {
this._uniformBuffer.bindToEffect(effect, "Material");
this.bindViewProjection(effect);
if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
// Fresnel
if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
}
if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
}
if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
}
if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
}
if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
}
}
// Textures
if (scene.texturesEnabled) {
if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
}
if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
}
if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
}
if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
}
if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
}
if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
}
if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
}
if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
if (scene._mirroredCameraPosition) {
this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
}
else {
this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
}
}
if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
var depth = 1.0;
if (!this._refractionTexture.isCube) {
this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
if (this._refractionTexture.depth) {
depth = this._refractionTexture.depth;
}
}
this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
}
}
// Point size
if (this.pointsCloud) {
this._uniformBuffer.updateFloat("pointSize", this.pointSize);
}
if (defines.SPECULARTERM) {
this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
}
this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
// Diffuse
this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
}
// Textures
if (scene.texturesEnabled) {
if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
effect.setTexture("diffuseSampler", this._diffuseTexture);
}
if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
effect.setTexture("ambientSampler", this._ambientTexture);
}
if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
effect.setTexture("opacitySampler", this._opacityTexture);
}
if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
if (this._reflectionTexture.isCube) {
effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
}
else {
effect.setTexture("reflection2DSampler", this._reflectionTexture);
}
}
if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
effect.setTexture("emissiveSampler", this._emissiveTexture);
}
if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
effect.setTexture("lightmapSampler", this._lightmapTexture);
}
if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
effect.setTexture("specularSampler", this._specularTexture);
}
if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
effect.setTexture("bumpSampler", this._bumpTexture);
}
if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
var depth = 1.0;
if (this._refractionTexture.isCube) {
effect.setTexture("refractionCubeSampler", this._refractionTexture);
}
else {
effect.setTexture("refraction2DSampler", this._refractionTexture);
}
}
}
// Clip plane
BABYLON.MaterialHelper.BindClipPlane(effect, scene);
// Colors
scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
BABYLON.MaterialHelper.BindEyePosition(effect, scene);
effect.setColor3("vAmbientColor", this._globalAmbientColor);
}
if (mustRebind || !this.isFrozen) {
// Lights
if (scene.lightsEnabled && !this._disableLighting) {
BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
}
// View
if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
this.bindView(effect);
}
// Fog
BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
// Morph targets
if (defines.NUM_MORPH_INFLUENCERS) {
BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
}
// Log. depth
BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
// image processing
if (!this._imageProcessingConfiguration.applyByPostProcess) {
this._imageProcessingConfiguration.bind(this._activeEffect);
}
}
this._uniformBuffer.update();
this._afterBind(mesh, this._activeEffect);
};
StandardMaterial.prototype.getAnimatables = function () {
var results = [];
if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
results.push(this._diffuseTexture);
}
if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
results.push(this._ambientTexture);
}
if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
results.push(this._opacityTexture);
}
if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
results.push(this._reflectionTexture);
}
if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
results.push(this._emissiveTexture);
}
if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
results.push(this._specularTexture);
}
if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
results.push(this._bumpTexture);
}
if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
results.push(this._lightmapTexture);
}
if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
results.push(this._refractionTexture);
}
return results;
};
StandardMaterial.prototype.getActiveTextures = function () {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this._diffuseTexture) {
activeTextures.push(this._diffuseTexture);
}
if (this._ambientTexture) {
activeTextures.push(this._ambientTexture);
}
if (this._opacityTexture) {
activeTextures.push(this._opacityTexture);
}
if (this._reflectionTexture) {
activeTextures.push(this._reflectionTexture);
}
if (this._emissiveTexture) {
activeTextures.push(this._emissiveTexture);
}
if (this._specularTexture) {
activeTextures.push(this._specularTexture);
}
if (this._bumpTexture) {
activeTextures.push(this._bumpTexture);
}
if (this._lightmapTexture) {
activeTextures.push(this._lightmapTexture);
}
if (this._refractionTexture) {
activeTextures.push(this._refractionTexture);
}
return activeTextures;
};
StandardMaterial.prototype.hasTexture = function (texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this._diffuseTexture === texture) {
return true;
}
if (this._ambientTexture === texture) {
return true;
}
if (this._opacityTexture === texture) {
return true;
}
if (this._reflectionTexture === texture) {
return true;
}
if (this._emissiveTexture === texture) {
return true;
}
if (this._specularTexture === texture) {
return true;
}
if (this._bumpTexture === texture) {
return true;
}
if (this._lightmapTexture === texture) {
return true;
}
if (this._refractionTexture === texture) {
return true;
}
return false;
};
StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
if (forceDisposeTextures) {
if (this._diffuseTexture) {
this._diffuseTexture.dispose();
}
if (this._ambientTexture) {
this._ambientTexture.dispose();
}
if (this._opacityTexture) {
this._opacityTexture.dispose();
}
if (this._reflectionTexture) {
this._reflectionTexture.dispose();
}
if (this._emissiveTexture) {
this._emissiveTexture.dispose();
}
if (this._specularTexture) {
this._specularTexture.dispose();
}
if (this._bumpTexture) {
this._bumpTexture.dispose();
}
if (this._lightmapTexture) {
this._lightmapTexture.dispose();
}
if (this._refractionTexture) {
this._refractionTexture.dispose();
}
}
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
_super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
};
StandardMaterial.prototype.clone = function (name) {
var _this = this;
var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
result.name = name;
result.id = name;
return result;
};
StandardMaterial.prototype.serialize = function () {
return BABYLON.SerializationHelper.Serialize(this);
};
// Statics
StandardMaterial.Parse = function (source, scene, rootUrl) {
return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
};
Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
get: function () {
return StandardMaterial._DiffuseTextureEnabled;
},
set: function (value) {
if (StandardMaterial._DiffuseTextureEnabled === value) {
return;
}
StandardMaterial._DiffuseTextureEnabled = value;
BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
get: function () {
return StandardMaterial._AmbientTextureEnabled;
},
set: function (value) {
if (StandardMaterial._AmbientTextureEnabled === value) {
return;
}
StandardMaterial._AmbientTextureEnabled = value;
BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
get: function () {
return StandardMaterial._OpacityTextureEnabled;
},
set: function (value) {
if (StandardMaterial._OpacityTextureEnabled === value) {
return;
}
StandardMaterial._OpacityTextureEnabled = value;
BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
get: function () {
return StandardMaterial._ReflectionTextureEnabled;
},
set: function (value) {
if (StandardMaterial._ReflectionTextureEnabled === value) {
return;
}
StandardMaterial._ReflectionTextureEnabled = value;
BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
get: function () {
return StandardMaterial._EmissiveTextureEnabled;
},
set: function (value) {
if (StandardMaterial._EmissiveTextureEnabled === value) {
return;
}
StandardMaterial._EmissiveTextureEnabled = value;
BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
get: function () {
return StandardMaterial._SpecularTextureEnabled;
},
set: function (value) {
if (StandardMaterial._SpecularTextureEnabled === value) {
return;
}
StandardMaterial._SpecularTextureEnabled = value;
BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
get: function () {
return StandardMaterial._BumpTextureEnabled;
},
set: function (value) {
if (StandardMaterial._BumpTextureEnabled === value) {
return;
}
StandardMaterial._BumpTextureEnabled = value;
BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
get: function () {
return StandardMaterial._LightmapTextureEnabled;
},
set: function (value) {
if (StandardMaterial._LightmapTextureEnabled === value) {
return;
}
StandardMaterial._LightmapTextureEnabled = value;
BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
get: function () {
return StandardMaterial._RefractionTextureEnabled;
},
set: function (value) {
if (StandardMaterial._RefractionTextureEnabled === value) {
return;
}
StandardMaterial._RefractionTextureEnabled = value;
BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
get: function () {
return StandardMaterial._ColorGradingTextureEnabled;
},
set: function (value) {
if (StandardMaterial._ColorGradingTextureEnabled === value) {
return;
}
StandardMaterial._ColorGradingTextureEnabled = value;
BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial, "FresnelEnabled", {
get: function () {
return StandardMaterial._FresnelEnabled;
},
set: function (value) {
if (StandardMaterial._FresnelEnabled === value) {
return;
}
StandardMaterial._FresnelEnabled = value;
BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
},
enumerable: true,
configurable: true
});
// Flags used to enable or disable a type of texture for all Standard Materials
StandardMaterial._DiffuseTextureEnabled = true;
StandardMaterial._AmbientTextureEnabled = true;
StandardMaterial._OpacityTextureEnabled = true;
StandardMaterial._ReflectionTextureEnabled = true;
StandardMaterial._EmissiveTextureEnabled = true;
StandardMaterial._SpecularTextureEnabled = true;
StandardMaterial._BumpTextureEnabled = true;
StandardMaterial._LightmapTextureEnabled = true;
StandardMaterial._RefractionTextureEnabled = true;
StandardMaterial._ColorGradingTextureEnabled = true;
StandardMaterial._FresnelEnabled = true;
__decorate([
BABYLON.serializeAsTexture("diffuseTexture")
], StandardMaterial.prototype, "_diffuseTexture", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "diffuseTexture", void 0);
__decorate([
BABYLON.serializeAsTexture("ambientTexture")
], StandardMaterial.prototype, "_ambientTexture", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "ambientTexture", void 0);
__decorate([
BABYLON.serializeAsTexture("opacityTexture")
], StandardMaterial.prototype, "_opacityTexture", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "opacityTexture", void 0);
__decorate([
BABYLON.serializeAsTexture("reflectionTexture")
], StandardMaterial.prototype, "_reflectionTexture", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "reflectionTexture", void 0);
__decorate([
BABYLON.serializeAsTexture("emissiveTexture")
], StandardMaterial.prototype, "_emissiveTexture", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "emissiveTexture", void 0);
__decorate([
BABYLON.serializeAsTexture("specularTexture")
], StandardMaterial.prototype, "_specularTexture", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "specularTexture", void 0);
__decorate([
BABYLON.serializeAsTexture("bumpTexture")
], StandardMaterial.prototype, "_bumpTexture", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "bumpTexture", void 0);
__decorate([
BABYLON.serializeAsTexture("lightmapTexture")
], StandardMaterial.prototype, "_lightmapTexture", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "lightmapTexture", void 0);
__decorate([
BABYLON.serializeAsTexture("refractionTexture")
], StandardMaterial.prototype, "_refractionTexture", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "refractionTexture", void 0);
__decorate([
BABYLON.serializeAsColor3("ambient")
], StandardMaterial.prototype, "ambientColor", void 0);
__decorate([
BABYLON.serializeAsColor3("diffuse")
], StandardMaterial.prototype, "diffuseColor", void 0);
__decorate([
BABYLON.serializeAsColor3("specular")
], StandardMaterial.prototype, "specularColor", void 0);
__decorate([
BABYLON.serializeAsColor3("emissive")
], StandardMaterial.prototype, "emissiveColor", void 0);
__decorate([
BABYLON.serialize()
], StandardMaterial.prototype, "specularPower", void 0);
__decorate([
BABYLON.serialize("useAlphaFromDiffuseTexture")
], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
__decorate([
BABYLON.serialize("useEmissiveAsIllumination")
], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
__decorate([
BABYLON.serialize("linkEmissiveWithDiffuse")
], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
__decorate([
BABYLON.serialize("useSpecularOverAlpha")
], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
__decorate([
BABYLON.serialize("useReflectionOverAlpha")
], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
__decorate([
BABYLON.serialize("disableLighting")
], StandardMaterial.prototype, "_disableLighting", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
], StandardMaterial.prototype, "disableLighting", void 0);
__decorate([
BABYLON.serialize("useParallax")
], StandardMaterial.prototype, "_useParallax", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useParallax", void 0);
__decorate([
BABYLON.serialize("useParallaxOcclusion")
], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
__decorate([
BABYLON.serialize()
], StandardMaterial.prototype, "parallaxScaleBias", void 0);
__decorate([
BABYLON.serialize("roughness")
], StandardMaterial.prototype, "_roughness", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "roughness", void 0);
__decorate([
BABYLON.serialize()
], StandardMaterial.prototype, "indexOfRefraction", void 0);
__decorate([
BABYLON.serialize()
], StandardMaterial.prototype, "invertRefractionY", void 0);
__decorate([
BABYLON.serialize("useLightmapAsShadowmap")
], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
__decorate([
BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
__decorate([
BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
__decorate([
BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
__decorate([
BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
__decorate([
BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
__decorate([
BABYLON.serialize("useReflectionFresnelFromSpecular")
], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
__decorate([
BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
__decorate([
BABYLON.serialize("maxSimultaneousLights")
], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
__decorate([
BABYLON.serialize("invertNormalMapX")
], StandardMaterial.prototype, "_invertNormalMapX", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "invertNormalMapX", void 0);
__decorate([
BABYLON.serialize("invertNormalMapY")
], StandardMaterial.prototype, "_invertNormalMapY", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "invertNormalMapY", void 0);
__decorate([
BABYLON.serialize("twoSidedLighting")
], StandardMaterial.prototype, "_twoSidedLighting", void 0);
__decorate([
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "twoSidedLighting", void 0);
__decorate([
BABYLON.serialize()
], StandardMaterial.prototype, "useLogarithmicDepth", null);
return StandardMaterial;
}(BABYLON.PushMaterial));
BABYLON.StandardMaterial = StandardMaterial;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.standardMaterial.js.map
var BABYLON;
(function (BABYLON) {
var PBRMaterialDefines = /** @class */ (function (_super) {
__extends(PBRMaterialDefines, _super);
function PBRMaterialDefines() {
var _this = _super.call(this) || this;
_this.PBR = true;
_this.MAINUV1 = false;
_this.MAINUV2 = false;
_this.UV1 = false;
_this.UV2 = false;
_this.ALBEDO = false;
_this.ALBEDODIRECTUV = 0;
_this.VERTEXCOLOR = false;
_this.AMBIENT = false;
_this.AMBIENTDIRECTUV = 0;
_this.AMBIENTINGRAYSCALE = false;
_this.OPACITY = false;
_this.VERTEXALPHA = false;
_this.OPACITYDIRECTUV = 0;
_this.OPACITYRGB = false;
_this.ALPHATEST = false;
_this.DEPTHPREPASS = false;
_this.ALPHABLEND = false;
_this.ALPHAFROMALBEDO = false;
_this.ALPHATESTVALUE = 0.5;
_this.SPECULAROVERALPHA = false;
_this.RADIANCEOVERALPHA = false;
_this.ALPHAFRESNEL = false;
_this.LINEARALPHAFRESNEL = false;
_this.PREMULTIPLYALPHA = false;
_this.EMISSIVE = false;
_this.EMISSIVEDIRECTUV = 0;
_this.REFLECTIVITY = false;
_this.REFLECTIVITYDIRECTUV = 0;
_this.SPECULARTERM = false;
_this.MICROSURFACEFROMREFLECTIVITYMAP = false;
_this.MICROSURFACEAUTOMATIC = false;
_this.LODBASEDMICROSFURACE = false;
_this.MICROSURFACEMAP = false;
_this.MICROSURFACEMAPDIRECTUV = 0;
_this.METALLICWORKFLOW = false;
_this.ROUGHNESSSTOREINMETALMAPALPHA = false;
_this.ROUGHNESSSTOREINMETALMAPGREEN = false;
_this.METALLNESSSTOREINMETALMAPBLUE = false;
_this.AOSTOREINMETALMAPRED = false;
_this.ENVIRONMENTBRDF = false;
_this.NORMAL = false;
_this.TANGENT = false;
_this.BUMP = false;
_this.BUMPDIRECTUV = 0;
_this.PARALLAX = false;
_this.PARALLAXOCCLUSION = false;
_this.NORMALXYSCALE = true;
_this.LIGHTMAP = false;
_this.LIGHTMAPDIRECTUV = 0;
_this.USELIGHTMAPASSHADOWMAP = false;
_this.REFLECTION = false;
_this.REFLECTIONMAP_3D = false;
_this.REFLECTIONMAP_SPHERICAL = false;
_this.REFLECTIONMAP_PLANAR = false;
_this.REFLECTIONMAP_CUBIC = false;
_this.REFLECTIONMAP_PROJECTION = false;
_this.REFLECTIONMAP_SKYBOX = false;
_this.REFLECTIONMAP_EXPLICIT = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
_this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
_this.INVERTCUBICMAP = false;
_this.USESPHERICALFROMREFLECTIONMAP = false;
_this.USESPHERICALINVERTEX = false;
_this.REFLECTIONMAP_OPPOSITEZ = false;
_this.LODINREFLECTIONALPHA = false;
_this.GAMMAREFLECTION = false;
_this.RADIANCEOCCLUSION = false;
_this.HORIZONOCCLUSION = false;
_this.REFRACTION = false;
_this.REFRACTIONMAP_3D = false;
_this.REFRACTIONMAP_OPPOSITEZ = false;
_this.LODINREFRACTIONALPHA = false;
_this.GAMMAREFRACTION = false;
_this.LINKREFRACTIONTOTRANSPARENCY = false;
_this.INSTANCES = false;
_this.NUM_BONE_INFLUENCERS = 0;
_this.BonesPerMesh = 0;
_this.NONUNIFORMSCALING = false;
_this.MORPHTARGETS = false;
_this.MORPHTARGETS_NORMAL = false;
_this.MORPHTARGETS_TANGENT = false;
_this.NUM_MORPH_INFLUENCERS = 0;
_this.IMAGEPROCESSING = false;
_this.VIGNETTE = false;
_this.VIGNETTEBLENDMODEMULTIPLY = false;
_this.VIGNETTEBLENDMODEOPAQUE = false;
_this.TONEMAPPING = false;
_this.CONTRAST = false;
_this.COLORCURVES = false;
_this.COLORGRADING = false;
_this.COLORGRADING3D = false;
_this.SAMPLER3DGREENDEPTH = false;
_this.SAMPLER3DBGRMAP = false;
_this.IMAGEPROCESSINGPOSTPROCESS = false;
_this.EXPOSURE = false;
_this.USEPHYSICALLIGHTFALLOFF = false;
_this.TWOSIDEDLIGHTING = false;
_this.SHADOWFLOAT = false;
_this.CLIPPLANE = false;
_this.POINTSIZE = false;
_this.FOG = false;
_this.LOGARITHMICDEPTH = false;
_this.FORCENORMALFORWARD = false;
_this.rebuild();
return _this;
}
PBRMaterialDefines.prototype.reset = function () {
_super.prototype.reset.call(this);
this.ALPHATESTVALUE = 0.5;
this.PBR = true;
};
return PBRMaterialDefines;
}(BABYLON.MaterialDefines));
/**
* The Physically based material base class of BJS.
*
* This offers the main features of a standard PBR material.
* For more information, please refer to the documentation :
* http://doc.babylonjs.com/extensions/Physically_Based_Rendering
*/
var PBRBaseMaterial = /** @class */ (function (_super) {
__extends(PBRBaseMaterial, _super);
/**
* Instantiates a new PBRMaterial instance.
*
* @param name The material name
* @param scene The scene the material will be use in.
*/
function PBRBaseMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
/**
* Intensity of the direct lights e.g. the four lights available in your scene.
* This impacts both the direct diffuse and specular highlights.
*/
_this._directIntensity = 1.0;
/**
* Intensity of the emissive part of the material.
* This helps controlling the emissive effect without modifying the emissive color.
*/
_this._emissiveIntensity = 1.0;
/**
* Intensity of the environment e.g. how much the environment will light the object
* either through harmonics for rough material or through the refelction for shiny ones.
*/
_this._environmentIntensity = 1.0;
/**
* This is a special control allowing the reduction of the specular highlights coming from the
* four lights of the scene. Those highlights may not be needed in full environment lighting.
*/
_this._specularIntensity = 1.0;
_this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
/**
* Debug Control allowing disabling the bump map on this material.
*/
_this._disableBumpMap = false;
/**
* AKA Occlusion Texture Intensity in other nomenclature.
*/
_this._ambientTextureStrength = 1.0;
_this._ambientColor = new BABYLON.Color3(0, 0, 0);
/**
* AKA Diffuse Color in other nomenclature.
*/
_this._albedoColor = new BABYLON.Color3(1, 1, 1);
/**
* AKA Specular Color in other nomenclature.
*/
_this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
_this._reflectionColor = new BABYLON.Color3(1, 1, 1);
_this._emissiveColor = new BABYLON.Color3(0, 0, 0);
/**
* AKA Glossiness in other nomenclature.
*/
_this._microSurface = 0.9;
/**
* source material index of refraction (IOR)' / 'destination material IOR.
*/
_this._indexOfRefraction = 0.66;
/**
* Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
*/
_this._invertRefractionY = false;
/**
* This parameters will make the material used its opacity to control how much it is refracting aginst not.
* Materials half opaque for instance using refraction could benefit from this control.
*/
_this._linkRefractionWithTransparency = false;
_this._useLightmapAsShadowmap = false;
/**
* This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
* makes the reflect vector face the model (under horizon).
*/
_this._useHorizonOcclusion = true;
/**
* This parameters will enable/disable radiance occlusion by preventing the radiance to lit
* too much the area relying on ambient texture to define their ambient occlusion.
*/
_this._useRadianceOcclusion = true;
/**
* Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
*/
_this._useAlphaFromAlbedoTexture = false;
/**
* Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
* A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
*/
_this._useSpecularOverAlpha = true;
/**
* Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
*/
_this._useMicroSurfaceFromReflectivityMapAlpha = false;
/**
* Specifies if the metallic texture contains the roughness information in its alpha channel.
*/
_this._useRoughnessFromMetallicTextureAlpha = true;
/**
* Specifies if the metallic texture contains the roughness information in its green channel.
*/
_this._useRoughnessFromMetallicTextureGreen = false;
/**
* Specifies if the metallic texture contains the metallness information in its blue channel.
*/
_this._useMetallnessFromMetallicTextureBlue = false;
/**
* Specifies if the metallic texture contains the ambient occlusion information in its red channel.
*/
_this._useAmbientOcclusionFromMetallicTextureRed = false;
/**
* Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
*/
_this._useAmbientInGrayScale = false;
/**
* In case the reflectivity map does not contain the microsurface information in its alpha channel,
* The material will try to infer what glossiness each pixel should be.
*/
_this._useAutoMicroSurfaceFromReflectivityMap = false;
/**
* BJS is using an harcoded light falloff based on a manually sets up range.
* In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
* This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
*/
_this._usePhysicalLightFalloff = true;
/**
* Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
* A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
*/
_this._useRadianceOverAlpha = true;
/**
* Allows using the bump map in parallax mode.
*/
_this._useParallax = false;
/**
* Allows using the bump map in parallax occlusion mode.
*/
_this._useParallaxOcclusion = false;
/**
* Controls the scale bias of the parallax mode.
*/
_this._parallaxScaleBias = 0.05;
/**
* If sets to true, disables all the lights affecting the material.
*/
_this._disableLighting = false;
/**
* Number of Simultaneous lights allowed on the material.
*/
_this._maxSimultaneousLights = 4;
/**
* If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
*/
_this._invertNormalMapX = false;
/**
* If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
*/
_this._invertNormalMapY = false;
/**
* If sets to true and backfaceCulling is false, normals will be flipped on the backside.
*/
_this._twoSidedLighting = false;
/**
* Defines the alpha limits in alpha test mode.
*/
_this._alphaCutOff = 0.4;
/**
* Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
*/
_this._forceAlphaTest = false;
/**
* A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
* And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
*/
_this._useAlphaFresnel = false;
/**
* A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
* And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
*/
_this._useLinearAlphaFresnel = false;
/**
* The transparency mode of the material.
*/
_this._transparencyMode = null;
/**
* Specifies the environment BRDF texture used to comput the scale and offset roughness values
* from cos thetav and roughness:
* http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
*/
_this._environmentBRDFTexture = null;
/**
* Force the shader to compute irradiance in the fragment shader in order to take bump in account.
*/
_this._forceIrradianceInFragment = false;
/**
* Force normal to face away from face.
*/
_this._forceNormalForward = false;
_this._renderTargets = new BABYLON.SmartArray(16);
_this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
// Setup the default processing configuration to the scene.
_this._attachImageProcessingConfiguration(null);
_this.getRenderTargetTextures = function () {
_this._renderTargets.reset();
if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
_this._renderTargets.push(_this._reflectionTexture);
}
if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
_this._renderTargets.push(_this._refractionTexture);
}
return _this._renderTargets;
};
_this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
return _this;
}
/**
* Attaches a new image processing configuration to the PBR Material.
* @param configuration
*/
PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
var _this = this;
if (configuration === this._imageProcessingConfiguration) {
return;
}
// Detaches observer.
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
// Pick the scene configuration if needed.
if (!configuration) {
this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
}
else {
this._imageProcessingConfiguration = configuration;
}
// Attaches observer.
this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
_this._markAllSubMeshesAsImageProcessingDirty();
});
};
PBRBaseMaterial.prototype.getClassName = function () {
return "PBRBaseMaterial";
};
Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
get: function () {
return this._useLogarithmicDepth;
},
set: function (value) {
this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
/**
* Gets the current transparency mode.
*/
get: function () {
return this._transparencyMode;
},
/**
* Sets the transparency mode of the material.
*/
set: function (value) {
if (this._transparencyMode === value) {
return;
}
this._transparencyMode = value;
this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
/**
* Returns true if alpha blending should be disabled.
*/
get: function () {
return (this._linkRefractionWithTransparency ||
this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
},
enumerable: true,
configurable: true
});
/**
* Specifies whether or not this material should be rendered in alpha blend mode.
*/
PBRBaseMaterial.prototype.needAlphaBlending = function () {
if (this._disableAlphaBlending) {
return false;
}
return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
};
/**
* Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
*/
PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
if (this._disableAlphaBlending) {
return false;
}
return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
};
/**
* Specifies whether or not this material should be rendered in alpha test mode.
*/
PBRBaseMaterial.prototype.needAlphaTesting = function () {
if (this._forceAlphaTest) {
return true;
}
if (this._linkRefractionWithTransparency) {
return false;
}
return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
};
/**
* Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
*/
PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
};
PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
return this._albedoTexture;
};
PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
var _this = this;
if (subMesh.effect && this.isFrozen) {
if (this._wasPreviouslyReady) {
return true;
}
}
if (!subMesh._materialDefines) {
subMesh._materialDefines = new PBRMaterialDefines();
}
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!this.checkReadyOnEveryCall && subMesh.effect) {
if (defines._renderId === scene.getRenderId()) {
return true;
}
}
var engine = scene.getEngine();
// Lights
BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
defines._needNormals = true;
// Textures
if (defines._areTexturesDirty) {
defines._needUVs = false;
if (scene.texturesEnabled) {
if (scene.getEngine().getCaps().textureLOD) {
defines.LODBASEDMICROSFURACE = true;
}
if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
if (!this._albedoTexture.isReadyOrNotBlocking()) {
return false;
}
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
}
else {
defines.ALBEDO = false;
}
if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
if (!this._ambientTexture.isReadyOrNotBlocking()) {
return false;
}
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
}
else {
defines.AMBIENT = false;
}
if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
if (!this._opacityTexture.isReadyOrNotBlocking()) {
return false;
}
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
}
else {
defines.OPACITY = false;
}
var reflectionTexture = this._getReflectionTexture();
if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
if (!reflectionTexture.isReadyOrNotBlocking()) {
return false;
}
defines.REFLECTION = true;
defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
defines.INVERTCUBICMAP = true;
}
defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
switch (reflectionTexture.coordinatesMode) {
case BABYLON.Texture.CUBIC_MODE:
case BABYLON.Texture.INVCUBIC_MODE:
defines.REFLECTIONMAP_CUBIC = true;
break;
case BABYLON.Texture.EXPLICIT_MODE:
defines.REFLECTIONMAP_EXPLICIT = true;
break;
case BABYLON.Texture.PLANAR_MODE:
defines.REFLECTIONMAP_PLANAR = true;
break;
case BABYLON.Texture.PROJECTION_MODE:
defines.REFLECTIONMAP_PROJECTION = true;
break;
case BABYLON.Texture.SKYBOX_MODE:
defines.REFLECTIONMAP_SKYBOX = true;
break;
case BABYLON.Texture.SPHERICAL_MODE:
defines.REFLECTIONMAP_SPHERICAL = true;
break;
case BABYLON.Texture.EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
break;
case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
break;
case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
break;
}
if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
if (reflectionTexture.sphericalPolynomial) {
defines.USESPHERICALFROMREFLECTIONMAP = true;
if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
defines.USESPHERICALINVERTEX = false;
}
else {
defines.USESPHERICALINVERTEX = true;
}
}
}
}
else {
defines.REFLECTION = false;
defines.REFLECTIONMAP_3D = false;
defines.REFLECTIONMAP_SPHERICAL = false;
defines.REFLECTIONMAP_PLANAR = false;
defines.REFLECTIONMAP_CUBIC = false;
defines.REFLECTIONMAP_PROJECTION = false;
defines.REFLECTIONMAP_SKYBOX = false;
defines.REFLECTIONMAP_EXPLICIT = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
defines.INVERTCUBICMAP = false;
defines.USESPHERICALFROMREFLECTIONMAP = false;
defines.USESPHERICALINVERTEX = false;
defines.REFLECTIONMAP_OPPOSITEZ = false;
defines.LODINREFLECTIONALPHA = false;
defines.GAMMAREFLECTION = false;
}
if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
if (!this._lightmapTexture.isReadyOrNotBlocking()) {
return false;
}
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
}
else {
defines.LIGHTMAP = false;
}
if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
if (!this._emissiveTexture.isReadyOrNotBlocking()) {
return false;
}
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
}
else {
defines.EMISSIVE = false;
}
if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
if (this._metallicTexture) {
if (!this._metallicTexture.isReadyOrNotBlocking()) {
return false;
}
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
defines.METALLICWORKFLOW = true;
defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
}
else if (this._reflectivityTexture) {
if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
return false;
}
defines.METALLICWORKFLOW = false;
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
}
else {
defines.METALLICWORKFLOW = false;
defines.REFLECTIVITY = false;
}
if (this._microSurfaceTexture) {
if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
return false;
}
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
}
else {
defines.MICROSURFACEMAP = false;
}
}
else {
defines.REFLECTIVITY = false;
defines.MICROSURFACEMAP = false;
}
if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
// Bump texure can not be none blocking.
if (!this._bumpTexture.isReady()) {
return false;
}
BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
defines.PARALLAX = true;
defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
}
else {
defines.PARALLAX = false;
}
}
else {
defines.BUMP = false;
}
var refractionTexture = this._getRefractionTexture();
if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
if (!refractionTexture.isReadyOrNotBlocking()) {
return false;
}
defines.REFRACTION = true;
defines.REFRACTIONMAP_3D = refractionTexture.isCube;
defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
if (this._linkRefractionWithTransparency) {
defines.LINKREFRACTIONTOTRANSPARENCY = true;
}
}
else {
defines.REFRACTION = false;
}
if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
// This is blocking.
if (!this._environmentBRDFTexture.isReady()) {
return false;
}
defines.ENVIRONMENTBRDF = true;
}
else {
defines.ENVIRONMENTBRDF = false;
}
if (this._shouldUseAlphaFromAlbedoTexture()) {
defines.ALPHAFROMALBEDO = true;
}
else {
defines.ALPHAFROMALBEDO = false;
}
}
defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
defines.METALLICWORKFLOW = true;
}
else {
defines.METALLICWORKFLOW = false;
}
if (!this.backFaceCulling && this._twoSidedLighting) {
defines.TWOSIDEDLIGHTING = true;
}
else {
defines.TWOSIDEDLIGHTING = false;
}
defines.ALPHATESTVALUE = this._alphaCutOff;
defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
}
if (defines._areImageProcessingDirty) {
if (!this._imageProcessingConfiguration.isReady()) {
return false;
}
this._imageProcessingConfiguration.prepareDefines(defines);
}
defines.FORCENORMALFORWARD = this._forceNormalForward;
defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
// Misc.
BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
// Values that need to be evaluated on every frame
BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
// Attribs
if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
var bufferMesh = null;
if (mesh instanceof BABYLON.InstancedMesh) {
bufferMesh = mesh.sourceMesh;
}
else if (mesh instanceof BABYLON.Mesh) {
bufferMesh = mesh;
}
if (bufferMesh) {
if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
// If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
var normals = normalVertexBuffer.getData();
var vertexBufferOffset = normalVertexBuffer.getOffset();
var strideSize = normalVertexBuffer.getStrideSize();
var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
defines.NORMAL = false;
}
if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
// If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
var tangents = tangentVertexBuffer.getData();
var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
var strideSize_1 = tangentVertexBuffer.getStrideSize();
var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
defines.TANGENT = false;
}
}
}
else {
if (!scene.getEngine().getCaps().standardDerivatives) {
bufferMesh.createNormals(true);
BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
}
}
}
}
// Get correct effect
if (defines.isDirty) {
defines.markAsProcessed();
scene.resetCachedMaterial();
// Fallbacks
var fallbacks = new BABYLON.EffectFallbacks();
var fallbackRank = 0;
if (defines.USESPHERICALINVERTEX) {
fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
}
if (defines.FOG) {
fallbacks.addFallback(fallbackRank, "FOG");
}
if (defines.POINTSIZE) {
fallbacks.addFallback(fallbackRank, "POINTSIZE");
}
if (defines.LOGARITHMICDEPTH) {
fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
}
if (defines.PARALLAX) {
fallbacks.addFallback(fallbackRank, "PARALLAX");
}
if (defines.PARALLAXOCCLUSION) {
fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
}
if (defines.ENVIRONMENTBRDF) {
fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
}
if (defines.TANGENT) {
fallbacks.addFallback(fallbackRank++, "TANGENT");
}
if (defines.BUMP) {
fallbacks.addFallback(fallbackRank++, "BUMP");
}
fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
if (defines.SPECULARTERM) {
fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
}
if (defines.USESPHERICALFROMREFLECTIONMAP) {
fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
}
if (defines.LIGHTMAP) {
fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
}
if (defines.NORMAL) {
fallbacks.addFallback(fallbackRank++, "NORMAL");
}
if (defines.AMBIENT) {
fallbacks.addFallback(fallbackRank++, "AMBIENT");
}
if (defines.EMISSIVE) {
fallbacks.addFallback(fallbackRank++, "EMISSIVE");
}
if (defines.VERTEXCOLOR) {
fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
}
if (defines.NUM_BONE_INFLUENCERS > 0) {
fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
}
if (defines.MORPHTARGETS) {
fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
}
//Attributes
var attribs = [BABYLON.VertexBuffer.PositionKind];
if (defines.NORMAL) {
attribs.push(BABYLON.VertexBuffer.NormalKind);
}
if (defines.TANGENT) {
attribs.push(BABYLON.VertexBuffer.TangentKind);
}
if (defines.UV1) {
attribs.push(BABYLON.VertexBuffer.UVKind);
}
if (defines.UV2) {
attribs.push(BABYLON.VertexBuffer.UV2Kind);
}
if (defines.VERTEXCOLOR) {
attribs.push(BABYLON.VertexBuffer.ColorKind);
}
BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
"vFogInfos", "vFogColor", "pointSize",
"vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
"mBones",
"vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
"vLightingIntensity",
"logarithmicDepthConstant",
"vSphericalX", "vSphericalY", "vSphericalZ",
"vSphericalXX", "vSphericalYY", "vSphericalZZ",
"vSphericalXY", "vSphericalYZ", "vSphericalZX",
"vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
"vTangentSpaceParams"
];
var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
"bumpSampler", "lightmapSampler", "opacitySampler",
"refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
"reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
"microSurfaceSampler", "environmentBrdfSampler"];
var uniformBuffers = ["Material", "Scene"];
BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: defines,
maxSimultaneousLights: this._maxSimultaneousLights
});
var onCompiled = function (effect) {
if (_this.onCompiled) {
_this.onCompiled(effect);
}
_this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
};
var join = defines.toString();
subMesh.setEffect(scene.getEngine().createEffect("pbr", {
attributes: attribs,
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: join,
fallbacks: fallbacks,
onCompiled: onCompiled,
onError: this.onError,
indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
}, engine), defines);
this.buildUniformLayout();
}
if (!subMesh.effect || !subMesh.effect.isReady()) {
return false;
}
defines._renderId = scene.getRenderId();
this._wasPreviouslyReady = true;
return true;
};
PBRBaseMaterial.prototype.buildUniformLayout = function () {
// Order is important !
this._uniformBuffer.addUniform("vAlbedoInfos", 2);
this._uniformBuffer.addUniform("vAmbientInfos", 3);
this._uniformBuffer.addUniform("vOpacityInfos", 2);
this._uniformBuffer.addUniform("vEmissiveInfos", 2);
this._uniformBuffer.addUniform("vLightmapInfos", 2);
this._uniformBuffer.addUniform("vReflectivityInfos", 3);
this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
this._uniformBuffer.addUniform("vRefractionInfos", 4);
this._uniformBuffer.addUniform("vReflectionInfos", 2);
this._uniformBuffer.addUniform("vBumpInfos", 3);
this._uniformBuffer.addUniform("albedoMatrix", 16);
this._uniformBuffer.addUniform("ambientMatrix", 16);
this._uniformBuffer.addUniform("opacityMatrix", 16);
this._uniformBuffer.addUniform("emissiveMatrix", 16);
this._uniformBuffer.addUniform("lightmapMatrix", 16);
this._uniformBuffer.addUniform("reflectivityMatrix", 16);
this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
this._uniformBuffer.addUniform("bumpMatrix", 16);
this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
this._uniformBuffer.addUniform("refractionMatrix", 16);
this._uniformBuffer.addUniform("reflectionMatrix", 16);
this._uniformBuffer.addUniform("vReflectionColor", 3);
this._uniformBuffer.addUniform("vAlbedoColor", 4);
this._uniformBuffer.addUniform("vLightingIntensity", 4);
this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
this._uniformBuffer.addUniform("vReflectivityColor", 4);
this._uniformBuffer.addUniform("vEmissiveColor", 3);
this._uniformBuffer.addUniform("pointSize", 1);
this._uniformBuffer.create();
};
PBRBaseMaterial.prototype.unbind = function () {
if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
this._uniformBuffer.setTexture("reflectionSampler", null);
}
if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
this._uniformBuffer.setTexture("refractionSampler", null);
}
_super.prototype.unbind.call(this);
};
PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
this._activeEffect.setMatrix("world", world);
};
PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!defines) {
return;
}
var effect = subMesh.effect;
if (!effect) {
return;
}
this._activeEffect = effect;
// Matrices
this.bindOnlyWorldMatrix(world);
var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
// Bones
BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
var reflectionTexture = null;
if (mustRebind) {
this._uniformBuffer.bindToEffect(effect, "Material");
this.bindViewProjection(effect);
reflectionTexture = this._getReflectionTexture();
var refractionTexture = this._getRefractionTexture();
if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
// Texture uniforms
if (scene.texturesEnabled) {
if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
}
if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
}
if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
}
if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
var polynomials = reflectionTexture.sphericalPolynomial;
if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
}
this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
}
if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
}
if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
}
if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
if (this._metallicTexture) {
this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
}
else if (this._reflectivityTexture) {
this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
}
if (this._microSurfaceTexture) {
this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
}
}
if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
if (scene._mirroredCameraPosition) {
this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
}
else {
this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
}
}
if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
var depth = 1.0;
if (!refractionTexture.isCube) {
if (refractionTexture.depth) {
depth = refractionTexture.depth;
}
}
this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
}
}
// Point size
if (this.pointsCloud) {
this._uniformBuffer.updateFloat("pointSize", this.pointSize);
}
// Colors
if (defines.METALLICWORKFLOW) {
BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
}
else {
this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
}
this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
// Misc
this._lightingInfos.x = this._directIntensity;
this._lightingInfos.y = this._emissiveIntensity;
this._lightingInfos.z = this._environmentIntensity;
this._lightingInfos.w = this._specularIntensity;
this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
}
// Textures
if (scene.texturesEnabled) {
if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
}
if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
}
if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
}
if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
if (defines.LODBASEDMICROSFURACE) {
this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
}
else {
this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
}
}
if (defines.ENVIRONMENTBRDF) {
this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
}
if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
if (defines.LODBASEDMICROSFURACE) {
this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
}
else {
this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
}
}
if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
}
if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
}
if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
if (this._metallicTexture) {
this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
}
else if (this._reflectivityTexture) {
this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
}
if (this._microSurfaceTexture) {
this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
}
}
if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
}
}
// Clip plane
BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
// Colors
scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
effect.setColor3("vAmbientColor", this._globalAmbientColor);
}
if (mustRebind || !this.isFrozen) {
// Lights
if (scene.lightsEnabled && !this._disableLighting) {
BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
}
// View
if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
this.bindView(effect);
}
// Fog
BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
// Morph targets
if (defines.NUM_MORPH_INFLUENCERS) {
BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
}
// image processing
this._imageProcessingConfiguration.bind(this._activeEffect);
// Log. depth
BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
}
this._uniformBuffer.update();
this._afterBind(mesh);
};
PBRBaseMaterial.prototype.getAnimatables = function () {
var results = [];
if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
results.push(this._albedoTexture);
}
if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
results.push(this._ambientTexture);
}
if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
results.push(this._opacityTexture);
}
if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
results.push(this._reflectionTexture);
}
if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
results.push(this._emissiveTexture);
}
if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
results.push(this._metallicTexture);
}
else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
results.push(this._reflectivityTexture);
}
if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
results.push(this._bumpTexture);
}
if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
results.push(this._lightmapTexture);
}
if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
results.push(this._refractionTexture);
}
return results;
};
PBRBaseMaterial.prototype._getReflectionTexture = function () {
if (this._reflectionTexture) {
return this._reflectionTexture;
}
return this.getScene().environmentTexture;
};
PBRBaseMaterial.prototype._getRefractionTexture = function () {
if (this._refractionTexture) {
return this._refractionTexture;
}
if (this._linkRefractionWithTransparency) {
return this.getScene().environmentTexture;
}
return null;
};
PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
if (forceDisposeTextures) {
if (this._albedoTexture) {
this._albedoTexture.dispose();
}
if (this._ambientTexture) {
this._ambientTexture.dispose();
}
if (this._opacityTexture) {
this._opacityTexture.dispose();
}
if (this._reflectionTexture) {
this._reflectionTexture.dispose();
}
if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
this._environmentBRDFTexture.dispose();
}
if (this._emissiveTexture) {
this._emissiveTexture.dispose();
}
if (this._metallicTexture) {
this._metallicTexture.dispose();
}
if (this._reflectivityTexture) {
this._reflectivityTexture.dispose();
}
if (this._bumpTexture) {
this._bumpTexture.dispose();
}
if (this._lightmapTexture) {
this._lightmapTexture.dispose();
}
if (this._refractionTexture) {
this._refractionTexture.dispose();
}
}
this._renderTargets.dispose();
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
_super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
};
PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
__decorate([
BABYLON.serializeAsImageProcessingConfiguration()
], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
__decorate([
BABYLON.serialize()
], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
__decorate([
BABYLON.serialize()
], PBRBaseMaterial.prototype, "transparencyMode", null);
return PBRBaseMaterial;
}(BABYLON.PushMaterial));
BABYLON.PBRBaseMaterial = PBRBaseMaterial;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.pbrBaseMaterial.js.map
var BABYLON;
(function (BABYLON) {
var Internals;
(function (Internals) {
/**
* The Physically based simple base material of BJS.
*
* This enables better naming and convention enforcements on top of the pbrMaterial.
* It is used as the base class for both the specGloss and metalRough conventions.
*/
var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
__extends(PBRBaseSimpleMaterial, _super);
/**
* Instantiates a new PBRMaterial instance.
*
* @param name The material name
* @param scene The scene the material will be use in.
*/
function PBRBaseSimpleMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
/**
* Number of Simultaneous lights allowed on the material.
*/
_this.maxSimultaneousLights = 4;
/**
* If sets to true, disables all the lights affecting the material.
*/
_this.disableLighting = false;
/**
* If sets to true, x component of normal map value will invert (x = 1.0 - x).
*/
_this.invertNormalMapX = false;
/**
* If sets to true, y component of normal map value will invert (y = 1.0 - y).
*/
_this.invertNormalMapY = false;
/**
* Emissivie color used to self-illuminate the model.
*/
_this.emissiveColor = new BABYLON.Color3(0, 0, 0);
/**
* Occlusion Channel Strenght.
*/
_this.occlusionStrength = 1.0;
_this.useLightmapAsShadowmap = false;
_this._useAlphaFromAlbedoTexture = true;
_this._useAmbientInGrayScale = true;
return _this;
}
Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
/**
* Gets the current double sided mode.
*/
get: function () {
return this._twoSidedLighting;
},
/**
* If sets to true and backfaceCulling is false, normals will be flipped on the backside.
*/
set: function (value) {
if (this._twoSidedLighting === value) {
return;
}
this._twoSidedLighting = value;
this.backFaceCulling = !value;
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: true,
configurable: true
});
/**
* Return the active textures of the material.
*/
PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this.environmentTexture) {
activeTextures.push(this.environmentTexture);
}
if (this.normalTexture) {
activeTextures.push(this.normalTexture);
}
if (this.emissiveTexture) {
activeTextures.push(this.emissiveTexture);
}
if (this.occlusionTexture) {
activeTextures.push(this.occlusionTexture);
}
if (this.lightmapTexture) {
activeTextures.push(this.lightmapTexture);
}
return activeTextures;
};
PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this.lightmapTexture === texture) {
return true;
}
return false;
};
PBRBaseSimpleMaterial.prototype.getClassName = function () {
return "PBRBaseSimpleMaterial";
};
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
__decorate([
BABYLON.serializeAsColor3("emissive"),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
__decorate([
BABYLON.serialize()
], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
return PBRBaseSimpleMaterial;
}(BABYLON.PBRBaseMaterial));
Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
})(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
var BABYLON;
(function (BABYLON) {
/**
* The Physically based material of BJS.
*
* This offers the main features of a standard PBR material.
* For more information, please refer to the documentation :
* http://doc.babylonjs.com/extensions/Physically_Based_Rendering
*/
var PBRMaterial = /** @class */ (function (_super) {
__extends(PBRMaterial, _super);
/**
* Instantiates a new PBRMaterial instance.
*
* @param name The material name
* @param scene The scene the material will be use in.
*/
function PBRMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
/**
* Intensity of the direct lights e.g. the four lights available in your scene.
* This impacts both the direct diffuse and specular highlights.
*/
_this.directIntensity = 1.0;
/**
* Intensity of the emissive part of the material.
* This helps controlling the emissive effect without modifying the emissive color.
*/
_this.emissiveIntensity = 1.0;
/**
* Intensity of the environment e.g. how much the environment will light the object
* either through harmonics for rough material or through the refelction for shiny ones.
*/
_this.environmentIntensity = 1.0;
/**
* This is a special control allowing the reduction of the specular highlights coming from the
* four lights of the scene. Those highlights may not be needed in full environment lighting.
*/
_this.specularIntensity = 1.0;
/**
* Debug Control allowing disabling the bump map on this material.
*/
_this.disableBumpMap = false;
/**
* AKA Occlusion Texture Intensity in other nomenclature.
*/
_this.ambientTextureStrength = 1.0;
_this.ambientColor = new BABYLON.Color3(0, 0, 0);
/**
* AKA Diffuse Color in other nomenclature.
*/
_this.albedoColor = new BABYLON.Color3(1, 1, 1);
/**
* AKA Specular Color in other nomenclature.
*/
_this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
_this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
_this.emissiveColor = new BABYLON.Color3(0, 0, 0);
/**
* AKA Glossiness in other nomenclature.
*/
_this.microSurface = 1.0;
/**
* source material index of refraction (IOR)' / 'destination material IOR.
*/
_this.indexOfRefraction = 0.66;
/**
* Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
*/
_this.invertRefractionY = false;
/**
* This parameters will make the material used its opacity to control how much it is refracting aginst not.
* Materials half opaque for instance using refraction could benefit from this control.
*/
_this.linkRefractionWithTransparency = false;
_this.useLightmapAsShadowmap = false;
/**
* Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
*/
_this.useAlphaFromAlbedoTexture = false;
/**
* Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
*/
_this.forceAlphaTest = false;
/**
* Defines the alpha limits in alpha test mode.
*/
_this.alphaCutOff = 0.4;
/**
* Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
* A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
*/
_this.useSpecularOverAlpha = true;
/**
* Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
*/
_this.useMicroSurfaceFromReflectivityMapAlpha = false;
/**
* Specifies if the metallic texture contains the roughness information in its alpha channel.
*/
_this.useRoughnessFromMetallicTextureAlpha = true;
/**
* Specifies if the metallic texture contains the roughness information in its green channel.
*/
_this.useRoughnessFromMetallicTextureGreen = false;
/**
* Specifies if the metallic texture contains the metallness information in its blue channel.
*/
_this.useMetallnessFromMetallicTextureBlue = false;
/**
* Specifies if the metallic texture contains the ambient occlusion information in its red channel.
*/
_this.useAmbientOcclusionFromMetallicTextureRed = false;
/**
* Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
*/
_this.useAmbientInGrayScale = false;
/**
* In case the reflectivity map does not contain the microsurface information in its alpha channel,
* The material will try to infer what glossiness each pixel should be.
*/
_this.useAutoMicroSurfaceFromReflectivityMap = false;
/**
* BJS is using an harcoded light falloff based on a manually sets up range.
* In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
* This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
*/
_this.usePhysicalLightFalloff = true;
/**
* Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
* A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
*/
_this.useRadianceOverAlpha = true;
/**
* Allows using the bump map in parallax mode.
*/
_this.useParallax = false;
/**
* Allows using the bump map in parallax occlusion mode.
*/
_this.useParallaxOcclusion = false;
/**
* Controls the scale bias of the parallax mode.
*/
_this.parallaxScaleBias = 0.05;
/**
* If sets to true, disables all the lights affecting the material.
*/
_this.disableLighting = false;
/**
* Force the shader to compute irradiance in the fragment shader in order to take bump in account.
*/
_this.forceIrradianceInFragment = false;
/**
* Number of Simultaneous lights allowed on the material.
*/
_this.maxSimultaneousLights = 4;
/**
* If sets to true, x component of normal map value will invert (x = 1.0 - x).
*/
_this.invertNormalMapX = false;
/**
* If sets to true, y component of normal map value will invert (y = 1.0 - y).
*/
_this.invertNormalMapY = false;
/**
* If sets to true and backfaceCulling is false, normals will be flipped on the backside.
*/
_this.twoSidedLighting = false;
/**
* A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
* And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
*/
_this.useAlphaFresnel = false;
/**
* A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
* And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
*/
_this.useLinearAlphaFresnel = false;
/**
* A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
* And/Or occlude the blended part.
*/
_this.environmentBRDFTexture = null;
/**
* Force normal to face away from face.
*/
_this.forceNormalForward = false;
/**
* This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
* makes the reflect vector face the model (under horizon).
*/
_this.useHorizonOcclusion = true;
/**
* This parameters will enable/disable radiance occlusion by preventing the radiance to lit
* too much the area relying on ambient texture to define their ambient occlusion.
*/
_this.useRadianceOcclusion = true;
_this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
return _this;
}
Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
/**
* PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
*/
get: function () {
return this._PBRMATERIAL_OPAQUE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
/**
* PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
*/
get: function () {
return this._PBRMATERIAL_ALPHATEST;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
/**
* PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
*/
get: function () {
return this._PBRMATERIAL_ALPHABLEND;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
/**
* PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
* They are also discarded below the alpha cutoff threshold to improve performances.
*/
get: function () {
return this._PBRMATERIAL_ALPHATESTANDBLEND;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
/**
* Gets the image processing configuration used either in this material.
*/
get: function () {
return this._imageProcessingConfiguration;
},
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
set: function (value) {
this._attachImageProcessingConfiguration(value);
// Ensure the effect will be rebuilt.
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
/**
* Gets wether the color curves effect is enabled.
*/
get: function () {
return this.imageProcessingConfiguration.colorCurvesEnabled;
},
/**
* Sets wether the color curves effect is enabled.
*/
set: function (value) {
this.imageProcessingConfiguration.colorCurvesEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
/**
* Gets wether the color grading effect is enabled.
*/
get: function () {
return this.imageProcessingConfiguration.colorGradingEnabled;
},
/**
* Gets wether the color grading effect is enabled.
*/
set: function (value) {
this.imageProcessingConfiguration.colorGradingEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
/**
* Gets wether tonemapping is enabled or not.
*/
get: function () {
return this._imageProcessingConfiguration.toneMappingEnabled;
},
/**
* Sets wether tonemapping is enabled or not
*/
set: function (value) {
this._imageProcessingConfiguration.toneMappingEnabled = value;
},
enumerable: true,
configurable: true
});
;
;
Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
get: function () {
return this._imageProcessingConfiguration.exposure;
},
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
set: function (value) {
this._imageProcessingConfiguration.exposure = value;
},
enumerable: true,
configurable: true
});
;
;
Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
/**
* Gets The camera contrast used on this material.
*/
get: function () {
return this._imageProcessingConfiguration.contrast;
},
/**
* Sets The camera contrast used on this material.
*/
set: function (value) {
this._imageProcessingConfiguration.contrast = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
/**
* Gets the Color Grading 2D Lookup Texture.
*/
get: function () {
return this._imageProcessingConfiguration.colorGradingTexture;
},
/**
* Sets the Color Grading 2D Lookup Texture.
*/
set: function (value) {
this._imageProcessingConfiguration.colorGradingTexture = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
get: function () {
return this._imageProcessingConfiguration.colorCurves;
},
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
set: function (value) {
this._imageProcessingConfiguration.colorCurves = value;
},
enumerable: true,
configurable: true
});
PBRMaterial.prototype.getClassName = function () {
return "PBRMaterial";
};
PBRMaterial.prototype.getActiveTextures = function () {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this._albedoTexture) {
activeTextures.push(this._albedoTexture);
}
if (this._ambientTexture) {
activeTextures.push(this._ambientTexture);
}
if (this._opacityTexture) {
activeTextures.push(this._opacityTexture);
}
if (this._reflectionTexture) {
activeTextures.push(this._reflectionTexture);
}
if (this._emissiveTexture) {
activeTextures.push(this._emissiveTexture);
}
if (this._reflectivityTexture) {
activeTextures.push(this._reflectivityTexture);
}
if (this._metallicTexture) {
activeTextures.push(this._metallicTexture);
}
if (this._microSurfaceTexture) {
activeTextures.push(this._microSurfaceTexture);
}
if (this._bumpTexture) {
activeTextures.push(this._bumpTexture);
}
if (this._lightmapTexture) {
activeTextures.push(this._lightmapTexture);
}
if (this._refractionTexture) {
activeTextures.push(this._refractionTexture);
}
return activeTextures;
};
PBRMaterial.prototype.hasTexture = function (texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this._albedoTexture === texture) {
return true;
}
if (this._ambientTexture === texture) {
return true;
}
if (this._opacityTexture === texture) {
return true;
}
if (this._reflectionTexture === texture) {
return true;
}
if (this._reflectivityTexture === texture) {
return true;
}
if (this._metallicTexture === texture) {
return true;
}
if (this._microSurfaceTexture === texture) {
return true;
}
if (this._bumpTexture === texture) {
return true;
}
if (this._lightmapTexture === texture) {
return true;
}
if (this._refractionTexture === texture) {
return true;
}
return false;
};
PBRMaterial.prototype.clone = function (name) {
var _this = this;
var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
clone.id = name;
clone.name = name;
return clone;
};
PBRMaterial.prototype.serialize = function () {
var serializationObject = BABYLON.SerializationHelper.Serialize(this);
serializationObject.customType = "BABYLON.PBRMaterial";
return serializationObject;
};
// Statics
PBRMaterial.Parse = function (source, scene, rootUrl) {
return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
};
PBRMaterial._PBRMATERIAL_OPAQUE = 0;
PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "directIntensity", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "emissiveIntensity", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "environmentIntensity", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "specularIntensity", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "disableBumpMap", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "albedoTexture", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "ambientTexture", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "ambientTextureStrength", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "opacityTexture", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectionTexture", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "emissiveTexture", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectivityTexture", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallicTexture", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallic", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "roughness", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "microSurfaceTexture", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "bumpTexture", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
], PBRMaterial.prototype, "lightmapTexture", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "refractionTexture", void 0);
__decorate([
BABYLON.serializeAsColor3("ambient"),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "ambientColor", void 0);
__decorate([
BABYLON.serializeAsColor3("albedo"),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "albedoColor", void 0);
__decorate([
BABYLON.serializeAsColor3("reflectivity"),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectivityColor", void 0);
__decorate([
BABYLON.serializeAsColor3("reflection"),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectionColor", void 0);
__decorate([
BABYLON.serializeAsColor3("emissive"),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "emissiveColor", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "microSurface", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "indexOfRefraction", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "invertRefractionY", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "forceAlphaTest", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "alphaCutOff", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useParallax", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "parallaxScaleBias", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRMaterial.prototype, "disableLighting", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "invertNormalMapX", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "invertNormalMapY", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "twoSidedLighting", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAlphaFresnel", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "forceNormalForward", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
return PBRMaterial;
}(BABYLON.PBRBaseMaterial));
BABYLON.PBRMaterial = PBRMaterial;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.pbrMaterial.js.map
var BABYLON;
(function (BABYLON) {
/**
* The PBR material of BJS following the metal roughness convention.
*
* This fits to the PBR convention in the GLTF definition:
* https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
*/
var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
__extends(PBRMetallicRoughnessMaterial, _super);
/**
* Instantiates a new PBRMetalRoughnessMaterial instance.
*
* @param name The material name
* @param scene The scene the material will be use in.
*/
function PBRMetallicRoughnessMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this._useRoughnessFromMetallicTextureAlpha = false;
_this._useRoughnessFromMetallicTextureGreen = true;
_this._useMetallnessFromMetallicTextureBlue = true;
return _this;
}
/**
* Return the currrent class name of the material.
*/
PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
return "PBRMetallicRoughnessMaterial";
};
/**
* Return the active textures of the material.
*/
PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this.baseTexture) {
activeTextures.push(this.baseTexture);
}
if (this.metallicRoughnessTexture) {
activeTextures.push(this.metallicRoughnessTexture);
}
return activeTextures;
};
PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this.baseTexture === texture) {
return true;
}
if (this.metallicRoughnessTexture === texture) {
return true;
}
return false;
};
PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
var _this = this;
var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
clone.id = name;
clone.name = name;
return clone;
};
/**
* Serialize the material to a parsable JSON object.
*/
PBRMetallicRoughnessMaterial.prototype.serialize = function () {
var serializationObject = BABYLON.SerializationHelper.Serialize(this);
serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
return serializationObject;
};
/**
* Parses a JSON object correponding to the serialize function.
*/
PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
};
__decorate([
BABYLON.serializeAsColor3(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
return PBRMetallicRoughnessMaterial;
}(BABYLON.Internals.PBRBaseSimpleMaterial));
BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
var BABYLON;
(function (BABYLON) {
/**
* The PBR material of BJS following the specular glossiness convention.
*
* This fits to the PBR convention in the GLTF definition:
* https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
*/
var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
__extends(PBRSpecularGlossinessMaterial, _super);
/**
* Instantiates a new PBRSpecularGlossinessMaterial instance.
*
* @param name The material name
* @param scene The scene the material will be use in.
*/
function PBRSpecularGlossinessMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this._useMicroSurfaceFromReflectivityMapAlpha = true;
return _this;
}
/**
* Return the currrent class name of the material.
*/
PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
return "PBRSpecularGlossinessMaterial";
};
/**
* Return the active textures of the material.
*/
PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this.diffuseTexture) {
activeTextures.push(this.diffuseTexture);
}
if (this.specularGlossinessTexture) {
activeTextures.push(this.specularGlossinessTexture);
}
return activeTextures;
};
PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this.diffuseTexture === texture) {
return true;
}
if (this.specularGlossinessTexture === texture) {
return true;
}
return false;
};
PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
var _this = this;
var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
clone.id = name;
clone.name = name;
return clone;
};
/**
* Serialize the material to a parsable JSON object.
*/
PBRSpecularGlossinessMaterial.prototype.serialize = function () {
var serializationObject = BABYLON.SerializationHelper.Serialize(this);
serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
return serializationObject;
};
/**
* Parses a JSON object correponding to the serialize function.
*/
PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
};
__decorate([
BABYLON.serializeAsColor3("diffuse"),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
__decorate([
BABYLON.serializeAsColor3("specular"),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
__decorate([
BABYLON.serialize(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
__decorate([
BABYLON.serializeAsTexture(),
BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
return PBRSpecularGlossinessMaterial;
}(BABYLON.Internals.PBRBaseSimpleMaterial));
BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
var BABYLON;
(function (BABYLON) {
BABYLON.CameraInputTypes = {};
var CameraInputsManager = /** @class */ (function () {
function CameraInputsManager(camera) {
this.attached = {};
this.camera = camera;
this.checkInputs = function () { };
}
CameraInputsManager.prototype.add = function (input) {
var type = input.getSimpleName();
if (this.attached[type]) {
BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
return;
}
this.attached[type] = input;
input.camera = this.camera;
//for checkInputs, we are dynamically creating a function
//the goal is to avoid the performance penalty of looping for inputs in the render loop
if (input.checkInputs) {
this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
}
if (this.attachedElement) {
input.attachControl(this.attachedElement);
}
};
CameraInputsManager.prototype.remove = function (inputToRemove) {
for (var cam in this.attached) {
var input = this.attached[cam];
if (input === inputToRemove) {
input.detachControl(this.attachedElement);
input.camera = null;
delete this.attached[cam];
this.rebuildInputCheck();
}
}
};
CameraInputsManager.prototype.removeByType = function (inputType) {
for (var cam in this.attached) {
var input = this.attached[cam];
if (input.getClassName() === inputType) {
input.detachControl(this.attachedElement);
input.camera = null;
delete this.attached[cam];
this.rebuildInputCheck();
}
}
};
CameraInputsManager.prototype._addCheckInputs = function (fn) {
var current = this.checkInputs;
return function () {
current();
fn();
};
};
CameraInputsManager.prototype.attachInput = function (input) {
if (this.attachedElement) {
input.attachControl(this.attachedElement, this.noPreventDefault);
}
};
CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
if (noPreventDefault === void 0) { noPreventDefault = false; }
if (this.attachedElement) {
return;
}
noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
this.attachedElement = element;
this.noPreventDefault = noPreventDefault;
for (var cam in this.attached) {
this.attached[cam].attachControl(element, noPreventDefault);
}
};
CameraInputsManager.prototype.detachElement = function (element, disconnect) {
if (disconnect === void 0) { disconnect = false; }
if (this.attachedElement !== element) {
return;
}
for (var cam in this.attached) {
this.attached[cam].detachControl(element);
if (disconnect) {
this.attached[cam].camera = null;
}
}
this.attachedElement = null;
};
CameraInputsManager.prototype.rebuildInputCheck = function () {
this.checkInputs = function () { };
for (var cam in this.attached) {
var input = this.attached[cam];
if (input.checkInputs) {
this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
}
}
};
CameraInputsManager.prototype.clear = function () {
if (this.attachedElement) {
this.detachElement(this.attachedElement, true);
}
this.attached = {};
this.attachedElement = null;
this.checkInputs = function () { };
};
CameraInputsManager.prototype.serialize = function (serializedCamera) {
var inputs = {};
for (var cam in this.attached) {
var input = this.attached[cam];
var res = BABYLON.SerializationHelper.Serialize(input);
inputs[input.getClassName()] = res;
}
serializedCamera.inputsmgr = inputs;
};
CameraInputsManager.prototype.parse = function (parsedCamera) {
var parsedInputs = parsedCamera.inputsmgr;
if (parsedInputs) {
this.clear();
for (var n in parsedInputs) {
var construct = BABYLON.CameraInputTypes[n];
if (construct) {
var parsedinput = parsedInputs[n];
var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
this.add(input);
}
}
}
else {
//2016-03-08 this part is for managing backward compatibility
for (var n in this.attached) {
var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
if (construct) {
var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
this.remove(this.attached[n]);
this.add(input);
}
}
}
};
return CameraInputsManager;
}());
BABYLON.CameraInputsManager = CameraInputsManager;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.cameraInputsManager.js.map
var BABYLON;
(function (BABYLON) {
var FreeCameraMouseInput = /** @class */ (function () {
function FreeCameraMouseInput(touchEnabled) {
if (touchEnabled === void 0) { touchEnabled = true; }
this.touchEnabled = touchEnabled;
this.buttons = [0, 1, 2];
this.angularSensibility = 2000.0;
this.previousPosition = null;
}
FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
var _this = this;
var engine = this.camera.getEngine();
if (!this._pointerInput) {
this._pointerInput = function (p, s) {
var evt = p.event;
if (engine.isInVRExclusivePointerMode) {
return;
}
if (!_this.touchEnabled && evt.pointerType === "touch") {
return;
}
if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
return;
}
var srcElement = (evt.srcElement || evt.target);
if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
try {
srcElement.setPointerCapture(evt.pointerId);
}
catch (e) {
//Nothing to do with the error. Execution will continue.
}
_this.previousPosition = {
x: evt.clientX,
y: evt.clientY
};
if (!noPreventDefault) {
evt.preventDefault();
element.focus();
}
}
else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
try {
srcElement.releasePointerCapture(evt.pointerId);
}
catch (e) {
//Nothing to do with the error.
}
_this.previousPosition = null;
if (!noPreventDefault) {
evt.preventDefault();
}
}
else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
if (!_this.previousPosition || engine.isPointerLock) {
return;
}
var offsetX = evt.clientX - _this.previousPosition.x;
var offsetY = evt.clientY - _this.previousPosition.y;
if (_this.camera.getScene().useRightHandedSystem) {
_this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
}
else {
_this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
}
_this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
_this.previousPosition = {
x: evt.clientX,
y: evt.clientY
};
if (!noPreventDefault) {
evt.preventDefault();
}
}
};
}
this._onMouseMove = function (evt) {
if (!engine.isPointerLock) {
return;
}
if (engine.isInVRExclusivePointerMode) {
return;
}
var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
if (_this.camera.getScene().useRightHandedSystem) {
_this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
}
else {
_this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
}
_this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
_this.previousPosition = null;
if (!noPreventDefault) {
evt.preventDefault();
}
};
this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
element.addEventListener("mousemove", this._onMouseMove, false);
};
FreeCameraMouseInput.prototype.detachControl = function (element) {
if (this._observer && element) {
this.camera.getScene().onPointerObservable.remove(this._observer);
if (this._onMouseMove) {
element.removeEventListener("mousemove", this._onMouseMove);
}
this._observer = null;
this._onMouseMove = null;
this.previousPosition = null;
}
};
FreeCameraMouseInput.prototype.getClassName = function () {
return "FreeCameraMouseInput";
};
FreeCameraMouseInput.prototype.getSimpleName = function () {
return "mouse";
};
__decorate([
BABYLON.serialize()
], FreeCameraMouseInput.prototype, "buttons", void 0);
__decorate([
BABYLON.serialize()
], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
return FreeCameraMouseInput;
}());
BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.freeCameraMouseInput.js.map
var BABYLON;
(function (BABYLON) {
var FreeCameraKeyboardMoveInput = /** @class */ (function () {
function FreeCameraKeyboardMoveInput() {
this._keys = new Array();
this.keysUp = [38];
this.keysDown = [40];
this.keysLeft = [37];
this.keysRight = [39];
}
FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
var _this = this;
if (this._onCanvasBlurObserver) {
return;
}
this._scene = this.camera.getScene();
this._engine = this._scene.getEngine();
this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
_this._keys = [];
});
this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
var evt = info.event;
if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
_this.keysDown.indexOf(evt.keyCode) !== -1 ||
_this.keysLeft.indexOf(evt.keyCode) !== -1 ||
_this.keysRight.indexOf(evt.keyCode) !== -1) {
var index = _this._keys.indexOf(evt.keyCode);
if (index === -1) {
_this._keys.push(evt.keyCode);
}
if (!noPreventDefault) {
evt.preventDefault();
}
}
}
else {
if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
_this.keysDown.indexOf(evt.keyCode) !== -1 ||
_this.keysLeft.indexOf(evt.keyCode) !== -1 ||
_this.keysRight.indexOf(evt.keyCode) !== -1) {
var index = _this._keys.indexOf(evt.keyCode);
if (index >= 0) {
_this._keys.splice(index, 1);
}
if (!noPreventDefault) {
evt.preventDefault();
}
}
}
});
};
FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
if (this._scene) {
if (this._onKeyboardObserver) {
this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
}
if (this._onCanvasBlurObserver) {
this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
}
this._onKeyboardObserver = null;
this._onCanvasBlurObserver = null;
}
this._keys = [];
};
FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
if (this._onKeyboardObserver) {
var camera = this.camera;
// Keyboard
for (var index = 0; index < this._keys.length; index++) {
var keyCode = this._keys[index];
var speed = camera._computeLocalCameraSpeed();
if (this.keysLeft.indexOf(keyCode) !== -1) {
camera._localDirection.copyFromFloats(-speed, 0, 0);
}
else if (this.keysUp.indexOf(keyCode) !== -1) {
camera._localDirection.copyFromFloats(0, 0, speed);
}
else if (this.keysRight.indexOf(keyCode) !== -1) {
camera._localDirection.copyFromFloats(speed, 0, 0);
}
else if (this.keysDown.indexOf(keyCode) !== -1) {
camera._localDirection.copyFromFloats(0, 0, -speed);
}
if (camera.getScene().useRightHandedSystem) {
camera._localDirection.z *= -1;
}
camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
camera.cameraDirection.addInPlace(camera._transformedDirection);
}
}
};
FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
return "FreeCameraKeyboardMoveInput";
};
FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
this._keys = [];
};
FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
return "keyboard";
};
__decorate([
BABYLON.serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
__decorate([
BABYLON.serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
__decorate([
BABYLON.serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
__decorate([
BABYLON.serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
return FreeCameraKeyboardMoveInput;
}());
BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
var BABYLON;
(function (BABYLON) {
var FreeCameraInputsManager = /** @class */ (function (_super) {
__extends(FreeCameraInputsManager, _super);
function FreeCameraInputsManager(camera) {
return _super.call(this, camera) || this;
}
FreeCameraInputsManager.prototype.addKeyboard = function () {
this.add(new BABYLON.FreeCameraKeyboardMoveInput());
return this;
};
FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
if (touchEnabled === void 0) { touchEnabled = true; }
this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
return this;
};
FreeCameraInputsManager.prototype.addGamepad = function () {
this.add(new BABYLON.FreeCameraGamepadInput());
return this;
};
FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
this.add(new BABYLON.FreeCameraDeviceOrientationInput());
return this;
};
FreeCameraInputsManager.prototype.addTouch = function () {
this.add(new BABYLON.FreeCameraTouchInput());
return this;
};
FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
this.add(new BABYLON.FreeCameraVirtualJoystickInput());
return this;
};
return FreeCameraInputsManager;
}(BABYLON.CameraInputsManager));
BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.freeCameraInputsManager.js.map
var BABYLON;
(function (BABYLON) {
var TargetCamera = /** @class */ (function (_super) {
__extends(TargetCamera, _super);
function TargetCamera(name, position, scene) {
var _this = _super.call(this, name, position, scene) || this;
_this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
_this.cameraRotation = new BABYLON.Vector2(0, 0);
_this.rotation = new BABYLON.Vector3(0, 0, 0);
_this.speed = 2.0;
_this.noRotationConstraint = false;
_this.lockedTarget = null;
_this._currentTarget = BABYLON.Vector3.Zero();
_this._viewMatrix = BABYLON.Matrix.Zero();
_this._camMatrix = BABYLON.Matrix.Zero();
_this._cameraTransformMatrix = BABYLON.Matrix.Zero();
_this._cameraRotationMatrix = BABYLON.Matrix.Zero();
_this._referencePoint = new BABYLON.Vector3(0, 0, 1);
_this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
_this._transformedReferencePoint = BABYLON.Vector3.Zero();
_this._lookAtTemp = BABYLON.Matrix.Zero();
_this._tempMatrix = BABYLON.Matrix.Zero();
return _this;
}
TargetCamera.prototype.getFrontPosition = function (distance) {
var direction = this.getTarget().subtract(this.position);
direction.normalize();
direction.scaleInPlace(distance);
return this.globalPosition.add(direction);
};
TargetCamera.prototype._getLockedTargetPosition = function () {
if (!this.lockedTarget) {
return null;
}
if (this.lockedTarget.absolutePosition) {
this.lockedTarget.computeWorldMatrix();
}
return this.lockedTarget.absolutePosition || this.lockedTarget;
};
TargetCamera.prototype.storeState = function () {
this._storedPosition = this.position.clone();
this._storedRotation = this.rotation.clone();
if (this.rotationQuaternion) {
this._storedRotationQuaternion = this.rotationQuaternion.clone();
}
return _super.prototype.storeState.call(this);
};
/**
* Restored camera state. You must call storeState() first
*/
TargetCamera.prototype._restoreStateValues = function () {
if (!_super.prototype._restoreStateValues.call(this)) {
return false;
}
this.position = this._storedPosition.clone();
this.rotation = this._storedRotation.clone();
if (this.rotationQuaternion) {
this.rotationQuaternion = this._storedRotationQuaternion.clone();
}
this.cameraDirection.copyFromFloats(0, 0, 0);
this.cameraRotation.copyFromFloats(0, 0);
return true;
};
// Cache
TargetCamera.prototype._initCache = function () {
_super.prototype._initCache.call(this);
this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
};
TargetCamera.prototype._updateCache = function (ignoreParentClass) {
if (!ignoreParentClass) {
_super.prototype._updateCache.call(this);
}
var lockedTargetPosition = this._getLockedTargetPosition();
if (!lockedTargetPosition) {
this._cache.lockedTarget = null;
}
else {
if (!this._cache.lockedTarget) {
this._cache.lockedTarget = lockedTargetPosition.clone();
}
else {
this._cache.lockedTarget.copyFrom(lockedTargetPosition);
}
}
this._cache.rotation.copyFrom(this.rotation);
if (this.rotationQuaternion)
this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
};
// Synchronized
TargetCamera.prototype._isSynchronizedViewMatrix = function () {
if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
return false;
}
var lockedTargetPosition = this._getLockedTargetPosition();
return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
&& (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
};
// Methods
TargetCamera.prototype._computeLocalCameraSpeed = function () {
var engine = this.getEngine();
return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
};
// Target
TargetCamera.prototype.setTarget = function (target) {
this.upVector.normalize();
BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
this._camMatrix.invert();
this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
var vDir = target.subtract(this.position);
if (vDir.x >= 0.0) {
this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
}
else {
this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
}
this.rotation.z = 0;
if (isNaN(this.rotation.x)) {
this.rotation.x = 0;
}
if (isNaN(this.rotation.y)) {
this.rotation.y = 0;
}
if (isNaN(this.rotation.z)) {
this.rotation.z = 0;
}
if (this.rotationQuaternion) {
BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
}
};
/**
* Return the current target position of the camera. This value is expressed in local space.
*/
TargetCamera.prototype.getTarget = function () {
return this._currentTarget;
};
TargetCamera.prototype._decideIfNeedsToMove = function () {
return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
};
TargetCamera.prototype._updatePosition = function () {
if (this.parent) {
this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
return;
}
this.position.addInPlace(this.cameraDirection);
};
TargetCamera.prototype._checkInputs = function () {
var needToMove = this._decideIfNeedsToMove();
var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
// Move
if (needToMove) {
this._updatePosition();
}
// Rotate
if (needToRotate) {
this.rotation.x += this.cameraRotation.x;
this.rotation.y += this.cameraRotation.y;
//rotate, if quaternion is set and rotation was used
if (this.rotationQuaternion) {
var len = this.rotation.lengthSquared();
if (len) {
BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
}
}
if (!this.noRotationConstraint) {
var limit = (Math.PI / 2) * 0.95;
if (this.rotation.x > limit)
this.rotation.x = limit;
if (this.rotation.x < -limit)
this.rotation.x = -limit;
}
}
// Inertia
if (needToMove) {
if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
this.cameraDirection.x = 0;
}
if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
this.cameraDirection.y = 0;
}
if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
this.cameraDirection.z = 0;
}
this.cameraDirection.scaleInPlace(this.inertia);
}
if (needToRotate) {
if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
this.cameraRotation.x = 0;
}
if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
this.cameraRotation.y = 0;
}
this.cameraRotation.scaleInPlace(this.inertia);
}
_super.prototype._checkInputs.call(this);
};
TargetCamera.prototype._updateCameraRotationMatrix = function () {
if (this.rotationQuaternion) {
this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
}
else {
BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
}
//update the up vector!
BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
};
TargetCamera.prototype._getViewMatrix = function () {
if (this.lockedTarget) {
this.setTarget(this._getLockedTargetPosition());
}
// Compute
this._updateCameraRotationMatrix();
BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
// Computing target and final matrix
this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
if (this.getScene().useRightHandedSystem) {
BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
}
else {
BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
}
return this._viewMatrix;
};
/**
* @override
* Override Camera.createRigCamera
*/
TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
if (!this.rotationQuaternion) {
this.rotationQuaternion = new BABYLON.Quaternion();
}
rigCamera._cameraRigParams = {};
rigCamera.rotationQuaternion = new BABYLON.Quaternion();
}
return rigCamera;
}
return null;
};
/**
* @override
* Override Camera._updateRigCameras
*/
TargetCamera.prototype._updateRigCameras = function () {
var camLeft = this._rigCameras[0];
var camRight = this._rigCameras[1];
switch (this.cameraRigMode) {
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
//provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
camLeft.setTarget(this.getTarget());
camRight.setTarget(this.getTarget());
break;
case BABYLON.Camera.RIG_MODE_VR:
if (camLeft.rotationQuaternion) {
camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
}
else {
camLeft.rotation.copyFrom(this.rotation);
camRight.rotation.copyFrom(this.rotation);
}
camLeft.position.copyFrom(this.position);
camRight.position.copyFrom(this.position);
break;
}
_super.prototype._updateRigCameras.call(this);
};
TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
if (!this._rigCamTransformMatrix) {
this._rigCamTransformMatrix = new BABYLON.Matrix();
}
var target = this.getTarget();
BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
};
TargetCamera.prototype.getClassName = function () {
return "TargetCamera";
};
__decorate([
BABYLON.serializeAsVector3()
], TargetCamera.prototype, "rotation", void 0);
__decorate([
BABYLON.serialize()
], TargetCamera.prototype, "speed", void 0);
__decorate([
BABYLON.serializeAsMeshReference("lockedTargetId")
], TargetCamera.prototype, "lockedTarget", void 0);
return TargetCamera;
}(BABYLON.Camera));
BABYLON.TargetCamera = TargetCamera;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.targetCamera.js.map
var BABYLON;
(function (BABYLON) {
var FreeCamera = /** @class */ (function (_super) {
__extends(FreeCamera, _super);
function FreeCamera(name, position, scene) {
var _this = _super.call(this, name, position, scene) || this;
_this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
_this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
_this.checkCollisions = false;
_this.applyGravity = false;
_this._needMoveForGravity = false;
_this._oldPosition = BABYLON.Vector3.Zero();
_this._diffPosition = BABYLON.Vector3.Zero();
_this._newPosition = BABYLON.Vector3.Zero();
// Collisions
_this._collisionMask = -1;
_this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
if (collidedMesh === void 0) { collidedMesh = null; }
//TODO move this to the collision coordinator!
if (_this.getScene().workerCollisions)
newPosition.multiplyInPlace(_this._collider._radius);
var updatePosition = function (newPos) {
_this._newPosition.copyFrom(newPos);
_this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
_this.position.addInPlace(_this._diffPosition);
if (_this.onCollide && collidedMesh) {
_this.onCollide(collidedMesh);
}
}
};
updatePosition(newPosition);
};
_this.inputs = new BABYLON.FreeCameraInputsManager(_this);
_this.inputs.addKeyboard().addMouse();
return _this;
}
Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
//-- begin properties for backward compatibility for inputs
get: function () {
var mouse = this.inputs.attached["mouse"];
if (mouse)
return mouse.angularSensibility;
return 0;
},
set: function (value) {
var mouse = this.inputs.attached["mouse"];
if (mouse)
mouse.angularSensibility = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FreeCamera.prototype, "keysUp", {
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
return keyboard.keysUp;
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
keyboard.keysUp = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FreeCamera.prototype, "keysDown", {
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
return keyboard.keysDown;
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
keyboard.keysDown = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FreeCamera.prototype, "keysLeft", {
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
return keyboard.keysLeft;
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
keyboard.keysLeft = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FreeCamera.prototype, "keysRight", {
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
return keyboard.keysRight;
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
keyboard.keysRight = value;
},
enumerable: true,
configurable: true
});
// Controls
FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
this.inputs.attachElement(element, noPreventDefault);
};
FreeCamera.prototype.detachControl = function (element) {
this.inputs.detachElement(element);
this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
this.cameraRotation = new BABYLON.Vector2(0, 0);
};
Object.defineProperty(FreeCamera.prototype, "collisionMask", {
get: function () {
return this._collisionMask;
},
set: function (mask) {
this._collisionMask = !isNaN(mask) ? mask : -1;
},
enumerable: true,
configurable: true
});
FreeCamera.prototype._collideWithWorld = function (displacement) {
var globalPosition;
if (this.parent) {
globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
}
else {
globalPosition = this.position;
}
globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
this._oldPosition.addInPlace(this.ellipsoidOffset);
if (!this._collider) {
this._collider = new BABYLON.Collider();
}
this._collider._radius = this.ellipsoid;
this._collider.collisionMask = this._collisionMask;
//no need for clone, as long as gravity is not on.
var actualDisplacement = displacement;
//add gravity to the direction to prevent the dual-collision checking
if (this.applyGravity) {
//this prevents mending with cameraDirection, a global variable of the free camera class.
actualDisplacement = displacement.add(this.getScene().gravity);
}
this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
};
FreeCamera.prototype._checkInputs = function () {
if (!this._localDirection) {
this._localDirection = BABYLON.Vector3.Zero();
this._transformedDirection = BABYLON.Vector3.Zero();
}
this.inputs.checkInputs();
_super.prototype._checkInputs.call(this);
};
FreeCamera.prototype._decideIfNeedsToMove = function () {
return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
};
FreeCamera.prototype._updatePosition = function () {
if (this.checkCollisions && this.getScene().collisionsEnabled) {
this._collideWithWorld(this.cameraDirection);
}
else {
_super.prototype._updatePosition.call(this);
}
};
FreeCamera.prototype.dispose = function () {
this.inputs.clear();
_super.prototype.dispose.call(this);
};
FreeCamera.prototype.getClassName = function () {
return "FreeCamera";
};
__decorate([
BABYLON.serializeAsVector3()
], FreeCamera.prototype, "ellipsoid", void 0);
__decorate([
BABYLON.serializeAsVector3()
], FreeCamera.prototype, "ellipsoidOffset", void 0);
__decorate([
BABYLON.serialize()
], FreeCamera.prototype, "checkCollisions", void 0);
__decorate([
BABYLON.serialize()
], FreeCamera.prototype, "applyGravity", void 0);
return FreeCamera;
}(BABYLON.TargetCamera));
BABYLON.FreeCamera = FreeCamera;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.freeCamera.js.map
var BABYLON;
(function (BABYLON) {
var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
function ArcRotateCameraKeyboardMoveInput() {
this._keys = new Array();
this.keysUp = [38];
this.keysDown = [40];
this.keysLeft = [37];
this.keysRight = [39];
this.keysReset = [220];
this.panningSensibility = 50.0;
this.zoomingSensibility = 25.0;
this.useAltToZoom = true;
}
ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
var _this = this;
if (this._onCanvasBlurObserver) {
return;
}
this._scene = this.camera.getScene();
this._engine = this._scene.getEngine();
this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
_this._keys = [];
});
this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
var evt = info.event;
if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
_this._ctrlPressed = evt.ctrlKey;
_this._altPressed = evt.altKey;
if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
_this.keysDown.indexOf(evt.keyCode) !== -1 ||
_this.keysLeft.indexOf(evt.keyCode) !== -1 ||
_this.keysRight.indexOf(evt.keyCode) !== -1 ||
_this.keysReset.indexOf(evt.keyCode) !== -1) {
var index = _this._keys.indexOf(evt.keyCode);
if (index === -1) {
_this._keys.push(evt.keyCode);
}
if (evt.preventDefault) {
if (!noPreventDefault) {
evt.preventDefault();
}
}
}
}
else {
if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
_this.keysDown.indexOf(evt.keyCode) !== -1 ||
_this.keysLeft.indexOf(evt.keyCode) !== -1 ||
_this.keysRight.indexOf(evt.keyCode) !== -1 ||
_this.keysReset.indexOf(evt.keyCode) !== -1) {
var index = _this._keys.indexOf(evt.keyCode);
if (index >= 0) {
_this._keys.splice(index, 1);
}
if (evt.preventDefault) {
if (!noPreventDefault) {
evt.preventDefault();
}
}
}
}
});
};
ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
if (this._scene) {
if (this._onKeyboardObserver) {
this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
}
if (this._onCanvasBlurObserver) {
this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
}
this._onKeyboardObserver = null;
this._onCanvasBlurObserver = null;
}
this._keys = [];
};
ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
if (this._onKeyboardObserver) {
var camera = this.camera;
for (var index = 0; index < this._keys.length; index++) {
var keyCode = this._keys[index];
if (this.keysLeft.indexOf(keyCode) !== -1) {
if (this._ctrlPressed && this.camera._useCtrlForPanning) {
camera.inertialPanningX -= 1 / this.panningSensibility;
}
else {
camera.inertialAlphaOffset -= 0.01;
}
}
else if (this.keysUp.indexOf(keyCode) !== -1) {
if (this._ctrlPressed && this.camera._useCtrlForPanning) {
camera.inertialPanningY += 1 / this.panningSensibility;
}
else if (this._altPressed && this.useAltToZoom) {
camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
}
else {
camera.inertialBetaOffset -= 0.01;
}
}
else if (this.keysRight.indexOf(keyCode) !== -1) {
if (this._ctrlPressed && this.camera._useCtrlForPanning) {
camera.inertialPanningX += 1 / this.panningSensibility;
}
else {
camera.inertialAlphaOffset += 0.01;
}
}
else if (this.keysDown.indexOf(keyCode) !== -1) {
if (this._ctrlPressed && this.camera._useCtrlForPanning) {
camera.inertialPanningY -= 1 / this.panningSensibility;
}
else if (this._altPressed && this.useAltToZoom) {
camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
}
else {
camera.inertialBetaOffset += 0.01;
}
}
else if (this.keysReset.indexOf(keyCode) !== -1) {
camera.restoreState();
}
}
}
};
ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
return "ArcRotateCameraKeyboardMoveInput";
};
ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
return "keyboard";
};
__decorate([
BABYLON.serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
return ArcRotateCameraKeyboardMoveInput;
}());
BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
var BABYLON;
(function (BABYLON) {
var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
function ArcRotateCameraMouseWheelInput() {
this.wheelPrecision = 3.0;
/**
* wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
* It defines the percentage of current camera.radius to use as delta when wheel is used.
*/
this.wheelDeltaPercentage = 0;
}
ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
var _this = this;
this._wheel = function (p, s) {
//sanity check - this should be a PointerWheel event.
if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
return;
var event = p.event;
var delta = 0;
if (event.wheelDelta) {
delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
}
else if (event.detail) {
delta = -event.detail / _this.wheelPrecision;
}
if (delta)
_this.camera.inertialRadiusOffset += delta;
if (event.preventDefault) {
if (!noPreventDefault) {
event.preventDefault();
}
}
};
this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
};
ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
if (this._observer && element) {
this.camera.getScene().onPointerObservable.remove(this._observer);
this._observer = null;
this._wheel = null;
}
};
ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
return "ArcRotateCameraMouseWheelInput";
};
ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
return "mousewheel";
};
__decorate([
BABYLON.serialize()
], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
return ArcRotateCameraMouseWheelInput;
}());
BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
var BABYLON;
(function (BABYLON) {
var ArcRotateCameraPointersInput = /** @class */ (function () {
function ArcRotateCameraPointersInput() {
this.buttons = [0, 1, 2];
this.angularSensibilityX = 1000.0;
this.angularSensibilityY = 1000.0;
this.pinchPrecision = 12.0;
/**
* pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
* It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
*/
this.pinchDeltaPercentage = 0;
this.panningSensibility = 1000.0;
this.multiTouchPanning = true;
this.multiTouchPanAndZoom = true;
this._isPanClick = false;
this.pinchInwards = true;
}
ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
var _this = this;
var engine = this.camera.getEngine();
var cacheSoloPointer; // cache pointer object for better perf on camera rotation
var pointA = null;
var pointB = null;
var previousPinchSquaredDistance = 0;
var initialDistance = 0;
var twoFingerActivityCount = 0;
var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
this._pointerInput = function (p, s) {
var evt = p.event;
var isTouch = p.event.pointerType === "touch";
if (engine.isInVRExclusivePointerMode) {
return;
}
if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
return;
}
var srcElement = (evt.srcElement || evt.target);
if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
try {
srcElement.setPointerCapture(evt.pointerId);
}
catch (e) {
//Nothing to do with the error. Execution will continue.
}
// Manage panning with pan button click
_this._isPanClick = evt.button === _this.camera._panningMouseButton;
// manage pointers
cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
if (pointA === null) {
pointA = cacheSoloPointer;
}
else if (pointB === null) {
pointB = cacheSoloPointer;
}
if (!noPreventDefault) {
evt.preventDefault();
element.focus();
}
}
else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
_this.camera.restoreState();
}
else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
try {
srcElement.releasePointerCapture(evt.pointerId);
}
catch (e) {
//Nothing to do with the error.
}
cacheSoloPointer = null;
previousPinchSquaredDistance = 0;
previousMultiTouchPanPosition.isPaning = false;
previousMultiTouchPanPosition.isPinching = false;
twoFingerActivityCount = 0;
initialDistance = 0;
if (!isTouch) {
pointB = null; // Mouse and pen are mono pointer
}
//would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
//but emptying completly pointers collection is required to fix a bug on iPhone :
//when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
//will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
if (engine.badOS) {
pointA = pointB = null;
}
else {
//only remove the impacted pointer in case of multitouch allowing on most
//platforms switching from rotate to zoom and pan seamlessly.
if (pointB && pointA && pointA.pointerId == evt.pointerId) {
pointA = pointB;
pointB = null;
cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
}
else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
pointB = null;
cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
}
else {
pointA = pointB = null;
}
}
if (!noPreventDefault) {
evt.preventDefault();
}
}
else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
if (!noPreventDefault) {
evt.preventDefault();
}
// One button down
if (pointA && pointB === null && cacheSoloPointer) {
if (_this.panningSensibility !== 0 &&
((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
_this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
_this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
}
else {
var offsetX = evt.clientX - cacheSoloPointer.x;
var offsetY = evt.clientY - cacheSoloPointer.y;
_this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
_this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
}
cacheSoloPointer.x = evt.clientX;
cacheSoloPointer.y = evt.clientY;
}
else if (pointA && pointB) {
//if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
ed.x = evt.clientX;
ed.y = evt.clientY;
var direction = _this.pinchInwards ? 1 : -1;
var distX = pointA.x - pointB.x;
var distY = pointA.y - pointB.y;
var pinchSquaredDistance = (distX * distX) + (distY * distY);
var pinchDistance = Math.sqrt(pinchSquaredDistance);
if (previousPinchSquaredDistance === 0) {
initialDistance = pinchDistance;
previousPinchSquaredDistance = pinchSquaredDistance;
previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
return;
}
if (_this.multiTouchPanAndZoom) {
if (_this.pinchDeltaPercentage) {
_this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
}
else {
_this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
(_this.pinchPrecision *
((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
direction);
}
if (_this.panningSensibility !== 0) {
var pointersCenterX = (pointA.x + pointB.x) / 2;
var pointersCenterY = (pointA.y + pointB.y) / 2;
var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
previousMultiTouchPanPosition.x = pointersCenterX;
previousMultiTouchPanPosition.y = pointersCenterY;
_this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
_this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
}
}
else {
twoFingerActivityCount++;
if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
if (_this.pinchDeltaPercentage) {
_this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
}
else {
_this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
(_this.pinchPrecision *
((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
direction);
}
previousMultiTouchPanPosition.isPaning = false;
previousMultiTouchPanPosition.isPinching = true;
}
else {
if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
if (!previousMultiTouchPanPosition.isPaning) {
previousMultiTouchPanPosition.isPaning = true;
previousMultiTouchPanPosition.isPinching = false;
previousMultiTouchPanPosition.x = ed.x;
previousMultiTouchPanPosition.y = ed.y;
return;
}
_this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
_this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
}
}
if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
previousMultiTouchPanPosition.x = ed.x;
previousMultiTouchPanPosition.y = ed.y;
}
}
previousPinchSquaredDistance = pinchSquaredDistance;
}
}
};
this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
this._onContextMenu = function (evt) {
evt.preventDefault();
};
if (!this.camera._useCtrlForPanning) {
element.addEventListener("contextmenu", this._onContextMenu, false);
}
this._onLostFocus = function () {
//this._keys = [];
pointA = pointB = null;
previousPinchSquaredDistance = 0;
previousMultiTouchPanPosition.isPaning = false;
previousMultiTouchPanPosition.isPinching = false;
twoFingerActivityCount = 0;
cacheSoloPointer = null;
initialDistance = 0;
};
this._onMouseMove = function (evt) {
if (!engine.isPointerLock) {
return;
}
var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
_this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
_this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
if (!noPreventDefault) {
evt.preventDefault();
}
};
this._onGestureStart = function (e) {
if (window.MSGesture === undefined) {
return;
}
if (!_this._MSGestureHandler) {
_this._MSGestureHandler = new MSGesture();
_this._MSGestureHandler.target = element;
}
_this._MSGestureHandler.addPointer(e.pointerId);
};
this._onGesture = function (e) {
_this.camera.radius *= e.scale;
if (e.preventDefault) {
if (!noPreventDefault) {
e.stopPropagation();
e.preventDefault();
}
}
};
element.addEventListener("mousemove", this._onMouseMove, false);
element.addEventListener("MSPointerDown", this._onGestureStart, false);
element.addEventListener("MSGestureChange", this._onGesture, false);
BABYLON.Tools.RegisterTopRootEvents([
{ name: "blur", handler: this._onLostFocus }
]);
};
ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
if (this._onLostFocus) {
BABYLON.Tools.UnregisterTopRootEvents([
{ name: "blur", handler: this._onLostFocus }
]);
}
if (element && this._observer) {
this.camera.getScene().onPointerObservable.remove(this._observer);
this._observer = null;
if (this._onContextMenu) {
element.removeEventListener("contextmenu", this._onContextMenu);
}
if (this._onMouseMove) {
element.removeEventListener("mousemove", this._onMouseMove);
}
if (this._onGestureStart) {
element.removeEventListener("MSPointerDown", this._onGestureStart);
}
if (this._onGesture) {
element.removeEventListener("MSGestureChange", this._onGesture);
}
this._isPanClick = false;
this.pinchInwards = true;
this._onMouseMove = null;
this._onGestureStart = null;
this._onGesture = null;
this._MSGestureHandler = null;
this._onLostFocus = null;
this._onContextMenu = null;
}
};
ArcRotateCameraPointersInput.prototype.getClassName = function () {
return "ArcRotateCameraPointersInput";
};
ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
return "pointers";
};
__decorate([
BABYLON.serialize()
], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
return ArcRotateCameraPointersInput;
}());
BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
var BABYLON;
(function (BABYLON) {
var ArcRotateCamera = /** @class */ (function (_super) {
__extends(ArcRotateCamera, _super);
function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
_this.inertialAlphaOffset = 0;
_this.inertialBetaOffset = 0;
_this.inertialRadiusOffset = 0;
_this.lowerAlphaLimit = null;
_this.upperAlphaLimit = null;
_this.lowerBetaLimit = 0.01;
_this.upperBetaLimit = Math.PI;
_this.lowerRadiusLimit = null;
_this.upperRadiusLimit = null;
_this.inertialPanningX = 0;
_this.inertialPanningY = 0;
_this.pinchToPanMaxDistance = 20;
_this.panningDistanceLimit = null;
_this.panningOriginTarget = BABYLON.Vector3.Zero();
_this.panningInertia = 0.9;
//-- end properties for backward compatibility for inputs
_this.zoomOnFactor = 1;
_this.targetScreenOffset = BABYLON.Vector2.Zero();
_this.allowUpsideDown = true;
_this._viewMatrix = new BABYLON.Matrix();
// Panning
_this.panningAxis = new BABYLON.Vector3(1, 1, 0);
_this.onMeshTargetChangedObservable = new BABYLON.Observable();
_this.checkCollisions = false;
_this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
_this._previousPosition = BABYLON.Vector3.Zero();
_this._collisionVelocity = BABYLON.Vector3.Zero();
_this._newPosition = BABYLON.Vector3.Zero();
_this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
if (collidedMesh === void 0) { collidedMesh = null; }
if (_this.getScene().workerCollisions && _this.checkCollisions) {
newPosition.multiplyInPlace(_this._collider._radius);
}
if (!collidedMesh) {
_this._previousPosition.copyFrom(_this.position);
}
else {
_this.setPosition(newPosition);
if (_this.onCollide) {
_this.onCollide(collidedMesh);
}
}
// Recompute because of constraints
var cosa = Math.cos(_this.alpha);
var sina = Math.sin(_this.alpha);
var cosb = Math.cos(_this.beta);
var sinb = Math.sin(_this.beta);
if (sinb === 0) {
sinb = 0.0001;
}
var target = _this._getTargetPosition();
target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
_this.position.copyFrom(_this._newPosition);
var up = _this.upVector;
if (_this.allowUpsideDown && _this.beta < 0) {
up = up.clone();
up = up.negate();
}
BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
_this._viewMatrix.m[12] += _this.targetScreenOffset.x;
_this._viewMatrix.m[13] += _this.targetScreenOffset.y;
_this._collisionTriggered = false;
};
_this._target = BABYLON.Vector3.Zero();
if (target) {
_this.setTarget(target);
}
_this.alpha = alpha;
_this.beta = beta;
_this.radius = radius;
_this.getViewMatrix();
_this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
_this.inputs.addKeyboard().addMouseWheel().addPointers();
return _this;
}
Object.defineProperty(ArcRotateCamera.prototype, "target", {
get: function () {
return this._target;
},
set: function (value) {
this.setTarget(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
//-- begin properties for backward compatibility for inputs
get: function () {
var pointers = this.inputs.attached["pointers"];
if (pointers)
return pointers.angularSensibilityX;
return 0;
},
set: function (value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.angularSensibilityX = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
get: function () {
var pointers = this.inputs.attached["pointers"];
if (pointers)
return pointers.angularSensibilityY;
return 0;
},
set: function (value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.angularSensibilityY = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
get: function () {
var pointers = this.inputs.attached["pointers"];
if (pointers)
return pointers.pinchPrecision;
return 0;
},
set: function (value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.pinchPrecision = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
get: function () {
var pointers = this.inputs.attached["pointers"];
if (pointers)
return pointers.pinchDeltaPercentage;
return 0;
},
set: function (value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.pinchDeltaPercentage = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
get: function () {
var pointers = this.inputs.attached["pointers"];
if (pointers)
return pointers.panningSensibility;
return 0;
},
set: function (value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.panningSensibility = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
return keyboard.keysUp;
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
keyboard.keysUp = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
return keyboard.keysDown;
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
keyboard.keysDown = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
return keyboard.keysLeft;
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
keyboard.keysLeft = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
return keyboard.keysRight;
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard)
keyboard.keysRight = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
get: function () {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel)
return mousewheel.wheelPrecision;
return 0;
},
set: function (value) {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel)
mousewheel.wheelPrecision = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
get: function () {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel)
return mousewheel.wheelDeltaPercentage;
return 0;
},
set: function (value) {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel)
mousewheel.wheelDeltaPercentage = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
get: function () {
return this._bouncingBehavior;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
get: function () {
return this._bouncingBehavior != null;
},
set: function (value) {
if (value === this.useBouncingBehavior) {
return;
}
if (value) {
this._bouncingBehavior = new BABYLON.BouncingBehavior();
this.addBehavior(this._bouncingBehavior);
}
else if (this._bouncingBehavior) {
this.removeBehavior(this._bouncingBehavior);
this._bouncingBehavior = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
get: function () {
return this._framingBehavior;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
get: function () {
return this._framingBehavior != null;
},
set: function (value) {
if (value === this.useFramingBehavior) {
return;
}
if (value) {
this._framingBehavior = new BABYLON.FramingBehavior();
this.addBehavior(this._framingBehavior);
}
else if (this._framingBehavior) {
this.removeBehavior(this._framingBehavior);
this._framingBehavior = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
get: function () {
return this._autoRotationBehavior;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
get: function () {
return this._autoRotationBehavior != null;
},
set: function (value) {
if (value === this.useAutoRotationBehavior) {
return;
}
if (value) {
this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
this.addBehavior(this._autoRotationBehavior);
}
else if (this._autoRotationBehavior) {
this.removeBehavior(this._autoRotationBehavior);
this._autoRotationBehavior = null;
}
},
enumerable: true,
configurable: true
});
// Cache
ArcRotateCamera.prototype._initCache = function () {
_super.prototype._initCache.call(this);
this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.alpha = undefined;
this._cache.beta = undefined;
this._cache.radius = undefined;
this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
};
ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
if (!ignoreParentClass) {
_super.prototype._updateCache.call(this);
}
this._cache._target.copyFrom(this._getTargetPosition());
this._cache.alpha = this.alpha;
this._cache.beta = this.beta;
this._cache.radius = this.radius;
this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
};
ArcRotateCamera.prototype._getTargetPosition = function () {
if (this._targetHost && this._targetHost.getAbsolutePosition) {
var pos = this._targetHost.getAbsolutePosition();
if (this._targetBoundingCenter) {
pos.addToRef(this._targetBoundingCenter, this._target);
}
else {
this._target.copyFrom(pos);
}
}
var lockedTargetPosition = this._getLockedTargetPosition();
if (lockedTargetPosition) {
return lockedTargetPosition;
}
return this._target;
};
ArcRotateCamera.prototype.storeState = function () {
this._storedAlpha = this.alpha;
this._storedBeta = this.beta;
this._storedRadius = this.radius;
this._storedTarget = this._getTargetPosition().clone();
return _super.prototype.storeState.call(this);
};
/**
* Restored camera state. You must call storeState() first
*/
ArcRotateCamera.prototype._restoreStateValues = function () {
if (!_super.prototype._restoreStateValues.call(this)) {
return false;
}
this.alpha = this._storedAlpha;
this.beta = this._storedBeta;
this.radius = this._storedRadius;
this.setTarget(this._storedTarget.clone());
this.inertialAlphaOffset = 0;
this.inertialBetaOffset = 0;
this.inertialRadiusOffset = 0;
this.inertialPanningX = 0;
this.inertialPanningY = 0;
return true;
};
// Synchronized
ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
if (!_super.prototype._isSynchronizedViewMatrix.call(this))
return false;
return this._cache._target.equals(this._getTargetPosition())
&& this._cache.alpha === this.alpha
&& this._cache.beta === this.beta
&& this._cache.radius === this.radius
&& this._cache.targetScreenOffset.equals(this.targetScreenOffset);
};
// Methods
ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
var _this = this;
if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
if (panningMouseButton === void 0) { panningMouseButton = 2; }
this._useCtrlForPanning = useCtrlForPanning;
this._panningMouseButton = panningMouseButton;
this.inputs.attachElement(element, noPreventDefault);
this._reset = function () {
_this.inertialAlphaOffset = 0;
_this.inertialBetaOffset = 0;
_this.inertialRadiusOffset = 0;
_this.inertialPanningX = 0;
_this.inertialPanningY = 0;
};
};
ArcRotateCamera.prototype.detachControl = function (element) {
this.inputs.detachElement(element);
if (this._reset) {
this._reset();
}
};
ArcRotateCamera.prototype._checkInputs = function () {
//if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
if (this._collisionTriggered) {
return;
}
this.inputs.checkInputs();
// Inertia
if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
if (this.getScene().useRightHandedSystem) {
this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
}
else {
this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
}
this.beta += this.inertialBetaOffset;
this.radius -= this.inertialRadiusOffset;
this.inertialAlphaOffset *= this.inertia;
this.inertialBetaOffset *= this.inertia;
this.inertialRadiusOffset *= this.inertia;
if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
this.inertialAlphaOffset = 0;
if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
this.inertialBetaOffset = 0;
if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
this.inertialRadiusOffset = 0;
}
// Panning inertia
if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
if (!this._localDirection) {
this._localDirection = BABYLON.Vector3.Zero();
this._transformedDirection = BABYLON.Vector3.Zero();
}
this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
this._localDirection.multiplyInPlace(this.panningAxis);
this._viewMatrix.invertToRef(this._cameraTransformMatrix);
BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
//Eliminate y if map panning is enabled (panningAxis == 1,0,1)
if (!this.panningAxis.y) {
this._transformedDirection.y = 0;
}
if (!this._targetHost) {
if (this.panningDistanceLimit) {
this._transformedDirection.addInPlace(this._target);
var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
this._target.copyFrom(this._transformedDirection);
}
}
else {
this._target.addInPlace(this._transformedDirection);
}
}
this.inertialPanningX *= this.panningInertia;
this.inertialPanningY *= this.panningInertia;
if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
this.inertialPanningX = 0;
if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
this.inertialPanningY = 0;
}
// Limits
this._checkLimits();
_super.prototype._checkInputs.call(this);
};
ArcRotateCamera.prototype._checkLimits = function () {
if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
if (this.allowUpsideDown && this.beta > Math.PI) {
this.beta = this.beta - (2 * Math.PI);
}
}
else {
if (this.beta < this.lowerBetaLimit) {
this.beta = this.lowerBetaLimit;
}
}
if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
if (this.allowUpsideDown && this.beta < -Math.PI) {
this.beta = this.beta + (2 * Math.PI);
}
}
else {
if (this.beta > this.upperBetaLimit) {
this.beta = this.upperBetaLimit;
}
}
if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
this.alpha = this.lowerAlphaLimit;
}
if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
this.alpha = this.upperAlphaLimit;
}
if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
this.radius = this.lowerRadiusLimit;
}
if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
this.radius = this.upperRadiusLimit;
}
};
ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
var radiusv3 = this.position.subtract(this._getTargetPosition());
this.radius = radiusv3.length();
if (this.radius === 0) {
this.radius = 0.0001; // Just to avoid division by zero
}
// Alpha
this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
if (radiusv3.z < 0) {
this.alpha = 2 * Math.PI - this.alpha;
}
// Beta
this.beta = Math.acos(radiusv3.y / this.radius);
this._checkLimits();
};
ArcRotateCamera.prototype.setPosition = function (position) {
if (this.position.equals(position)) {
return;
}
this.position.copyFrom(position);
this.rebuildAnglesAndRadius();
};
ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
if (toBoundingCenter === void 0) { toBoundingCenter = false; }
if (allowSamePosition === void 0) { allowSamePosition = false; }
if (target.getBoundingInfo) {
if (toBoundingCenter) {
this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
}
else {
this._targetBoundingCenter = null;
}
this._targetHost = target;
this._target = this._getTargetPosition();
this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
}
else {
var newTarget = target;
var currentTarget = this._getTargetPosition();
if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
return;
}
this._targetHost = null;
this._target = newTarget;
this._targetBoundingCenter = null;
this.onMeshTargetChangedObservable.notifyObservers(null);
}
this.rebuildAnglesAndRadius();
};
ArcRotateCamera.prototype._getViewMatrix = function () {
// Compute
var cosa = Math.cos(this.alpha);
var sina = Math.sin(this.alpha);
var cosb = Math.cos(this.beta);
var sinb = Math.sin(this.beta);
if (sinb === 0) {
sinb = 0.0001;
}
var target = this._getTargetPosition();
target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
if (this.getScene().collisionsEnabled && this.checkCollisions) {
if (!this._collider) {
this._collider = new BABYLON.Collider();
}
this._collider._radius = this.collisionRadius;
this._newPosition.subtractToRef(this.position, this._collisionVelocity);
this._collisionTriggered = true;
this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
}
else {
this.position.copyFrom(this._newPosition);
var up = this.upVector;
if (this.allowUpsideDown && sinb < 0) {
up = up.clone();
up = up.negate();
}
if (this.getScene().useRightHandedSystem) {
BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
}
else {
BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
}
this._viewMatrix.m[12] += this.targetScreenOffset.x;
this._viewMatrix.m[13] += this.targetScreenOffset.y;
}
this._currentTarget = target;
return this._viewMatrix;
};
ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
meshes = meshes || this.getScene().meshes;
var minMaxVector = BABYLON.Mesh.MinMax(meshes);
var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
this.radius = distance * this.zoomOnFactor;
this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
};
ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
var meshesOrMinMaxVector;
var distance;
if (meshesOrMinMaxVectorAndDistance.min === undefined) {
var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
}
else {
var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
meshesOrMinMaxVector = minMaxVectorAndDistance;
distance = minMaxVectorAndDistance.distance;
}
this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
if (!doNotUpdateMaxZ) {
this.maxZ = distance * 2;
}
};
/**
* @override
* Override Camera.createRigCamera
*/
ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
var alphaShift = 0;
switch (this.cameraRigMode) {
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
case BABYLON.Camera.RIG_MODE_VR:
alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
break;
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
break;
}
var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
rigCam._cameraRigParams = {};
return rigCam;
};
/**
* @override
* Override Camera._updateRigCameras
*/
ArcRotateCamera.prototype._updateRigCameras = function () {
var camLeft = this._rigCameras[0];
var camRight = this._rigCameras[1];
camLeft.beta = camRight.beta = this.beta;
camLeft.radius = camRight.radius = this.radius;
switch (this.cameraRigMode) {
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
case BABYLON.Camera.RIG_MODE_VR:
camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
break;
case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
break;
}
_super.prototype._updateRigCameras.call(this);
};
ArcRotateCamera.prototype.dispose = function () {
this.inputs.clear();
_super.prototype.dispose.call(this);
};
ArcRotateCamera.prototype.getClassName = function () {
return "ArcRotateCamera";
};
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "alpha", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "beta", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "radius", void 0);
__decorate([
BABYLON.serializeAsVector3("target")
], ArcRotateCamera.prototype, "_target", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "inertialPanningX", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "inertialPanningY", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
__decorate([
BABYLON.serializeAsVector3()
], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "panningInertia", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
__decorate([
BABYLON.serialize()
], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
return ArcRotateCamera;
}(BABYLON.TargetCamera));
BABYLON.ArcRotateCamera = ArcRotateCamera;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.arcRotateCamera.js.map
var BABYLON;
(function (BABYLON) {
var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
__extends(ArcRotateCameraInputsManager, _super);
function ArcRotateCameraInputsManager(camera) {
return _super.call(this, camera) || this;
}
ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
return this;
};
ArcRotateCameraInputsManager.prototype.addPointers = function () {
this.add(new BABYLON.ArcRotateCameraPointersInput());
return this;
};
ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
return this;
};
ArcRotateCameraInputsManager.prototype.addGamepad = function () {
this.add(new BABYLON.ArcRotateCameraGamepadInput());
return this;
};
ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
return this;
};
return ArcRotateCameraInputsManager;
}(BABYLON.CameraInputsManager));
BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
var BABYLON;
(function (BABYLON) {
var HemisphericLight = /** @class */ (function (_super) {
__extends(HemisphericLight, _super);
/**
* Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
* The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
* The HemisphericLight can't cast shadows.
* Documentation : http://doc.babylonjs.com/tutorials/lights
*/
function HemisphericLight(name, direction, scene) {
var _this = _super.call(this, name, scene) || this;
_this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
_this.direction = direction || BABYLON.Vector3.Up();
return _this;
}
HemisphericLight.prototype._buildUniformLayout = function () {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 3);
this._uniformBuffer.addUniform("vLightGround", 3);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
/**
* Returns the string "HemisphericLight".
*/
HemisphericLight.prototype.getClassName = function () {
return "HemisphericLight";
};
/**
* Sets the HemisphericLight direction towards the passed target (Vector3).
* Returns the updated direction.
*/
HemisphericLight.prototype.setDirectionToTarget = function (target) {
this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
return this.direction;
};
HemisphericLight.prototype.getShadowGenerator = function () {
return null;
};
/**
* Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
* Returns the HemisphericLight.
*/
HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
return this;
};
HemisphericLight.prototype._getWorldMatrix = function () {
if (!this._worldMatrix) {
this._worldMatrix = BABYLON.Matrix.Identity();
}
return this._worldMatrix;
};
/**
* Returns the integer 3.
*/
HemisphericLight.prototype.getTypeID = function () {
return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
};
__decorate([
BABYLON.serializeAsColor3()
], HemisphericLight.prototype, "groundColor", void 0);
__decorate([
BABYLON.serializeAsVector3()
], HemisphericLight.prototype, "direction", void 0);
return HemisphericLight;
}(BABYLON.Light));
BABYLON.HemisphericLight = HemisphericLight;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.hemisphericLight.js.map
var BABYLON;
(function (BABYLON) {
var ShadowLight = /** @class */ (function (_super) {
__extends(ShadowLight, _super);
function ShadowLight() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._needProjectionMatrixCompute = true;
return _this;
}
Object.defineProperty(ShadowLight.prototype, "direction", {
get: function () {
return this._direction;
},
set: function (value) {
this._direction = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
get: function () {
return this._shadowMinZ;
},
set: function (value) {
this._shadowMinZ = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
get: function () {
return this._shadowMaxZ;
},
set: function (value) {
this._shadowMaxZ = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
/**
* Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
*/
ShadowLight.prototype.computeTransformedInformation = function () {
if (this.parent && this.parent.getWorldMatrix) {
if (!this.transformedPosition) {
this.transformedPosition = BABYLON.Vector3.Zero();
}
BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
// In case the direction is present.
if (this.direction) {
if (!this.transformedDirection) {
this.transformedDirection = BABYLON.Vector3.Zero();
}
BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
}
return true;
}
return false;
};
/**
* Return the depth scale used for the shadow map.
*/
ShadowLight.prototype.getDepthScale = function () {
return 50.0;
};
/**
* Returns the light direction (Vector3) for any passed face index.
*/
ShadowLight.prototype.getShadowDirection = function (faceIndex) {
return this.transformedDirection ? this.transformedDirection : this.direction;
};
/**
* Returns the DirectionalLight absolute position in the World.
*/
ShadowLight.prototype.getAbsolutePosition = function () {
return this.transformedPosition ? this.transformedPosition : this.position;
};
/**
* Sets the DirectionalLight direction toward the passed target (Vector3).
* Returns the updated DirectionalLight direction (Vector3).
*/
ShadowLight.prototype.setDirectionToTarget = function (target) {
this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
return this.direction;
};
/**
* Returns the light rotation (Vector3).
*/
ShadowLight.prototype.getRotation = function () {
this.direction.normalize();
var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
};
/**
* Boolean : false by default.
*/
ShadowLight.prototype.needCube = function () {
return false;
};
/**
* Specifies wether or not the projection matrix should be recomputed this frame.
*/
ShadowLight.prototype.needProjectionMatrixCompute = function () {
return this._needProjectionMatrixCompute;
};
/**
* Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
*/
ShadowLight.prototype.forceProjectionMatrixCompute = function () {
this._needProjectionMatrixCompute = true;
};
/**
* Get the world matrix of the sahdow lights.
*/
ShadowLight.prototype._getWorldMatrix = function () {
if (!this._worldMatrix) {
this._worldMatrix = BABYLON.Matrix.Identity();
}
BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
return this._worldMatrix;
};
/**
* Gets the minZ used for shadow according to both the scene and the light.
* @param activeCamera
*/
ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
};
/**
* Gets the maxZ used for shadow according to both the scene and the light.
* @param activeCamera
*/
ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
};
/**
* Sets the projection matrix according to the type of light and custom projection matrix definition.
* Returns the light.
*/
ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
if (this.customProjectionMatrixBuilder) {
this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
}
else {
this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
}
return this;
};
__decorate([
BABYLON.serializeAsVector3()
], ShadowLight.prototype, "position", void 0);
__decorate([
BABYLON.serializeAsVector3()
], ShadowLight.prototype, "direction", null);
__decorate([
BABYLON.serialize()
], ShadowLight.prototype, "shadowMinZ", null);
__decorate([
BABYLON.serialize()
], ShadowLight.prototype, "shadowMaxZ", null);
return ShadowLight;
}(BABYLON.Light));
BABYLON.ShadowLight = ShadowLight;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.shadowLight.js.map
var BABYLON;
(function (BABYLON) {
var PointLight = /** @class */ (function (_super) {
__extends(PointLight, _super);
/**
* Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
* A PointLight emits the light in every direction.
* It can cast shadows.
* If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
* ```javascript
* var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
* ```
* Documentation : http://doc.babylonjs.com/tutorials/lights
*/
function PointLight(name, position, scene) {
var _this = _super.call(this, name, scene) || this;
_this._shadowAngle = Math.PI / 2;
_this.position = position;
return _this;
}
Object.defineProperty(PointLight.prototype, "shadowAngle", {
/**
* Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
* This specifies what angle the shadow will use to be created.
*
* It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
*/
get: function () {
return this._shadowAngle;
},
/**
* Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
* This specifies what angle the shadow will use to be created.
*
* It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
*/
set: function (value) {
this._shadowAngle = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
Object.defineProperty(PointLight.prototype, "direction", {
get: function () {
return this._direction;
},
/**
* In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
*/
set: function (value) {
var previousNeedCube = this.needCube();
this._direction = value;
if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
this._shadowGenerator.recreateShadowMap();
}
},
enumerable: true,
configurable: true
});
/**
* Returns the string "PointLight"
*/
PointLight.prototype.getClassName = function () {
return "PointLight";
};
/**
* Returns the integer 0.
*/
PointLight.prototype.getTypeID = function () {
return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
};
/**
* Specifies wether or not the shadowmap should be a cube texture.
*/
PointLight.prototype.needCube = function () {
return !this.direction;
};
/**
* Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
*/
PointLight.prototype.getShadowDirection = function (faceIndex) {
if (this.direction) {
return _super.prototype.getShadowDirection.call(this, faceIndex);
}
else {
switch (faceIndex) {
case 0:
return new BABYLON.Vector3(1.0, 0.0, 0.0);
case 1:
return new BABYLON.Vector3(-1.0, 0.0, 0.0);
case 2:
return new BABYLON.Vector3(0.0, -1.0, 0.0);
case 3:
return new BABYLON.Vector3(0.0, 1.0, 0.0);
case 4:
return new BABYLON.Vector3(0.0, 0.0, 1.0);
case 5:
return new BABYLON.Vector3(0.0, 0.0, -1.0);
}
}
return BABYLON.Vector3.Zero();
};
/**
* Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
* - fov = PI / 2
* - aspect ratio : 1.0
* - z-near and far equal to the active camera minZ and maxZ.
* Returns the PointLight.
*/
PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
};
PointLight.prototype._buildUniformLayout = function () {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 3);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
/**
* Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
* Returns the PointLight.
*/
PointLight.prototype.transferToEffect = function (effect, lightIndex) {
if (this.computeTransformedInformation()) {
this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
return this;
}
this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
return this;
};
__decorate([
BABYLON.serialize()
], PointLight.prototype, "shadowAngle", null);
return PointLight;
}(BABYLON.ShadowLight));
BABYLON.PointLight = PointLight;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.pointLight.js.map
var BABYLON;
(function (BABYLON) {
var DirectionalLight = /** @class */ (function (_super) {
__extends(DirectionalLight, _super);
/**
* Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
* The directional light is emitted from everywhere in the given direction.
* It can cast shawdows.
* Documentation : http://doc.babylonjs.com/tutorials/lights
*/
function DirectionalLight(name, direction, scene) {
var _this = _super.call(this, name, scene) || this;
_this._shadowFrustumSize = 0;
_this._shadowOrthoScale = 0.5;
_this.autoUpdateExtends = true;
// Cache
_this._orthoLeft = Number.MAX_VALUE;
_this._orthoRight = Number.MIN_VALUE;
_this._orthoTop = Number.MIN_VALUE;
_this._orthoBottom = Number.MAX_VALUE;
_this.position = direction.scale(-1.0);
_this.direction = direction;
return _this;
}
Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
/**
* Fix frustum size for the shadow generation. This is disabled if the value is 0.
*/
get: function () {
return this._shadowFrustumSize;
},
/**
* Specifies a fix frustum size for the shadow generation.
*/
set: function (value) {
this._shadowFrustumSize = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
get: function () {
return this._shadowOrthoScale;
},
set: function (value) {
this._shadowOrthoScale = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
/**
* Returns the string "DirectionalLight".
*/
DirectionalLight.prototype.getClassName = function () {
return "DirectionalLight";
};
/**
* Returns the integer 1.
*/
DirectionalLight.prototype.getTypeID = function () {
return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
};
/**
* Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
* Returns the DirectionalLight Shadow projection matrix.
*/
DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
if (this.shadowFrustumSize > 0) {
this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
}
else {
this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
}
};
/**
* Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
* Returns the DirectionalLight Shadow projection matrix.
*/
DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
};
/**
* Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
* Returns the DirectionalLight Shadow projection matrix.
*/
DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
// Check extends
if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
var tempVector3 = BABYLON.Vector3.Zero();
this._orthoLeft = Number.MAX_VALUE;
this._orthoRight = Number.MIN_VALUE;
this._orthoTop = Number.MIN_VALUE;
this._orthoBottom = Number.MAX_VALUE;
for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
var mesh = renderList[meshIndex];
if (!mesh) {
continue;
}
var boundingInfo = mesh.getBoundingInfo();
var boundingBox = boundingInfo.boundingBox;
for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
if (tempVector3.x < this._orthoLeft)
this._orthoLeft = tempVector3.x;
if (tempVector3.y < this._orthoBottom)
this._orthoBottom = tempVector3.y;
if (tempVector3.x > this._orthoRight)
this._orthoRight = tempVector3.x;
if (tempVector3.y > this._orthoTop)
this._orthoTop = tempVector3.y;
}
}
}
var xOffset = this._orthoRight - this._orthoLeft;
var yOffset = this._orthoTop - this._orthoBottom;
BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
};
DirectionalLight.prototype._buildUniformLayout = function () {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 3);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
/**
* Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
* Returns the DirectionalLight.
*/
DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
if (this.computeTransformedInformation()) {
this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
return this;
}
this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
return this;
};
/**
* Gets the minZ used for shadow according to both the scene and the light.
*
* Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
* -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
* @param activeCamera
*/
DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
return 1;
};
/**
* Gets the maxZ used for shadow according to both the scene and the light.
*
* Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
* -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
* @param activeCamera
*/
DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
return 1;
};
__decorate([
BABYLON.serialize()
], DirectionalLight.prototype, "shadowFrustumSize", null);
__decorate([
BABYLON.serialize()
], DirectionalLight.prototype, "shadowOrthoScale", null);
__decorate([
BABYLON.serialize()
], DirectionalLight.prototype, "autoUpdateExtends", void 0);
return DirectionalLight;
}(BABYLON.ShadowLight));
BABYLON.DirectionalLight = DirectionalLight;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.directionalLight.js.map
var BABYLON;
(function (BABYLON) {
var SpotLight = /** @class */ (function (_super) {
__extends(SpotLight, _super);
/**
* Creates a SpotLight object in the scene with the passed parameters :
* - `position` (Vector3) is the initial SpotLight position,
* - `direction` (Vector3) is the initial SpotLight direction,
* - `angle` (float, in radians) is the spot light cone angle,
* - `exponent` (float) is the light decay speed with the distance from the emission spot.
* A spot light is a simply light oriented cone.
* It can cast shadows.
* Documentation : http://doc.babylonjs.com/tutorials/lights
*/
function SpotLight(name, position, direction, angle, exponent, scene) {
var _this = _super.call(this, name, scene) || this;
_this.position = position;
_this.direction = direction;
_this.angle = angle;
_this.exponent = exponent;
return _this;
}
Object.defineProperty(SpotLight.prototype, "angle", {
get: function () {
return this._angle;
},
set: function (value) {
this._angle = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
get: function () {
return this._shadowAngleScale;
},
/**
* Allows scaling the angle of the light for shadow generation only.
*/
set: function (value) {
this._shadowAngleScale = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
/**
* Returns the string "SpotLight".
*/
SpotLight.prototype.getClassName = function () {
return "SpotLight";
};
/**
* Returns the integer 2.
*/
SpotLight.prototype.getTypeID = function () {
return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
};
/**
* Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
* Returns the SpotLight.
*/
SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
this._shadowAngleScale = this._shadowAngleScale || 1;
var angle = this._shadowAngleScale * this._angle;
BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
};
SpotLight.prototype._buildUniformLayout = function () {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 3);
this._uniformBuffer.addUniform("vLightDirection", 3);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
/**
* Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
* Return the SpotLight.
*/
SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
var normalizeDirection;
if (this.computeTransformedInformation()) {
this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
}
else {
this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
}
this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
return this;
};
__decorate([
BABYLON.serialize()
], SpotLight.prototype, "angle", null);
__decorate([
BABYLON.serialize()
/**
* Allows scaling the angle of the light for shadow generation only.
*/
], SpotLight.prototype, "shadowAngleScale", null);
__decorate([
BABYLON.serialize()
], SpotLight.prototype, "exponent", void 0);
return SpotLight;
}(BABYLON.ShadowLight));
BABYLON.SpotLight = SpotLight;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.spotLight.js.map
var BABYLON;
(function (BABYLON) {
var AnimationRange = /** @class */ (function () {
function AnimationRange(name, from, to) {
this.name = name;
this.from = from;
this.to = to;
}
AnimationRange.prototype.clone = function () {
return new AnimationRange(this.name, this.from, this.to);
};
return AnimationRange;
}());
BABYLON.AnimationRange = AnimationRange;
/**
* Composed of a frame, and an action function
*/
var AnimationEvent = /** @class */ (function () {
function AnimationEvent(frame, action, onlyOnce) {
this.frame = frame;
this.action = action;
this.onlyOnce = onlyOnce;
this.isDone = false;
}
return AnimationEvent;
}());
BABYLON.AnimationEvent = AnimationEvent;
var PathCursor = /** @class */ (function () {
function PathCursor(path) {
this.path = path;
this._onchange = new Array();
this.value = 0;
this.animations = new Array();
}
PathCursor.prototype.getPoint = function () {
var point = this.path.getPointAtLengthPosition(this.value);
return new BABYLON.Vector3(point.x, 0, point.y);
};
PathCursor.prototype.moveAhead = function (step) {
if (step === void 0) { step = 0.002; }
this.move(step);
return this;
};
PathCursor.prototype.moveBack = function (step) {
if (step === void 0) { step = 0.002; }
this.move(-step);
return this;
};
PathCursor.prototype.move = function (step) {
if (Math.abs(step) > 1) {
throw "step size should be less than 1.";
}
this.value += step;
this.ensureLimits();
this.raiseOnChange();
return this;
};
PathCursor.prototype.ensureLimits = function () {
while (this.value > 1) {
this.value -= 1;
}
while (this.value < 0) {
this.value += 1;
}
return this;
};
// used by animation engine
PathCursor.prototype.raiseOnChange = function () {
var _this = this;
this._onchange.forEach(function (f) { return f(_this); });
return this;
};
PathCursor.prototype.onchange = function (f) {
this._onchange.push(f);
return this;
};
return PathCursor;
}());
BABYLON.PathCursor = PathCursor;
var Animation = /** @class */ (function () {
function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
this.name = name;
this.targetProperty = targetProperty;
this.framePerSecond = framePerSecond;
this.dataType = dataType;
this.loopMode = loopMode;
this.enableBlending = enableBlending;
this._runtimeAnimations = new Array();
// The set of event that will be linked to this animation
this._events = new Array();
this.blendingSpeed = 0.01;
this._ranges = {};
this.targetPropertyPath = targetProperty.split(".");
this.dataType = dataType;
this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
}
Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
var dataType = undefined;
if (!isNaN(parseFloat(from)) && isFinite(from)) {
dataType = Animation.ANIMATIONTYPE_FLOAT;
}
else if (from instanceof BABYLON.Quaternion) {
dataType = Animation.ANIMATIONTYPE_QUATERNION;
}
else if (from instanceof BABYLON.Vector3) {
dataType = Animation.ANIMATIONTYPE_VECTOR3;
}
else if (from instanceof BABYLON.Vector2) {
dataType = Animation.ANIMATIONTYPE_VECTOR2;
}
else if (from instanceof BABYLON.Color3) {
dataType = Animation.ANIMATIONTYPE_COLOR3;
}
else if (from instanceof BABYLON.Size) {
dataType = Animation.ANIMATIONTYPE_SIZE;
}
if (dataType == undefined) {
return null;
}
var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
animation.setKeys(keys);
if (easingFunction !== undefined) {
animation.setEasingFunction(easingFunction);
}
return animation;
};
/**
* Sets up an animation.
* @param property the property to animate
* @param animationType the animation type to apply
* @param easingFunction the easing function used in the animation
* @returns The created animation
*/
Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
animation.setEasingFunction(easingFunction);
return animation;
};
Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
if (!animation) {
return null;
}
return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
};
Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
if (!animation) {
return null;
}
node.animations.push(animation);
return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
};
/**
* Transition property of the Camera to the target Value.
* @param property The property to transition
* @param targetValue The target Value of the property
* @param host The object where the property to animate belongs
* @param scene Scene used to run the animation
* @param frameRate Framerate (in frame/s) to use
* @param transition The transition type we want to use
* @param duration The duration of the animation, in milliseconds
* @param onAnimationEnd Call back trigger at the end of the animation.
*/
Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
if (onAnimationEnd === void 0) { onAnimationEnd = null; }
if (duration <= 0) {
host[property] = targetValue;
if (onAnimationEnd) {
onAnimationEnd();
}
return null;
}
var endFrame = frameRate * (duration / 1000);
transition.setKeys([{
frame: 0,
value: host[property].clone ? host[property].clone() : host[property]
},
{
frame: endFrame,
value: targetValue
}]);
if (!host.animations) {
host.animations = [];
}
host.animations.push(transition);
var animation = scene.beginAnimation(host, 0, endFrame, false);
animation.onAnimationEnd = onAnimationEnd;
return animation;
};
Object.defineProperty(Animation.prototype, "runtimeAnimations", {
/**
* Return the array of runtime animations currently using this animation
*/
get: function () {
return this._runtimeAnimations;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
get: function () {
for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
var runtimeAnimation = _a[_i];
if (!runtimeAnimation.isStopped) {
return true;
}
}
return false;
},
enumerable: true,
configurable: true
});
// Methods
/**
* @param {boolean} fullDetails - support for multiple levels of logging within scene loading
*/
Animation.prototype.toString = function (fullDetails) {
var ret = "Name: " + this.name + ", property: " + this.targetProperty;
ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
if (fullDetails) {
ret += ", Ranges: {";
var first = true;
for (var name in this._ranges) {
if (first) {
ret += ", ";
first = false;
}
ret += name;
}
ret += "}";
}
return ret;
};
/**
* Add an event to this animation.
*/
Animation.prototype.addEvent = function (event) {
this._events.push(event);
};
/**
* Remove all events found at the given frame
* @param frame
*/
Animation.prototype.removeEvents = function (frame) {
for (var index = 0; index < this._events.length; index++) {
if (this._events[index].frame === frame) {
this._events.splice(index, 1);
index--;
}
}
};
Animation.prototype.getEvents = function () {
return this._events;
};
Animation.prototype.createRange = function (name, from, to) {
// check name not already in use; could happen for bones after serialized
if (!this._ranges[name]) {
this._ranges[name] = new AnimationRange(name, from, to);
}
};
Animation.prototype.deleteRange = function (name, deleteFrames) {
if (deleteFrames === void 0) { deleteFrames = true; }
var range = this._ranges[name];
if (!range) {
return;
}
if (deleteFrames) {
var from = range.from;
var to = range.to;
// this loop MUST go high to low for multiple splices to work
for (var key = this._keys.length - 1; key >= 0; key--) {
if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
this._keys.splice(key, 1);
}
}
}
this._ranges[name] = null; // said much faster than 'delete this._range[name]'
};
Animation.prototype.getRange = function (name) {
return this._ranges[name];
};
Animation.prototype.getKeys = function () {
return this._keys;
};
Animation.prototype.getHighestFrame = function () {
var ret = 0;
for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
if (ret < this._keys[key].frame) {
ret = this._keys[key].frame;
}
}
return ret;
};
Animation.prototype.getEasingFunction = function () {
return this._easingFunction;
};
Animation.prototype.setEasingFunction = function (easingFunction) {
this._easingFunction = easingFunction;
};
Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
};
Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
};
Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
};
Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
};
Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
};
Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
};
Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
};
Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
};
Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
return BABYLON.Size.Lerp(startValue, endValue, gradient);
};
Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
return BABYLON.Color3.Lerp(startValue, endValue, gradient);
};
Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
};
Animation.prototype.clone = function () {
var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
clone.enableBlending = this.enableBlending;
clone.blendingSpeed = this.blendingSpeed;
if (this._keys) {
clone.setKeys(this._keys);
}
if (this._ranges) {
clone._ranges = {};
for (var name in this._ranges) {
var range = this._ranges[name];
if (!range) {
continue;
}
clone._ranges[name] = range.clone();
}
}
return clone;
};
Animation.prototype.setKeys = function (values) {
this._keys = values.slice(0);
};
Animation.prototype.serialize = function () {
var serializationObject = {};
serializationObject.name = this.name;
serializationObject.property = this.targetProperty;
serializationObject.framePerSecond = this.framePerSecond;
serializationObject.dataType = this.dataType;
serializationObject.loopBehavior = this.loopMode;
serializationObject.enableBlending = this.enableBlending;
serializationObject.blendingSpeed = this.blendingSpeed;
var dataType = this.dataType;
serializationObject.keys = [];
var keys = this.getKeys();
for (var index = 0; index < keys.length; index++) {
var animationKey = keys[index];
var key = {};
key.frame = animationKey.frame;
switch (dataType) {
case Animation.ANIMATIONTYPE_FLOAT:
key.values = [animationKey.value];
break;
case Animation.ANIMATIONTYPE_QUATERNION:
case Animation.ANIMATIONTYPE_MATRIX:
case Animation.ANIMATIONTYPE_VECTOR3:
case Animation.ANIMATIONTYPE_COLOR3:
key.values = animationKey.value.asArray();
break;
}
serializationObject.keys.push(key);
}
serializationObject.ranges = [];
for (var name in this._ranges) {
var source = this._ranges[name];
if (!source) {
continue;
}
var range = {};
range.name = name;
range.from = source.from;
range.to = source.to;
serializationObject.ranges.push(range);
}
return serializationObject;
};
Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
get: function () {
return Animation._ANIMATIONTYPE_FLOAT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
get: function () {
return Animation._ANIMATIONTYPE_VECTOR3;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
get: function () {
return Animation._ANIMATIONTYPE_VECTOR2;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
get: function () {
return Animation._ANIMATIONTYPE_SIZE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
get: function () {
return Animation._ANIMATIONTYPE_QUATERNION;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
get: function () {
return Animation._ANIMATIONTYPE_MATRIX;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
get: function () {
return Animation._ANIMATIONTYPE_COLOR3;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
get: function () {
return Animation._ANIMATIONLOOPMODE_RELATIVE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
get: function () {
return Animation._ANIMATIONLOOPMODE_CYCLE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
get: function () {
return Animation._ANIMATIONLOOPMODE_CONSTANT;
},
enumerable: true,
configurable: true
});
Animation.Parse = function (parsedAnimation) {
var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
var dataType = parsedAnimation.dataType;
var keys = [];
var data;
var index;
if (parsedAnimation.enableBlending) {
animation.enableBlending = parsedAnimation.enableBlending;
}
if (parsedAnimation.blendingSpeed) {
animation.blendingSpeed = parsedAnimation.blendingSpeed;
}
for (index = 0; index < parsedAnimation.keys.length; index++) {
var key = parsedAnimation.keys[index];
var inTangent;
var outTangent;
switch (dataType) {
case Animation.ANIMATIONTYPE_FLOAT:
data = key.values[0];
if (key.values.length >= 1) {
inTangent = key.values[1];
}
if (key.values.length >= 2) {
outTangent = key.values[2];
}
break;
case Animation.ANIMATIONTYPE_QUATERNION:
data = BABYLON.Quaternion.FromArray(key.values);
if (key.values.length >= 8) {
var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
inTangent = _inTangent;
}
}
if (key.values.length >= 12) {
var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
outTangent = _outTangent;
}
}
break;
case Animation.ANIMATIONTYPE_MATRIX:
data = BABYLON.Matrix.FromArray(key.values);
break;
case Animation.ANIMATIONTYPE_COLOR3:
data = BABYLON.Color3.FromArray(key.values);
break;
case Animation.ANIMATIONTYPE_VECTOR3:
default:
data = BABYLON.Vector3.FromArray(key.values);
break;
}
var keyData = {};
keyData.frame = key.frame;
keyData.value = data;
if (inTangent != undefined) {
keyData.inTangent = inTangent;
}
if (outTangent != undefined) {
keyData.outTangent = outTangent;
}
keys.push(keyData);
}
animation.setKeys(keys);
if (parsedAnimation.ranges) {
for (index = 0; index < parsedAnimation.ranges.length; index++) {
data = parsedAnimation.ranges[index];
animation.createRange(data.name, data.from, data.to);
}
}
return animation;
};
Animation.AppendSerializedAnimations = function (source, destination) {
if (source.animations) {
destination.animations = [];
for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
var animation = source.animations[animationIndex];
destination.animations.push(animation.serialize());
}
}
};
Animation.AllowMatricesInterpolation = false;
// Statics
Animation._ANIMATIONTYPE_FLOAT = 0;
Animation._ANIMATIONTYPE_VECTOR3 = 1;
Animation._ANIMATIONTYPE_QUATERNION = 2;
Animation._ANIMATIONTYPE_MATRIX = 3;
Animation._ANIMATIONTYPE_COLOR3 = 4;
Animation._ANIMATIONTYPE_VECTOR2 = 5;
Animation._ANIMATIONTYPE_SIZE = 6;
Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
Animation._ANIMATIONLOOPMODE_CYCLE = 1;
Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
return Animation;
}());
BABYLON.Animation = Animation;
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.animation.js.map
var BABYLON;
(function (BABYLON) {
var AnimationGroup = /** @class */ (function () {
function AnimationGroup(name, scene) {
if (scene === void 0) { scene = null; }
this.name = name;
// private _animations = new Array();
// private _targets = new Array