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 () { if (this.x !== this.y) { return true; } if (this.x !== this.z) { return true; } if (this.y !== this.z) { 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); }; // Methods /** * Normalize the current Vector3. * Returns the updated Vector3. */ 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; }; /** * 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 matrix = MathTmp.Matrix[0]; world.multiplyToRef(view, matrix); matrix.multiplyToRef(projection, matrix); matrix.invert(); var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0); var vector = Vector3.TransformCoordinates(screenSource, matrix); 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)) { vector = vector.scale(1.0 / num); } return vector; }; 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]; BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat); BABYLON.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); BABYLON.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); BABYLON.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); BABYLON.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); BABYLON.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); BABYLON.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 (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 (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); }; 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 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; 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; } 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._duplicateId = 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; } if (!value.__smartArrayFlags) { value.__smartArrayFlags = {}; } value.__smartArrayFlags[this._id] = this._duplicateId; }; SmartArray.prototype.forEach = function (func) { for (var index = 0; index < this.length; index++) { func(this.data[index]); } }; SmartArray.prototype.pushNoDuplicate = function (value) { if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) { return false; } this.push(value); return true; }; SmartArray.prototype.sort = function (compareFn) { this.data.sort(compareFn); }; SmartArray.prototype.reset = function () { this.length = 0; this._duplicateId++; }; 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.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); } }; 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; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.smartArray.js.map var BABYLON; (function (BABYLON) { // 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.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, img) { if (Tools.CorsBehavior) { switch (typeof (Tools.CorsBehavior)) { case "function": var result = Tools.CorsBehavior(url); if (result) { img.crossOrigin = result; } break; case "string": default: img.crossOrigin = Tools.CorsBehavior; break; } } }; // 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(); if (url.substr(0, 5) !== "data:") { Tools.SetCorsBehavior(url, img); } img.onload = function () { onLoad(img); }; img.onerror = function (err) { Tools.Error("Error while trying to load image: " + url); if (Tools.UseFallbackTexture) { img.src = Tools.fallbackTexture; onLoad(img); } else { 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:") !== 0) { noIndexedDB(); } else { 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 = ""; } } else { Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?"); img.src = Tools.fallbackTexture; } } } return img; }; //ANY Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) { url = Tools.CleanUrl(url); url = Tools.PreprocessUrl(url); var request = null; var noIndexedDB = function () { 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); } else { var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl); if (onError) { onError(req, e); } else { throw e; } } } }; request.send(null); }; var loadFromIndexedDB = function () { if (database) { database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer); } }; 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); } else { var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?"; if (onError) { var e = new Error(errorMessage); onError(undefined, e); } else { Tools.Error(errorMessage); } } } else { // 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) { 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); } }; Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) { if (mimeType === void 0) { mimeType = "image/png"; } var base64Image = screenshotCanvas.toDataURL(mimeType); if (successCallback) { successCallback(base64Image); } else { //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 = base64Image; 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(); //Or opening a new tab with the image if it is not possible to automatically start download. } else { var newWindow = window.open(""); var img = newWindow.document.createElement("img"); img.src = base64Image; 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) { if (mimeType === void 0) { mimeType = "image/png"; } if (samples === void 0) { samples = 1; } 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; texture.onAfterRenderObservable.add(function () { Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType); }); 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.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 }); /** * 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 partialLoad = 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 cascadeLoad = function (rootUrl, scene, onfinish, files, onError) { if (onError === void 0) { onError = null; } var loadedImages = []; loadedImages._internalCount = 0; for (var index = 0; index < 6; index++) { partialLoad(files[index], index, loadedImages, 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(); 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._activeTexturesCache = {}; 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; // 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); } }; 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; // 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.1-alpha"; }, 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, BABYLON.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, BABYLON.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, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.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). this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format. 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; // 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._activeTexturesCache) { this._activeTexturesCache[key] = null; } }; 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 () { return this._drawCalls.current; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", { get: function () { return this._drawCalls; }, 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); } }; /** * 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._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(); } }; /** * 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) { // TODO: Backwards compatible for 1.0? 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) { // Apply states this.applyStates(); this._drawCalls.addCount(1, false); // Render var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT; var mult = this._uintIndicesCurrentlySet ? 4 : 2; if (instancesCount) { this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount); return; } this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult); }; Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) { // Apply states this.applyStates(); this._drawCalls.addCount(1, false); if (instancesCount) { this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount); return; } this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount); }; Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) { // Apply states this.applyStates(); this._drawCalls.addCount(1, false); if (instancesCount) { this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount); return; } this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount); }; // 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; 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) { context = context || this._gl; var vertexShader = compileRawShader(context, vertexCode, "vertex"); var fragmentShader = compileRawShader(context, fragmentCode, "fragment"); return this._createShaderProgram(vertexShader, fragmentShader, context); }; Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) { context = context || this._gl; 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); return this._createShaderProgram(vertexShader, fragmentShader, context); }; Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context) { var shaderProgram = context.createProgram(); if (!shaderProgram) { throw new Error("Unable to create program"); } context.attachShader(shaderProgram, vertexShader); context.attachShader(shaderProgram, fragmentShader); context.linkProgram(shaderProgram); 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.setProgram(effect.getProgram()); 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) { 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; } if (onLoad) { texture.onLoadedObservable.add(onLoad); } if (!fallBack) this._internalTexturesCache.push(texture); var onerror = function () { if (scene) { scene._removePendingData(texture); } // 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 (onError) { onError(); } }; 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, onerror); } 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); _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) { if (compression === void 0) { compression = null; } if (!texture) { return; } var internalFormat = this._getInternalFormat(format); 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.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, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, 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) { if (compression === void 0) { compression = null; } 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; if (!this._doNotHandleContextLost) { texture._bufferView = data; } this.updateRawTexture(texture, data, format, invertY, compression); 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) { 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); 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(); texture.width = ktx.pixelWidth; texture.height = ktx.pixelHeight; texture.isReady = true; }, undefined, undefined, true, onerror); } else if (isDDS) { 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); } 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(); 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"); } cascadeLoad(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); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_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(); 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.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); var needConversion = false; if (internalFormat === gl.RGB) { internalFormat = gl.RGBA; needConversion = true; } 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) { 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]); this._gl.uniform1i(uniform, index); } this._currentEffect = null; }; Engine.prototype.activateTexture = function (texture) { if (this._activeTexture !== texture) { this._gl.activeTexture(texture); this._activeTexture = texture; } }; Engine.prototype._bindTextureDirectly = function (target, texture) { if (this._activeTexturesCache[this._activeTexture] !== texture) { this._gl.bindTexture(target, texture ? texture._webGLTexture : null); this._activeTexturesCache[this._activeTexture] = texture; } }; Engine.prototype._bindTexture = function (channel, texture) { if (channel < 0) { return; } this.activateTexture(this._gl.TEXTURE0 + 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.activateTexture(this._gl["TEXTURE" + 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; } this._gl.uniform1i(uniform, channel); this._setTexture(channel, texture); }; Engine.prototype._setTexture = function (channel, texture) { // Not ready? if (!texture) { if (this._activeTexturesCache[channel] != null) { this.activateTexture(this._gl["TEXTURE" + 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; } // Video var alreadyActivated = false; if (texture.video) { this.activateTexture(this._gl["TEXTURE" + channel]); alreadyActivated = true; texture.update(); } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { texture.delayLoad(); return; } 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 (this._activeTexturesCache[channel] === internalTexture) { return; } if (!alreadyActivated) { this.activateTexture(this._gl["TEXTURE" + channel]); } if (internalTexture && internalTexture.is3D) { this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture); 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); 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); 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); } }; 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] = channel + i; } this._gl.uniform1iv(uniform, this._textureUnits); for (var index = 0; index < textures.length; index++) { this._setTexture(channel + index, textures[index]); } }; 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 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(); 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(BABYLON.Engine.TEXTURETYPE_FLOAT); }; Engine.prototype._canRenderToHalfFloatFramebuffer = function () { if (this._webGLVersion > 1) { return this._caps.colorBufferFloat; } return this._canRenderToFramebuffer(BABYLON.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.beginQuery = function (algorithmType, query) { var glAlgorithm = this.getGlAlgorithmType(algorithmType); this._gl.beginQuery(glAlgorithm, query); }; Engine.prototype.endQuery = function (algorithmType) { var glAlgorithm = this.getGlAlgorithmType(algorithmType); this._gl.endQuery(glAlgorithm); return this; }; Engine.prototype.getGlAlgorithmType = function (algorithmType) { return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED; }; // 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; } }; 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 index = this._behaviors.indexOf(behavior); if (index !== -1) { return this; } 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 (directDecendantsOnly, predicate) { var results = []; this._getDescendants(results, directDecendantsOnly, function (node) { return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh)); }); 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; }; 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); }; 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 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) || 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 }; // Normal matrix _this._nonUniformScaling = false; // 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 after the world matrix is updated * @type {BABYLON.Observable} */ _this.onAfterWorldMatrixUpdateObservable = 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.position = BABYLON.Vector3.Zero(); /** * 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._rotation = BABYLON.Vector3.Zero(); _this._scaling = BABYLON.Vector3.One(); _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE; _this.visibility = 1.0; _this.alphaIndex = Number.MAX_VALUE; _this.infiniteDistance = false; _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.scalingDeterminant = 1; _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; // 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._localWorld = BABYLON.Matrix.Zero(); _this._worldMatrix = BABYLON.Matrix.Zero(); _this._absolutePosition = BABYLON.Vector3.Zero(); _this._collisionsTransformMatrix = BABYLON.Matrix.Zero(); _this._collisionsScalingMatrix = BABYLON.Matrix.Zero(); _this._isDirty = false; _this._pivotMatrix = BABYLON.Matrix.Identity(); _this._postMultiplyPivotMatrix = false; _this._isDisposed = false; _this._renderId = 0; _this._intersectionsInProgress = new Array(); _this._isWorldMatrixFrozen = false; _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 AbstractMesh._BILLBOARDMODE_NONE; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", { get: function () { return AbstractMesh._BILLBOARDMODE_X; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", { get: function () { return AbstractMesh._BILLBOARDMODE_Y; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", { get: function () { return AbstractMesh._BILLBOARDMODE_Z; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", { get: function () { return AbstractMesh._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, "isFacetDataEnabled", { /** * Read-only boolean : is the feature facetData enabled ? */ get: function () { return this._facetDataEnabled; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", { get: function () { return this._nonUniformScaling; }, set: function (value) { if (this._nonUniformScaling === value) { return; } this._nonUniformScaling = true; this._markSubMeshesAsMiscDirty(); }, enumerable: true, configurable: 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, "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(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; }, set: function (newScaling) { this._scaling = newScaling; if (this.physicsImpostor) { this.physicsImpostor.forceUpdate(); } }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.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 }); // Methods /** * Copies the paramater passed Matrix into the mesh Pose matrix. * Returns the AbstractMesh. */ AbstractMesh.prototype.updatePoseMatrix = function (matrix) { this._poseMatrix.copyFrom(matrix); return this; }; /** * Returns the mesh Pose matrix. * Returned object : Matrix */ AbstractMesh.prototype.getPoseMatrix = function () { return this._poseMatrix; }; /** * 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._updateBoundingInfo(); } return this._boundingInfo; }; /** * 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 last update of the World matrix * Returns a Matrix. */ AbstractMesh.prototype.getWorldMatrix = function () { if (this._masterMesh) { return this._masterMesh.getWorldMatrix(); } if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) { this.computeWorldMatrix(); } return this._worldMatrix; }; Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", { /** * Returns directly the last state of the mesh World matrix. * A Matrix is returned. */ get: function () { return this._worldMatrix; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "absolutePosition", { /** * Returns the current mesh absolute position. * Retuns a Vector3. */ get: function () { return this._absolutePosition; }, enumerable: true, configurable: true }); /** * Prevents the World matrix to be computed any longer. * Returns the AbstractMesh. */ AbstractMesh.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. */ AbstractMesh.prototype.unfreezeWorldMatrix = function () { this._isWorldMatrixFrozen = false; this.computeWorldMatrix(true); return this; }; Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", { /** * True if the World matrix has been frozen. * Returns a boolean. */ get: function () { return this._isWorldMatrixFrozen; }, enumerable: true, configurable: true }); /** * 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. */ AbstractMesh.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, 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, 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 */ AbstractMesh.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. */ AbstractMesh.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. */ AbstractMesh.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; }; /** * Retuns the mesh absolute position in the World. * Returns a Vector3. */ AbstractMesh.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. */ AbstractMesh.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; }; // ================================== 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); }; /** * Sets a new pivot matrix to the mesh. * Returns the AbstractMesh. */ AbstractMesh.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. */ AbstractMesh.prototype.getPivotMatrix = function () { return this._pivotMatrix; }; AbstractMesh.prototype._isSynchronized = function () { if (this._isDirty) { return false; } if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== 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; }; AbstractMesh.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; }; AbstractMesh.prototype.markAsDirty = function (property) { if (property === "rotation") { this.rotationQuaternion = null; } this._currentRenderId = Number.MAX_VALUE; this._isDirty = true; return this; }; /** * Return the minimum and maximum world vectors of the entire hierarchy under current mesh */ AbstractMesh.prototype.getHierarchyBoundingVectors = function () { this.computeWorldMatrix(true); var min; var max; var boundingInfo = this.getBoundingInfo(); if (!this.subMeshes || !boundingInfo) { 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; } 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; childMesh.computeWorldMatrix(true); var childBoundingInfo = childMesh.getBoundingInfo(); if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) { continue; } 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; }; /** * 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. */ AbstractMesh.prototype.computeWorldMatrix = function (force) { if (this._isWorldMatrixFrozen) { return this._worldMatrix; } if (!force && this.isSynchronized(true)) { this._currentRenderId = this.getScene().getRenderId(); 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 !== AbstractMesh.BILLBOARDMODE_NONE && camera) { if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) { // Need to decompose each rotation here var currentPosition = BABYLON.Tmp.Vector3[3]; if (this.parent && this.parent.getWorldMatrix) { if (this._meshToBoneReferal) { this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.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 & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) { finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z); } if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) { finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z); } if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === 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 !== AbstractMesh.BILLBOARDMODE_NONE) { if (this._meshToBoneReferal) { this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.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._meshToBoneReferal) { this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]); BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.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.nonUniformScaling = true; } else if (this.parent && this.parent._nonUniformScaling) { this.nonUniformScaling = this.parent._nonUniformScaling; } else { this.nonUniformScaling = false; } // Bounding info this._updateBoundingInfo(); // 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; }; /** * 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 AbstractMesh. */ AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) { this.onAfterWorldMatrixUpdateObservable.add(func); return this; }; /** * Removes a registered callback function. * Returns the AbstractMesh. */ AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) { this.onAfterWorldMatrixUpdateObservable.removeCallback(func); return this; }; /** * Sets the mesh position in its local space. * Returns the AbstractMesh. */ AbstractMesh.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. */ AbstractMesh.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. */ AbstractMesh.prototype.locallyTranslate = function (vector3) { this.computeWorldMatrix(true); this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld); return this; }; AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) { /// Orients a mesh towards a target point. Mesh must be drawn facing user. /// The position (must be in same space as current mesh) to look at /// optional yaw (y-axis) correction in radians /// optional pitch (x-axis) correction in radians /// optional roll (z-axis) correction in radians /// Mesh oriented towards targetMesh 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 = 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); this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion(); BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion); return this; }; AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) { this._meshToBoneReferal = affectedMesh; this.parent = bone; if (bone.getWorldMatrix().determinant() < 0) { this.scalingDeterminant *= -1; } return this; }; AbstractMesh.prototype.detachFromBone = function () { if (!this.parent) { return this; } if (this.parent.getWorldMatrix().determinant() < 0) { this.scalingDeterminant *= -1; } this._meshToBoneReferal = null; this.parent = null; return this; }; /** * 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 }); AbstractMesh.prototype.moveWithCollisions = function (displacement) { var globalPosition = this.getAbsolutePosition(); globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions); this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset); 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 if (boundingInfo) { 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. * Some internal references are kept for further use. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`. * Returns nothing. */ AbstractMesh.prototype.dispose = function (doNotRecurse) { var _this = this; var index; // Action manager if (this.actionManager) { this.actionManager.dispose(); this.actionManager = null; } // Skeleton this.skeleton = null; // Animations this.getScene().stopAnimation(this); // 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 (!doNotRecurse) { // Particles for (index = 0; index < this.getScene().particleSystems.length; index++) { if (this.getScene().particleSystems[index].emitter === this) { this.getScene().particleSystems[index].dispose(); index--; } } // Children var objects = this.getDescendants(true); for (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); } } // facet data if (this._facetDataEnabled) { this.disableFacetData(); } this.onAfterWorldMatrixUpdateObservable.clear(); this.onCollideObservable.clear(); this.onCollisionPositionChangeObservable.clear(); this._isDisposed = true; _super.prototype.dispose.call(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. */ AbstractMesh.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. */ AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) { BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result); return this; }; AbstractMesh.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. */ AbstractMesh.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. */ AbstractMesh.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. */ AbstractMesh.prototype.getAbsolutePivotPoint = function () { var point = BABYLON.Vector3.Zero(); this.getAbsolutePivotPointToRef(point); return point; }; /** * Defines the passed mesh as the parent of the current mesh. * Returns the AbstractMesh. */ AbstractMesh.prototype.setParent = function (mesh) { var parent = mesh; if (mesh == null) { var rotation = BABYLON.Tmp.Quaternion[0]; var position = BABYLON.Tmp.Vector3[0]; var scale = BABYLON.Tmp.Vector3[1]; this.getWorldMatrix().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; } else { var position = BABYLON.Tmp.Vector3[0]; var m1 = BABYLON.Tmp.Matrix[0]; parent.getWorldMatrix().invertToRef(m1); BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position); this.position.copyFrom(position); } this.parent = parent; return this; }; /** * 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; }; /** * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates. * Returns the AbstractMesh. */ AbstractMesh.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; }; // 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; 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 (!bInfo) { return this; } 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; BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters); 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(); if (!bInfo) { return null; } 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; } return this; }; /** * 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); }; 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.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery); occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this); engine.endQuery(this.occlusionQueryAlgorithmType); this._isOcclusionQueryInProgress = true; }; // Statics AbstractMesh._BILLBOARDMODE_NONE = 0; AbstractMesh._BILLBOARDMODE_X = 1; AbstractMesh._BILLBOARDMODE_Y = 2; AbstractMesh._BILLBOARDMODE_Z = 4; AbstractMesh._BILLBOARDMODE_ALL = 7; 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; AbstractMesh._rotationAxisCache = new BABYLON.Quaternion(); AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0); return AbstractMesh; }(BABYLON.Node)); 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.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; this._currentIndex = index; 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.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) { 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._particlesDuration.beginMonitoring(); 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._particlesDuration.endMonitoring(false); }; RenderingGroup.prototype._renderSprites = function () { if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) { return; } // Sprites var activeCamera = this._scene.activeCamera; this._scene._spritesDuration.beginMonitoring(); 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._spritesDuration.endMonitoring(false); }; 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.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 * @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 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 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 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 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._previousHasSwiped = 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 (abstract) meshes added to this scene. * @see BABYLON.AbstractMesh * @type {BABYLON.AbstractMesh[]} */ this.meshes = 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.SmartArray(256); // Procedural textures this.proceduralTexturesEnabled = true; this._proceduralTextures = new Array(); this.soundTracks = new Array(); this._audioEnabled = true; this._headphone = false; // Performance counters this._totalMeshesCounter = new BABYLON.PerfCounter(); this._totalLightsCounter = new BABYLON.PerfCounter(); this._totalMaterialsCounter = new BABYLON.PerfCounter(); this._totalTexturesCounter = new BABYLON.PerfCounter(); this._totalVertices = new BABYLON.PerfCounter(); this._activeIndices = new BABYLON.PerfCounter(); this._activeParticles = new BABYLON.PerfCounter(); this._interFrameDuration = new BABYLON.PerfCounter(); this._lastFrameDuration = new BABYLON.PerfCounter(); this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter(); this._renderTargetsDuration = new BABYLON.PerfCounter(); this._particlesDuration = new BABYLON.PerfCounter(); this._renderDuration = new BABYLON.PerfCounter(); this._spritesDuration = 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.SmartArray(256); this._activeParticleSystems = new BABYLON.SmartArray(256); this._activeSkeletons = new BABYLON.SmartArray(32); this._softwareSkinnedMeshes = new BABYLON.SmartArray(32); this._activeAnimatables = new Array(); this._transformMatrix = BABYLON.Matrix.Zero(); this._useAlternateCameraConfiguration = false; this._alternateRendering = false; this.requireLightSorting = false; this._activeMeshesFrozen = false; 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(); } 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 () { return this._interFrameDuration.current; }; Object.defineProperty(Scene.prototype, "interFramePerfCounter", { get: function () { return this._interFrameDuration; }, enumerable: true, configurable: true }); Scene.prototype.getLastFrameDuration = function () { return this._lastFrameDuration.current; }; Object.defineProperty(Scene.prototype, "lastFramePerfCounter", { get: function () { return this._lastFrameDuration; }, enumerable: true, configurable: true }); Scene.prototype.getEvaluateActiveMeshesDuration = function () { return this._evaluateActiveMeshesDuration.current; }; Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", { get: function () { return this._evaluateActiveMeshesDuration; }, enumerable: true, configurable: true }); Scene.prototype.getActiveMeshes = function () { return this._activeMeshes; }; Scene.prototype.getRenderTargetsDuration = function () { return this._renderTargetsDuration.current; }; Scene.prototype.getRenderDuration = function () { return this._renderDuration.current; }; Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", { get: function () { return this._renderDuration; }, enumerable: true, configurable: true }); Scene.prototype.getParticlesDuration = function () { return this._particlesDuration.current; }; Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", { get: function () { return this._particlesDuration; }, enumerable: true, configurable: true }); Scene.prototype.getSpritesDuration = function () { return this._spritesDuration.current; }; Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", { get: function () { return this._spritesDuration; }, 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; 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; _this._previousHasSwiped = clickInfo.hasSwiped; 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; _this._previousHasSwiped = clickInfo.hasSwiped; } } } } 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 index = this._pendingData.indexOf(data); if (index !== -1) { this._pendingData.splice(index, 1); } }; Scene.prototype.getWaitingItemsCount = function () { return this._pendingData.length; }; /** * 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); } }; 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 = (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); } //notify the collision coordinator if (this.collisionCoordinator) { this.collisionCoordinator.onMeshRemoved(toRemove); } this.onMeshRemovedObservable.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 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 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.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.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(); if (boundingInfo) { 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.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); } } // Particle systems this._particlesDuration.beginMonitoring(); if (this.particlesEnabled) { BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0); 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); } } BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0); } this._particlesDuration.endMonitoring(false); }; 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(); if (boundingInfo) { 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._evaluateActiveMeshesDuration.beginMonitoring(); BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation"); this._evaluateActiveMeshes(); this._evaluateActiveMeshesDuration.endMonitoring(false); BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation"); // Software skinning for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) { var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex]; mesh.applySkeleton(mesh.skeleton); } // Render targets this._renderTargetsDuration.beginMonitoring(); 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._renderTargetsDuration.endMonitoring(false); // Prepare Frame this.postProcessManager._prepareFrame(); this._renderDuration.beginMonitoring(); // 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); } // Render BABYLON.Tools.StartPerformanceCounter("Main render"); // Activate HighlightLayer stencil if (renderhighlights) { this._engine.setStencilBuffer(true); } this._renderingManager.render(null, null, true, true); // Restore HighlightLayer stencil if (renderhighlights) { this._engine.setStencilBuffer(stencilState); } BABYLON.Tools.EndPerformanceCounter("Main render"); // 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); } this._renderDuration.endMonitoring(false); // 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._interFrameDuration.endMonitoring(); this._lastFrameDuration.beginMonitoring(); this._particlesDuration.fetchNewFrame(); this._spritesDuration.fetchNewFrame(); this._activeParticles.fetchNewFrame(); this._renderDuration.fetchNewFrame(); this._renderTargetsDuration.fetchNewFrame(); this._evaluateActiveMeshesDuration.fetchNewFrame(); this._totalVertices.fetchNewFrame(); this._activeIndices.fetchNewFrame(); this._activeBones.fetchNewFrame(); this.getEngine().drawCallsPerfCounter.fetchNewFrame(); this._meshesForIntersections.reset(); this.resetCachedMaterial(); BABYLON.Tools.StartPerformanceCounter("Scene rendering"); // 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)) / 1000; var defaultTimeStep = (60.0 / 1000.0); if (this._physicsEngine) { defaultTimeStep = this._physicsEngine.getTimeStep(); } var maxSubSteps = this._engine.getLockstepMaxSteps(); this._timeAccumulator += deltaTime; // compute the amount of fixed steps we should have taken since the last step var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep); internalSteps = Math.min(internalSteps, maxSubSteps); for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) { this.onBeforeStepObservable.notifyObservers(this); // Animations this._animationRatio = defaultTimeStep * (60.0 / 1000.0); this._animate(); // Physics if (this._physicsEngine) { BABYLON.Tools.StartPerformanceCounter("Physics"); this._physicsEngine._step(defaultTimeStep); BABYLON.Tools.EndPerformanceCounter("Physics"); } this._timeAccumulator -= defaultTimeStep; this.onAfterStepObservable.notifyObservers(this); this._currentStepId++; if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) { this._evaluateActiveMeshes(); } } } else { // Animations var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)); this._animationRatio = deltaTime * (60.0 / 1000.0); this._animate(); // Physics if (this._physicsEngine) { BABYLON.Tools.StartPerformanceCounter("Physics"); this._physicsEngine._step(deltaTime / 1000.0); BABYLON.Tools.EndPerformanceCounter("Physics"); } } // Before render this.onBeforeRenderObservable.notifyObservers(this); // Customs render targets this._renderTargetsDuration.beginMonitoring(); 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._renderTargetsDuration.endMonitoring(); 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; } BABYLON.Tools.EndPerformanceCounter("Scene rendering"); this._interFrameDuration.beginMonitoring(); this._lastFrameDuration.endMonitoring(); this._totalMeshesCounter.addCount(this.meshes.length, true); this._totalLightsCounter.addCount(this.lights.length, true); this._totalMaterialsCounter.addCount(this.materials.length, true); this._totalTexturesCounter.addCount(this.textures.length, true); 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.importedMeshesFiles = new Array(); 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.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); } // 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(); 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(); if (boundingInfo) { 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 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); return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix()); // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix()); }; Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) { if (!BABYLON.PickingInfo) { return null; } 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); return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix()); }; 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; return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, 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) { var ray = this.createPickingRayInCameraSpace(x, y, camera); if (!ray) { return null; } return this._internalPickSprites(ray, 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); return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix); }, 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); return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix); }, 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.createDefaultVRExperience = function (webVROptions) { if (webVROptions === void 0) { webVROptions = {}; } this.VRHelper = 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.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._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(); 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 () { if (parsedTexture.mirrorPlane) { var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene); 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); renderTargetTexture._waitingRenderList = parsedTexture.renderList; return renderTargetTexture; } else { var texture; if (parsedTexture.base64String) { texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene); } else { texture = new Texture(rootUrl + parsedTexture.name, scene); } 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"], ["_poseMatrix"]); // Tags if (BABYLON.Tags.HasTags(source)) { BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true)); } // 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 for (index = 0; index < scene.meshes.length; index++) { var mesh = scene.meshes[index]; if (mesh.parent === source) { // doNotCloneChildren is always going to be False mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren); } } } // 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 }); // 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(); if (!boundingInfo) { return this; } 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 () { if (this._boundingInfo && this._boundingInfo.isLocked) { return this; } var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); 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._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). * 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(); // Draw order switch (fillMode) { case BABYLON.Material.PointFillMode: engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount); break; case BABYLON.Material.WireFrameFillMode: if (this._unIndexed) { engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount); } else { engine.draw(false, 0, subMesh.linesIndexCount, instancesCount); } break; default: if (this._unIndexed) { engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount); } else { engine.draw(true, 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.bindOnlyWorldMatrix(world); } return this; }; /** * 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(this, scene); } return this; }; Mesh.prototype._queueLoad = function (mesh, scene) { var _this = this; scene._addPendingData(mesh); 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/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.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. * This also frees the memory allocated under the hood to all the buffers used by WebGL. */ Mesh.prototype.dispose = function (doNotRecurse) { var _this = this; this.morphTargetManager = null; if (this._geometry) { this._geometry.releaseForMesh(this, true); } // Sources var meshes = this.getScene().meshes; meshes.forEach(function (mesh) { 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); }; /** * 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 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, 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); this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3); if (morphTarget.hasNormals) { this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3); } if (morphTarget.hasTangents) { this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), 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 what is a deep copy of the passed mesh. * The parameter `parsedMesh` is the mesh to be copied. * 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.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 (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; if (!matricesWeightsExtraData || !matricesIndicesExtraData) { return this; } 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(); if (!boundingInfo) { return; } 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) ? BABYLON.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._boundingInfo; 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(); if (!boundingInfo) { return this; } //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(); if (!boundingInfo) { return false; } 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.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 (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._meshRank = rank; 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; 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); } else { this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines); } this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this); if (engine.webGLVersion > 1) { 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) { if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) { return; } Effect._baseCache[this._uniformBuffersNames[name]] = buffer; this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]); }; 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 BABYLON; (function (BABYLON) { var MaterialHelper = /** @class */ (function () { function MaterialHelper() { } 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) { if (useMorphTargets === void 0) { useMorphTargets = false; } 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) { defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind); defines["VERTEXALPHA"] = mesh.hasVertexAlpha; } 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) { if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; } if (!defines["SHADOWS"]) { return; } for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) { if (!defines["LIGHT" + lightIndex]) { break; } if (lightIndex > 0) { fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex); } if (defines["SHADOW" + lightIndex]) { fallbacks.addFallback(0, "SHADOW" + lightIndex); } if (defines["SHADOWPCF" + lightIndex]) { fallbacks.addFallback(0, "SHADOWPCF" + lightIndex); } if (defines["SHADOWESM" + lightIndex]) { fallbacks.addFallback(0, "SHADOWESM" + lightIndex); } } }; 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 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, "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.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 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(options ? options.alphaTest : _this.needAlphaTesting()); if (options && options.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); ; }; Material._TriangleFillMode = 0; Material._WireFrameFillMode = 1; Material._PointFillMode = 2; 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 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 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); 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) { if (length === void 0) { length = 0; } if (!other && !source) { return null; } if (!other) { return this._mergeElement(source, new Float32Array(source.length), length); } if (!source) { if (length === 0 || length === other.length) { return other; } return this._mergeElement(new Float32Array(length - other.length), 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 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 (index > 0) { indices.push(idx - 1); indices.push(idx); } idx++; } } var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; 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 */ 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 faceNormalSign = 1; var ratio = 0; 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; } // 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; 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); } } // 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; } if (!this._scene.activeCamera) { return; } 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.draw(true, 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.draw(true, 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; this._lastChangeTimeMs = 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; this._lastChangeTimeMs = 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; /** * 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 }); /** * 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) { 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; 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) { var texture = this.colorGradingTexture; defines.COLORGRADING3D = (texture.getScene().getEngine().webGLVersion > 1) ? true : false; } 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); 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) { 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 BABYLON.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 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); if (scene.activeCamera) { effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition); } 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 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.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.USESPHERICALINFRAGMENT = false; _this.REFLECTIONMAP_OPPOSITEZ = false; _this.LODINREFLECTIONALPHA = false; _this.GAMMAREFLECTION = 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; /** * Specifies that the alpha is coming form the albedo channel alpha channel. */ _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. */ _this._useAlphaFresnel = false; /** * 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. * (Temporary internal fix to remove before 3.1) */ _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 }); PBRBaseMaterial.prototype.needAlphaBlending = function () { if (this._linkRefractionWithTransparency) { return false; } return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture(); }; PBRBaseMaterial.prototype.needAlphaTesting = function () { if (this._forceAlphaTest) { return true; } if (this._linkRefractionWithTransparency) { return false; } return this._albedoTexture != null && this._albedoTexture.hasAlpha; }; PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () { return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture; }; 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.USESPHERICALINFRAGMENT = 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.USESPHERICALINFRAGMENT = 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 = reflectionTexture.invertZ; defines.LODINREFRACTIONALPHA = reflectionTexture.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.needAlphaBlending(); defines.ALPHAFRESNEL = this._useAlphaFresnel; } if (defines._areImageProcessingDirty) { if (!this._imageProcessingConfiguration.isReady()) { return false; } this._imageProcessingConfiguration.prepareDefines(defines); } defines.FORCENORMALFORWARD = this._forceNormalForward; // 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)) { if (mesh) { if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) { mesh.createNormals(true); BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name); } } } // Get correct effect if (defines.isDirty) { defines.markAsProcessed(); scene.resetCachedMaterial(); // Fallbacks var fallbacks = new BABYLON.EffectFallbacks(); if (defines.ENVIRONMENTBRDF) { fallbacks.addFallback(0, "ENVIRONMENTBRDF"); } if (defines.REFLECTION) { fallbacks.addFallback(0, "REFLECTION"); } if (defines.REFRACTION) { fallbacks.addFallback(0, "REFRACTION"); } if (defines.REFLECTIVITY) { fallbacks.addFallback(0, "REFLECTIVITY"); } 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.NUM_BONE_INFLUENCERS > 0) { fallbacks.addCPUSkinningFallback(0, mesh); } //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._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._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); 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._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE; _this._useAmbientInGrayScale = true; return _this; } Object.defineProperty(PBRBaseSimpleMaterial.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; if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) { this._forceAlphaTest = true; } else { this._forceAlphaTest = false; } this._markAllSubMeshesAsTexturesDirty(); }, enumerable: true, configurable: true }); 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 }); /** * Specifies wether or not the alpha value of the albedo texture should be used. */ PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () { return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE; }; /** * Specifies wether or not the meshes using this material should be rendered in alpha blend mode. */ PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () { if (this._linkRefractionWithTransparency) { return false; } return (this.alpha < 1.0) || (this._shouldUseAlphaFromAlbedoTexture() && (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND)); }; /** * Specifies wether or not the meshes using this material should be rendered in alpha test mode. */ PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () { if (this._linkRefractionWithTransparency) { return false; } return this._shouldUseAlphaFromAlbedoTexture() && this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST; }; /** * 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); } return activeTextures; }; 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, "transparencyMode", null); __decorate([ BABYLON.serialize() ], PBRBaseSimpleMaterial.prototype, "doubleSided", null); 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. */ _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. */ _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. */ _this.environmentBRDFTexture = null; /** * Force normal to face away from face. * (Temporary internal fix to remove before 3.1) */ _this.forceNormalForward = false; _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.serializeAsTexture(), BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "environmentBRDFTexture", void 0); __decorate([ BABYLON.serialize(), BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "forceNormalForward", 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._defaultUpVector = 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._defaultUpVector, 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._defaultUpVector, this._cameraRotationMatrix, this.upVector); }; TargetCamera.prototype._getViewMatrix = function () { if (!this.lockedTarget) { // Compute this._updateCameraRotationMatrix(); BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint); // Computing target and final matrix this.position.addToRef(this._transformedReferencePoint, this._currentTarget); } else { var targetPosition = this._getLockedTargetPosition(); if (targetPosition) { this._currentTarget.copyFrom(targetPosition); } } if (this.getScene().useRightHandedSystem) { BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix); } else { BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, 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.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); 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.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; 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 (p.event.pointerType !== "touch") { 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(); if (!boundingInfo) { continue; } 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 BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.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 RuntimeAnimation = /** @class */ (function () { function RuntimeAnimation(target, animation) { this._offsetsCache = {}; this._highLimitsCache = {}; this._stopped = false; this._blendingFactor = 0; this._ratioOffset = 0; this._animation = animation; this._target = target; animation._runtimeAnimations.push(this); } Object.defineProperty(RuntimeAnimation.prototype, "animation", { get: function () { return this._animation; }, enumerable: true, configurable: true }); RuntimeAnimation.prototype.reset = function () { this._offsetsCache = {}; this._highLimitsCache = {}; this.currentFrame = 0; this._blendingFactor = 0; this._originalBlendValue = null; }; RuntimeAnimation.prototype.isStopped = function () { return this._stopped; }; RuntimeAnimation.prototype.dispose = function () { var index = this._animation.runtimeAnimations.indexOf(this); if (index > -1) { this._animation.runtimeAnimations.splice(index, 1); } }; RuntimeAnimation.prototype._getKeyValue = function (value) { if (typeof value === "function") { return value(); } return value; }; RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) { if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) { return highLimitValue.clone ? highLimitValue.clone() : highLimitValue; } this.currentFrame = currentFrame; var keys = this._animation.getKeys(); // Try to get a hash to find the right key var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1)); if (keys[startKeyIndex].frame >= currentFrame) { while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) { startKeyIndex--; } } for (var key = startKeyIndex; key < keys.length; key++) { var endKey = keys[key + 1]; if (endKey.frame >= currentFrame) { var startKey = keys[key]; var startValue = this._getKeyValue(startKey.value); var endValue = this._getKeyValue(endKey.value); var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined; var frameDelta = endKey.frame - startKey.frame; // gradient : percent of currentFrame between the frame inf and the frame sup var gradient = (currentFrame - startKey.frame) / frameDelta; // check for easingFunction and correction of gradient var easingFunction = this._animation.getEasingFunction(); if (easingFunction != null) { gradient = easingFunction.ease(gradient); } switch (this._animation.dataType) { // Float case BABYLON.Animation.ANIMATIONTYPE_FLOAT: var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient); switch (loopMode) { case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE: case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT: return floatValue; case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE: return offsetValue * repeatCount + floatValue; } break; // Quaternion case BABYLON.Animation.ANIMATIONTYPE_QUATERNION: var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient); switch (loopMode) { case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE: case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT: return quatValue; case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE: return quatValue.add(offsetValue.scale(repeatCount)); } return quatValue; // Vector3 case BABYLON.Animation.ANIMATIONTYPE_VECTOR3: var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient); switch (loopMode) { case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE: case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT: return vec3Value; case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE: return vec3Value.add(offsetValue.scale(repeatCount)); } // Vector2 case BABYLON.Animation.ANIMATIONTYPE_VECTOR2: var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient); switch (loopMode) { case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE: case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT: return vec2Value; case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE: return vec2Value.add(offsetValue.scale(repeatCount)); } // Size case BABYLON.Animation.ANIMATIONTYPE_SIZE: switch (loopMode) { case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE: case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT: return this._animation.sizeInterpolateFunction(startValue, endValue, gradient); case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE: return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount)); } // Color3 case BABYLON.Animation.ANIMATIONTYPE_COLOR3: switch (loopMode) { case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE: case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT: return this._animation.color3InterpolateFunction(startValue, endValue, gradient); case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE: return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount)); } // Matrix case BABYLON.Animation.ANIMATIONTYPE_MATRIX: switch (loopMode) { case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE: case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT: if (BABYLON.Animation.AllowMatricesInterpolation) { return this._animation.matrixInterpolateFunction(startValue, endValue, gradient); } case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE: return startValue; } default: break; } break; } } return this._getKeyValue(keys[keys.length - 1].value); }; RuntimeAnimation.prototype.setValue = function (currentValue, blend) { if (blend === void 0) { blend = false; } // Set value var path; var destination; var targetPropertyPath = this._animation.targetPropertyPath; if (targetPropertyPath.length > 1) { var property = this._target[targetPropertyPath[0]]; for (var index = 1; index < targetPropertyPath.length - 1; index++) { property = property[targetPropertyPath[index]]; } path = targetPropertyPath[targetPropertyPath.length - 1]; destination = property; } else { path = targetPropertyPath[0]; destination = this._target; } // Blending if (this._animation.enableBlending && this._blendingFactor <= 1.0) { if (!this._originalBlendValue) { if (destination[path].clone) { this._originalBlendValue = destination[path].clone(); } else { this._originalBlendValue = destination[path]; } } if (this._originalBlendValue.prototype) { if (this._originalBlendValue.prototype.Lerp) { destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor); } else { destination[path] = currentValue; } } else if (this._originalBlendValue.m) { destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor); } else { destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue; } this._blendingFactor += this._animation.blendingSpeed; } else { destination[path] = currentValue; } if (this._target.markAsDirty) { this._target.markAsDirty(this._animation.targetProperty); } }; RuntimeAnimation.prototype.goToFrame = function (frame) { var keys = this._animation.getKeys(); if (frame < keys[0].frame) { frame = keys[0].frame; } else if (frame > keys[keys.length - 1].frame) { frame = keys[keys.length - 1].frame; } var currentValue = this._interpolate(frame, 0, this._animation.loopMode); this.setValue(currentValue); }; RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) { var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0; this._ratioOffset = this._previousRatio - newRatio; }; RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) { if (blend === void 0) { blend = false; } var targetPropertyPath = this._animation.targetPropertyPath; if (!targetPropertyPath || targetPropertyPath.length < 1) { this._stopped = true; return false; } var returnValue = true; var keys = this._animation.getKeys(); // Adding a start key at frame 0 if missing if (keys[0].frame !== 0) { var newKey = { frame: 0, value: keys[0].value }; keys.splice(0, 0, newKey); } // Check limits if (from < keys[0].frame || from > keys[keys.length - 1].frame) { from = keys[0].frame; } if (to < keys[0].frame || to > keys[keys.length - 1].frame) { to = keys[keys.length - 1].frame; } //to and from cannot be the same key if (from === to) { if (from > keys[0].frame) { from--; } else if (to < keys[keys.length - 1].frame) { to++; } } // Compute ratio var range = to - from; var offsetValue; // ratio represents the frame delta between from and to var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset; var highLimitValue = 0; this._previousDelay = delay; this._previousRatio = ratio; if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { returnValue = false; highLimitValue = this._getKeyValue(keys[keys.length - 1].value); } else { // Get max value if required if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) { var keyOffset = to.toString() + from.toString(); if (!this._offsetsCache[keyOffset]) { var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE); var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE); switch (this._animation.dataType) { // Float case BABYLON.Animation.ANIMATIONTYPE_FLOAT: this._offsetsCache[keyOffset] = toValue - fromValue; break; // Quaternion case BABYLON.Animation.ANIMATIONTYPE_QUATERNION: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); break; // Vector3 case BABYLON.Animation.ANIMATIONTYPE_VECTOR3: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); // Vector2 case BABYLON.Animation.ANIMATIONTYPE_VECTOR2: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); // Size case BABYLON.Animation.ANIMATIONTYPE_SIZE: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); // Color3 case BABYLON.Animation.ANIMATIONTYPE_COLOR3: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); default: break; } this._highLimitsCache[keyOffset] = toValue; } highLimitValue = this._highLimitsCache[keyOffset]; offsetValue = this._offsetsCache[keyOffset]; } } if (offsetValue === undefined) { switch (this._animation.dataType) { // Float case BABYLON.Animation.ANIMATIONTYPE_FLOAT: offsetValue = 0; break; // Quaternion case BABYLON.Animation.ANIMATIONTYPE_QUATERNION: offsetValue = new BABYLON.Quaternion(0, 0, 0, 0); break; // Vector3 case BABYLON.Animation.ANIMATIONTYPE_VECTOR3: offsetValue = BABYLON.Vector3.Zero(); break; // Vector2 case BABYLON.Animation.ANIMATIONTYPE_VECTOR2: offsetValue = BABYLON.Vector2.Zero(); break; // Size case BABYLON.Animation.ANIMATIONTYPE_SIZE: offsetValue = BABYLON.Size.Zero(); break; // Color3 case BABYLON.Animation.ANIMATIONTYPE_COLOR3: offsetValue = BABYLON.Color3.Black(); } } // Compute value var repeatCount = (ratio / range) >> 0; var currentFrame = returnValue ? from + ratio % range : to; var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue); // Set value this.setValue(currentValue); // Check events var events = this._animation.getEvents(); for (var index = 0; index < events.length; index++) { // Make sure current frame has passed event frame and that event frame is within the current range // Also, handle both forward and reverse animations if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) || (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) { var event = events[index]; if (!event.isDone) { // If event should be done only once, remove it. if (event.onlyOnce) { events.splice(index, 1); index--; } event.isDone = true; event.action(); } // Don't do anything if the event has already be done. } else if (events[index].isDone && !events[index].onlyOnce) { // reset event, the animation is looping events[index].isDone = false; } } if (!returnValue) { this._stopped = true; } return returnValue; }; return RuntimeAnimation; }()); BABYLON.RuntimeAnimation = RuntimeAnimation; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.runtimeAnimation.js.map var BABYLON; (function (BABYLON) { var Animatable = /** @class */ (function () { function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) { if (fromFrame === void 0) { fromFrame = 0; } if (toFrame === void 0) { toFrame = 100; } if (loopAnimation === void 0) { loopAnimation = false; } if (speedRatio === void 0) { speedRatio = 1.0; } this.target = target; this.fromFrame = fromFrame; this.toFrame = toFrame; this.loopAnimation = loopAnimation; this.onAnimationEnd = onAnimationEnd; this._localDelayOffset = null; this._pausedDelay = null; this._runtimeAnimations = new Array(); this._paused = false; this._speedRatio = 1; this.animationStarted = false; if (animations) { this.appendAnimations(target, animations); } this._speedRatio = speedRatio; this._scene = scene; scene._activeAnimatables.push(this); } Object.defineProperty(Animatable.prototype, "speedRatio", { get: function () { return this._speedRatio; }, set: function (value) { for (var index = 0; index < this._runtimeAnimations.length; index++) { var animation = this._runtimeAnimations[index]; animation._prepareForSpeedRatioChange(value); } this._speedRatio = value; }, enumerable: true, configurable: true }); // Methods Animatable.prototype.getAnimations = function () { return this._runtimeAnimations; }; Animatable.prototype.appendAnimations = function (target, animations) { for (var index = 0; index < animations.length; index++) { var animation = animations[index]; this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation)); } }; Animatable.prototype.getAnimationByTargetProperty = function (property) { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { if (runtimeAnimations[index].animation.targetProperty === property) { return runtimeAnimations[index].animation; } } return null; }; Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { if (runtimeAnimations[index].animation.targetProperty === property) { return runtimeAnimations[index]; } } return null; }; Animatable.prototype.reset = function () { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].reset(); } this._localDelayOffset = null; this._pausedDelay = null; }; Animatable.prototype.enableBlending = function (blendingSpeed) { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].animation.enableBlending = true; runtimeAnimations[index].animation.blendingSpeed = blendingSpeed; } }; Animatable.prototype.disableBlending = function () { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].animation.enableBlending = false; } }; Animatable.prototype.goToFrame = function (frame) { var runtimeAnimations = this._runtimeAnimations; if (runtimeAnimations[0]) { var fps = runtimeAnimations[0].animation.framePerSecond; var currentFrame = runtimeAnimations[0].currentFrame; var adjustTime = frame - currentFrame; var delay = adjustTime * 1000 / fps; if (this._localDelayOffset === null) { this._localDelayOffset = 0; } this._localDelayOffset -= delay; } for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].goToFrame(frame); } }; Animatable.prototype.pause = function () { if (this._paused) { return; } this._paused = true; }; Animatable.prototype.restart = function () { this._paused = false; }; Animatable.prototype.stop = function (animationName) { if (animationName) { var idx = this._scene._activeAnimatables.indexOf(this); if (idx > -1) { var runtimeAnimations = this._runtimeAnimations; for (var index = runtimeAnimations.length - 1; index >= 0; index--) { if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) { continue; } runtimeAnimations[index].dispose(); runtimeAnimations.splice(index, 1); } if (runtimeAnimations.length == 0) { this._scene._activeAnimatables.splice(idx, 1); if (this.onAnimationEnd) { this.onAnimationEnd(); } } } } else { var index = this._scene._activeAnimatables.indexOf(this); if (index > -1) { this._scene._activeAnimatables.splice(index, 1); var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].dispose(); } if (this.onAnimationEnd) { this.onAnimationEnd(); } } } }; Animatable.prototype._animate = function (delay) { if (this._paused) { this.animationStarted = false; if (this._pausedDelay === null) { this._pausedDelay = delay; } return true; } if (this._localDelayOffset === null) { this._localDelayOffset = delay; } else if (this._pausedDelay !== null) { this._localDelayOffset += delay - this._pausedDelay; this._pausedDelay = null; } // Animating var running = false; var runtimeAnimations = this._runtimeAnimations; var index; for (index = 0; index < runtimeAnimations.length; index++) { var animation = runtimeAnimations[index]; var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio); running = running || isRunning; } this.animationStarted = running; if (!running) { // Remove from active animatables index = this._scene._activeAnimatables.indexOf(this); this._scene._activeAnimatables.splice(index, 1); // Dispose all runtime animations for (index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].dispose(); } } if (!running && this.onAnimationEnd) { this.onAnimationEnd(); this.onAnimationEnd = null; } return running; }; return Animatable; }()); BABYLON.Animatable = Animatable; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.animatable.js.map var BABYLON; (function (BABYLON) { var EasingFunction = /** @class */ (function () { function EasingFunction() { // Properties this._easingMode = EasingFunction.EASINGMODE_EASEIN; } Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", { get: function () { return EasingFunction._EASINGMODE_EASEIN; }, enumerable: true, configurable: true }); Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", { get: function () { return EasingFunction._EASINGMODE_EASEOUT; }, enumerable: true, configurable: true }); Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", { get: function () { return EasingFunction._EASINGMODE_EASEINOUT; }, enumerable: true, configurable: true }); EasingFunction.prototype.setEasingMode = function (easingMode) { var n = Math.min(Math.max(easingMode, 0), 2); this._easingMode = n; }; EasingFunction.prototype.getEasingMode = function () { return this._easingMode; }; EasingFunction.prototype.easeInCore = function (gradient) { throw new Error('You must implement this method'); }; EasingFunction.prototype.ease = function (gradient) { switch (this._easingMode) { case EasingFunction.EASINGMODE_EASEIN: return this.easeInCore(gradient); case EasingFunction.EASINGMODE_EASEOUT: return (1 - this.easeInCore(1 - gradient)); } if (gradient >= 0.5) { return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5); } return (this.easeInCore(gradient * 2) * 0.5); }; //Statics EasingFunction._EASINGMODE_EASEIN = 0; EasingFunction._EASINGMODE_EASEOUT = 1; EasingFunction._EASINGMODE_EASEINOUT = 2; return EasingFunction; }()); BABYLON.EasingFunction = EasingFunction; var CircleEase = /** @class */ (function (_super) { __extends(CircleEase, _super); function CircleEase() { return _super !== null && _super.apply(this, arguments) || this; } CircleEase.prototype.easeInCore = function (gradient) { gradient = Math.max(0, Math.min(1, gradient)); return (1.0 - Math.sqrt(1.0 - (gradient * gradient))); }; return CircleEase; }(EasingFunction)); BABYLON.CircleEase = CircleEase; var BackEase = /** @class */ (function (_super) { __extends(BackEase, _super); function BackEase(amplitude) { if (amplitude === void 0) { amplitude = 1; } var _this = _super.call(this) || this; _this.amplitude = amplitude; return _this; } BackEase.prototype.easeInCore = function (gradient) { var num = Math.max(0, this.amplitude); return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient))); }; return BackEase; }(EasingFunction)); BABYLON.BackEase = BackEase; var BounceEase = /** @class */ (function (_super) { __extends(BounceEase, _super); function BounceEase(bounces, bounciness) { if (bounces === void 0) { bounces = 3; } if (bounciness === void 0) { bounciness = 2; } var _this = _super.call(this) || this; _this.bounces = bounces; _this.bounciness = bounciness; return _this; } BounceEase.prototype.easeInCore = function (gradient) { var y = Math.max(0.0, this.bounces); var bounciness = this.bounciness; if (bounciness <= 1.0) { bounciness = 1.001; } var num9 = Math.pow(bounciness, y); var num5 = 1.0 - bounciness; var num4 = ((1.0 - num9) / num5) + (num9 * 0.5); var num15 = gradient * num4; var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness); var num3 = Math.floor(num65); var num13 = num3 + 1.0; var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4); var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4); var num7 = (num8 + num12) * 0.5; var num6 = gradient - num7; var num2 = num7 - num8; return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2)); }; return BounceEase; }(EasingFunction)); BABYLON.BounceEase = BounceEase; var CubicEase = /** @class */ (function (_super) { __extends(CubicEase, _super); function CubicEase() { return _super !== null && _super.apply(this, arguments) || this; } CubicEase.prototype.easeInCore = function (gradient) { return (gradient * gradient * gradient); }; return CubicEase; }(EasingFunction)); BABYLON.CubicEase = CubicEase; var ElasticEase = /** @class */ (function (_super) { __extends(ElasticEase, _super); function ElasticEase(oscillations, springiness) { if (oscillations === void 0) { oscillations = 3; } if (springiness === void 0) { springiness = 3; } var _this = _super.call(this) || this; _this.oscillations = oscillations; _this.springiness = springiness; return _this; } ElasticEase.prototype.easeInCore = function (gradient) { var num2; var num3 = Math.max(0.0, this.oscillations); var num = Math.max(0.0, this.springiness); if (num == 0) { num2 = gradient; } else { num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0); } return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient)); }; return ElasticEase; }(EasingFunction)); BABYLON.ElasticEase = ElasticEase; var ExponentialEase = /** @class */ (function (_super) { __extends(ExponentialEase, _super); function ExponentialEase(exponent) { if (exponent === void 0) { exponent = 2; } var _this = _super.call(this) || this; _this.exponent = exponent; return _this; } ExponentialEase.prototype.easeInCore = function (gradient) { if (this.exponent <= 0) { return gradient; } return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0)); }; return ExponentialEase; }(EasingFunction)); BABYLON.ExponentialEase = ExponentialEase; var PowerEase = /** @class */ (function (_super) { __extends(PowerEase, _super); function PowerEase(power) { if (power === void 0) { power = 2; } var _this = _super.call(this) || this; _this.power = power; return _this; } PowerEase.prototype.easeInCore = function (gradient) { var y = Math.max(0.0, this.power); return Math.pow(gradient, y); }; return PowerEase; }(EasingFunction)); BABYLON.PowerEase = PowerEase; var QuadraticEase = /** @class */ (function (_super) { __extends(QuadraticEase, _super); function QuadraticEase() { return _super !== null && _super.apply(this, arguments) || this; } QuadraticEase.prototype.easeInCore = function (gradient) { return (gradient * gradient); }; return QuadraticEase; }(EasingFunction)); BABYLON.QuadraticEase = QuadraticEase; var QuarticEase = /** @class */ (function (_super) { __extends(QuarticEase, _super); function QuarticEase() { return _super !== null && _super.apply(this, arguments) || this; } QuarticEase.prototype.easeInCore = function (gradient) { return (gradient * gradient * gradient * gradient); }; return QuarticEase; }(EasingFunction)); BABYLON.QuarticEase = QuarticEase; var QuinticEase = /** @class */ (function (_super) { __extends(QuinticEase, _super); function QuinticEase() { return _super !== null && _super.apply(this, arguments) || this; } QuinticEase.prototype.easeInCore = function (gradient) { return (gradient * gradient * gradient * gradient * gradient); }; return QuinticEase; }(EasingFunction)); BABYLON.QuinticEase = QuinticEase; var SineEase = /** @class */ (function (_super) { __extends(SineEase, _super); function SineEase() { return _super !== null && _super.apply(this, arguments) || this; } SineEase.prototype.easeInCore = function (gradient) { return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient))); }; return SineEase; }(EasingFunction)); BABYLON.SineEase = SineEase; var BezierCurveEase = /** @class */ (function (_super) { __extends(BezierCurveEase, _super); function BezierCurveEase(x1, y1, x2, y2) { if (x1 === void 0) { x1 = 0; } if (y1 === void 0) { y1 = 0; } if (x2 === void 0) { x2 = 1; } if (y2 === void 0) { y2 = 1; } var _this = _super.call(this) || this; _this.x1 = x1; _this.y1 = y1; _this.x2 = x2; _this.y2 = y2; return _this; } BezierCurveEase.prototype.easeInCore = function (gradient) { return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2); }; return BezierCurveEase; }(EasingFunction)); BABYLON.BezierCurveEase = BezierCurveEase; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.easing.js.map var BABYLON; (function (BABYLON) { var Condition = /** @class */ (function () { function Condition(actionManager) { this._actionManager = actionManager; } Condition.prototype.isValid = function () { return true; }; Condition.prototype._getProperty = function (propertyPath) { return this._actionManager._getProperty(propertyPath); }; Condition.prototype._getEffectiveTarget = function (target, propertyPath) { return this._actionManager._getEffectiveTarget(target, propertyPath); }; Condition.prototype.serialize = function () { }; Condition.prototype._serialize = function (serializedCondition) { return { type: 2, children: [], name: serializedCondition.name, properties: serializedCondition.properties }; }; return Condition; }()); BABYLON.Condition = Condition; var ValueCondition = /** @class */ (function (_super) { __extends(ValueCondition, _super); function ValueCondition(actionManager, target, propertyPath, value, operator) { if (operator === void 0) { operator = ValueCondition.IsEqual; } var _this = _super.call(this, actionManager) || this; _this.propertyPath = propertyPath; _this.value = value; _this.operator = operator; _this._target = target; _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath); _this._property = _this._getProperty(_this.propertyPath); return _this; } Object.defineProperty(ValueCondition, "IsEqual", { get: function () { return ValueCondition._IsEqual; }, enumerable: true, configurable: true }); Object.defineProperty(ValueCondition, "IsDifferent", { get: function () { return ValueCondition._IsDifferent; }, enumerable: true, configurable: true }); Object.defineProperty(ValueCondition, "IsGreater", { get: function () { return ValueCondition._IsGreater; }, enumerable: true, configurable: true }); Object.defineProperty(ValueCondition, "IsLesser", { get: function () { return ValueCondition._IsLesser; }, enumerable: true, configurable: true }); // Methods ValueCondition.prototype.isValid = function () { switch (this.operator) { case ValueCondition.IsGreater: return this._effectiveTarget[this._property] > this.value; case ValueCondition.IsLesser: return this._effectiveTarget[this._property] < this.value; case ValueCondition.IsEqual: case ValueCondition.IsDifferent: var check; if (this.value.equals) { check = this.value.equals(this._effectiveTarget[this._property]); } else { check = this.value === this._effectiveTarget[this._property]; } return this.operator === ValueCondition.IsEqual ? check : !check; } return false; }; ValueCondition.prototype.serialize = function () { return this._serialize({ name: "ValueCondition", properties: [ BABYLON.Action._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }, { name: "operator", value: ValueCondition.GetOperatorName(this.operator) } ] }); }; ValueCondition.GetOperatorName = function (operator) { switch (operator) { case ValueCondition._IsEqual: return "IsEqual"; case ValueCondition._IsDifferent: return "IsDifferent"; case ValueCondition._IsGreater: return "IsGreater"; case ValueCondition._IsLesser: return "IsLesser"; default: return ""; } }; // Statics ValueCondition._IsEqual = 0; ValueCondition._IsDifferent = 1; ValueCondition._IsGreater = 2; ValueCondition._IsLesser = 3; return ValueCondition; }(Condition)); BABYLON.ValueCondition = ValueCondition; var PredicateCondition = /** @class */ (function (_super) { __extends(PredicateCondition, _super); function PredicateCondition(actionManager, predicate) { var _this = _super.call(this, actionManager) || this; _this.predicate = predicate; return _this; } PredicateCondition.prototype.isValid = function () { return this.predicate(); }; return PredicateCondition; }(Condition)); BABYLON.PredicateCondition = PredicateCondition; var StateCondition = /** @class */ (function (_super) { __extends(StateCondition, _super); function StateCondition(actionManager, target, value) { var _this = _super.call(this, actionManager) || this; _this.value = value; _this._target = target; return _this; } // Methods StateCondition.prototype.isValid = function () { return this._target.state === this.value; }; StateCondition.prototype.serialize = function () { return this._serialize({ name: "StateCondition", properties: [ BABYLON.Action._GetTargetProperty(this._target), { name: "value", value: this.value } ] }); }; return StateCondition; }(Condition)); BABYLON.StateCondition = StateCondition; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.condition.js.map var BABYLON; (function (BABYLON) { var Action = /** @class */ (function () { function Action(triggerOptions, condition) { this.triggerOptions = triggerOptions; this.onBeforeExecuteObservable = new BABYLON.Observable(); if (triggerOptions.parameter) { this.trigger = triggerOptions.trigger; this._triggerParameter = triggerOptions.parameter; } else { this.trigger = triggerOptions; } this._nextActiveAction = this; this._condition = condition; } // Methods Action.prototype._prepare = function () { }; Action.prototype.getTriggerParameter = function () { return this._triggerParameter; }; Action.prototype._executeCurrent = function (evt) { if (this._nextActiveAction._condition) { var condition = this._nextActiveAction._condition; var currentRenderId = this._actionManager.getScene().getRenderId(); // We cache the current evaluation for the current frame if (condition._evaluationId === currentRenderId) { if (!condition._currentResult) { return; } } else { condition._evaluationId = currentRenderId; if (!condition.isValid()) { condition._currentResult = false; return; } condition._currentResult = true; } } this.onBeforeExecuteObservable.notifyObservers(this); this._nextActiveAction.execute(evt); this.skipToNextActiveAction(); }; Action.prototype.execute = function (evt) { }; Action.prototype.skipToNextActiveAction = function () { if (this._nextActiveAction._child) { if (!this._nextActiveAction._child._actionManager) { this._nextActiveAction._child._actionManager = this._actionManager; } this._nextActiveAction = this._nextActiveAction._child; } else { this._nextActiveAction = this; } }; Action.prototype.then = function (action) { this._child = action; action._actionManager = this._actionManager; action._prepare(); return action; }; Action.prototype._getProperty = function (propertyPath) { return this._actionManager._getProperty(propertyPath); }; Action.prototype._getEffectiveTarget = function (target, propertyPath) { return this._actionManager._getEffectiveTarget(target, propertyPath); }; Action.prototype.serialize = function (parent) { }; // Called by BABYLON.Action objects in serialize(...). Internal use Action.prototype._serialize = function (serializedAction, parent) { var serializationObject = { type: 1, children: [], name: serializedAction.name, properties: serializedAction.properties || [] }; // Serialize child if (this._child) { this._child.serialize(serializationObject); } // Check if "this" has a condition if (this._condition) { var serializedCondition = this._condition.serialize(); serializedCondition.children.push(serializationObject); if (parent) { parent.children.push(serializedCondition); } return serializedCondition; } if (parent) { parent.children.push(serializationObject); } return serializationObject; }; Action._SerializeValueAsString = function (value) { if (typeof value === "number") { return value.toString(); } if (typeof value === "boolean") { return value ? "true" : "false"; } if (value instanceof BABYLON.Vector2) { return value.x + ", " + value.y; } if (value instanceof BABYLON.Vector3) { return value.x + ", " + value.y + ", " + value.z; } if (value instanceof BABYLON.Color3) { return value.r + ", " + value.g + ", " + value.b; } if (value instanceof BABYLON.Color4) { return value.r + ", " + value.g + ", " + value.b + ", " + value.a; } return value; // string }; Action._GetTargetProperty = function (target) { return { name: "target", targetType: target instanceof BABYLON.Mesh ? "MeshProperties" : target instanceof BABYLON.Light ? "LightProperties" : target instanceof BABYLON.Camera ? "CameraProperties" : "SceneProperties", value: target instanceof BABYLON.Scene ? "Scene" : target.name }; }; return Action; }()); BABYLON.Action = Action; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.action.js.map var BABYLON; (function (BABYLON) { /** * ActionEvent is the event beint sent when an action is triggered. */ var ActionEvent = /** @class */ (function () { /** * @param source The mesh or sprite that triggered the action. * @param pointerX The X mouse cursor position at the time of the event * @param pointerY The Y mouse cursor position at the time of the event * @param meshUnderPointer The mesh that is currently pointed at (can be null) * @param sourceEvent the original (browser) event that triggered the ActionEvent */ function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) { this.source = source; this.pointerX = pointerX; this.pointerY = pointerY; this.meshUnderPointer = meshUnderPointer; this.sourceEvent = sourceEvent; this.additionalData = additionalData; } /** * Helper function to auto-create an ActionEvent from a source mesh. * @param source The source mesh that triggered the event * @param evt {Event} The original (browser) event */ ActionEvent.CreateNew = function (source, evt, additionalData) { var scene = source.getScene(); return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData); }; /** * Helper function to auto-create an ActionEvent from a source mesh. * @param source The source sprite that triggered the event * @param scene Scene associated with the sprite * @param evt {Event} The original (browser) event */ ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) { return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData); }; /** * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew * @param scene the scene where the event occurred * @param evt {Event} The original (browser) event */ ActionEvent.CreateNewFromScene = function (scene, evt) { return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt); }; ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) { return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData); }; return ActionEvent; }()); BABYLON.ActionEvent = ActionEvent; /** * Action Manager manages all events to be triggered on a given mesh or the global scene. * A single scene can have many Action Managers to handle predefined actions on specific meshes. */ var ActionManager = /** @class */ (function () { function ActionManager(scene) { // Members this.actions = new Array(); this.hoverCursor = ''; this._scene = scene; scene._actionManagers.push(this); } Object.defineProperty(ActionManager, "NothingTrigger", { get: function () { return ActionManager._NothingTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnPickTrigger", { get: function () { return ActionManager._OnPickTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnLeftPickTrigger", { get: function () { return ActionManager._OnLeftPickTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnRightPickTrigger", { get: function () { return ActionManager._OnRightPickTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnCenterPickTrigger", { get: function () { return ActionManager._OnCenterPickTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnPickDownTrigger", { get: function () { return ActionManager._OnPickDownTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnDoublePickTrigger", { get: function () { return ActionManager._OnDoublePickTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnPickUpTrigger", { get: function () { return ActionManager._OnPickUpTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnPickOutTrigger", { /// This trigger will only be raised if you also declared a OnPickDown get: function () { return ActionManager._OnPickOutTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnLongPressTrigger", { get: function () { return ActionManager._OnLongPressTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnPointerOverTrigger", { get: function () { return ActionManager._OnPointerOverTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnPointerOutTrigger", { get: function () { return ActionManager._OnPointerOutTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnEveryFrameTrigger", { get: function () { return ActionManager._OnEveryFrameTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", { get: function () { return ActionManager._OnIntersectionEnterTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", { get: function () { return ActionManager._OnIntersectionExitTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnKeyDownTrigger", { get: function () { return ActionManager._OnKeyDownTrigger; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "OnKeyUpTrigger", { get: function () { return ActionManager._OnKeyUpTrigger; }, enumerable: true, configurable: true }); // Methods ActionManager.prototype.dispose = function () { var index = this._scene._actionManagers.indexOf(this); for (var i = 0; i < this.actions.length; i++) { var action = this.actions[i]; ActionManager.Triggers[action.trigger]--; if (ActionManager.Triggers[action.trigger] === 0) { delete ActionManager.Triggers[action.trigger]; } } if (index > -1) { this._scene._actionManagers.splice(index, 1); } }; ActionManager.prototype.getScene = function () { return this._scene; }; /** * Does this action manager handles actions of any of the given triggers * @param {number[]} triggers - the triggers to be tested * @return {boolean} whether one (or more) of the triggers is handeled */ ActionManager.prototype.hasSpecificTriggers = function (triggers) { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (triggers.indexOf(action.trigger) > -1) { return true; } } return false; }; /** * Does this action manager handles actions of a given trigger * @param {number} trigger - the trigger to be tested * @return {boolean} whether the trigger is handeled */ ActionManager.prototype.hasSpecificTrigger = function (trigger) { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger === trigger) { return true; } } return false; }; Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", { /** * Does this action manager has pointer triggers * @return {boolean} whether or not it has pointer triggers */ get: function () { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) { return true; } } return false; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager.prototype, "hasPickTriggers", { /** * Does this action manager has pick triggers * @return {boolean} whether or not it has pick triggers */ get: function () { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) { return true; } } return false; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "HasTriggers", { /** * Does exist one action manager with at least one trigger * @return {boolean} whether or not it exists one action manager with one trigger **/ get: function () { for (var t in ActionManager.Triggers) { if (ActionManager.Triggers.hasOwnProperty(t)) { return true; } } return false; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager, "HasPickTriggers", { /** * Does exist one action manager with at least one pick trigger * @return {boolean} whether or not it exists one action manager with one pick trigger **/ get: function () { for (var t in ActionManager.Triggers) { if (ActionManager.Triggers.hasOwnProperty(t)) { var t_int = parseInt(t); if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) { return true; } } } return false; }, enumerable: true, configurable: true }); /** * Does exist one action manager that handles actions of a given trigger * @param {number} trigger - the trigger to be tested * @return {boolean} whether the trigger is handeled by at least one action manager **/ ActionManager.HasSpecificTrigger = function (trigger) { for (var t in ActionManager.Triggers) { if (ActionManager.Triggers.hasOwnProperty(t)) { var t_int = parseInt(t); if (t_int === trigger) { return true; } } } return false; }; /** * Registers an action to this action manager * @param {BABYLON.Action} action - the action to be registered * @return {BABYLON.Action} the action amended (prepared) after registration */ ActionManager.prototype.registerAction = function (action) { if (action.trigger === ActionManager.OnEveryFrameTrigger) { if (this.getScene().actionManager !== this) { BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"); return null; } } this.actions.push(action); if (ActionManager.Triggers[action.trigger]) { ActionManager.Triggers[action.trigger]++; } else { ActionManager.Triggers[action.trigger] = 1; } action._actionManager = this; action._prepare(); return action; }; /** * Process a specific trigger * @param {number} trigger - the trigger to process * @param evt {BABYLON.ActionEvent} the event details to be processed */ ActionManager.prototype.processTrigger = function (trigger, evt) { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger === trigger) { if (evt) { if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) { var parameter = action.getTriggerParameter(); if (parameter && parameter !== evt.sourceEvent.keyCode) { if (!parameter.toLowerCase) { continue; } var lowerCase = parameter.toLowerCase(); if (lowerCase !== evt.sourceEvent.key) { var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode; var actualkey = String.fromCharCode(unicode).toLowerCase(); if (actualkey !== lowerCase) { continue; } } } } } action._executeCurrent(evt); } } }; ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) { var properties = propertyPath.split("."); for (var index = 0; index < properties.length - 1; index++) { target = target[properties[index]]; } return target; }; ActionManager.prototype._getProperty = function (propertyPath) { var properties = propertyPath.split("."); return properties[properties.length - 1]; }; ActionManager.prototype.serialize = function (name) { var root = { children: new Array(), name: name, type: 3, properties: new Array() // Empty for root but required }; for (var i = 0; i < this.actions.length; i++) { var triggerObject = { type: 0, children: new Array(), name: ActionManager.GetTriggerName(this.actions[i].trigger), properties: new Array() }; var triggerOptions = this.actions[i].triggerOptions; if (triggerOptions && typeof triggerOptions !== "number") { if (triggerOptions.parameter instanceof BABYLON.Node) { triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter)); } else { var parameter = {}; BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]); if (triggerOptions.parameter.mesh) { parameter._meshId = triggerOptions.parameter.mesh.id; } triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter }); } } // Serialize child action, recursively this.actions[i].serialize(triggerObject); // Add serialized trigger root.children.push(triggerObject); } return root; }; ActionManager.Parse = function (parsedActions, object, scene) { var actionManager = new BABYLON.ActionManager(scene); if (object === null) scene.actionManager = actionManager; else object.actionManager = actionManager; // instanciate a new object var instanciate = function (name, params) { var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype); newInstance.constructor.apply(newInstance, params); return newInstance; }; var parseParameter = function (name, value, target, propertyPath) { if (propertyPath === null) { // String, boolean or float var floatValue = parseFloat(value); if (value === "true" || value === "false") return value === "true"; else return isNaN(floatValue) ? value : floatValue; } var effectiveTarget = propertyPath.split("."); var values = value.split(","); // Get effective Target for (var i = 0; i < effectiveTarget.length; i++) { target = target[effectiveTarget[i]]; } // Return appropriate value with its type if (typeof (target) === "boolean") return values[0] === "true"; if (typeof (target) === "string") return values[0]; // Parameters with multiple values such as Vector3 etc. var split = new Array(); for (var i = 0; i < values.length; i++) split.push(parseFloat(values[i])); if (target instanceof BABYLON.Vector3) return BABYLON.Vector3.FromArray(split); if (target instanceof BABYLON.Vector4) return BABYLON.Vector4.FromArray(split); if (target instanceof BABYLON.Color3) return BABYLON.Color3.FromArray(split); if (target instanceof BABYLON.Color4) return BABYLON.Color4.FromArray(split); return parseFloat(values[0]); }; // traverse graph per trigger var traverse = function (parsedAction, trigger, condition, action, combineArray) { if (combineArray === void 0) { combineArray = null; } if (parsedAction.detached) return; var parameters = new Array(); var target = null; var propertyPath = null; var combine = parsedAction.combine && parsedAction.combine.length > 0; // Parameters if (parsedAction.type === 2) parameters.push(actionManager); else parameters.push(trigger); if (combine) { var actions = new Array(); for (var j = 0; j < parsedAction.combine.length; j++) { traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions); } parameters.push(actions); } else { for (var i = 0; i < parsedAction.properties.length; i++) { var value = parsedAction.properties[i].value; var name = parsedAction.properties[i].name; var targetType = parsedAction.properties[i].targetType; if (name === "target") if (targetType !== null && targetType === "SceneProperties") value = target = scene; else value = target = scene.getNodeByName(value); else if (name === "parent") value = scene.getNodeByName(value); else if (name === "sound") value = scene.getSoundByName(value); else if (name !== "propertyPath") { if (parsedAction.type === 2 && name === "operator") value = BABYLON.ValueCondition[value]; else value = parseParameter(name, value, target, name === "value" ? propertyPath : null); } else { propertyPath = value; } parameters.push(value); } } if (combineArray === null) { parameters.push(condition); } else { parameters.push(null); } // If interpolate value action if (parsedAction.name === "InterpolateValueAction") { var param = parameters[parameters.length - 2]; parameters[parameters.length - 1] = param; parameters[parameters.length - 2] = condition; } // Action or condition(s) and not CombineAction var newAction = instanciate(parsedAction.name, parameters); if (newAction instanceof BABYLON.Condition && condition !== null) { var nothing = new BABYLON.DoNothingAction(trigger, condition); if (action) action.then(nothing); else actionManager.registerAction(nothing); action = nothing; } if (combineArray === null) { if (newAction instanceof BABYLON.Condition) { condition = newAction; newAction = action; } else { condition = null; if (action) action.then(newAction); else actionManager.registerAction(newAction); } } else { combineArray.push(newAction); } for (var i = 0; i < parsedAction.children.length; i++) traverse(parsedAction.children[i], trigger, condition, newAction, null); }; // triggers for (var i = 0; i < parsedActions.children.length; i++) { var triggerParams; var trigger = parsedActions.children[i]; if (trigger.properties.length > 0) { var param = trigger.properties[0].value; var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param); if (value._meshId) { value.mesh = scene.getMeshByID(value._meshId); } triggerParams = { trigger: ActionManager[trigger.name], parameter: value }; } else triggerParams = ActionManager[trigger.name]; for (var j = 0; j < trigger.children.length; j++) { if (!trigger.detached) traverse(trigger.children[j], triggerParams, null, null); } } }; ActionManager.GetTriggerName = function (trigger) { switch (trigger) { case 0: return "NothingTrigger"; case 1: return "OnPickTrigger"; case 2: return "OnLeftPickTrigger"; case 3: return "OnRightPickTrigger"; case 4: return "OnCenterPickTrigger"; case 5: return "OnPickDownTrigger"; case 6: return "OnPickUpTrigger"; case 7: return "OnLongPressTrigger"; case 8: return "OnPointerOverTrigger"; case 9: return "OnPointerOutTrigger"; case 10: return "OnEveryFrameTrigger"; case 11: return "OnIntersectionEnterTrigger"; case 12: return "OnIntersectionExitTrigger"; case 13: return "OnKeyDownTrigger"; case 14: return "OnKeyUpTrigger"; case 15: return "OnPickOutTrigger"; default: return ""; } }; // Statics ActionManager._NothingTrigger = 0; ActionManager._OnPickTrigger = 1; ActionManager._OnLeftPickTrigger = 2; ActionManager._OnRightPickTrigger = 3; ActionManager._OnCenterPickTrigger = 4; ActionManager._OnPickDownTrigger = 5; ActionManager._OnDoublePickTrigger = 6; ActionManager._OnPickUpTrigger = 7; ActionManager._OnLongPressTrigger = 8; ActionManager._OnPointerOverTrigger = 9; ActionManager._OnPointerOutTrigger = 10; ActionManager._OnEveryFrameTrigger = 11; ActionManager._OnIntersectionEnterTrigger = 12; ActionManager._OnIntersectionExitTrigger = 13; ActionManager._OnKeyDownTrigger = 14; ActionManager._OnKeyUpTrigger = 15; ActionManager._OnPickOutTrigger = 16; ActionManager.Triggers = {}; return ActionManager; }()); BABYLON.ActionManager = ActionManager; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.actionManager.js.map var BABYLON; (function (BABYLON) { var InterpolateValueAction = /** @class */ (function (_super) { __extends(InterpolateValueAction, _super); function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) { if (duration === void 0) { duration = 1000; } var _this = _super.call(this, triggerOptions, condition) || this; _this.propertyPath = propertyPath; _this.value = value; _this.duration = duration; _this.stopOtherAnimations = stopOtherAnimations; _this.onInterpolationDone = onInterpolationDone; _this.onInterpolationDoneObservable = new BABYLON.Observable(); _this._target = _this._effectiveTarget = target; return _this; } InterpolateValueAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); }; InterpolateValueAction.prototype.execute = function () { var _this = this; var scene = this._actionManager.getScene(); var keys = [ { frame: 0, value: this._effectiveTarget[this._property] }, { frame: 100, value: this.value } ]; var dataType; if (typeof this.value === "number") { dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT; } else if (this.value instanceof BABYLON.Color3) { dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3; } else if (this.value instanceof BABYLON.Vector3) { dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3; } else if (this.value instanceof BABYLON.Matrix) { dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX; } else if (this.value instanceof BABYLON.Quaternion) { dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION; } else { BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")"); return; } var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT); animation.setKeys(keys); if (this.stopOtherAnimations) { scene.stopAnimation(this._effectiveTarget); } var wrapper = function () { _this.onInterpolationDoneObservable.notifyObservers(_this); if (_this.onInterpolationDone) { _this.onInterpolationDone(); } }; scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper); }; InterpolateValueAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "InterpolateValueAction", properties: [ BABYLON.Action._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }, { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) }, { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false } ] }, parent); }; return InterpolateValueAction; }(BABYLON.Action)); BABYLON.InterpolateValueAction = InterpolateValueAction; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.interpolateValueAction.js.map var BABYLON; (function (BABYLON) { var SwitchBooleanAction = /** @class */ (function (_super) { __extends(SwitchBooleanAction, _super); function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.propertyPath = propertyPath; _this._target = _this._effectiveTarget = target; return _this; } SwitchBooleanAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); }; SwitchBooleanAction.prototype.execute = function () { this._effectiveTarget[this._property] = !this._effectiveTarget[this._property]; }; SwitchBooleanAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SwitchBooleanAction", properties: [ BABYLON.Action._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath } ] }, parent); }; return SwitchBooleanAction; }(BABYLON.Action)); BABYLON.SwitchBooleanAction = SwitchBooleanAction; var SetStateAction = /** @class */ (function (_super) { __extends(SetStateAction, _super); function SetStateAction(triggerOptions, target, value, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.value = value; _this._target = target; return _this; } SetStateAction.prototype.execute = function () { this._target.state = this.value; }; SetStateAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SetStateAction", properties: [ BABYLON.Action._GetTargetProperty(this._target), { name: "value", value: this.value } ] }, parent); }; return SetStateAction; }(BABYLON.Action)); BABYLON.SetStateAction = SetStateAction; var SetValueAction = /** @class */ (function (_super) { __extends(SetValueAction, _super); function SetValueAction(triggerOptions, target, propertyPath, value, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.propertyPath = propertyPath; _this.value = value; _this._target = _this._effectiveTarget = target; return _this; } SetValueAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); }; SetValueAction.prototype.execute = function () { this._effectiveTarget[this._property] = this.value; if (this._target.markAsDirty) { this._target.markAsDirty(this._property); } }; SetValueAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SetValueAction", properties: [ BABYLON.Action._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) } ] }, parent); }; return SetValueAction; }(BABYLON.Action)); BABYLON.SetValueAction = SetValueAction; var IncrementValueAction = /** @class */ (function (_super) { __extends(IncrementValueAction, _super); function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.propertyPath = propertyPath; _this.value = value; _this._target = _this._effectiveTarget = target; return _this; } IncrementValueAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); if (typeof this._effectiveTarget[this._property] !== "number") { BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values"); } }; IncrementValueAction.prototype.execute = function () { this._effectiveTarget[this._property] += this.value; if (this._target.markAsDirty) { this._target.markAsDirty(this._property); } }; IncrementValueAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "IncrementValueAction", properties: [ BABYLON.Action._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) } ] }, parent); }; return IncrementValueAction; }(BABYLON.Action)); BABYLON.IncrementValueAction = IncrementValueAction; var PlayAnimationAction = /** @class */ (function (_super) { __extends(PlayAnimationAction, _super); function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.from = from; _this.to = to; _this.loop = loop; _this._target = target; return _this; } PlayAnimationAction.prototype._prepare = function () { }; PlayAnimationAction.prototype.execute = function () { var scene = this._actionManager.getScene(); scene.beginAnimation(this._target, this.from, this.to, this.loop); }; PlayAnimationAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "PlayAnimationAction", properties: [ BABYLON.Action._GetTargetProperty(this._target), { name: "from", value: String(this.from) }, { name: "to", value: String(this.to) }, { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false } ] }, parent); }; return PlayAnimationAction; }(BABYLON.Action)); BABYLON.PlayAnimationAction = PlayAnimationAction; var StopAnimationAction = /** @class */ (function (_super) { __extends(StopAnimationAction, _super); function StopAnimationAction(triggerOptions, target, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._target = target; return _this; } StopAnimationAction.prototype._prepare = function () { }; StopAnimationAction.prototype.execute = function () { var scene = this._actionManager.getScene(); scene.stopAnimation(this._target); }; StopAnimationAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "StopAnimationAction", properties: [BABYLON.Action._GetTargetProperty(this._target)] }, parent); }; return StopAnimationAction; }(BABYLON.Action)); BABYLON.StopAnimationAction = StopAnimationAction; var DoNothingAction = /** @class */ (function (_super) { __extends(DoNothingAction, _super); function DoNothingAction(triggerOptions, condition) { if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; } return _super.call(this, triggerOptions, condition) || this; } DoNothingAction.prototype.execute = function () { }; DoNothingAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "DoNothingAction", properties: [] }, parent); }; return DoNothingAction; }(BABYLON.Action)); BABYLON.DoNothingAction = DoNothingAction; var CombineAction = /** @class */ (function (_super) { __extends(CombineAction, _super); function CombineAction(triggerOptions, children, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.children = children; return _this; } CombineAction.prototype._prepare = function () { for (var index = 0; index < this.children.length; index++) { this.children[index]._actionManager = this._actionManager; this.children[index]._prepare(); } }; CombineAction.prototype.execute = function (evt) { for (var index = 0; index < this.children.length; index++) { this.children[index].execute(evt); } }; CombineAction.prototype.serialize = function (parent) { var serializationObject = _super.prototype._serialize.call(this, { name: "CombineAction", properties: [], combine: [] }, parent); for (var i = 0; i < this.children.length; i++) { serializationObject.combine.push(this.children[i].serialize(null)); } return serializationObject; }; return CombineAction; }(BABYLON.Action)); BABYLON.CombineAction = CombineAction; var ExecuteCodeAction = /** @class */ (function (_super) { __extends(ExecuteCodeAction, _super); function ExecuteCodeAction(triggerOptions, func, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.func = func; return _this; } ExecuteCodeAction.prototype.execute = function (evt) { this.func(evt); }; return ExecuteCodeAction; }(BABYLON.Action)); BABYLON.ExecuteCodeAction = ExecuteCodeAction; var SetParentAction = /** @class */ (function (_super) { __extends(SetParentAction, _super); function SetParentAction(triggerOptions, target, parent, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._target = target; _this._parent = parent; return _this; } SetParentAction.prototype._prepare = function () { }; SetParentAction.prototype.execute = function () { if (this._target.parent === this._parent) { return; } var invertParentWorldMatrix = this._parent.getWorldMatrix().clone(); invertParentWorldMatrix.invert(); this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix); this._target.parent = this._parent; }; SetParentAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SetParentAction", properties: [ BABYLON.Action._GetTargetProperty(this._target), BABYLON.Action._GetTargetProperty(this._parent), ] }, parent); }; return SetParentAction; }(BABYLON.Action)); BABYLON.SetParentAction = SetParentAction; var PlaySoundAction = /** @class */ (function (_super) { __extends(PlaySoundAction, _super); function PlaySoundAction(triggerOptions, sound, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._sound = sound; return _this; } PlaySoundAction.prototype._prepare = function () { }; PlaySoundAction.prototype.execute = function () { if (this._sound !== undefined) this._sound.play(); }; PlaySoundAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "PlaySoundAction", properties: [{ name: "sound", value: this._sound.name }] }, parent); }; return PlaySoundAction; }(BABYLON.Action)); BABYLON.PlaySoundAction = PlaySoundAction; var StopSoundAction = /** @class */ (function (_super) { __extends(StopSoundAction, _super); function StopSoundAction(triggerOptions, sound, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._sound = sound; return _this; } StopSoundAction.prototype._prepare = function () { }; StopSoundAction.prototype.execute = function () { if (this._sound !== undefined) this._sound.stop(); }; StopSoundAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "StopSoundAction", properties: [{ name: "sound", value: this._sound.name }] }, parent); }; return StopSoundAction; }(BABYLON.Action)); BABYLON.StopSoundAction = StopSoundAction; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.directActions.js.map var BABYLON; (function (BABYLON) { var SpriteManager = /** @class */ (function () { function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) { if (epsilon === void 0) { epsilon = 0.01; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } this.name = name; this.sprites = new Array(); this.renderingGroupId = 0; this.layerMask = 0x0FFFFFFF; this.fogEnabled = true; this.isPickable = false; /** * An event triggered when the manager is disposed. * @type {BABYLON.Observable} */ this.onDisposeObservable = new BABYLON.Observable(); this._vertexBuffers = {}; this._capacity = capacity; this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode); this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; if (cellSize.width && cellSize.height) { this.cellWidth = cellSize.width; this.cellHeight = cellSize.height; } else if (cellSize !== undefined) { this.cellWidth = cellSize; this.cellHeight = cellSize; } else { return; } this._epsilon = epsilon; this._scene = scene; this._scene.spriteManagers.push(this); var indices = []; var index = 0; for (var count = 0; count < capacity; count++) { indices.push(index); indices.push(index + 1); indices.push(index + 2); indices.push(index); indices.push(index + 2); indices.push(index + 3); index += 4; } this._indexBuffer = scene.getEngine().createIndexBuffer(indices); // VBO // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a) this._vertexData = new Float32Array(capacity * 16 * 4); this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16); var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4); var options = this._buffer.createVertexBuffer("options", 4, 4); var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4); var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions; this._vertexBuffers["options"] = options; this._vertexBuffers["cellInfo"] = cellInfo; this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors; // Effects this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], ""); this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG"); } Object.defineProperty(SpriteManager.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(SpriteManager.prototype, "texture", { get: function () { return this._spriteTexture; }, set: function (value) { this._spriteTexture = value; }, enumerable: true, configurable: true }); SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) { var arrayOffset = index * 16; if (offsetX === 0) offsetX = this._epsilon; else if (offsetX === 1) offsetX = 1 - this._epsilon; if (offsetY === 0) offsetY = this._epsilon; else if (offsetY === 1) offsetY = 1 - this._epsilon; this._vertexData[arrayOffset] = sprite.position.x; this._vertexData[arrayOffset + 1] = sprite.position.y; this._vertexData[arrayOffset + 2] = sprite.position.z; this._vertexData[arrayOffset + 3] = sprite.angle; this._vertexData[arrayOffset + 4] = sprite.width; this._vertexData[arrayOffset + 5] = sprite.height; this._vertexData[arrayOffset + 6] = offsetX; this._vertexData[arrayOffset + 7] = offsetY; this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0; this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0; var offset = (sprite.cellIndex / rowSize) >> 0; this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize; this._vertexData[arrayOffset + 11] = offset; // Color this._vertexData[arrayOffset + 12] = sprite.color.r; this._vertexData[arrayOffset + 13] = sprite.color.g; this._vertexData[arrayOffset + 14] = sprite.color.b; this._vertexData[arrayOffset + 15] = sprite.color.a; }; SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) { var count = Math.min(this._capacity, this.sprites.length); var min = BABYLON.Vector3.Zero(); var max = BABYLON.Vector3.Zero(); var distance = Number.MAX_VALUE; var currentSprite = null; var cameraSpacePosition = BABYLON.Vector3.Zero(); var cameraView = camera.getViewMatrix(); for (var index = 0; index < count; index++) { var sprite = this.sprites[index]; if (!sprite) { continue; } if (predicate) { if (!predicate(sprite)) { continue; } } else if (!sprite.isPickable) { continue; } BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition); min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z); max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z); if (ray.intersectsBoxMinMax(min, max)) { var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin); if (distance > currentDistance) { distance = currentDistance; currentSprite = sprite; if (fastCheck) { break; } } } } if (currentSprite) { var result = new BABYLON.PickingInfo(); result.hit = true; result.pickedSprite = currentSprite; result.distance = distance; return result; } return null; }; SpriteManager.prototype.render = function () { // Check if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) return; var engine = this._scene.getEngine(); var baseSize = this._spriteTexture.getBaseSize(); // Sprites var deltaTime = engine.getDeltaTime(); var max = Math.min(this._capacity, this.sprites.length); var rowSize = baseSize.width / this.cellWidth; var offset = 0; for (var index = 0; index < max; index++) { var sprite = this.sprites[index]; if (!sprite) { continue; } sprite._animate(deltaTime); this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize); this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize); this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize); this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize); } this._buffer.update(this._vertexData); // Render var effect = this._effectBase; if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) { effect = this._effectFog; } engine.enableEffect(effect); var viewMatrix = this._scene.getViewMatrix(); effect.setTexture("diffuseSampler", this._spriteTexture); effect.setMatrix("view", viewMatrix); effect.setMatrix("projection", this._scene.getProjectionMatrix()); effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height); // Fog if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) { effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity); effect.setColor3("vFogColor", this._scene.fogColor); } // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); // Draw order engine.setDepthFunctionToLessOrEqual(); effect.setBool("alphaTest", true); engine.setColorWrite(false); engine.draw(true, 0, max * 6); engine.setColorWrite(true); effect.setBool("alphaTest", false); engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE); engine.draw(true, 0, max * 6); engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE); }; SpriteManager.prototype.dispose = function () { if (this._buffer) { this._buffer.dispose(); this._buffer = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } if (this._spriteTexture) { this._spriteTexture.dispose(); this._spriteTexture = null; } // Remove from scene var index = this._scene.spriteManagers.indexOf(this); this._scene.spriteManagers.splice(index, 1); // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); }; return SpriteManager; }()); BABYLON.SpriteManager = SpriteManager; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.spriteManager.js.map var BABYLON; (function (BABYLON) { var Sprite = /** @class */ (function () { function Sprite(name, manager) { this.name = name; this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); this.width = 1.0; this.height = 1.0; this.angle = 0; this.cellIndex = 0; this.invertU = 0; this.invertV = 0; this.animations = new Array(); this.isPickable = false; this._animationStarted = false; this._loopAnimation = false; this._fromIndex = 0; this._toIndex = 0; this._delay = 0; this._direction = 1; this._time = 0; this._manager = manager; this._manager.sprites.push(this); this.position = BABYLON.Vector3.Zero(); } Object.defineProperty(Sprite.prototype, "size", { get: function () { return this.width; }, set: function (value) { this.width = value; this.height = value; }, enumerable: true, configurable: true }); Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) { this._fromIndex = from; this._toIndex = to; this._loopAnimation = loop; this._delay = delay; this._animationStarted = true; this._direction = from < to ? 1 : -1; this.cellIndex = from; this._time = 0; this._onAnimationEnd = onAnimationEnd; }; Sprite.prototype.stopAnimation = function () { this._animationStarted = false; }; Sprite.prototype._animate = function (deltaTime) { if (!this._animationStarted) return; this._time += deltaTime; if (this._time > this._delay) { this._time = this._time % this._delay; this.cellIndex += this._direction; if (this.cellIndex > this._toIndex) { if (this._loopAnimation) { this.cellIndex = this._fromIndex; } else { this.cellIndex = this._toIndex; this._animationStarted = false; if (this._onAnimationEnd) { this._onAnimationEnd(); } if (this.disposeWhenFinishedAnimating) { this.dispose(); } } } } }; Sprite.prototype.dispose = function () { for (var i = 0; i < this._manager.sprites.length; i++) { if (this._manager.sprites[i] == this) { this._manager.sprites.splice(i, 1); } } }; return Sprite; }()); BABYLON.Sprite = Sprite; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.sprite.js.map var BABYLON; (function (BABYLON) { var IntersectionInfo = /** @class */ (function () { function IntersectionInfo(bu, bv, distance) { this.bu = bu; this.bv = bv; this.distance = distance; this.faceId = 0; this.subMeshId = 0; } return IntersectionInfo; }()); BABYLON.IntersectionInfo = IntersectionInfo; var PickingInfo = /** @class */ (function () { function PickingInfo() { this.hit = false; this.distance = 0; this.pickedPoint = null; this.pickedMesh = null; this.bu = 0; this.bv = 0; this.faceId = -1; this.subMeshId = 0; this.pickedSprite = null; } // Methods PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) { if (useWorldCoordinates === void 0) { useWorldCoordinates = false; } if (useVerticesNormals === void 0) { useVerticesNormals = true; } if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) { return null; } var indices = this.pickedMesh.getIndices(); if (!indices) { return null; } var result; if (useVerticesNormals) { var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind); var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3); var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3); var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3); normal0 = normal0.scale(this.bu); normal1 = normal1.scale(this.bv); normal2 = normal2.scale(1.0 - this.bu - this.bv); result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z); } else { var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind); var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3); var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3); var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3); var p1p2 = vertex1.subtract(vertex2); var p3p2 = vertex3.subtract(vertex2); result = BABYLON.Vector3.Cross(p1p2, p3p2); } if (useWorldCoordinates) { result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix()); } return BABYLON.Vector3.Normalize(result); }; PickingInfo.prototype.getTextureCoordinates = function () { if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) { return null; } var indices = this.pickedMesh.getIndices(); if (!indices) { return null; } var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind); if (!uvs) { return null; } var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2); var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2); var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2); uv0 = uv0.scale(1.0 - this.bu - this.bv); uv1 = uv1.scale(this.bu); uv2 = uv2.scale(this.bv); return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y); }; return PickingInfo; }()); BABYLON.PickingInfo = PickingInfo; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.pickingInfo.js.map var BABYLON; (function (BABYLON) { var Ray = /** @class */ (function () { function Ray(origin, direction, length) { if (length === void 0) { length = Number.MAX_VALUE; } this.origin = origin; this.direction = direction; this.length = length; } // Methods Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) { var d = 0.0; var maxValue = Number.MAX_VALUE; var inv; var min; var max; var temp; if (Math.abs(this.direction.x) < 0.0000001) { if (this.origin.x < minimum.x || this.origin.x > maximum.x) { return false; } } else { inv = 1.0 / this.direction.x; min = (minimum.x - this.origin.x) * inv; max = (maximum.x - this.origin.x) * inv; if (max === -Infinity) { max = Infinity; } if (min > max) { temp = min; min = max; max = temp; } d = Math.max(min, d); maxValue = Math.min(max, maxValue); if (d > maxValue) { return false; } } if (Math.abs(this.direction.y) < 0.0000001) { if (this.origin.y < minimum.y || this.origin.y > maximum.y) { return false; } } else { inv = 1.0 / this.direction.y; min = (minimum.y - this.origin.y) * inv; max = (maximum.y - this.origin.y) * inv; if (max === -Infinity) { max = Infinity; } if (min > max) { temp = min; min = max; max = temp; } d = Math.max(min, d); maxValue = Math.min(max, maxValue); if (d > maxValue) { return false; } } if (Math.abs(this.direction.z) < 0.0000001) { if (this.origin.z < minimum.z || this.origin.z > maximum.z) { return false; } } else { inv = 1.0 / this.direction.z; min = (minimum.z - this.origin.z) * inv; max = (maximum.z - this.origin.z) * inv; if (max === -Infinity) { max = Infinity; } if (min > max) { temp = min; min = max; max = temp; } d = Math.max(min, d); maxValue = Math.min(max, maxValue); if (d > maxValue) { return false; } } return true; }; Ray.prototype.intersectsBox = function (box) { return this.intersectsBoxMinMax(box.minimum, box.maximum); }; Ray.prototype.intersectsSphere = function (sphere) { var x = sphere.center.x - this.origin.x; var y = sphere.center.y - this.origin.y; var z = sphere.center.z - this.origin.z; var pyth = (x * x) + (y * y) + (z * z); var rr = sphere.radius * sphere.radius; if (pyth <= rr) { return true; } var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z); if (dot < 0.0) { return false; } var temp = pyth - (dot * dot); return temp <= rr; }; Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) { if (!this._edge1) { this._edge1 = BABYLON.Vector3.Zero(); this._edge2 = BABYLON.Vector3.Zero(); this._pvec = BABYLON.Vector3.Zero(); this._tvec = BABYLON.Vector3.Zero(); this._qvec = BABYLON.Vector3.Zero(); } vertex1.subtractToRef(vertex0, this._edge1); vertex2.subtractToRef(vertex0, this._edge2); BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec); var det = BABYLON.Vector3.Dot(this._edge1, this._pvec); if (det === 0) { return null; } var invdet = 1 / det; this.origin.subtractToRef(vertex0, this._tvec); var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet; if (bu < 0 || bu > 1.0) { return null; } BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec); var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet; if (bv < 0 || bu + bv > 1.0) { return null; } //check if the distance is longer than the predefined length. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet; if (distance > this.length) { return null; } return new BABYLON.IntersectionInfo(bu, bv, distance); }; Ray.prototype.intersectsPlane = function (plane) { var distance; var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction); if (Math.abs(result1) < 9.99999997475243E-07) { return null; } else { var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin); distance = (-plane.d - result2) / result1; if (distance < 0.0) { if (distance < -9.99999997475243E-07) { return null; } else { return 0; } } return distance; } }; Ray.prototype.intersectsMesh = function (mesh, fastCheck) { var tm = BABYLON.Tmp.Matrix[0]; mesh.getWorldMatrix().invertToRef(tm); if (this._tmpRay) { Ray.TransformToRef(this, tm, this._tmpRay); } else { this._tmpRay = Ray.Transform(this, tm); } return mesh.intersects(this._tmpRay, fastCheck); }; Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) { if (results) { results.length = 0; } else { results = []; } for (var i = 0; i < meshes.length; i++) { var pickInfo = this.intersectsMesh(meshes[i], fastCheck); if (pickInfo.hit) { results.push(pickInfo); } } results.sort(this._comparePickingInfo); return results; }; Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) { if (pickingInfoA.distance < pickingInfoB.distance) { return -1; } else if (pickingInfoA.distance > pickingInfoB.distance) { return 1; } else { return 0; } }; /** * Intersection test between the ray and a given segment whithin a given tolerance (threshold) * @param sega the first point of the segment to test the intersection against * @param segb the second point of the segment to test the intersection against * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection */ Ray.prototype.intersectionSegment = function (sega, segb, threshold) { var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl)); var u = segb.subtract(sega); var v = rsegb.subtract(this.origin); var w = sega.subtract(this.origin); var a = BABYLON.Vector3.Dot(u, u); // always >= 0 var b = BABYLON.Vector3.Dot(u, v); var c = BABYLON.Vector3.Dot(v, v); // always >= 0 var d = BABYLON.Vector3.Dot(u, w); var e = BABYLON.Vector3.Dot(v, w); var D = a * c - b * b; // always >= 0 var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0 var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0 // compute the line parameters of the two closest points if (D < Ray.smallnum) { sN = 0.0; // force using point P0 on segment S1 sD = 1.0; // to prevent possible division by 0.0 later tN = e; tD = c; } else { sN = (b * e - c * d); tN = (a * e - b * d); if (sN < 0.0) { sN = 0.0; tN = e; tD = c; } else if (sN > sD) { sN = sD; tN = e + b; tD = c; } } if (tN < 0.0) { tN = 0.0; // recompute sc for this edge if (-d < 0.0) { sN = 0.0; } else if (-d > a) sN = sD; else { sN = -d; sD = a; } } else if (tN > tD) { tN = tD; // recompute sc for this edge if ((-d + b) < 0.0) { sN = 0; } else if ((-d + b) > a) { sN = sD; } else { sN = (-d + b); sD = a; } } // finally do the division to get sc and tc sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD); tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD); // get the difference of the two closest points var qtc = v.multiplyByFloats(tc, tc, tc); var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc) var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result if (isIntersected) { return qtc.length(); } return -1; }; // Statics Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) { var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection); var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection); var direction = end.subtract(start); direction.normalize(); return new Ray(start, direction); }; /** * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be * transformed to the given world matrix. * @param origin The origin point * @param end The end point * @param world a matrix to transform the ray to. Default is the identity matrix. */ Ray.CreateNewFromTo = function (origin, end, world) { if (world === void 0) { world = BABYLON.Matrix.Identity(); } var direction = end.subtract(origin); var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z)); direction.normalize(); return Ray.Transform(new Ray(origin, direction, length), world); }; Ray.Transform = function (ray, matrix) { var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0)); Ray.TransformToRef(ray, matrix, result); return result; }; Ray.TransformToRef = function (ray, matrix, result) { BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin); BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction); result.length = ray.length; var dir = result.direction; var len = dir.length(); if (!(len === 0 || len === 1)) { var num = 1.0 / len; dir.x *= num; dir.y *= num; dir.z *= num; result.length *= len; } }; Ray.smallnum = 0.00000001; Ray.rayl = 10e8; return Ray; }()); BABYLON.Ray = Ray; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.ray.js.map var BABYLON; (function (BABYLON) { var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) { if (boxMin.x > sphereCenter.x + sphereRadius) return false; if (sphereCenter.x - sphereRadius > boxMax.x) return false; if (boxMin.y > sphereCenter.y + sphereRadius) return false; if (sphereCenter.y - sphereRadius > boxMax.y) return false; if (boxMin.z > sphereCenter.z + sphereRadius) return false; if (sphereCenter.z - sphereRadius > boxMax.z) return false; return true; }; var getLowestRoot = (function () { var result = { root: 0, found: false }; return function (a, b, c, maxR) { result.root = 0; result.found = false; var determinant = b * b - 4.0 * a * c; if (determinant < 0) return result; var sqrtD = Math.sqrt(determinant); var r1 = (-b - sqrtD) / (2.0 * a); var r2 = (-b + sqrtD) / (2.0 * a); if (r1 > r2) { var temp = r2; r2 = r1; r1 = temp; } if (r1 > 0 && r1 < maxR) { result.root = r1; result.found = true; return result; } if (r2 > 0 && r2 < maxR) { result.root = r2; result.found = true; return result; } return result; }; })(); var Collider = /** @class */ (function () { function Collider() { this.radius = BABYLON.Vector3.One(); this.retry = 0; this.basePointWorld = BABYLON.Vector3.Zero(); this.velocityWorld = BABYLON.Vector3.Zero(); this.normalizedVelocity = BABYLON.Vector3.Zero(); this._collisionPoint = BABYLON.Vector3.Zero(); this._planeIntersectionPoint = BABYLON.Vector3.Zero(); this._tempVector = BABYLON.Vector3.Zero(); this._tempVector2 = BABYLON.Vector3.Zero(); this._tempVector3 = BABYLON.Vector3.Zero(); this._tempVector4 = BABYLON.Vector3.Zero(); this._edge = BABYLON.Vector3.Zero(); this._baseToVertex = BABYLON.Vector3.Zero(); this._destinationPoint = BABYLON.Vector3.Zero(); this._slidePlaneNormal = BABYLON.Vector3.Zero(); this._displacementVector = BABYLON.Vector3.Zero(); this._collisionMask = -1; } Object.defineProperty(Collider.prototype, "collisionMask", { get: function () { return this._collisionMask; }, set: function (mask) { this._collisionMask = !isNaN(mask) ? mask : -1; }, enumerable: true, configurable: true }); // Methods Collider.prototype._initialize = function (source, dir, e) { this.velocity = dir; BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity); this.basePoint = source; source.multiplyToRef(this.radius, this.basePointWorld); dir.multiplyToRef(this.radius, this.velocityWorld); this.velocityWorldLength = this.velocityWorld.length(); this.epsilon = e; this.collisionFound = false; }; Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) { pa.subtractToRef(point, this._tempVector); pb.subtractToRef(point, this._tempVector2); BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4); var d = BABYLON.Vector3.Dot(this._tempVector4, n); if (d < 0) return false; pc.subtractToRef(point, this._tempVector3); BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4); d = BABYLON.Vector3.Dot(this._tempVector4, n); if (d < 0) return false; BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4); d = BABYLON.Vector3.Dot(this._tempVector4, n); return d >= 0; }; Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) { var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter); var max = Math.max(this.radius.x, this.radius.y, this.radius.z); if (distance > this.velocityWorldLength + max + sphereRadius) { return false; } if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max)) return false; return true; }; Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) { var t0; var embeddedInPlane = false; //defensive programming, actually not needed. if (!trianglePlaneArray) { trianglePlaneArray = []; } if (!trianglePlaneArray[faceIndex]) { trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0); trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3); } var trianglePlane = trianglePlaneArray[faceIndex]; if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0)) return; var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint); var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity); if (normalDotVelocity == 0) { if (Math.abs(signedDistToTrianglePlane) >= 1.0) return; embeddedInPlane = true; t0 = 0; } else { t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity; var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity; if (t0 > t1) { var temp = t1; t1 = t0; t0 = temp; } if (t0 > 1.0 || t1 < 0.0) return; if (t0 < 0) t0 = 0; if (t0 > 1.0) t0 = 1.0; } this._collisionPoint.copyFromFloats(0, 0, 0); var found = false; var t = 1.0; if (!embeddedInPlane) { this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint); this.velocity.scaleToRef(t0, this._tempVector); this._planeIntersectionPoint.addInPlace(this._tempVector); if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) { found = true; t = t0; this._collisionPoint.copyFrom(this._planeIntersectionPoint); } } if (!found) { var velocitySquaredLength = this.velocity.lengthSquared(); var a = velocitySquaredLength; this.basePoint.subtractToRef(p1, this._tempVector); var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector)); var c = this._tempVector.lengthSquared() - 1.0; var lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { t = lowestRoot.root; found = true; this._collisionPoint.copyFrom(p1); } this.basePoint.subtractToRef(p2, this._tempVector); b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector)); c = this._tempVector.lengthSquared() - 1.0; lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { t = lowestRoot.root; found = true; this._collisionPoint.copyFrom(p2); } this.basePoint.subtractToRef(p3, this._tempVector); b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector)); c = this._tempVector.lengthSquared() - 1.0; lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { t = lowestRoot.root; found = true; this._collisionPoint.copyFrom(p3); } p2.subtractToRef(p1, this._edge); p1.subtractToRef(this.basePoint, this._baseToVertex); var edgeSquaredLength = this._edge.lengthSquared(); var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity); var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex); a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity; b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex; c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; if (f >= 0.0 && f <= 1.0) { t = lowestRoot.root; found = true; this._edge.scaleInPlace(f); p1.addToRef(this._edge, this._collisionPoint); } } p3.subtractToRef(p2, this._edge); p2.subtractToRef(this.basePoint, this._baseToVertex); edgeSquaredLength = this._edge.lengthSquared(); edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity); edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex); a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity; b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex; c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; if (f >= 0.0 && f <= 1.0) { t = lowestRoot.root; found = true; this._edge.scaleInPlace(f); p2.addToRef(this._edge, this._collisionPoint); } } p1.subtractToRef(p3, this._edge); p3.subtractToRef(this.basePoint, this._baseToVertex); edgeSquaredLength = this._edge.lengthSquared(); edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity); edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex); a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity; b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex; c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; if (f >= 0.0 && f <= 1.0) { t = lowestRoot.root; found = true; this._edge.scaleInPlace(f); p3.addToRef(this._edge, this._collisionPoint); } } } if (found) { var distToCollision = t * this.velocity.length(); if (!this.collisionFound || distToCollision < this.nearestDistance) { if (!this.intersectionPoint) { this.intersectionPoint = this._collisionPoint.clone(); } else { this.intersectionPoint.copyFrom(this._collisionPoint); } this.nearestDistance = distToCollision; this.collisionFound = true; } } }; Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) { for (var i = indexStart; i < indexEnd; i += 3) { var p1 = pts[indices[i] - decal]; var p2 = pts[indices[i + 1] - decal]; var p3 = pts[indices[i + 2] - decal]; this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial); } }; Collider.prototype._getResponse = function (pos, vel) { pos.addToRef(vel, this._destinationPoint); vel.scaleInPlace((this.nearestDistance / vel.length())); this.basePoint.addToRef(vel, pos); pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal); this._slidePlaneNormal.normalize(); this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector); pos.addInPlace(this._displacementVector); this.intersectionPoint.addInPlace(this._displacementVector); this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint)); this._destinationPoint.subtractInPlace(this._slidePlaneNormal); this._destinationPoint.subtractToRef(this.intersectionPoint, vel); }; return Collider; }()); BABYLON.Collider = Collider; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.collider.js.map var BABYLON; (function (BABYLON) { //WebWorker code will be inserted to this variable. BABYLON.CollisionWorker = ""; var WorkerTaskType; (function (WorkerTaskType) { WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT"; WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE"; WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE"; })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {})); var WorkerReplyType; (function (WorkerReplyType) { WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS"; WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR"; })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {})); var CollisionCoordinatorWorker = /** @class */ (function () { function CollisionCoordinatorWorker() { var _this = this; this._scaledPosition = BABYLON.Vector3.Zero(); this._scaledVelocity = BABYLON.Vector3.Zero(); this.onMeshUpdated = function (mesh) { _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh); }; this.onGeometryUpdated = function (geometry) { _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry); }; this._afterRender = function () { if (!_this._init) return; if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) { return; } //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update. //TODO make sure update runs as fast as possible to be able to update 60 FPS. if (_this._runningUpdated > 4) { return; } ++_this._runningUpdated; var payload = { updatedMeshes: _this._addUpdateMeshesList, updatedGeometries: _this._addUpdateGeometriesList, removedGeometries: _this._toRemoveGeometryArray, removedMeshes: _this._toRemoveMeshesArray }; var message = { payload: payload, taskType: WorkerTaskType.UPDATE }; var serializable = []; for (var id in payload.updatedGeometries) { if (payload.updatedGeometries.hasOwnProperty(id)) { //prepare transferables serializable.push(message.payload.updatedGeometries[id].indices.buffer); serializable.push(message.payload.updatedGeometries[id].normals.buffer); serializable.push(message.payload.updatedGeometries[id].positions.buffer); } } _this._worker.postMessage(message, serializable); _this._addUpdateMeshesList = {}; _this._addUpdateGeometriesList = {}; _this._toRemoveGeometryArray = []; _this._toRemoveMeshesArray = []; }; this._onMessageFromWorker = function (e) { var returnData = e.data; if (returnData.error != WorkerReplyType.SUCCESS) { //TODO what errors can be returned from the worker? BABYLON.Tools.Warn("error returned from worker!"); return; } switch (returnData.taskType) { case WorkerTaskType.INIT: _this._init = true; //Update the worked with ALL of the scene's current state _this._scene.meshes.forEach(function (mesh) { _this.onMeshAdded(mesh); }); _this._scene.getGeometries().forEach(function (geometry) { _this.onGeometryAdded(geometry); }); break; case WorkerTaskType.UPDATE: _this._runningUpdated--; break; case WorkerTaskType.COLLIDE: _this._runningCollisionTask = false; var returnPayload = returnData.payload; if (!_this._collisionsCallbackArray[returnPayload.collisionId]) return; var callback = _this._collisionsCallbackArray[returnPayload.collisionId]; if (callback) { var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId); if (mesh) { callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh); } } //cleanup _this._collisionsCallbackArray[returnPayload.collisionId] = null; break; } }; this._collisionsCallbackArray = []; this._init = false; this._runningUpdated = 0; this._runningCollisionTask = false; this._addUpdateMeshesList = {}; this._addUpdateGeometriesList = {}; this._toRemoveGeometryArray = []; this._toRemoveMeshesArray = []; } CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) { if (!this._init) return; if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) return; position.divideToRef(collider.radius, this._scaledPosition); displacement.divideToRef(collider.radius, this._scaledVelocity); this._collisionsCallbackArray[collisionIndex] = onNewPosition; var payload = { collider: { position: this._scaledPosition.asArray(), velocity: this._scaledVelocity.asArray(), radius: collider.radius.asArray() }, collisionId: collisionIndex, excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null, maximumRetry: maximumRetry }; var message = { payload: payload, taskType: WorkerTaskType.COLLIDE }; this._worker.postMessage(message); }; CollisionCoordinatorWorker.prototype.init = function (scene) { this._scene = scene; this._scene.registerAfterRender(this._afterRender); var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' })); this._worker = new Worker(workerUrl); this._worker.onmessage = this._onMessageFromWorker; var message = { payload: {}, taskType: WorkerTaskType.INIT }; this._worker.postMessage(message); }; CollisionCoordinatorWorker.prototype.destroy = function () { this._scene.unregisterAfterRender(this._afterRender); this._worker.terminate(); }; CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) { mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated); this.onMeshUpdated(mesh); }; CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) { this._toRemoveMeshesArray.push(mesh.uniqueId); }; CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) { //TODO this will break if the user uses his own function. This should be an array of callbacks! geometry.onGeometryUpdated = this.onGeometryUpdated; this.onGeometryUpdated(geometry); }; CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) { this._toRemoveGeometryArray.push(geometry.id); }; CollisionCoordinatorWorker.SerializeMesh = function (mesh) { var submeshes = []; if (mesh.subMeshes) { submeshes = mesh.subMeshes.map(function (sm, idx) { var boundingInfo = sm.getBoundingInfo(); return { position: idx, verticesStart: sm.verticesStart, verticesCount: sm.verticesCount, indexStart: sm.indexStart, indexCount: sm.indexCount, hasMaterial: !!sm.getMaterial(), sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(), sphereRadius: boundingInfo.boundingSphere.radiusWorld, boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(), boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray() }; }); } var geometryId = null; if (mesh instanceof BABYLON.Mesh) { var geometry = mesh.geometry; geometryId = geometry ? geometry.id : null; } else if (mesh instanceof BABYLON.InstancedMesh) { var geometry = mesh.sourceMesh.geometry; geometryId = geometry ? geometry.id : null; } var boundingInfo = mesh.getBoundingInfo(); return { uniqueId: mesh.uniqueId, id: mesh.id, name: mesh.name, geometryId: geometryId, sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(), sphereRadius: boundingInfo.boundingSphere.radiusWorld, boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(), boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(), worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(), subMeshes: submeshes, checkCollisions: mesh.checkCollisions }; }; CollisionCoordinatorWorker.SerializeGeometry = function (geometry) { return { id: geometry.id, positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []), normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []), indices: new Uint32Array(geometry.getIndices() || []), }; }; return CollisionCoordinatorWorker; }()); BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker; var CollisionCoordinatorLegacy = /** @class */ (function () { function CollisionCoordinatorLegacy() { this._scaledPosition = BABYLON.Vector3.Zero(); this._scaledVelocity = BABYLON.Vector3.Zero(); this._finalPosition = BABYLON.Vector3.Zero(); } CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) { position.divideToRef(collider.radius, this._scaledPosition); displacement.divideToRef(collider.radius, this._scaledVelocity); collider.collidedMesh = null; collider.retry = 0; collider.initialVelocity = this._scaledVelocity; collider.initialPosition = this._scaledPosition; this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh); this._finalPosition.multiplyInPlace(collider.radius); //run the callback onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh); }; CollisionCoordinatorLegacy.prototype.init = function (scene) { this._scene = scene; }; CollisionCoordinatorLegacy.prototype.destroy = function () { //Legacy need no destruction method. }; //No update in legacy mode CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { }; CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { }; CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { }; CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { }; CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { }; CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { }; CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) { if (excludedMesh === void 0) { excludedMesh = null; } var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0; if (collider.retry >= maximumRetry) { finalPosition.copyFrom(position); return; } // Check if this is a mesh else camera or -1 var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask); collider._initialize(position, velocity, closeDistance); // Check all meshes for (var index = 0; index < this._scene.meshes.length; index++) { var mesh = this._scene.meshes[index]; if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) { mesh._checkCollision(collider); } } if (!collider.collisionFound) { position.addToRef(velocity, finalPosition); return; } if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) { collider._getResponse(position, velocity); } if (velocity.length() <= closeDistance) { finalPosition.copyFrom(position); return; } collider.retry++; this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh); }; return CollisionCoordinatorLegacy; }()); BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.collisionCoordinator.js.map var BABYLON; (function (BABYLON) { var Particle = /** @class */ (function () { function Particle(particleSystem) { this.particleSystem = particleSystem; this.position = BABYLON.Vector3.Zero(); this.direction = BABYLON.Vector3.Zero(); this.color = new BABYLON.Color4(0, 0, 0, 0); this.colorStep = new BABYLON.Color4(0, 0, 0, 0); this.lifeTime = 1.0; this.age = 0; this.size = 0; this.angle = 0; this.angularSpeed = 0; this._currentFrameCounter = 0; this.cellIndex = 0; if (!this.particleSystem.isAnimationSheetEnabled) { return; } this.cellIndex = this.particleSystem.startSpriteCellID; if (this.particleSystem.spriteCellChangeSpeed == 0) { this.updateCellIndex = this.updateCellIndexWithSpeedCalculated; } else { this.updateCellIndex = this.updateCellIndexWithCustomSpeed; } } Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) { // (ageOffset / scaledUpdateSpeed) / available cells var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex); this._currentFrameCounter += scaledUpdateSpeed; if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) { this._currentFrameCounter = 0; this.cellIndex++; if (this.cellIndex > this.particleSystem.endSpriteCellID) { this.cellIndex = this.particleSystem.endSpriteCellID; } } }; Particle.prototype.updateCellIndexWithCustomSpeed = function () { if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) { this.cellIndex++; this._currentFrameCounter = 0; if (this.cellIndex > this.particleSystem.endSpriteCellID) { if (this.particleSystem.spriteCellLoop) { this.cellIndex = this.particleSystem.startSpriteCellID; } else { this.cellIndex = this.particleSystem.endSpriteCellID; } } } else { this._currentFrameCounter++; } }; Particle.prototype.copyTo = function (other) { other.position.copyFrom(this.position); other.direction.copyFrom(this.direction); other.color.copyFrom(this.color); other.colorStep.copyFrom(this.colorStep); other.lifeTime = this.lifeTime; other.age = this.age; other.size = this.size; other.angle = this.angle; other.angularSpeed = this.angularSpeed; other.particleSystem = this.particleSystem; other.cellIndex = this.cellIndex; }; return Particle; }()); BABYLON.Particle = Particle; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.particle.js.map var BABYLON; (function (BABYLON) { var randomNumber = function (min, max) { if (min === max) { return (min); } var random = Math.random(); return ((random * (max - min)) + min); }; var ParticleSystem = /** @class */ (function () { // end of sheet animation function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) { if (customEffect === void 0) { customEffect = null; } if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; } if (epsilon === void 0) { epsilon = 0.01; } var _this = this; this.name = name; this._isAnimationSheetEnabled = _isAnimationSheetEnabled; // Members this.animations = []; this.renderingGroupId = 0; this.emitter = null; this.emitRate = 10; this.manualEmitCount = -1; this.updateSpeed = 0.01; this.targetStopDuration = 0; this.disposeOnStop = false; this.minEmitPower = 1; this.maxEmitPower = 1; this.minLifeTime = 1; this.maxLifeTime = 1; this.minSize = 1; this.maxSize = 1; this.minAngularSpeed = 0; this.maxAngularSpeed = 0; this.layerMask = 0x0FFFFFFF; this.customShader = null; this.preventAutoStart = false; /** * An event triggered when the system is disposed. * @type {BABYLON.Observable} */ this.onDisposeObservable = new BABYLON.Observable(); this.onAnimationEnd = null; this.blendMode = ParticleSystem.BLENDMODE_ONEONE; this.forceDepthWrite = false; this.gravity = BABYLON.Vector3.Zero(); this.direction1 = new BABYLON.Vector3(0, 1.0, 0); this.direction2 = new BABYLON.Vector3(0, 1.0, 0); this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5); this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5); this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0); this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); this.particles = new Array(); this._stockParticles = new Array(); this._newPartsExcess = 0; this._vertexBuffers = {}; this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0); this._colorDiff = new BABYLON.Color4(0, 0, 0, 0); this._scaledDirection = BABYLON.Vector3.Zero(); this._scaledGravity = BABYLON.Vector3.Zero(); this._currentRenderId = -1; this._started = false; this._stopped = false; this._actualFrame = 0; // sheet animation this.startSpriteCellID = 0; this.endSpriteCellID = 0; this.spriteCellLoop = true; this.spriteCellChangeSpeed = 0; this.spriteCellWidth = 0; this.spriteCellHeight = 0; this._vertexBufferSize = 11; this.appendParticleVertexes = null; this.id = name; this._capacity = capacity; this._epsilon = epsilon; if (_isAnimationSheetEnabled) { this._vertexBufferSize = 12; } this._scene = scene || BABYLON.Engine.LastCreatedScene; this._customEffect = customEffect; scene.particleSystems.push(this); this._createIndexBuffer(); // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4); this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize); var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3); var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4); var options = this._vertexBuffer.createVertexBuffer("options", 7, 4); if (this._isAnimationSheetEnabled) { var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1); this._vertexBuffers["cellIndex"] = cellIndexBuffer; } this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions; this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors; this._vertexBuffers["options"] = options; // Default behaviors this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) { var randX = randomNumber(_this.direction1.x, _this.direction2.x); var randY = randomNumber(_this.direction1.y, _this.direction2.y); var randZ = randomNumber(_this.direction1.z, _this.direction2.z); BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate); }; this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) { var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x); var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y); var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z); BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate); }; this.updateFunction = function (particles) { for (var index = 0; index < particles.length; index++) { var particle = particles[index]; particle.age += _this._scaledUpdateSpeed; if (particle.age >= particle.lifeTime) { _this.recycleParticle(particle); index--; continue; } else { particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep); particle.color.addInPlace(_this._scaledColorStep); if (particle.color.a < 0) particle.color.a = 0; particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed; particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection); particle.position.addInPlace(_this._scaledDirection); _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity); particle.direction.addInPlace(_this._scaledGravity); if (_this._isAnimationSheetEnabled) { particle.updateCellIndex(_this._scaledUpdateSpeed); } } } }; } Object.defineProperty(ParticleSystem.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(ParticleSystem.prototype, "isAnimationSheetEnabled", { get: function () { return this._isAnimationSheetEnabled; }, enumerable: true, configurable: true }); ParticleSystem.prototype._createIndexBuffer = function () { var indices = []; var index = 0; for (var count = 0; count < this._capacity; count++) { indices.push(index); indices.push(index + 1); indices.push(index + 2); indices.push(index); indices.push(index + 2); indices.push(index + 3); index += 4; } this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices); }; ParticleSystem.prototype.recycleParticle = function (particle) { var lastParticle = this.particles.pop(); if (lastParticle !== particle) { lastParticle.copyTo(particle); this._stockParticles.push(lastParticle); } }; ParticleSystem.prototype.getCapacity = function () { return this._capacity; }; ParticleSystem.prototype.isAlive = function () { return this._alive; }; ParticleSystem.prototype.isStarted = function () { return this._started; }; ParticleSystem.prototype.start = function () { this._started = true; this._stopped = false; this._actualFrame = 0; }; ParticleSystem.prototype.stop = function () { this._stopped = true; }; // animation sheet ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) { var offset = index * this._vertexBufferSize; this._vertexData[offset] = particle.position.x; this._vertexData[offset + 1] = particle.position.y; this._vertexData[offset + 2] = particle.position.z; this._vertexData[offset + 3] = particle.color.r; this._vertexData[offset + 4] = particle.color.g; this._vertexData[offset + 5] = particle.color.b; this._vertexData[offset + 6] = particle.color.a; this._vertexData[offset + 7] = particle.angle; this._vertexData[offset + 8] = particle.size; this._vertexData[offset + 9] = offsetX; this._vertexData[offset + 10] = offsetY; }; ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) { if (offsetX === 0) offsetX = this._epsilon; else if (offsetX === 1) offsetX = 1 - this._epsilon; if (offsetY === 0) offsetY = this._epsilon; else if (offsetY === 1) offsetY = 1 - this._epsilon; var offset = index * this._vertexBufferSize; this._vertexData[offset] = particle.position.x; this._vertexData[offset + 1] = particle.position.y; this._vertexData[offset + 2] = particle.position.z; this._vertexData[offset + 3] = particle.color.r; this._vertexData[offset + 4] = particle.color.g; this._vertexData[offset + 5] = particle.color.b; this._vertexData[offset + 6] = particle.color.a; this._vertexData[offset + 7] = particle.angle; this._vertexData[offset + 8] = particle.size; this._vertexData[offset + 9] = offsetX; this._vertexData[offset + 10] = offsetY; this._vertexData[offset + 11] = particle.cellIndex; }; ParticleSystem.prototype._update = function (newParticles) { // Update current this._alive = this.particles.length > 0; this.updateFunction(this.particles); // Add new ones var worldMatrix; if (this.emitter.position) { var emitterMesh = this.emitter; worldMatrix = emitterMesh.getWorldMatrix(); } else { var emitterPosition = this.emitter; worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z); } var particle; for (var index = 0; index < newParticles; index++) { if (this.particles.length === this._capacity) { break; } if (this._stockParticles.length !== 0) { particle = this._stockParticles.pop(); particle.age = 0; particle.cellIndex = this.startSpriteCellID; } else { particle = new BABYLON.Particle(this); } this.particles.push(particle); var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower); this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle); particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime); particle.size = randomNumber(this.minSize, this.maxSize); particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed); this.startPositionFunction(worldMatrix, particle.position, particle); var step = randomNumber(0, 1.0); BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color); this.colorDead.subtractToRef(particle.color, this._colorDiff); this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep); } }; ParticleSystem.prototype._getEffect = function () { if (this._customEffect) { return this._customEffect; } ; var defines = []; if (this._scene.clipPlane) { defines.push("#define CLIPPLANE"); } if (this._isAnimationSheetEnabled) { defines.push("#define ANIMATESHEET"); } // Effect var join = defines.join("\n"); if (this._cachedDefines !== join) { this._cachedDefines = join; var attributesNamesOrOptions; var effectCreationOption; if (this._isAnimationSheetEnabled) { attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"]; effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"]; } else { attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"]; effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"]; } this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join); } return this._effect; }; ParticleSystem.prototype.animate = function () { if (!this._started) return; var effect = this._getEffect(); // Check if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) return; if (this._currentRenderId === this._scene.getRenderId()) { return; } this._currentRenderId = this._scene.getRenderId(); this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio(); // determine the number of particles we need to create var newParticles; if (this.manualEmitCount > -1) { newParticles = this.manualEmitCount; this._newPartsExcess = 0; this.manualEmitCount = 0; } else { newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0); this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles; } if (this._newPartsExcess > 1.0) { newParticles += this._newPartsExcess >> 0; this._newPartsExcess -= this._newPartsExcess >> 0; } this._alive = false; if (!this._stopped) { this._actualFrame += this._scaledUpdateSpeed; if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) this.stop(); } else { newParticles = 0; } this._update(newParticles); // Stopped? if (this._stopped) { if (!this._alive) { this._started = false; if (this.onAnimationEnd) { this.onAnimationEnd(); } if (this.disposeOnStop) { this._scene._toBeDisposed.push(this); } } } // Animation sheet if (this._isAnimationSheetEnabled) { this.appendParticleVertexes = this.appenedParticleVertexesWithSheet; } else { this.appendParticleVertexes = this.appenedParticleVertexesNoSheet; } // Update VBO var offset = 0; for (var index = 0; index < this.particles.length; index++) { var particle = this.particles[index]; this.appendParticleVertexes(offset, particle); offset += 4; } if (this._vertexBuffer) { this._vertexBuffer.update(this._vertexData); } }; ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) { this._appendParticleVertexWithAnimation(offset++, particle, 0, 0); this._appendParticleVertexWithAnimation(offset++, particle, 1, 0); this._appendParticleVertexWithAnimation(offset++, particle, 1, 1); this._appendParticleVertexWithAnimation(offset++, particle, 0, 1); }; ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) { this._appendParticleVertex(offset++, particle, 0, 0); this._appendParticleVertex(offset++, particle, 1, 0); this._appendParticleVertex(offset++, particle, 1, 1); this._appendParticleVertex(offset++, particle, 0, 1); }; ParticleSystem.prototype.rebuild = function () { this._createIndexBuffer(); if (this._vertexBuffer) { this._vertexBuffer._rebuild(); } }; ParticleSystem.prototype.render = function () { var effect = this._getEffect(); // Check if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length) return 0; var engine = this._scene.getEngine(); // Render engine.enableEffect(effect); engine.setState(false); var viewMatrix = this._scene.getViewMatrix(); effect.setTexture("diffuseSampler", this.particleTexture); effect.setMatrix("view", viewMatrix); effect.setMatrix("projection", this._scene.getProjectionMatrix()); if (this._isAnimationSheetEnabled) { var baseSize = this.particleTexture.getBaseSize(); effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth); } effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a); if (this._scene.clipPlane) { var clipPlane = this._scene.clipPlane; var invView = viewMatrix.clone(); invView.invert(); effect.setMatrix("invView", invView); effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); } // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); // Draw order if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) { engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE); } else { engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE); } if (this.forceDepthWrite) { engine.setDepthWrite(true); } engine.draw(true, 0, this.particles.length * 6); engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE); return this.particles.length; }; ParticleSystem.prototype.dispose = function () { if (this._vertexBuffer) { this._vertexBuffer.dispose(); this._vertexBuffer = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } if (this.particleTexture) { this.particleTexture.dispose(); this.particleTexture = null; } // Remove from scene var index = this._scene.particleSystems.indexOf(this); if (index > -1) { this._scene.particleSystems.splice(index, 1); } // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); }; // Clone ParticleSystem.prototype.clone = function (name, newEmitter) { var custom = null; var program = null; if (this.customShader != null) { program = this.customShader; var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : ""; custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines); } var result = new ParticleSystem(name, this._capacity, this._scene, custom); result.customShader = program; BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]); if (newEmitter === undefined) { newEmitter = this.emitter; } result.emitter = newEmitter; if (this.particleTexture) { result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene); } if (!this.preventAutoStart) { result.start(); } return result; }; ParticleSystem.prototype.serialize = function () { var serializationObject = {}; serializationObject.name = this.name; serializationObject.id = this.id; // Emitter if (this.emitter.position) { var emitterMesh = this.emitter; serializationObject.emitterId = emitterMesh.id; } else { var emitterPosition = this.emitter; serializationObject.emitter = emitterPosition.asArray(); } serializationObject.capacity = this.getCapacity(); if (this.particleTexture) { serializationObject.textureName = this.particleTexture.name; } // Animations BABYLON.Animation.AppendSerializedAnimations(this, serializationObject); // Particle system serializationObject.minAngularSpeed = this.minAngularSpeed; serializationObject.maxAngularSpeed = this.maxAngularSpeed; serializationObject.minSize = this.minSize; serializationObject.maxSize = this.maxSize; serializationObject.minEmitPower = this.minEmitPower; serializationObject.maxEmitPower = this.maxEmitPower; serializationObject.minLifeTime = this.minLifeTime; serializationObject.maxLifeTime = this.maxLifeTime; serializationObject.emitRate = this.emitRate; serializationObject.minEmitBox = this.minEmitBox.asArray(); serializationObject.maxEmitBox = this.maxEmitBox.asArray(); serializationObject.gravity = this.gravity.asArray(); serializationObject.direction1 = this.direction1.asArray(); serializationObject.direction2 = this.direction2.asArray(); serializationObject.color1 = this.color1.asArray(); serializationObject.color2 = this.color2.asArray(); serializationObject.colorDead = this.colorDead.asArray(); serializationObject.updateSpeed = this.updateSpeed; serializationObject.targetStopDuration = this.targetStopDuration; serializationObject.textureMask = this.textureMask.asArray(); serializationObject.blendMode = this.blendMode; serializationObject.customShader = this.customShader; serializationObject.preventAutoStart = this.preventAutoStart; return serializationObject; }; ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) { var name = parsedParticleSystem.name; var custom = null; var program = null; if (parsedParticleSystem.customShader) { program = parsedParticleSystem.customShader; var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : ""; custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines); } var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom); particleSystem.customShader = program; if (parsedParticleSystem.id) { particleSystem.id = parsedParticleSystem.id; } // Auto start if (parsedParticleSystem.preventAutoStart) { particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart; } // Texture if (parsedParticleSystem.textureName) { particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene); particleSystem.particleTexture.name = parsedParticleSystem.textureName; } // Emitter if (parsedParticleSystem.emitterId) { particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId); } else { particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter); } // Animations if (parsedParticleSystem.animations) { for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) { var parsedAnimation = parsedParticleSystem.animations[animationIndex]; particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation)); } } if (parsedParticleSystem.autoAnimate) { scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0); } // Particle system particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed; particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed; particleSystem.minSize = parsedParticleSystem.minSize; particleSystem.maxSize = parsedParticleSystem.maxSize; particleSystem.minLifeTime = parsedParticleSystem.minLifeTime; particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime; particleSystem.minEmitPower = parsedParticleSystem.minEmitPower; particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower; particleSystem.emitRate = parsedParticleSystem.emitRate; particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox); particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox); particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity); particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1); particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2); particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1); particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2); particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead); particleSystem.updateSpeed = parsedParticleSystem.updateSpeed; particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration; particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask); particleSystem.blendMode = parsedParticleSystem.blendMode; if (!particleSystem.preventAutoStart) { particleSystem.start(); } return particleSystem; }; // Statics ParticleSystem.BLENDMODE_ONEONE = 0; ParticleSystem.BLENDMODE_STANDARD = 1; return ParticleSystem; }()); BABYLON.ParticleSystem = ParticleSystem; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.particleSystem.js.map var BABYLON; (function (BABYLON) { var SolidParticle = /** @class */ (function () { /** * Creates a Solid Particle object. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle() * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array. * `model` (ModelShape) is a reference to the model shape on what the particle is designed. * `shapeId` (integer) is the model shape identifier in the SPS. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30)) * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations. */ function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) { if (modelBoundingInfo === void 0) { modelBoundingInfo = null; } this.idx = 0; // particle global index this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color this.position = BABYLON.Vector3.Zero(); // position this.rotation = BABYLON.Vector3.Zero(); // rotation this.scaling = BABYLON.Vector3.One(); // scaling this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs this.velocity = BABYLON.Vector3.Zero(); // velocity this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space this.alive = true; // alive this.isVisible = true; // visibility this._pos = 0; // index of this particle in the global "positions" array this._ind = 0; // index of this particle in the global "indices" array this.shapeId = 0; // model shape id this.idxInShape = 0; // index of the particle in its shape id this._stillInvisible = false; // still set as invisible in order to skip useless computations this.idx = particleIndex; this._pos = positionIndex; this._ind = indiceIndex; this._model = model; this.shapeId = shapeId; this.idxInShape = idxInShape; this._sps = sps; if (modelBoundingInfo) { this._modelBoundingInfo = modelBoundingInfo; this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum); } } Object.defineProperty(SolidParticle.prototype, "scale", { /** * legacy support, changed scale to scaling */ get: function () { return this.scaling; }, set: function (scale) { this.scaling = scale; }, enumerable: true, configurable: true }); Object.defineProperty(SolidParticle.prototype, "quaternion", { /** * legacy support, changed quaternion to rotationQuaternion */ get: function () { return this.rotationQuaternion; }, set: function (q) { this.rotationQuaternion = q; }, enumerable: true, configurable: true }); /** * Returns a boolean. True if the particle intersects another particle or another mesh, else false. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB) * `target` is the object (solid particle or mesh) what the intersection is computed against. */ SolidParticle.prototype.intersectsMesh = function (target) { if (!this._boundingInfo || !target._boundingInfo) { return false; } if (this._sps._bSphereOnly) { return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere); } return this._boundingInfo.intersects(target._boundingInfo, false); }; return SolidParticle; }()); BABYLON.SolidParticle = SolidParticle; var ModelShape = /** @class */ (function () { /** * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS. * SPS internal tool, don't use it manually. */ function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) { this._indicesLength = 0; // length of the shape in the model indices array this.shapeID = id; this._shape = shape; this._indicesLength = indicesLength; this._shapeUV = shapeUV; this._positionFunction = posFunction; this._vertexFunction = vtxFunction; } return ModelShape; }()); BABYLON.ModelShape = ModelShape; var DepthSortedParticle = /** @class */ (function () { function DepthSortedParticle() { this.ind = 0; // index of the particle in the "indices" array this.indicesLength = 0; // length of the particle shape in the "indices" array this.sqDistance = 0.0; // squared distance from the particle to the camera } return DepthSortedParticle; }()); BABYLON.DepthSortedParticle = DepthSortedParticle; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.solidParticle.js.map var BABYLON; (function (BABYLON) { /** * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System */ var SolidParticleSystem = /** @class */ (function () { /** * Creates a SPS (Solid Particle System) object. * `name` (String) is the SPS name, this will be the underlying mesh name. * `scene` (Scene) is the scene in which the SPS is added. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh. */ function SolidParticleSystem(name, scene, options) { // public members /** * The SPS array of Solid Particle objects. Just access each particle as with any classic array. * Example : var p = SPS.particles[i]; */ this.particles = new Array(); /** * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value. */ this.nbParticles = 0; /** * If the particles must ever face the camera (default false). Useful for planar particles. */ this.billboard = false; /** * Recompute normals when adding a shape */ this.recomputeNormals = true; /** * This a counter ofr your own usage. It's not set by any SPS functions. */ this.counter = 0; /** * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns */ this.vars = {}; this._positions = new Array(); this._indices = new Array(); this._normals = new Array(); this._colors = new Array(); this._uvs = new Array(); this._index = 0; // indices index this._updatable = true; this._pickable = false; this._isVisibilityBoxLocked = false; this._alwaysVisible = false; this._depthSort = false; this._shapeCounter = 0; this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this); this._color = new BABYLON.Color4(0, 0, 0, 0); this._computeParticleColor = true; this._computeParticleTexture = true; this._computeParticleRotation = true; this._computeParticleVertex = false; this._computeBoundingBox = false; this._depthSortParticles = true; this._cam_axisZ = BABYLON.Vector3.Zero(); this._cam_axisY = BABYLON.Vector3.Zero(); this._cam_axisX = BABYLON.Vector3.Zero(); this._axisZ = BABYLON.Axis.Z; this._camDir = BABYLON.Vector3.Zero(); this._camInvertedPosition = BABYLON.Vector3.Zero(); this._rotMatrix = new BABYLON.Matrix(); this._invertMatrix = new BABYLON.Matrix(); this._rotated = BABYLON.Vector3.Zero(); this._quaternion = new BABYLON.Quaternion(); this._vertex = BABYLON.Vector3.Zero(); this._normal = BABYLON.Vector3.Zero(); this._yaw = 0.0; this._pitch = 0.0; this._roll = 0.0; this._halfroll = 0.0; this._halfpitch = 0.0; this._halfyaw = 0.0; this._sinRoll = 0.0; this._cosRoll = 0.0; this._sinPitch = 0.0; this._cosPitch = 0.0; this._sinYaw = 0.0; this._cosYaw = 0.0; this._mustUnrotateFixedNormals = false; this._minimum = BABYLON.Tmp.Vector3[0]; this._maximum = BABYLON.Tmp.Vector3[1]; this._minBbox = BABYLON.Tmp.Vector3[4]; this._maxBbox = BABYLON.Tmp.Vector3[5]; this._particlesIntersect = false; this._depthSortFunction = function (p1, p2) { return (p2.sqDistance - p1.sqDistance); }; this._needs32Bits = false; this._bSphereOnly = false; this._bSphereRadiusFactor = 1.0; this.name = name; this._scene = scene || BABYLON.Engine.LastCreatedScene; this._camera = scene.activeCamera; this._pickable = options ? options.isPickable : false; this._depthSort = options ? options.enableDepthSort : false; this._particlesIntersect = options ? options.particleIntersection : false; this._bSphereOnly = options ? options.boundingSphereOnly : false; this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0; if (options && options.updatable) { this._updatable = options.updatable; } else { this._updatable = true; } if (this._pickable) { this.pickedParticles = []; } if (this._depthSort) { this.depthSortedParticles = []; } } /** * Builds the SPS underlying mesh. Returns a standard Mesh. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane. */ SolidParticleSystem.prototype.buildMesh = function () { if (this.nbParticles === 0) { var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene); this.addShape(triangle, 1); triangle.dispose(); } this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices); this._positions32 = new Float32Array(this._positions); this._uvs32 = new Float32Array(this._uvs); this._colors32 = new Float32Array(this._colors); if (this.recomputeNormals) { BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals); } this._normals32 = new Float32Array(this._normals); this._fixedNormal32 = new Float32Array(this._normals); if (this._mustUnrotateFixedNormals) { this._unrotateFixedNormals(); } var vertexData = new BABYLON.VertexData(); vertexData.indices = this._indices32; vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind); vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind); if (this._uvs32) { vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind); ; } if (this._colors32) { vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind); } var mesh = new BABYLON.Mesh(this.name, this._scene); vertexData.applyToMesh(mesh, this._updatable); this.mesh = mesh; this.mesh.isPickable = this._pickable; // free memory if (!this._depthSort) { this._indices = null; } this._positions = null; this._normals = null; this._uvs = null; this._colors = null; if (!this._updatable) { this.particles.length = 0; } return mesh; }; /** * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places. * Thus the particles generated from `digest()` have their property `position` set yet. * `mesh` ( Mesh ) is the mesh to be digested * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets */ SolidParticleSystem.prototype.digest = function (mesh, options) { var size = (options && options.facetNb) || 1; var number = (options && options.number) || 0; var delta = (options && options.delta) || 0; var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind); var meshInd = mesh.getIndices(); var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind); var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind); var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind); var f = 0; // facet counter var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices // compute size from number if (number) { number = (number > totalFacets) ? totalFacets : number; size = Math.round(totalFacets / number); delta = 0; } else { size = (size > totalFacets) ? totalFacets : size; } var facetPos = []; // submesh positions var facetInd = []; // submesh indices var facetUV = []; // submesh UV var facetCol = []; // submesh colors var barycenter = BABYLON.Tmp.Vector3[0]; var sizeO = size; while (f < totalFacets) { size = sizeO + Math.floor((1 + delta) * Math.random()); if (f > totalFacets - size) { size = totalFacets - f; } // reset temp arrays facetPos.length = 0; facetInd.length = 0; facetUV.length = 0; facetCol.length = 0; // iterate over "size" facets var fi = 0; for (var j = f * 3; j < (f + size) * 3; j++) { facetInd.push(fi); var i = meshInd[j]; facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]); if (meshUV) { facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]); } if (meshCol) { facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]); } fi++; } // create a model shape for each single particle var idx = this.nbParticles; var shape = this._posToShape(facetPos); var shapeUV = this._uvsToShapeUV(facetUV); // compute the barycenter of the shape var v; for (v = 0; v < shape.length; v++) { barycenter.addInPlace(shape[v]); } barycenter.scaleInPlace(1 / shape.length); // shift the shape from its barycenter to the origin for (v = 0; v < shape.length; v++) { shape[v].subtractInPlace(barycenter); } var bInfo; if (this._particlesIntersect) { bInfo = new BABYLON.BoundingInfo(barycenter, barycenter); } var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null); // add the particle in the SPS var currentPos = this._positions.length; var currentInd = this._indices.length; this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null); this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo); // initialize the particle position this.particles[this.nbParticles].position.addInPlace(barycenter); this._index += shape.length; idx++; this.nbParticles++; this._shapeCounter++; f += size; } return this; }; // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape() SolidParticleSystem.prototype._unrotateFixedNormals = function () { var index = 0; var idx = 0; for (var p = 0; p < this.particles.length; p++) { this._particle = this.particles[p]; this._shape = this._particle._model._shape; if (this._particle.rotationQuaternion) { this._quaternion.copyFrom(this._particle.rotationQuaternion); } else { this._yaw = this._particle.rotation.y; this._pitch = this._particle.rotation.x; this._roll = this._particle.rotation.z; this._quaternionRotationYPR(); } this._quaternionToRotationMatrix(); this._rotMatrix.invertToRef(this._invertMatrix); for (var pt = 0; pt < this._shape.length; pt++) { idx = index + pt * 3; BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal); this._fixedNormal32[idx] = this._normal.x; this._fixedNormal32[idx + 1] = this._normal.y; this._fixedNormal32[idx + 2] = this._normal.z; } index = idx + 3; } }; //reset copy SolidParticleSystem.prototype._resetCopy = function () { this._copy.position.x = 0; this._copy.position.y = 0; this._copy.position.z = 0; this._copy.rotation.x = 0; this._copy.rotation.y = 0; this._copy.rotation.z = 0; this._copy.rotationQuaternion = null; this._copy.scaling.x = 1.0; this._copy.scaling.y = 1.0; this._copy.scaling.z = 1.0; this._copy.uvs.x = 0; this._copy.uvs.y = 0; this._copy.uvs.z = 1.0; this._copy.uvs.w = 1.0; this._copy.color = null; }; // _meshBuilder : inserts the shape model in the global SPS mesh SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) { var i; var u = 0; var c = 0; var n = 0; this._resetCopy(); if (options && options.positionFunction) { options.positionFunction(this._copy, idx, idxInShape); this._mustUnrotateFixedNormals = true; } if (this._copy.rotationQuaternion) { this._quaternion.copyFrom(this._copy.rotationQuaternion); } else { this._yaw = this._copy.rotation.y; this._pitch = this._copy.rotation.x; this._roll = this._copy.rotation.z; this._quaternionRotationYPR(); } this._quaternionToRotationMatrix(); for (i = 0; i < shape.length; i++) { this._vertex.x = shape[i].x; this._vertex.y = shape[i].y; this._vertex.z = shape[i].z; if (options && options.vertexFunction) { options.vertexFunction(this._copy, this._vertex, i); } this._vertex.x *= this._copy.scaling.x; this._vertex.y *= this._copy.scaling.y; this._vertex.z *= this._copy.scaling.z; this._vertex.x += this._copy.pivot.x; this._vertex.y += this._copy.pivot.y; this._vertex.z += this._copy.pivot.z; BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated); positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z); if (meshUV) { uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y); u += 2; } if (this._copy.color) { this._color = this._copy.color; } else if (meshCol && meshCol[c] !== undefined) { this._color.r = meshCol[c]; this._color.g = meshCol[c + 1]; this._color.b = meshCol[c + 2]; this._color.a = meshCol[c + 3]; } else { this._color.r = 1.0; this._color.g = 1.0; this._color.b = 1.0; this._color.a = 1.0; } colors.push(this._color.r, this._color.g, this._color.b, this._color.a); c += 4; if (!this.recomputeNormals && meshNor) { this._normal.x = meshNor[n]; this._normal.y = meshNor[n + 1]; this._normal.z = meshNor[n + 2]; BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal); normals.push(this._normal.x, this._normal.y, this._normal.z); n += 3; } } for (i = 0; i < meshInd.length; i++) { var current_ind = p + meshInd[i]; indices.push(current_ind); if (current_ind > 65535) { this._needs32Bits = true; } } if (this._pickable) { var nbfaces = meshInd.length / 3; for (i = 0; i < nbfaces; i++) { this.pickedParticles.push({ idx: idx, faceId: i }); } } if (this._depthSort) { this.depthSortedParticles.push(new BABYLON.DepthSortedParticle()); } return this._copy; }; // returns a shape array from positions array SolidParticleSystem.prototype._posToShape = function (positions) { var shape = []; for (var i = 0; i < positions.length; i += 3) { shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2])); } return shape; }; // returns a shapeUV array from a Vector4 uvs SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) { var shapeUV = []; if (uvs) { for (var i = 0; i < uvs.length; i++) shapeUV.push(uvs[i]); } return shapeUV; }; // adds a new particle object in the particles array SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) { if (bInfo === void 0) { bInfo = null; } var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo); this.particles.push(sp); return sp; }; /** * Adds some particles to the SPS from the model shape. Returns the shape id. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps * `mesh` is any Mesh object that will be used as a model for the solid particles. * `nb` (positive integer) the number of particles to be created from this model * `positionFunction` is an optional javascript function to called for each particle on SPS creation. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation */ SolidParticleSystem.prototype.addShape = function (mesh, nb, options) { var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind); var meshInd = mesh.getIndices(); var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind); var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind); var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind); var bbInfo; if (this._particlesIntersect) { bbInfo = mesh.getBoundingInfo(); } var shape = this._posToShape(meshPos); var shapeUV = this._uvsToShapeUV(meshUV); var posfunc = options ? options.positionFunction : null; var vtxfunc = options ? options.vertexFunction : null; var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc); // particles var sp; var currentCopy; var idx = this.nbParticles; for (var i = 0; i < nb; i++) { var currentPos = this._positions.length; var currentInd = this._indices.length; currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options); if (this._updatable) { sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo); sp.position.copyFrom(currentCopy.position); sp.rotation.copyFrom(currentCopy.rotation); if (currentCopy.rotationQuaternion && sp.rotationQuaternion) { sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion); } if (currentCopy.color && sp.color) { sp.color.copyFrom(currentCopy.color); } sp.scaling.copyFrom(currentCopy.scaling); sp.uvs.copyFrom(currentCopy.uvs); } this._index += shape.length; idx++; } this.nbParticles += nb; this._shapeCounter++; return this._shapeCounter - 1; }; // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices SolidParticleSystem.prototype._rebuildParticle = function (particle) { this._resetCopy(); if (particle._model._positionFunction) { particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape); } if (this._copy.rotationQuaternion) { this._quaternion.copyFrom(this._copy.rotationQuaternion); } else { this._yaw = this._copy.rotation.y; this._pitch = this._copy.rotation.x; this._roll = this._copy.rotation.z; this._quaternionRotationYPR(); } this._quaternionToRotationMatrix(); this._shape = particle._model._shape; for (var pt = 0; pt < this._shape.length; pt++) { this._vertex.x = this._shape[pt].x; this._vertex.y = this._shape[pt].y; this._vertex.z = this._shape[pt].z; if (particle._model._vertexFunction) { particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction } this._vertex.x *= this._copy.scaling.x; this._vertex.y *= this._copy.scaling.y; this._vertex.z *= this._copy.scaling.z; this._vertex.x += this._copy.pivot.x; this._vertex.y += this._copy.pivot.y; this._vertex.z += this._copy.pivot.z; BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated); this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x; this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y; this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z; } particle.position.x = 0.0; particle.position.y = 0.0; particle.position.z = 0.0; particle.rotation.x = 0.0; particle.rotation.y = 0.0; particle.rotation.z = 0.0; particle.rotationQuaternion = null; particle.scaling.x = 1.0; particle.scaling.y = 1.0; particle.scaling.z = 1.0; }; /** * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed. * Returns the SPS. */ SolidParticleSystem.prototype.rebuildMesh = function () { for (var p = 0; p < this.particles.length; p++) { this._rebuildParticle(this.particles[p]); } this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false); return this; }; /** * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc. * This method calls `updateParticle()` for each particle of the SPS. * For an animated SPS, it is usually called within the render loop. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_ * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_ * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_ * Returns the SPS. */ SolidParticleSystem.prototype.setParticles = function (start, end, update) { if (start === void 0) { start = 0; } if (end === void 0) { end = this.nbParticles - 1; } if (update === void 0) { update = true; } if (!this._updatable) { return this; } // custom beforeUpdate this.beforeUpdateParticles(start, end, update); this._cam_axisX.x = 1.0; this._cam_axisX.y = 0.0; this._cam_axisX.z = 0.0; this._cam_axisY.x = 0.0; this._cam_axisY.y = 1.0; this._cam_axisY.z = 0.0; this._cam_axisZ.x = 0.0; this._cam_axisZ.y = 0.0; this._cam_axisZ.z = 1.0; // cases when the World Matrix is to be computed first if (this.billboard || this._depthSort) { this.mesh.computeWorldMatrix(true); this.mesh._worldMatrix.invertToRef(this._invertMatrix); } // if the particles will always face the camera if (this.billboard) { // compute the camera position and un-rotate it by the current mesh rotation this._camera.getDirectionToRef(this._axisZ, this._camDir); BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ); this._cam_axisZ.normalize(); // same for camera up vector extracted from the cam view matrix var view = this._camera.getViewMatrix(true); BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY); BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX); this._cam_axisY.normalize(); this._cam_axisX.normalize(); } // if depthSort, compute the camera global position in the mesh local system if (this._depthSort) { BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera } BABYLON.Matrix.IdentityToRef(this._rotMatrix); var idx = 0; // current position index in the global array positions32 var index = 0; // position start index in the global array positions32 of the current particle var colidx = 0; // current color index in the global array colors32 var colorIndex = 0; // color start index in the global array colors32 of the current particle var uvidx = 0; // current uv index in the global array uvs32 var uvIndex = 0; // uv start index in the global array uvs32 of the current particle var pt = 0; // current index in the particle model shape if (this.mesh.isFacetDataEnabled) { this._computeBoundingBox = true; } end = (end >= this.nbParticles) ? this.nbParticles - 1 : end; if (this._computeBoundingBox) { if (start == 0 && end == this.nbParticles - 1) { BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum); BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum); } else { if (this.mesh._boundingInfo) { this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum); this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum); } } } // particle loop index = this.particles[start]._pos; var vpos = (index / 3) | 0; colorIndex = vpos * 4; uvIndex = vpos * 2; for (var p = start; p <= end; p++) { this._particle = this.particles[p]; this._shape = this._particle._model._shape; this._shapeUV = this._particle._model._shapeUV; // call to custom user function to update the particle properties this.updateParticle(this._particle); // camera-particle distance for depth sorting if (this._depthSort && this._depthSortParticles) { var dsp = this.depthSortedParticles[p]; dsp.ind = this._particle._ind; dsp.indicesLength = this._particle._model._indicesLength; dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition); } // skip the computations for inactive or already invisible particles if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) { // increment indexes for the next particle pt = this._shape.length; index += pt * 3; colorIndex += pt * 4; uvIndex += pt * 2; continue; } if (this._particle.isVisible) { this._particle._stillInvisible = false; // un-mark permanent invisibility // particle rotation matrix if (this.billboard) { this._particle.rotation.x = 0.0; this._particle.rotation.y = 0.0; } if (this._computeParticleRotation || this.billboard) { if (this._particle.rotationQuaternion) { this._quaternion.copyFrom(this._particle.rotationQuaternion); } else { this._yaw = this._particle.rotation.y; this._pitch = this._particle.rotation.x; this._roll = this._particle.rotation.z; this._quaternionRotationYPR(); } this._quaternionToRotationMatrix(); } // particle vertex loop for (pt = 0; pt < this._shape.length; pt++) { idx = index + pt * 3; colidx = colorIndex + pt * 4; uvidx = uvIndex + pt * 2; this._vertex.x = this._shape[pt].x; this._vertex.y = this._shape[pt].y; this._vertex.z = this._shape[pt].z; if (this._computeParticleVertex) { this.updateParticleVertex(this._particle, this._vertex, pt); } // positions this._vertex.x *= this._particle.scaling.x; this._vertex.y *= this._particle.scaling.y; this._vertex.z *= this._particle.scaling.z; this._vertex.x += this._particle.pivot.x; this._vertex.y += this._particle.pivot.y; this._vertex.z += this._particle.pivot.z; this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8]; this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9]; this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10]; this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z; this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z; this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z; if (this._computeBoundingBox) { if (this._positions32[idx] < this._minimum.x) { this._minimum.x = this._positions32[idx]; } if (this._positions32[idx] > this._maximum.x) { this._maximum.x = this._positions32[idx]; } if (this._positions32[idx + 1] < this._minimum.y) { this._minimum.y = this._positions32[idx + 1]; } if (this._positions32[idx + 1] > this._maximum.y) { this._maximum.y = this._positions32[idx + 1]; } if (this._positions32[idx + 2] < this._minimum.z) { this._minimum.z = this._positions32[idx + 2]; } if (this._positions32[idx + 2] > this._maximum.z) { this._maximum.z = this._positions32[idx + 2]; } } // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals() if (!this._computeParticleVertex) { this._normal.x = this._fixedNormal32[idx]; this._normal.y = this._fixedNormal32[idx + 1]; this._normal.z = this._fixedNormal32[idx + 2]; this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8]; this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9]; this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10]; this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z; this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z; this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z; } if (this._computeParticleColor && this._particle.color) { this._colors32[colidx] = this._particle.color.r; this._colors32[colidx + 1] = this._particle.color.g; this._colors32[colidx + 2] = this._particle.color.b; this._colors32[colidx + 3] = this._particle.color.a; } if (this._computeParticleTexture) { this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x; this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y; } } } else { this._particle._stillInvisible = true; // mark the particle as invisible for (pt = 0; pt < this._shape.length; pt++) { idx = index + pt * 3; colidx = colorIndex + pt * 4; uvidx = uvIndex + pt * 2; this._positions32[idx] = 0.0; this._positions32[idx + 1] = 0.0; this._positions32[idx + 2] = 0.0; this._normals32[idx] = 0.0; this._normals32[idx + 1] = 0.0; this._normals32[idx + 2] = 0.0; if (this._computeParticleColor && this._particle.color) { this._colors32[colidx] = this._particle.color.r; this._colors32[colidx + 1] = this._particle.color.g; this._colors32[colidx + 2] = this._particle.color.b; this._colors32[colidx + 3] = this._particle.color.a; } if (this._computeParticleTexture) { this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x; this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y; } } } // if the particle intersections must be computed : update the bbInfo if (this._particlesIntersect) { var bInfo = this._particle._boundingInfo; var bBox = bInfo.boundingBox; var bSphere = bInfo.boundingSphere; if (!this._bSphereOnly) { // place, scale and rotate the particle bbox within the SPS local system, then update it for (var b = 0; b < bBox.vectors.length; b++) { this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x; this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y; this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z; this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8]; this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9]; this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10]; bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z; bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z; bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z; } bBox._update(this.mesh._worldMatrix); } // place and scale the particle bouding sphere in the SPS local system, then update it this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x; this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y; this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z; this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x; this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y; this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z; bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5; bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5; bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5; bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z)); bSphere._update(this.mesh._worldMatrix); } // increment indexes for the next particle index = idx + 3; colorIndex = colidx + 4; uvIndex = uvidx + 2; } // if the VBO must be updated if (update) { if (this._computeParticleColor) { this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false); } if (this._computeParticleTexture) { this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false); } this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false); if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) { if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) { // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[] var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null; BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params); for (var i = 0; i < this._normals32.length; i++) { this._fixedNormal32[i] = this._normals32[i]; } } if (!this.mesh.areNormalsFrozen) { this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false); } } if (this._depthSort && this._depthSortParticles) { this.depthSortedParticles.sort(this._depthSortFunction); var dspl = this.depthSortedParticles.length; var sorted = 0; var lind = 0; var sind = 0; var sid = 0; for (sorted = 0; sorted < dspl; sorted++) { lind = this.depthSortedParticles[sorted].indicesLength; sind = this.depthSortedParticles[sorted].ind; for (var i = 0; i < lind; i++) { this._indices32[sid] = this._indices[sind + i]; sid++; } } this.mesh.updateIndices(this._indices32); } } if (this._computeBoundingBox) { this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum); this.mesh._boundingInfo.update(this.mesh._worldMatrix); } this.afterUpdateParticles(start, end, update); return this; }; SolidParticleSystem.prototype._quaternionRotationYPR = function () { this._halfroll = this._roll * 0.5; this._halfpitch = this._pitch * 0.5; this._halfyaw = this._yaw * 0.5; this._sinRoll = Math.sin(this._halfroll); this._cosRoll = Math.cos(this._halfroll); this._sinPitch = Math.sin(this._halfpitch); this._cosPitch = Math.cos(this._halfpitch); this._sinYaw = Math.sin(this._halfyaw); this._cosYaw = Math.cos(this._halfyaw); this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll; this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll; this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll; this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll; }; SolidParticleSystem.prototype._quaternionToRotationMatrix = function () { this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z)); this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w); this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w); this._rotMatrix.m[3] = 0; this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w); this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x)); this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w); this._rotMatrix.m[7] = 0; this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w); this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w); this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x)); this._rotMatrix.m[11] = 0; this._rotMatrix.m[12] = 0; this._rotMatrix.m[13] = 0; this._rotMatrix.m[14] = 0; this._rotMatrix.m[15] = 1.0; }; /** * Disposes the SPS. * Returns nothing. */ SolidParticleSystem.prototype.dispose = function () { this.mesh.dispose(); this.vars = null; // drop references to internal big arrays for the GC this._positions = null; this._indices = null; this._normals = null; this._uvs = null; this._colors = null; this._indices32 = null; this._positions32 = null; this._normals32 = null; this._fixedNormal32 = null; this._uvs32 = null; this._colors32 = null; this.pickedParticles = null; }; /** * Visibilty helper : Recomputes the visible size according to the mesh bounding box * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility * Returns the SPS. */ SolidParticleSystem.prototype.refreshVisibleSize = function () { if (!this._isVisibilityBoxLocked) { this.mesh.refreshBoundingInfo(); } return this; }; /** * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box. * @param size the size (float) of the visibility box * note : this doesn't lock the SPS mesh bounding box. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility */ SolidParticleSystem.prototype.setVisibilityBox = function (size) { var vis = size / 2; this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis)); }; Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", { // getter and setter get: function () { return this._alwaysVisible; }, /** * Sets the SPS as always visible or not * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility */ set: function (val) { this._alwaysVisible = val; this.mesh.alwaysSelectAsActiveMesh = val; }, enumerable: true, configurable: true }); Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", { get: function () { return this._isVisibilityBoxLocked; }, /** * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility */ set: function (val) { this._isVisibilityBoxLocked = val; var boundingInfo = this.mesh.getBoundingInfo(); if (boundingInfo) { boundingInfo.isLocked = val; } }, enumerable: true, configurable: true }); Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", { // getters get: function () { return this._computeParticleRotation; }, // Optimizer setters /** * Tells to `setParticles()` to compute the particle rotations or not. * Default value : true. The SPS is faster when it's set to false. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate. */ set: function (val) { this._computeParticleRotation = val; }, enumerable: true, configurable: true }); Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", { get: function () { return this._computeParticleColor; }, /** * Tells to `setParticles()` to compute the particle colors or not. * Default value : true. The SPS is faster when it's set to false. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. */ set: function (val) { this._computeParticleColor = val; }, enumerable: true, configurable: true }); Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", { get: function () { return this._computeParticleTexture; }, /** * Tells to `setParticles()` to compute the particle textures or not. * Default value : true. The SPS is faster when it's set to false. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set. */ set: function (val) { this._computeParticleTexture = val; }, enumerable: true, configurable: true }); Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", { get: function () { return this._computeParticleVertex; }, /** * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not. * Default value : false. The SPS is faster when it's set to false. * Note : the particle custom vertex positions aren't stored values. */ set: function (val) { this._computeParticleVertex = val; }, enumerable: true, configurable: true }); Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", { get: function () { return this._computeBoundingBox; }, /** * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions. */ set: function (val) { this._computeBoundingBox = val; }, enumerable: true, configurable: true }); Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", { get: function () { return this._depthSortParticles; }, /** * Tells to `setParticles()` to sort or not the distance between each particle and the camera. * Skipped when `enableDepthSort` is set to `false` (default) at construction time. * Default : `true` */ set: function (val) { this._depthSortParticles = val; }, enumerable: true, configurable: true }); // ======================================================================= // Particle behavior logic // these following methods may be overwritten by the user to fit his needs /** * This function does nothing. It may be overwritten to set all the particle first values. * The SPS doesn't call this function, you may have to call it by your own. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management */ SolidParticleSystem.prototype.initParticles = function () { }; /** * This function does nothing. It may be overwritten to recycle a particle. * The SPS doesn't call this function, you may have to call it by your own. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management */ SolidParticleSystem.prototype.recycleParticle = function (particle) { return particle; }; /** * Updates a particle : this function should be overwritten by the user. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management * ex : just set a particle position or velocity and recycle conditions */ SolidParticleSystem.prototype.updateParticle = function (particle) { return particle; }; /** * Updates a vertex of a particle : it can be overwritten by the user. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only. * @param particle the current particle * @param vertex the current index of the current particle * @param pt the index of the current vertex in the particle shape * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape * ex : just set a vertex particle position */ SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) { return vertex; }; /** * This will be called before any other treatment by `setParticles()` and will be passed three parameters. * This does nothing and may be overwritten by the user. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() * @param update the boolean update value actually passed to setParticles() */ SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) { }; /** * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update. * This will be passed three parameters. * This does nothing and may be overwritten by the user. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() * @param update the boolean update value actually passed to setParticles() */ SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) { }; return SolidParticleSystem; }()); BABYLON.SolidParticleSystem = SolidParticleSystem; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.solidParticleSystem.js.map /// var BABYLON; (function (BABYLON) { var GroundMesh = /** @class */ (function (_super) { __extends(GroundMesh, _super); function GroundMesh(name, scene) { var _this = _super.call(this, name, scene) || this; _this.generateOctree = false; return _this; } GroundMesh.prototype.getClassName = function () { return "GroundMesh"; }; Object.defineProperty(GroundMesh.prototype, "subdivisions", { get: function () { return Math.min(this._subdivisionsX, this._subdivisionsY); }, enumerable: true, configurable: true }); Object.defineProperty(GroundMesh.prototype, "subdivisionsX", { get: function () { return this._subdivisionsX; }, enumerable: true, configurable: true }); Object.defineProperty(GroundMesh.prototype, "subdivisionsY", { get: function () { return this._subdivisionsY; }, enumerable: true, configurable: true }); GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) { if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; } this._subdivisionsX = chunksCount; this._subdivisionsY = chunksCount; this.subdivide(chunksCount); this.createOrUpdateSubmeshesOctree(octreeBlocksSize); }; /** * Returns a height (y) value in the Worl system : * the ground altitude at the coordinates (x, z) expressed in the World system. * Returns the ground y position if (x, z) are outside the ground surface. */ GroundMesh.prototype.getHeightAtCoordinates = function (x, z) { var world = this.getWorldMatrix(); var invMat = BABYLON.Tmp.Matrix[5]; world.invertToRef(invMat); var tmpVect = BABYLON.Tmp.Vector3[8]; BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space x = tmpVect.x; z = tmpVect.z; if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) { return this.position.y; } if (!this._heightQuads || this._heightQuads.length == 0) { this._initHeightQuads(); this._computeHeightQuads(); } var facet = this._getFacetAt(x, z); var y = -(facet.x * x + facet.z * z + facet.w) / facet.y; // return y in the World system BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect); return tmpVect.y; }; /** * Returns a normalized vector (Vector3) orthogonal to the ground * at the ground coordinates (x, z) expressed in the World system. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface. */ GroundMesh.prototype.getNormalAtCoordinates = function (x, z) { var normal = new BABYLON.Vector3(0.0, 1.0, 0.0); this.getNormalAtCoordinatesToRef(x, z, normal); return normal; }; /** * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground * at the ground coordinates (x, z) expressed in the World system. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface. * Returns the GroundMesh. */ GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) { var world = this.getWorldMatrix(); var tmpMat = BABYLON.Tmp.Matrix[5]; world.invertToRef(tmpMat); var tmpVect = BABYLON.Tmp.Vector3[8]; BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space x = tmpVect.x; z = tmpVect.z; if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) { return this; } if (!this._heightQuads || this._heightQuads.length == 0) { this._initHeightQuads(); this._computeHeightQuads(); } var facet = this._getFacetAt(x, z); BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref); return this; }; /** * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates() * if the ground has been updated. * This can be used in the render loop. * Returns the GroundMesh. */ GroundMesh.prototype.updateCoordinateHeights = function () { if (!this._heightQuads || this._heightQuads.length == 0) { this._initHeightQuads(); } this._computeHeightQuads(); return this; }; // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates GroundMesh.prototype._getFacetAt = function (x, z) { // retrieve col and row from x, z coordinates in the ground local system var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width); var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY); var quad = this._heightQuads[row * this._subdivisionsX + col]; var facet; if (z < quad.slope.x * x + quad.slope.y) { facet = quad.facet1; } else { facet = quad.facet2; } return facet; }; // Creates and populates the heightMap array with "facet" elements : // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0 // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 // Returns the GroundMesh. GroundMesh.prototype._initHeightQuads = function () { var subdivisionsX = this._subdivisionsX; var subdivisionsY = this._subdivisionsY; this._heightQuads = new Array(); for (var row = 0; row < subdivisionsY; row++) { for (var col = 0; col < subdivisionsX; col++) { var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) }; this._heightQuads[row * subdivisionsX + col] = quad; } } return this; }; // Compute each quad element values and update the the heightMap array : // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0 // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 // Returns the GroundMesh. GroundMesh.prototype._computeHeightQuads = function () { var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); if (!positions) { return this; } var v1 = BABYLON.Tmp.Vector3[3]; var v2 = BABYLON.Tmp.Vector3[2]; var v3 = BABYLON.Tmp.Vector3[1]; var v4 = BABYLON.Tmp.Vector3[0]; var v1v2 = BABYLON.Tmp.Vector3[4]; var v1v3 = BABYLON.Tmp.Vector3[5]; var v1v4 = BABYLON.Tmp.Vector3[6]; var norm1 = BABYLON.Tmp.Vector3[7]; var norm2 = BABYLON.Tmp.Vector3[8]; var i = 0; var j = 0; var k = 0; var cd = 0; // 2D slope coefficient : z = cd * x + h var h = 0; var d1 = 0; // facet plane equation : ax + by + cz + d = 0 var d2 = 0; var subdivisionsX = this._subdivisionsX; var subdivisionsY = this._subdivisionsY; for (var row = 0; row < subdivisionsY; row++) { for (var col = 0; col < subdivisionsX; col++) { i = col * 3; j = row * (subdivisionsX + 1) * 3; k = (row + 1) * (subdivisionsX + 1) * 3; v1.x = positions[j + i]; v1.y = positions[j + i + 1]; v1.z = positions[j + i + 2]; v2.x = positions[j + i + 3]; v2.y = positions[j + i + 4]; v2.z = positions[j + i + 5]; v3.x = positions[k + i]; v3.y = positions[k + i + 1]; v3.z = positions[k + i + 2]; v4.x = positions[k + i + 3]; v4.y = positions[k + i + 4]; v4.z = positions[k + i + 5]; // 2D slope V1V4 cd = (v4.z - v1.z) / (v4.x - v1.x); h = v1.z - cd * v1.x; // v1 belongs to the slope // facet equations : // we compute each facet normal vector // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0 // we compute the value d by applying the equation to v1 which belongs to the plane // then we store the facet equation in a Vector4 v2.subtractToRef(v1, v1v2); v3.subtractToRef(v1, v1v3); v4.subtractToRef(v1, v1v4); BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2); norm1.normalize(); norm2.normalize(); d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z); d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z); var quad = this._heightQuads[row * subdivisionsX + col]; quad.slope.copyFromFloats(cd, h); quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1); quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2); } } return this; }; GroundMesh.prototype.serialize = function (serializationObject) { _super.prototype.serialize.call(this, serializationObject); serializationObject.subdivisionsX = this._subdivisionsX; serializationObject.subdivisionsY = this._subdivisionsY; serializationObject.minX = this._minX; serializationObject.maxX = this._maxX; serializationObject.minZ = this._minZ; serializationObject.maxZ = this._maxZ; serializationObject.width = this._width; serializationObject.height = this._height; }; GroundMesh.Parse = function (parsedMesh, scene) { var result = new GroundMesh(parsedMesh.name, scene); result._subdivisionsX = parsedMesh.subdivisionsX || 1; result._subdivisionsY = parsedMesh.subdivisionsY || 1; result._minX = parsedMesh.minX; result._maxX = parsedMesh.maxX; result._minZ = parsedMesh.minZ; result._maxZ = parsedMesh.maxZ; result._width = parsedMesh.width; result._height = parsedMesh.height; return result; }; return GroundMesh; }(BABYLON.Mesh)); BABYLON.GroundMesh = GroundMesh; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.groundMesh.js.map var BABYLON; (function (BABYLON) { /** * Creates an instance based on a source mesh. */ var InstancedMesh = /** @class */ (function (_super) { __extends(InstancedMesh, _super); function InstancedMesh(name, source) { var _this = _super.call(this, name, source.getScene()) || this; source.instances.push(_this); _this._sourceMesh = source; _this.position.copyFrom(source.position); _this.rotation.copyFrom(source.rotation); _this.scaling.copyFrom(source.scaling); if (source.rotationQuaternion) { _this.rotationQuaternion = source.rotationQuaternion.clone(); } _this.infiniteDistance = source.infiniteDistance; _this.setPivotMatrix(source.getPivotMatrix()); _this.refreshBoundingInfo(); _this._syncSubMeshes(); return _this; } /** * Returns the string "InstancedMesh". */ InstancedMesh.prototype.getClassName = function () { return "InstancedMesh"; }; Object.defineProperty(InstancedMesh.prototype, "receiveShadows", { // Methods get: function () { return this._sourceMesh.receiveShadows; }, enumerable: true, configurable: true }); Object.defineProperty(InstancedMesh.prototype, "material", { get: function () { return this._sourceMesh.material; }, enumerable: true, configurable: true }); Object.defineProperty(InstancedMesh.prototype, "visibility", { get: function () { return this._sourceMesh.visibility; }, enumerable: true, configurable: true }); Object.defineProperty(InstancedMesh.prototype, "skeleton", { get: function () { return this._sourceMesh.skeleton; }, enumerable: true, configurable: true }); Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", { get: function () { return this._sourceMesh.renderingGroupId; }, enumerable: true, configurable: true }); /** * Returns the total number of vertices (integer). */ InstancedMesh.prototype.getTotalVertices = function () { return this._sourceMesh.getTotalVertices(); }; Object.defineProperty(InstancedMesh.prototype, "sourceMesh", { get: function () { return this._sourceMesh; }, enumerable: true, configurable: true }); /** * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc. */ InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) { return this._sourceMesh.getVerticesData(kind, copyWhenShared); }; /** * 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. */ InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) { if (this.sourceMesh) { this.sourceMesh.setVerticesData(kind, data, updatable, stride); } return this.sourceMesh; }; /** * 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. */ InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) { if (this.sourceMesh) { this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique); } return this.sourceMesh; }; /** * 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. */ InstancedMesh.prototype.setIndices = function (indices, totalVertices) { if (totalVertices === void 0) { totalVertices = null; } if (this.sourceMesh) { this.sourceMesh.setIndices(indices, totalVertices); } return this.sourceMesh; }; /** * Boolean : True if the mesh owns the requested kind of data. */ InstancedMesh.prototype.isVerticesDataPresent = function (kind) { return this._sourceMesh.isVerticesDataPresent(kind); }; /** * Returns an array of indices (IndicesArray). */ InstancedMesh.prototype.getIndices = function () { return this._sourceMesh.getIndices(); }; Object.defineProperty(InstancedMesh.prototype, "_positions", { get: function () { return this._sourceMesh._positions; }, enumerable: true, configurable: true }); /** * Sets a new updated BoundingInfo to the mesh. * Returns the mesh. */ InstancedMesh.prototype.refreshBoundingInfo = function () { var meshBB = this._sourceMesh.getBoundingInfo(); if (meshBB) { this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone()); } this._updateBoundingInfo(); return this; }; InstancedMesh.prototype._preActivate = function () { if (this._currentLOD) { this._currentLOD._preActivate(); } return this; }; InstancedMesh.prototype._activate = function (renderId) { if (this._currentLOD) { this._currentLOD._registerInstanceForRenderId(this, renderId); } return this; }; /** * Returns the current associated LOD AbstractMesh. */ InstancedMesh.prototype.getLOD = function (camera) { if (!camera) { return this; } var boundingInfo = this.getBoundingInfo(); if (!boundingInfo) { return this; } this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere); if (this._currentLOD === this.sourceMesh) { return this; } return this._currentLOD; }; InstancedMesh.prototype._syncSubMeshes = function () { this.releaseSubMeshes(); if (this._sourceMesh.subMeshes) { for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) { this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh); } } return this; }; InstancedMesh.prototype._generatePointsArray = function () { return this._sourceMesh._generatePointsArray(); }; /** * Creates a new InstancedMesh from the current mesh. * - name (string) : the cloned mesh name * - newParent (optional Node) : the optional Node to parent the clone to. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned. * * Returns the clone. */ InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) { var result = this._sourceMesh.createInstance(name); // Deep copy BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []); // Bounding info this.refreshBoundingInfo(); // Parent if (newParent) { result.parent = newParent; } if (!doNotCloneChildren) { // Children for (var index = 0; index < this.getScene().meshes.length; index++) { var mesh = this.getScene().meshes[index]; if (mesh.parent === this) { mesh.clone(mesh.name, result); } } } result.computeWorldMatrix(true); return result; }; /** * Disposes the InstancedMesh. * Returns nothing. */ InstancedMesh.prototype.dispose = function (doNotRecurse) { // Remove from mesh var index = this._sourceMesh.instances.indexOf(this); this._sourceMesh.instances.splice(index, 1); _super.prototype.dispose.call(this, doNotRecurse); }; return InstancedMesh; }(BABYLON.AbstractMesh)); BABYLON.InstancedMesh = InstancedMesh; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.instancedMesh.js.map /// var BABYLON; (function (BABYLON) { var LinesMesh = /** @class */ (function (_super) { __extends(LinesMesh, _super); function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) { if (scene === void 0) { scene = null; } if (parent === void 0) { parent = null; } var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this; _this.useVertexColor = useVertexColor; _this.color = new BABYLON.Color3(1, 1, 1); _this.alpha = 1; if (source) { _this.color = source.color.clone(); _this.alpha = source.alpha; _this.useVertexColor = source.useVertexColor; } _this._intersectionThreshold = 0.1; var options = { attributes: [BABYLON.VertexBuffer.PositionKind], uniforms: ["world", "viewProjection"], needAlphaBlending: false, }; if (!useVertexColor) { options.uniforms.push("color"); options.needAlphaBlending = true; } _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options); return _this; } Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", { /** * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. * This margin is expressed in world space coordinates, so its value may vary. * Default value is 0.1 * @returns the intersection Threshold value. */ get: function () { return this._intersectionThreshold; }, /** * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. * This margin is expressed in world space coordinates, so its value may vary. * @param value the new threshold to apply */ set: function (value) { if (this._intersectionThreshold === value) { return; } this._intersectionThreshold = value; if (this.geometry) { this.geometry.boundingBias = new BABYLON.Vector2(0, value); } }, enumerable: true, configurable: true }); /** * Returns the string "LineMesh" */ LinesMesh.prototype.getClassName = function () { return "LinesMesh"; }; Object.defineProperty(LinesMesh.prototype, "material", { get: function () { return this._colorShader; }, enumerable: true, configurable: true }); Object.defineProperty(LinesMesh.prototype, "checkCollisions", { get: function () { return false; }, enumerable: true, configurable: true }); LinesMesh.prototype.createInstance = function (name) { throw new Error("LinesMeshes do not support createInstance."); }; LinesMesh.prototype._bind = function (subMesh, effect, fillMode) { if (!this._geometry) { return this; } // VBOs this._geometry._bind(this._colorShader.getEffect()); // Color if (!this.useVertexColor) { this._colorShader.setColor4("color", this.color.toColor4(this.alpha)); } return this; }; LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) { if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) { return this; } var engine = this.getScene().getEngine(); // Draw order engine.draw(false, subMesh.indexStart, subMesh.indexCount); return this; }; LinesMesh.prototype.dispose = function (doNotRecurse) { this._colorShader.dispose(); _super.prototype.dispose.call(this, doNotRecurse); }; /** * Returns a new LineMesh object cloned from the current one. */ LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) { return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren); }; return LinesMesh; }(BABYLON.Mesh)); BABYLON.LinesMesh = LinesMesh; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.linesMesh.js.map var BABYLON; (function (BABYLON) { var ShaderMaterial = /** @class */ (function (_super) { __extends(ShaderMaterial, _super); function ShaderMaterial(name, scene, shaderPath, options) { var _this = _super.call(this, name, scene) || this; _this._textures = {}; _this._textureArrays = {}; _this._floats = {}; _this._floatsArrays = {}; _this._colors3 = {}; _this._colors3Arrays = {}; _this._colors4 = {}; _this._vectors2 = {}; _this._vectors3 = {}; _this._vectors4 = {}; _this._matrices = {}; _this._matrices3x3 = {}; _this._matrices2x2 = {}; _this._vectors3Arrays = {}; _this._cachedWorldViewMatrix = new BABYLON.Matrix(); _this._shaderPath = shaderPath; options.needAlphaBlending = options.needAlphaBlending || false; options.needAlphaTesting = options.needAlphaTesting || false; options.attributes = options.attributes || ["position", "normal", "uv"]; options.uniforms = options.uniforms || ["worldViewProjection"]; options.uniformBuffers = options.uniformBuffers || []; options.samplers = options.samplers || []; options.defines = options.defines || []; _this._options = options; return _this; } ShaderMaterial.prototype.getClassName = function () { return "ShaderMaterial"; }; ShaderMaterial.prototype.needAlphaBlending = function () { return this._options.needAlphaBlending; }; ShaderMaterial.prototype.needAlphaTesting = function () { return this._options.needAlphaTesting; }; ShaderMaterial.prototype._checkUniform = function (uniformName) { if (this._options.uniforms.indexOf(uniformName) === -1) { this._options.uniforms.push(uniformName); } }; ShaderMaterial.prototype.setTexture = function (name, texture) { if (this._options.samplers.indexOf(name) === -1) { this._options.samplers.push(name); } this._textures[name] = texture; return this; }; ShaderMaterial.prototype.setTextureArray = function (name, textures) { if (this._options.samplers.indexOf(name) === -1) { this._options.samplers.push(name); } this._checkUniform(name); this._textureArrays[name] = textures; return this; }; ShaderMaterial.prototype.setFloat = function (name, value) { this._checkUniform(name); this._floats[name] = value; return this; }; ShaderMaterial.prototype.setFloats = function (name, value) { this._checkUniform(name); this._floatsArrays[name] = value; return this; }; ShaderMaterial.prototype.setColor3 = function (name, value) { this._checkUniform(name); this._colors3[name] = value; return this; }; ShaderMaterial.prototype.setColor3Array = function (name, value) { this._checkUniform(name); this._colors3Arrays[name] = value.reduce(function (arr, color) { color.toArray(arr, arr.length); return arr; }, []); return this; }; ShaderMaterial.prototype.setColor4 = function (name, value) { this._checkUniform(name); this._colors4[name] = value; return this; }; ShaderMaterial.prototype.setVector2 = function (name, value) { this._checkUniform(name); this._vectors2[name] = value; return this; }; ShaderMaterial.prototype.setVector3 = function (name, value) { this._checkUniform(name); this._vectors3[name] = value; return this; }; ShaderMaterial.prototype.setVector4 = function (name, value) { this._checkUniform(name); this._vectors4[name] = value; return this; }; ShaderMaterial.prototype.setMatrix = function (name, value) { this._checkUniform(name); this._matrices[name] = value; return this; }; ShaderMaterial.prototype.setMatrix3x3 = function (name, value) { this._checkUniform(name); this._matrices3x3[name] = value; return this; }; ShaderMaterial.prototype.setMatrix2x2 = function (name, value) { this._checkUniform(name); this._matrices2x2[name] = value; return this; }; ShaderMaterial.prototype.setArray3 = function (name, value) { this._checkUniform(name); this._vectors3Arrays[name] = value; return this; }; ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) { if (!mesh) { return true; } if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) { return false; } return false; }; ShaderMaterial.prototype.isReady = function (mesh, useInstances) { var scene = this.getScene(); var engine = scene.getEngine(); if (!this.checkReadyOnEveryCall) { if (this._renderId === scene.getRenderId()) { if (this._checkCache(scene, mesh, useInstances)) { return true; } } } // Instances var defines = []; var attribs = []; var fallbacks = new BABYLON.EffectFallbacks(); if (useInstances) { defines.push("#define INSTANCES"); } for (var index = 0; index < this._options.defines.length; index++) { defines.push(this._options.defines[index]); } for (var index = 0; index < this._options.attributes.length; index++) { attribs.push(this._options.attributes[index]); } if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) { attribs.push(BABYLON.VertexBuffer.ColorKind); defines.push("#define VERTEXCOLOR"); } // Bones if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1)); fallbacks.addCPUSkinningFallback(0, mesh); if (this._options.uniforms.indexOf("mBones") === -1) { this._options.uniforms.push("mBones"); } } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } // Textures for (var name in this._textures) { if (!this._textures[name].isReady()) { return false; } } // Alpha test if (engine.getAlphaTesting()) { defines.push("#define ALPHATEST"); } var previousEffect = this._effect; var join = defines.join("\n"); this._effect = engine.createEffect(this._shaderPath, { attributes: attribs, uniformsNames: this._options.uniforms, uniformBuffersNames: this._options.uniformBuffers, samplers: this._options.samplers, defines: join, fallbacks: fallbacks, onCompiled: this.onCompiled, onError: this.onError }, engine); if (!this._effect.isReady()) { return false; } if (previousEffect !== this._effect) { scene.resetCachedMaterial(); } this._renderId = scene.getRenderId(); return true; }; ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) { var scene = this.getScene(); if (!this._effect) { return; } if (this._options.uniforms.indexOf("world") !== -1) { this._effect.setMatrix("world", world); } if (this._options.uniforms.indexOf("worldView") !== -1) { world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix); this._effect.setMatrix("worldView", this._cachedWorldViewMatrix); } if (this._options.uniforms.indexOf("worldViewProjection") !== -1) { this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix())); } }; ShaderMaterial.prototype.bind = function (world, mesh) { // Std values this.bindOnlyWorldMatrix(world); if (this._effect && this.getScene().getCachedMaterial() !== this) { if (this._options.uniforms.indexOf("view") !== -1) { this._effect.setMatrix("view", this.getScene().getViewMatrix()); } if (this._options.uniforms.indexOf("projection") !== -1) { this._effect.setMatrix("projection", this.getScene().getProjectionMatrix()); } if (this._options.uniforms.indexOf("viewProjection") !== -1) { this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix()); } // Bones BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect); var name; // Texture for (name in this._textures) { this._effect.setTexture(name, this._textures[name]); } // Texture arrays for (name in this._textureArrays) { this._effect.setTextureArray(name, this._textureArrays[name]); } // Float for (name in this._floats) { this._effect.setFloat(name, this._floats[name]); } // Float s for (name in this._floatsArrays) { this._effect.setArray(name, this._floatsArrays[name]); } // Color3 for (name in this._colors3) { this._effect.setColor3(name, this._colors3[name]); } for (name in this._colors3Arrays) { this._effect.setArray3(name, this._colors3Arrays[name]); } // Color4 for (name in this._colors4) { var color = this._colors4[name]; this._effect.setFloat4(name, color.r, color.g, color.b, color.a); } // Vector2 for (name in this._vectors2) { this._effect.setVector2(name, this._vectors2[name]); } // Vector3 for (name in this._vectors3) { this._effect.setVector3(name, this._vectors3[name]); } // Vector4 for (name in this._vectors4) { this._effect.setVector4(name, this._vectors4[name]); } // Matrix for (name in this._matrices) { this._effect.setMatrix(name, this._matrices[name]); } // Matrix 3x3 for (name in this._matrices3x3) { this._effect.setMatrix3x3(name, this._matrices3x3[name]); } // Matrix 2x2 for (name in this._matrices2x2) { this._effect.setMatrix2x2(name, this._matrices2x2[name]); } // Vector3Array for (name in this._vectors3Arrays) { this._effect.setArray3(name, this._vectors3Arrays[name]); } } this._afterBind(mesh); }; ShaderMaterial.prototype.getActiveTextures = function () { var activeTextures = _super.prototype.getActiveTextures.call(this); for (var name in this._textures) { activeTextures.push(this._textures[name]); } for (var name in this._textureArrays) { var array = this._textureArrays[name]; for (var index = 0; index < array.length; index++) { activeTextures.push(array[index]); } } return activeTextures; }; ShaderMaterial.prototype.hasTexture = function (texture) { if (_super.prototype.hasTexture.call(this, texture)) { return true; } for (var name in this._textures) { if (this._textures[name] === texture) { return true; } } for (var name in this._textureArrays) { var array = this._textureArrays[name]; for (var index = 0; index < array.length; index++) { if (array[index] === texture) { return true; } } } return false; }; ShaderMaterial.prototype.clone = function (name) { var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options); return newShaderMaterial; }; ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) { if (forceDisposeTextures) { var name; for (name in this._textures) { this._textures[name].dispose(); } for (name in this._textureArrays) { var array = this._textureArrays[name]; for (var index = 0; index < array.length; index++) { array[index].dispose(); } } } this._textures = {}; _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures); }; ShaderMaterial.prototype.serialize = function () { var serializationObject = BABYLON.SerializationHelper.Serialize(this); serializationObject.customType = "BABYLON.ShaderMaterial"; serializationObject.options = this._options; serializationObject.shaderPath = this._shaderPath; var name; // Texture serializationObject.textures = {}; for (name in this._textures) { serializationObject.textures[name] = this._textures[name].serialize(); } // Texture arrays serializationObject.textureArrays = {}; for (name in this._textureArrays) { serializationObject.textureArrays[name] = []; var array = this._textureArrays[name]; for (var index = 0; index < array.length; index++) { serializationObject.textureArrays[name].push(array[index].serialize()); } } // Float serializationObject.floats = {}; for (name in this._floats) { serializationObject.floats[name] = this._floats[name]; } // Float s serializationObject.FloatArrays = {}; for (name in this._floatsArrays) { serializationObject.FloatArrays[name] = this._floatsArrays[name]; } // Color3 serializationObject.colors3 = {}; for (name in this._colors3) { serializationObject.colors3[name] = this._colors3[name].asArray(); } // Color3 array serializationObject.colors3Arrays = {}; for (name in this._colors3Arrays) { serializationObject.colors3Arrays[name] = this._colors3Arrays[name]; } // Color4 serializationObject.colors4 = {}; for (name in this._colors4) { serializationObject.colors4[name] = this._colors4[name].asArray(); } // Vector2 serializationObject.vectors2 = {}; for (name in this._vectors2) { serializationObject.vectors2[name] = this._vectors2[name].asArray(); } // Vector3 serializationObject.vectors3 = {}; for (name in this._vectors3) { serializationObject.vectors3[name] = this._vectors3[name].asArray(); } // Vector4 serializationObject.vectors4 = {}; for (name in this._vectors4) { serializationObject.vectors4[name] = this._vectors4[name].asArray(); } // Matrix serializationObject.matrices = {}; for (name in this._matrices) { serializationObject.matrices[name] = this._matrices[name].asArray(); } // Matrix 3x3 serializationObject.matrices3x3 = {}; for (name in this._matrices3x3) { serializationObject.matrices3x3[name] = this._matrices3x3[name]; } // Matrix 2x2 serializationObject.matrices2x2 = {}; for (name in this._matrices2x2) { serializationObject.matrices2x2[name] = this._matrices2x2[name]; } // Vector3Array serializationObject.vectors3Arrays = {}; for (name in this._vectors3Arrays) { serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name]; } return serializationObject; }; ShaderMaterial.Parse = function (source, scene, rootUrl) { var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl); var name; // Texture for (name in source.textures) { material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl)); } // Texture arrays for (name in source.textureArrays) { var array = source.textureArrays[name]; var textureArray = new Array(); for (var index = 0; index < array.length; index++) { textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl)); } material.setTextureArray(name, textureArray); } // Float for (name in source.floats) { material.setFloat(name, source.floats[name]); } // Float s for (name in source.floatsArrays) { material.setFloats(name, source.floatsArrays[name]); } // Color3 for (name in source.colors3) { material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name])); } // Color3 arrays for (name in source.colors3Arrays) { var colors = source.colors3Arrays[name].reduce(function (arr, num, i) { if (i % 3 === 0) { arr.push([num]); } else { arr[arr.length - 1].push(num); } return arr; }, []).map(function (color) { return BABYLON.Color3.FromArray(color); }); material.setColor3Array(name, colors); } // Color4 for (name in source.colors4) { material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name])); } // Vector2 for (name in source.vectors2) { material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name])); } // Vector3 for (name in source.vectors3) { material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name])); } // Vector4 for (name in source.vectors4) { material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name])); } // Matrix for (name in source.matrices) { material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name])); } // Matrix 3x3 for (name in source.matrices3x3) { material.setMatrix3x3(name, source.matrices3x3[name]); } // Matrix 2x2 for (name in source.matrices2x2) { material.setMatrix2x2(name, source.matrices2x2[name]); } // Vector3Array for (name in source.vectors3Arrays) { material.setArray3(name, source.vectors3Arrays[name]); } return material; }; return ShaderMaterial; }(BABYLON.Material)); BABYLON.ShaderMaterial = ShaderMaterial; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.shaderMaterial.js.map var BABYLON; (function (BABYLON) { var MeshBuilder = /** @class */ (function () { function MeshBuilder() { } MeshBuilder.updateSideOrientation = function (orientation) { if (orientation == BABYLON.Mesh.DOUBLESIDE) { return BABYLON.Mesh.DOUBLESIDE; } if (orientation === undefined || orientation === null) { return BABYLON.Mesh.FRONTSIDE; } return orientation; }; /** * Creates a box mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box * The parameter `size` sets the size (float) of each box side (default 1). * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`). * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements). * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * 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. */ MeshBuilder.CreateBox = function (name, options, scene) { if (scene === void 0) { scene = null; } var box = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); box._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateBox(options); vertexData.applyToMesh(box, options.updatable); return box; }; /** * Creates a sphere mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere * The parameter `diameter` sets the diameter size (float) of the sphere (default 1). * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`). * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32). * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude). * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * 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. */ MeshBuilder.CreateSphere = function (name, options, scene) { var sphere = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); sphere._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateSphere(options); vertexData.applyToMesh(sphere, options.updatable); return sphere; }; /** * Creates a plane polygonal mesh. By default, this is a disc. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc * 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 create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * 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. */ MeshBuilder.CreateDisc = function (name, options, scene) { if (scene === void 0) { scene = null; } var disc = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); disc._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateDisc(options); vertexData.applyToMesh(disc, options.updatable); return disc; }; /** * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere * 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 * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * 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. */ MeshBuilder.CreateIcoSphere = function (name, options, scene) { var sphere = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); sphere._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateIcoSphere(options); vertexData.applyToMesh(sphere, options.updatable); return sphere; }; ; /** * Creates a ribbon mesh. * 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 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 * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values. * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that * if you set `closePath` to `true`, there's one extra vertex per path in the geometry. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ MeshBuilder.CreateRibbon = function (name, options, scene) { if (scene === void 0) { scene = null; } var pathArray = options.pathArray; var closeArray = options.closeArray; var closePath = options.closePath; var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); var instance = options.instance; var updatable = options.updatable; if (instance) { // positionFunction : ribbon case // only pathArray and sideOrientation parameters are taken into account for positions update BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]); var positionFunction = function (positions) { var minlg = pathArray[0].length; var i = 0; var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1; for (var si = 1; si <= ns; si++) { for (var p = 0; p < pathArray.length; p++) { var path = pathArray[p]; var l = path.length; minlg = (minlg < l) ? minlg : l; var j = 0; while (j < minlg) { positions[i] = path[j].x; positions[i + 1] = path[j].y; positions[i + 2] = path[j].z; if (path[j].x < BABYLON.Tmp.Vector3[0].x) { BABYLON.Tmp.Vector3[0].x = path[j].x; } if (path[j].x > BABYLON.Tmp.Vector3[1].x) { BABYLON.Tmp.Vector3[1].x = path[j].x; } if (path[j].y < BABYLON.Tmp.Vector3[0].y) { BABYLON.Tmp.Vector3[0].y = path[j].y; } if (path[j].y > BABYLON.Tmp.Vector3[1].y) { BABYLON.Tmp.Vector3[1].y = path[j].y; } if (path[j].z < BABYLON.Tmp.Vector3[0].z) { BABYLON.Tmp.Vector3[0].z = path[j].z; } if (path[j].z > BABYLON.Tmp.Vector3[1].z) { BABYLON.Tmp.Vector3[1].z = path[j].z; } j++; i += 3; } if (instance._closePath) { positions[i] = path[0].x; positions[i + 1] = path[0].y; positions[i + 2] = path[0].z; i += 3; } } } }; var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind); positionFunction(positions); instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]); instance._boundingInfo.update(instance._worldMatrix); instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false); if (options.colors) { var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind); for (var c = 0; c < options.colors.length; c++) { colors[c * 4] = options.colors[c].r; colors[c * 4 + 1] = options.colors[c].g; colors[c * 4 + 2] = options.colors[c].b; colors[c * 4 + 3] = options.colors[c].a; } instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false); } if (options.uvs) { var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind); for (var i = 0; i < options.uvs.length; i++) { uvs[i * 2] = options.uvs[i].x; uvs[i * 2 + 1] = options.uvs[i].y; } instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false); } if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) { var indices = instance.getIndices(); var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind); var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null; BABYLON.VertexData.ComputeNormals(positions, indices, normals, params); if (instance._closePath) { var indexFirst = 0; var indexLast = 0; for (var p = 0; p < pathArray.length; p++) { indexFirst = instance._idx[p] * 3; if (p + 1 < pathArray.length) { indexLast = (instance._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]; } } if (!(instance.areNormalsFrozen)) { instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false); } } return instance; } else { var ribbon = new BABYLON.Mesh(name, scene); ribbon._originalBuilderSideOrientation = sideOrientation; var vertexData = BABYLON.VertexData.CreateRibbon(options); if (closePath) { ribbon._idx = vertexData._idx; } ribbon._closePath = closePath; ribbon._closeArray = closeArray; vertexData.applyToMesh(ribbon, updatable); return ribbon; } }; /** * Creates a cylinder or a cone mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone * 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). * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements). * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3 * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7 * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17 * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface. * If `enclose` is false, a ring surface is one element. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379 * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * 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. */ MeshBuilder.CreateCylinder = function (name, options, scene) { var cylinder = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); cylinder._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateCylinder(options); vertexData.applyToMesh(cylinder, options.updatable); return cylinder; }; /** * Creates a torus mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus * 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 * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * 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. */ MeshBuilder.CreateTorus = function (name, options, scene) { var torus = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); torus._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateTorus(options); vertexData.applyToMesh(torus, options.updatable); return torus; }; /** * Creates a torus knot mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot * 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 * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * 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. */ MeshBuilder.CreateTorusKnot = function (name, options, scene) { var torusKnot = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); torusKnot._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateTorusKnot(options); vertexData.applyToMesh(torusKnot, options.updatable); return torusKnot; }; /** * Creates a line system mesh. * A line system is a pool of many lines gathered in a single mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function. * The parameter `lines` is an array of lines, each line being an array of successive Vector3. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ MeshBuilder.CreateLineSystem = function (name, options, scene) { var instance = options.instance; var lines = options.lines; if (instance) { var positionFunction = function (positions) { var i = 0; for (var l = 0; l < lines.length; l++) { var points = lines[l]; for (var p = 0; p < points.length; p++) { positions[i] = points[p].x; positions[i + 1] = points[p].y; positions[i + 2] = points[p].z; i += 3; } } }; instance.updateMeshPositions(positionFunction, false); return instance; } // line system creation var lineSystem = new BABYLON.LinesMesh(name, scene); var vertexData = BABYLON.VertexData.CreateLineSystem(options); vertexData.applyToMesh(lineSystem, options.updatable); return lineSystem; }; /** * Creates a line mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines * 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. */ MeshBuilder.CreateLines = function (name, options, scene) { if (scene === void 0) { scene = null; } var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene); return lines; }; /** * Creates a dashed line mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines * 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. */ MeshBuilder.CreateDashedLines = function (name, options, scene) { if (scene === void 0) { scene = null; } var points = options.points; var instance = options.instance; var gapSize = options.gapSize || 1; var dashSize = options.dashSize || 3; if (instance) { var positionFunction = function (positions) { var curvect = BABYLON.Vector3.Zero(); var nbSeg = positions.length / 6; var lg = 0; var nb = 0; var shft = 0; var dashshft = 0; var curshft = 0; var p = 0; var i = 0; var j = 0; for (i = 0; i < points.length - 1; i++) { points[i + 1].subtractToRef(points[i], curvect); lg += curvect.length(); } shft = lg / nbSeg; dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize); for (i = 0; i < points.length - 1; i++) { points[i + 1].subtractToRef(points[i], curvect); nb = Math.floor(curvect.length() / shft); curvect.normalize(); j = 0; while (j < nb && p < positions.length) { curshft = shft * j; positions[p] = points[i].x + curshft * curvect.x; positions[p + 1] = points[i].y + curshft * curvect.y; positions[p + 2] = points[i].z + curshft * curvect.z; positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x; positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y; positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z; p += 6; j++; } } while (p < positions.length) { positions[p] = points[i].x; positions[p + 1] = points[i].y; positions[p + 2] = points[i].z; p += 3; } }; instance.updateMeshPositions(positionFunction, false); return instance; } // dashed lines creation var dashedLines = new BABYLON.LinesMesh(name, scene); var vertexData = BABYLON.VertexData.CreateDashedLines(options); vertexData.applyToMesh(dashedLines, options.updatable); dashedLines.dashSize = dashSize; dashedLines.gapSize = gapSize; return dashedLines; }; /** * 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. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes * * 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 * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ MeshBuilder.ExtrudeShape = function (name, options, scene) { if (scene === void 0) { scene = null; } var path = options.path; var shape = options.shape; var scale = options.scale || 1; var rotation = options.rotation || 0; var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP; var updatable = options.updatable; var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); var instance = options.instance || null; var invertUV = options.invertUV || false; return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null); }; /** * 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. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes * * 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 * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) { var path = options.path; var shape = options.shape; var scaleFunction = options.scaleFunction || (function () { return 1; }); var rotationFunction = options.rotationFunction || (function () { return 0; }); var ribbonCloseArray = options.ribbonCloseArray || false; var ribbonClosePath = options.ribbonClosePath || false; var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP; var updatable = options.updatable; var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); var instance = options.instance; var invertUV = options.invertUV || false; return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null); }; /** * 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. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe * * 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. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc". * 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 * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ MeshBuilder.CreateLathe = function (name, options, scene) { var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0; var closed = (options.closed === undefined) ? true : options.closed; var shape = options.shape; var radius = options.radius || 1; var tessellation = options.tessellation || 64; var updatable = options.updatable; var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); var cap = options.cap || BABYLON.Mesh.NO_CAP; var pi2 = Math.PI * 2; var paths = new Array(); var invertUV = options.invertUV || false; var i = 0; var p = 0; var step = pi2 / tessellation * arc; var rotated; var path = new Array(); ; for (i = 0; i <= tessellation; i++) { var path = []; if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) { path.push(new BABYLON.Vector3(0, shape[0].y, 0)); path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius)); } for (p = 0; p < shape.length; p++) { rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius); path.push(rotated); } if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) { path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius)); path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0)); } paths.push(path); } // lathe ribbon var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene); return lathe; }; /** * Creates a plane mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane * The parameter `size` sets the size (float) of both sides of the plane at once (default 1). * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`). * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * 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. */ MeshBuilder.CreatePlane = function (name, options, scene) { var plane = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); plane._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreatePlane(options); vertexData.applyToMesh(plane, options.updatable); if (options.sourcePlane) { plane.translate(options.sourcePlane.normal, options.sourcePlane.d); var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z)); var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal); plane.rotate(vectorProduct, product); } return plane; }; /** * Creates a ground mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane * 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. */ MeshBuilder.CreateGround = function (name, options, scene) { var ground = new BABYLON.GroundMesh(name, scene); ground._setReady(false); ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1; ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1; ground._width = options.width || 1; ground._height = options.height || 1; ground._maxX = ground._width / 2; ground._maxZ = ground._height / 2; ground._minX = -ground._maxX; ground._minZ = -ground._maxZ; var vertexData = BABYLON.VertexData.CreateGround(options); vertexData.applyToMesh(ground, options.updatable); ground._setReady(true); return ground; }; /** * Creates a tiled ground mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground * 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. */ MeshBuilder.CreateTiledGround = function (name, options, scene) { var tiledGround = new BABYLON.Mesh(name, scene); var vertexData = BABYLON.VertexData.CreateTiledGround(options); vertexData.applyToMesh(tiledGround, options.updatable); return tiledGround; }; /** * Creates a ground mesh from a height map. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map * 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 `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height. * 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. */ MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) { var width = options.width || 10.0; var height = options.height || 10.0; var subdivisions = options.subdivisions || 1 | 0; var minHeight = options.minHeight || 0.0; var maxHeight = options.maxHeight || 1.0; var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11); var updatable = options.updatable; var onReady = options.onReady; var ground = new BABYLON.GroundMesh(name, scene); ground._subdivisionsX = subdivisions; ground._subdivisionsY = subdivisions; ground._width = width; ground._height = height; ground._maxX = ground._width / 2.0; ground._maxZ = ground._height / 2.0; ground._minX = -ground._maxX; ground._minZ = -ground._maxZ; ground._setReady(false); var onload = function (img) { // Getting height map data var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); if (!context) { throw new Error("Unable to get 2d context for CreateGroundFromHeightMap"); } var bufferWidth = img.width; var bufferHeight = img.height; canvas.width = bufferWidth; canvas.height = bufferHeight; 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, bufferWidth, bufferHeight).data; var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({ width: width, height: height, subdivisions: subdivisions, minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter, buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight }); vertexData.applyToMesh(ground, updatable); ground._setReady(true); //execute ready callback, if set if (onReady) { onReady(ground); } }; BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database); return ground; }; /** * Creates a polygon mesh. * 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. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * Remember you can only change the shape positions, not their number when updating a polygon. */ MeshBuilder.CreatePolygon = function (name, options, scene) { options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); var shape = options.shape; var holes = options.holes || []; var depth = options.depth || 0; var contours = []; var hole = []; for (var i = 0; i < shape.length; i++) { contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z); } var epsilon = 0.00000001; if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) { contours.pop(); } var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene); for (var hNb = 0; hNb < holes.length; hNb++) { hole = []; for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) { hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z)); } polygonTriangulation.addHole(hole); } var polygon = polygonTriangulation.build(options.updatable, depth); polygon._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs); vertexData.applyToMesh(polygon, options.updatable); return polygon; }; ; /** * Creates an extruded polygon mesh, with depth in the Y direction. * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements). * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors */ MeshBuilder.ExtrudePolygon = function (name, options, scene) { return MeshBuilder.CreatePolygon(name, 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. * * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube * 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 `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc. * 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 * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ MeshBuilder.CreateTube = function (name, options, scene) { var path = options.path; var instance = options.instance; var radius = 1.0; if (instance) { radius = instance.radius; } if (options.radius !== undefined) { radius = options.radius; } ; var tessellation = options.tessellation || 64 | 0; var radiusFunction = options.radiusFunction || null; var cap = options.cap || BABYLON.Mesh.NO_CAP; var invertUV = options.invertUV || false; var updatable = options.updatable; var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0; // tube geometry var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) { var tangents = path3D.getTangents(); var normals = path3D.getNormals(); var distances = path3D.getDistances(); var pi2 = Math.PI * 2; var step = pi2 / tessellation * arc; var returnRadius = function () { return radius; }; var radiusFunctionFinal = radiusFunction || returnRadius; var circlePath; var rad; var normal; var rotated; var rotationMatrix = BABYLON.Tmp.Matrix[0]; var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2; for (var i = 0; i < path.length; i++) { rad = radiusFunctionFinal(i, distances[i]); // current radius circlePath = Array(); // current circle array normal = normals[i]; // current normal for (var t = 0; t < tessellation; t++) { BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix); rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero(); BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated); rotated.scaleInPlace(rad).addInPlace(path[i]); circlePath[t] = rotated; } circlePaths[index] = circlePath; index++; } // cap var capPath = function (nbPoints, pathIndex) { var pointCap = Array(); for (var i = 0; i < nbPoints; i++) { pointCap.push(path[pathIndex]); } return pointCap; }; switch (cap) { case BABYLON.Mesh.NO_CAP: break; case BABYLON.Mesh.CAP_START: circlePaths[0] = capPath(tessellation, 0); circlePaths[1] = circlePaths[2].slice(0); break; case BABYLON.Mesh.CAP_END: circlePaths[index] = circlePaths[index - 1].slice(0); circlePaths[index + 1] = capPath(tessellation, path.length - 1); break; case BABYLON.Mesh.CAP_ALL: circlePaths[0] = capPath(tessellation, 0); circlePaths[1] = circlePaths[2].slice(0); circlePaths[index] = circlePaths[index - 1].slice(0); circlePaths[index + 1] = capPath(tessellation, path.length - 1); break; default: break; } return circlePaths; }; var path3D; var pathArray; if (instance) { var arc = options.arc || instance.arc; path3D = (instance.path3D).update(path); pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc); instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance }); instance.path3D = path3D; instance.pathArray = pathArray; instance.arc = arc; instance.radius = radius; return instance; } // tube creation path3D = new BABYLON.Path3D(path); var newPathArray = new Array(); cap = (cap < 0 || cap > 3) ? 0 : cap; pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc); var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene); tube.pathArray = pathArray; tube.path3D = path3D; tube.tessellation = tessellation; tube.cap = cap; tube.arc = options.arc; tube.radius = radius; return tube; }; /** * Creates a polyhedron mesh. * * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron * 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 * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). * 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. */ MeshBuilder.CreatePolyhedron = function (name, options, scene) { var polyhedron = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); polyhedron._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreatePolyhedron(options); vertexData.applyToMesh(polyhedron, options.updatable); return polyhedron; }; /** * Creates a decal mesh. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals * 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. */ MeshBuilder.CreateDecal = function (name, sourceMesh, options) { var indices = sourceMesh.getIndices(); var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind); var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind); var position = options.position || BABYLON.Vector3.Zero(); var normal = options.normal || BABYLON.Vector3.Up(); var size = options.size || BABYLON.Vector3.One(); var angle = options.angle || 0; // Getting correct rotation if (!normal) { var target = new BABYLON.Vector3(0, 0, 1); var camera = sourceMesh.getScene().activeCamera; var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix()); normal = camera.globalPosition.subtract(cameraWorldTarget); } var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2; var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z); var pitch = Math.atan2(normal.y, len); // Matrix var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z)); var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix); var meshWorldMatrix = sourceMesh.getWorldMatrix(); var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix); var vertexData = new BABYLON.VertexData(); vertexData.indices = []; vertexData.positions = []; vertexData.normals = []; vertexData.uvs = []; var currentVertexDataIndex = 0; var extractDecalVector3 = function (indexId) { var result = new BABYLON.PositionNormalVertex(); if (!indices || !positions || !normals) { return result; } var vertexId = indices[indexId]; result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]); // Send vector to decal local world result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix); // Get normal result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]); result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix); return result; }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js var clip = function (vertices, axis) { if (vertices.length === 0) { return vertices; } var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis)); var clipVertices = function (v0, v1) { var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize); return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor)); }; var result = new Array(); for (var index = 0; index < vertices.length; index += 3) { var v1Out; var v2Out; var v3Out; var total = 0; var nV1 = null; var nV2 = null; var nV3 = null; var nV4 = null; var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize; var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize; var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize; v1Out = d1 > 0; v2Out = d2 > 0; v3Out = d3 > 0; total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0); switch (total) { case 0: result.push(vertices[index]); result.push(vertices[index + 1]); result.push(vertices[index + 2]); break; case 1: if (v1Out) { nV1 = vertices[index + 1]; nV2 = vertices[index + 2]; nV3 = clipVertices(vertices[index], nV1); nV4 = clipVertices(vertices[index], nV2); } if (v2Out) { nV1 = vertices[index]; nV2 = vertices[index + 2]; nV3 = clipVertices(vertices[index + 1], nV1); nV4 = clipVertices(vertices[index + 1], nV2); result.push(nV3); result.push(nV2.clone()); result.push(nV1.clone()); result.push(nV2.clone()); result.push(nV3.clone()); result.push(nV4); break; } if (v3Out) { nV1 = vertices[index]; nV2 = vertices[index + 1]; nV3 = clipVertices(vertices[index + 2], nV1); nV4 = clipVertices(vertices[index + 2], nV2); } if (nV1 && nV2 && nV3 && nV4) { result.push(nV1.clone()); result.push(nV2.clone()); result.push(nV3); result.push(nV4); result.push(nV3.clone()); result.push(nV2.clone()); } break; case 2: if (!v1Out) { nV1 = vertices[index].clone(); nV2 = clipVertices(nV1, vertices[index + 1]); nV3 = clipVertices(nV1, vertices[index + 2]); result.push(nV1); result.push(nV2); result.push(nV3); } if (!v2Out) { nV1 = vertices[index + 1].clone(); nV2 = clipVertices(nV1, vertices[index + 2]); nV3 = clipVertices(nV1, vertices[index]); result.push(nV1); result.push(nV2); result.push(nV3); } if (!v3Out) { nV1 = vertices[index + 2].clone(); nV2 = clipVertices(nV1, vertices[index]); nV3 = clipVertices(nV1, vertices[index + 1]); result.push(nV1); result.push(nV2); result.push(nV3); } break; case 3: break; } } return result; }; for (var index = 0; index < indices.length; index += 3) { var faceVertices = new Array(); faceVertices.push(extractDecalVector3(index)); faceVertices.push(extractDecalVector3(index + 1)); faceVertices.push(extractDecalVector3(index + 2)); // Clip faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0)); faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0)); faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0)); faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0)); faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1)); faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1)); if (faceVertices.length === 0) { continue; } // Add UVs and get back to world for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) { var vertex = faceVertices[vIndex]; //TODO check for Int32Array | Uint32Array | Uint16Array vertexData.indices.push(currentVertexDataIndex); vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3); vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3); vertexData.uvs.push(0.5 + vertex.position.x / size.x); vertexData.uvs.push(0.5 + vertex.position.y / size.y); currentVertexDataIndex++; } } // Return mesh var decal = new BABYLON.Mesh(name, sourceMesh.getScene()); vertexData.applyToMesh(decal); decal.position = position.clone(); decal.rotation = new BABYLON.Vector3(pitch, yaw, angle); return decal; }; // Privates MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) { // extrusion geometry var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) { var tangents = path3D.getTangents(); var normals = path3D.getNormals(); var binormals = path3D.getBinormals(); var distances = path3D.getDistances(); var angle = 0; var returnScale = function () { return scale !== null ? scale : 1; }; var returnRotation = function () { return rotation !== null ? rotation : 0; }; var rotate = custom && rotateFunction ? rotateFunction : returnRotation; var scl = custom && scaleFunction ? scaleFunction : returnScale; var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2; var rotationMatrix = BABYLON.Tmp.Matrix[0]; for (var i = 0; i < curve.length; i++) { var shapePath = new Array(); var angleStep = rotate(i, distances[i]); var scaleRatio = scl(i, distances[i]); for (var p = 0; p < shape.length; p++) { BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix); var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y))); var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero(); BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated); rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]); shapePath[p] = rotated; } shapePaths[index] = shapePath; angle += angleStep; index++; } // cap var capPath = function (shapePath) { var pointCap = Array(); var barycenter = BABYLON.Vector3.Zero(); var i; for (i = 0; i < shapePath.length; i++) { barycenter.addInPlace(shapePath[i]); } barycenter.scaleInPlace(1.0 / shapePath.length); for (i = 0; i < shapePath.length; i++) { pointCap.push(barycenter); } return pointCap; }; switch (cap) { case BABYLON.Mesh.NO_CAP: break; case BABYLON.Mesh.CAP_START: shapePaths[0] = capPath(shapePaths[2]); shapePaths[1] = shapePaths[2]; break; case BABYLON.Mesh.CAP_END: shapePaths[index] = shapePaths[index - 1]; shapePaths[index + 1] = capPath(shapePaths[index - 1]); break; case BABYLON.Mesh.CAP_ALL: shapePaths[0] = capPath(shapePaths[2]); shapePaths[1] = shapePaths[2]; shapePaths[index] = shapePaths[index - 1]; shapePaths[index + 1] = capPath(shapePaths[index - 1]); break; default: break; } return shapePaths; }; var path3D; var pathArray; if (instance) { path3D = (instance.path3D).update(curve); pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom); instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance); return instance; } // extruded shape creation path3D = new BABYLON.Path3D(curve); var newShapePaths = new Array(); cap = (cap < 0 || cap > 3) ? 0 : cap; pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom); var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene); extrudedGeneric.pathArray = pathArray; extrudedGeneric.path3D = path3D; extrudedGeneric.cap = cap; return extrudedGeneric; }; return MeshBuilder; }()); BABYLON.MeshBuilder = MeshBuilder; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.meshBuilder.js.map var BABYLON; (function (BABYLON) { var AudioEngine = /** @class */ (function () { function AudioEngine() { this._audioContext = null; this._audioContextInitialized = false; this.canUseWebAudio = false; this.WarnedWebAudioUnsupported = false; this.unlocked = false; this.isMP3supported = false; this.isOGGsupported = false; if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') { window.AudioContext = window.AudioContext || window.webkitAudioContext; this.canUseWebAudio = true; } var audioElem = document.createElement('audio'); try { if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) { this.isMP3supported = true; } } catch (e) { // protect error during capability check. } try { if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) { this.isOGGsupported = true; } } catch (e) { // protect error during capability check. } if (/iPad|iPhone|iPod/.test(navigator.platform)) { this._unlockiOSaudio(); } else { this.unlocked = true; } } Object.defineProperty(AudioEngine.prototype, "audioContext", { get: function () { if (!this._audioContextInitialized) { this._initializeAudioContext(); } return this._audioContext; }, enumerable: true, configurable: true }); AudioEngine.prototype._unlockiOSaudio = function () { var _this = this; var unlockaudio = function () { if (!_this.audioContext) { return; } var buffer = _this.audioContext.createBuffer(1, 1, 22050); var source = _this.audioContext.createBufferSource(); source.buffer = buffer; source.connect(_this.audioContext.destination); source.start(0); setTimeout(function () { if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) { _this.unlocked = true; window.removeEventListener('touchend', unlockaudio, false); if (_this.onAudioUnlocked) { _this.onAudioUnlocked(); } } }, 0); }; window.addEventListener('touchend', unlockaudio, false); }; AudioEngine.prototype._initializeAudioContext = function () { try { if (this.canUseWebAudio) { this._audioContext = new AudioContext(); // create a global volume gain node this.masterGain = this._audioContext.createGain(); this.masterGain.gain.value = 1; this.masterGain.connect(this._audioContext.destination); this._audioContextInitialized = true; } } catch (e) { this.canUseWebAudio = false; BABYLON.Tools.Error("Web Audio: " + e.message); } }; AudioEngine.prototype.dispose = function () { if (this.canUseWebAudio && this._audioContextInitialized) { if (this._connectedAnalyser && this._audioContext) { this._connectedAnalyser.stopDebugCanvas(); this._connectedAnalyser.dispose(); this.masterGain.disconnect(); this.masterGain.connect(this._audioContext.destination); this._connectedAnalyser = null; } this.masterGain.gain.value = 1; } this.WarnedWebAudioUnsupported = false; }; AudioEngine.prototype.getGlobalVolume = function () { if (this.canUseWebAudio && this._audioContextInitialized) { return this.masterGain.gain.value; } else { return -1; } }; AudioEngine.prototype.setGlobalVolume = function (newVolume) { if (this.canUseWebAudio && this._audioContextInitialized) { this.masterGain.gain.value = newVolume; } }; AudioEngine.prototype.connectToAnalyser = function (analyser) { if (this._connectedAnalyser) { this._connectedAnalyser.stopDebugCanvas(); } if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) { this._connectedAnalyser = analyser; this.masterGain.disconnect(); this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination); } }; return AudioEngine; }()); BABYLON.AudioEngine = AudioEngine; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.audioEngine.js.map var BABYLON; (function (BABYLON) { var Sound = /** @class */ (function () { /** * Create a sound and attach it to a scene * @param name Name of your sound * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming */ function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) { if (readyToPlayCallback === void 0) { readyToPlayCallback = null; } var _this = this; this.autoplay = false; this.loop = false; this.useCustomAttenuation = false; this.spatialSound = false; this.refDistance = 1; this.rolloffFactor = 1; this.maxDistance = 100; this.distanceModel = "linear"; this._panningModel = "equalpower"; this._playbackRate = 1; this._streaming = false; this._startTime = 0; this._startOffset = 0; this._position = BABYLON.Vector3.Zero(); this._localDirection = new BABYLON.Vector3(1, 0, 0); this._volume = 1; this._isLoaded = false; this._isReadyToPlay = false; this.isPlaying = false; this.isPaused = false; this._isDirectional = false; // Used if you'd like to create a directional sound. // If not set, the sound will be omnidirectional this._coneInnerAngle = 360; this._coneOuterAngle = 360; this._coneOuterGain = 0; this._isOutputConnected = false; this._urlType = "Unknown"; this.name = name; this._scene = scene; this._readyToPlayCallback = readyToPlayCallback; // Default custom attenuation function is a linear attenuation this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) { if (currentDistance < maxDistance) { return currentVolume * (1 - currentDistance / maxDistance); } else { return 0; } }; if (options) { this.autoplay = options.autoplay || false; this.loop = options.loop || false; // if volume === 0, we need another way to check this option if (options.volume !== undefined) { this._volume = options.volume; } this.spatialSound = options.spatialSound || false; this.maxDistance = options.maxDistance || 100; this.useCustomAttenuation = options.useCustomAttenuation || false; this.rolloffFactor = options.rolloffFactor || 1; this.refDistance = options.refDistance || 1; this.distanceModel = options.distanceModel || "linear"; this._playbackRate = options.playbackRate || 1; this._streaming = options.streaming || false; } if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) { this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain(); this._soundGain.gain.value = this._volume; this._inputAudioNode = this._soundGain; this._ouputAudioNode = this._soundGain; if (this.spatialSound) { this._createSpatialParameters(); } this._scene.mainSoundTrack.AddSound(this); var validParameter = true; // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound if (urlOrArrayBuffer) { if (typeof (urlOrArrayBuffer) === "string") this._urlType = "String"; if (Array.isArray(urlOrArrayBuffer)) this._urlType = "Array"; if (urlOrArrayBuffer instanceof ArrayBuffer) this._urlType = "ArrayBuffer"; var urls = []; var codecSupportedFound = false; switch (this._urlType) { case "ArrayBuffer": if (urlOrArrayBuffer.byteLength > 0) { codecSupportedFound = true; this._soundLoaded(urlOrArrayBuffer); } break; case "String": urls.push(urlOrArrayBuffer); case "Array": if (urls.length === 0) urls = urlOrArrayBuffer; // If we found a supported format, we load it immediately and stop the loop for (var i = 0; i < urls.length; i++) { var url = urls[i]; if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) { codecSupportedFound = true; } if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) { codecSupportedFound = true; } if (url.indexOf(".wav", url.length - 4) !== -1) { codecSupportedFound = true; } if (url.indexOf("blob:") !== -1) { codecSupportedFound = true; } if (codecSupportedFound) { // Loading sound using XHR2 if (!this._streaming) { BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true); } else { this._htmlAudioElement = new Audio(url); this._htmlAudioElement.controls = false; this._htmlAudioElement.loop = this.loop; this._htmlAudioElement.crossOrigin = "anonymous"; this._htmlAudioElement.preload = "auto"; this._htmlAudioElement.addEventListener("canplaythrough", function () { _this._isReadyToPlay = true; if (_this.autoplay) { _this.play(); } if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }); document.body.appendChild(this._htmlAudioElement); } break; } } break; default: validParameter = false; break; } if (!validParameter) { BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound."); } else { if (!codecSupportedFound) { this._isReadyToPlay = true; // Simulating a ready to play event to avoid breaking code path if (this._readyToPlayCallback) { window.setTimeout(function () { if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }, 1000); } } } } } else { // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers this._scene.mainSoundTrack.AddSound(this); if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) { BABYLON.Tools.Error("Web Audio is not supported by your browser."); BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true; } // Simulating a ready to play event to avoid breaking code for non web audio browsers if (this._readyToPlayCallback) { window.setTimeout(function () { if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }, 1000); } } } Sound.prototype.dispose = function () { if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) { if (this.isPlaying) { this.stop(); } this._isReadyToPlay = false; if (this.soundTrackId === -1) { this._scene.mainSoundTrack.RemoveSound(this); } else { this._scene.soundTracks[this.soundTrackId].RemoveSound(this); } if (this._soundGain) { this._soundGain.disconnect(); this._soundGain = null; } if (this._soundPanner) { this._soundPanner.disconnect(); this._soundPanner = null; } if (this._soundSource) { this._soundSource.disconnect(); this._soundSource = null; } this._audioBuffer = null; if (this._htmlAudioElement) { this._htmlAudioElement.pause(); this._htmlAudioElement.src = ""; document.body.removeChild(this._htmlAudioElement); } if (this._connectedMesh && this._registerFunc) { this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc); this._connectedMesh = null; } } }; Sound.prototype.isReady = function () { return this._isReadyToPlay; }; Sound.prototype._soundLoaded = function (audioData) { var _this = this; this._isLoaded = true; if (!BABYLON.Engine.audioEngine.audioContext) { return; } BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) { _this._audioBuffer = buffer; _this._isReadyToPlay = true; if (_this.autoplay) { _this.play(); } if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); }); }; Sound.prototype.setAudioBuffer = function (audioBuffer) { if (BABYLON.Engine.audioEngine.canUseWebAudio) { this._audioBuffer = audioBuffer; this._isReadyToPlay = true; } }; Sound.prototype.updateOptions = function (options) { if (options) { this.loop = options.loop || this.loop; this.maxDistance = options.maxDistance || this.maxDistance; this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation; this.rolloffFactor = options.rolloffFactor || this.rolloffFactor; this.refDistance = options.refDistance || this.refDistance; this.distanceModel = options.distanceModel || this.distanceModel; this._playbackRate = options.playbackRate || this._playbackRate; this._updateSpatialParameters(); if (this.isPlaying) { if (this._streaming) { this._htmlAudioElement.playbackRate = this._playbackRate; } else { if (this._soundSource) { this._soundSource.playbackRate.value = this._playbackRate; } } } } }; Sound.prototype._createSpatialParameters = function () { if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) { if (this._scene.headphone) { this._panningModel = "HRTF"; } this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner(); this._updateSpatialParameters(); this._soundPanner.connect(this._ouputAudioNode); this._inputAudioNode = this._soundPanner; } }; Sound.prototype._updateSpatialParameters = function () { if (this.spatialSound && this._soundPanner) { if (this.useCustomAttenuation) { // Tricks to disable in a way embedded Web Audio attenuation this._soundPanner.distanceModel = "linear"; this._soundPanner.maxDistance = Number.MAX_VALUE; this._soundPanner.refDistance = 1; this._soundPanner.rolloffFactor = 1; this._soundPanner.panningModel = this._panningModel; } else { this._soundPanner.distanceModel = this.distanceModel; this._soundPanner.maxDistance = this.maxDistance; this._soundPanner.refDistance = this.refDistance; this._soundPanner.rolloffFactor = this.rolloffFactor; this._soundPanner.panningModel = this._panningModel; } } }; Sound.prototype.switchPanningModelToHRTF = function () { this._panningModel = "HRTF"; this._switchPanningModel(); }; Sound.prototype.switchPanningModelToEqualPower = function () { this._panningModel = "equalpower"; this._switchPanningModel(); }; Sound.prototype._switchPanningModel = function () { if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) { this._soundPanner.panningModel = this._panningModel; } }; Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) { if (BABYLON.Engine.audioEngine.canUseWebAudio) { if (this._isOutputConnected) { this._ouputAudioNode.disconnect(); } this._ouputAudioNode.connect(soundTrackAudioNode); this._isOutputConnected = true; } }; /** * Transform this sound into a directional source * @param coneInnerAngle Size of the inner cone in degree * @param coneOuterAngle Size of the outer cone in degree * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0) */ Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) { if (coneOuterAngle < coneInnerAngle) { BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."); return; } this._coneInnerAngle = coneInnerAngle; this._coneOuterAngle = coneOuterAngle; this._coneOuterGain = coneOuterGain; this._isDirectional = true; if (this.isPlaying && this.loop) { this.stop(); this.play(); } }; Sound.prototype.setPosition = function (newPosition) { this._position = newPosition; if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) { this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z); } }; Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) { this._localDirection = newLocalDirection; if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) { this._updateDirection(); } }; Sound.prototype._updateDirection = function () { if (!this._connectedMesh || !this._soundPanner) { return; } var mat = this._connectedMesh.getWorldMatrix(); var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat); direction.normalize(); this._soundPanner.setOrientation(direction.x, direction.y, direction.z); }; Sound.prototype.updateDistanceFromListener = function () { if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) { var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera); this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor); } }; Sound.prototype.setAttenuationFunction = function (callback) { this._customAttenuationFunction = callback; }; /** * Play the sound * @param time (optional) Start the sound after X seconds. Start immediately (0) by default. * @param offset (optional) Start the sound setting it at a specific time */ Sound.prototype.play = function (time, offset) { var _this = this; if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) { try { if (this._startOffset < 0) { time = -this._startOffset; this._startOffset = 0; } var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime; if (!this._soundSource || !this._streamingSource) { if (this.spatialSound && this._soundPanner) { this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z); if (this._isDirectional) { this._soundPanner.coneInnerAngle = this._coneInnerAngle; this._soundPanner.coneOuterAngle = this._coneOuterAngle; this._soundPanner.coneOuterGain = this._coneOuterGain; if (this._connectedMesh) { this._updateDirection(); } else { this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z); } } } } if (this._streaming) { if (!this._streamingSource) { this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement); this._htmlAudioElement.onended = function () { _this._onended(); }; this._htmlAudioElement.playbackRate = this._playbackRate; } this._streamingSource.disconnect(); this._streamingSource.connect(this._inputAudioNode); this._htmlAudioElement.play(); } else { this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource(); this._soundSource.buffer = this._audioBuffer; this._soundSource.connect(this._inputAudioNode); this._soundSource.loop = this.loop; this._soundSource.playbackRate.value = this._playbackRate; this._soundSource.onended = function () { _this._onended(); }; if (this._soundSource.buffer) { this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0); } } this._startTime = startTime; this.isPlaying = true; this.isPaused = false; } catch (ex) { BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message); } } }; Sound.prototype._onended = function () { this.isPlaying = false; if (this.onended) { this.onended(); } }; /** * Stop the sound * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default. */ Sound.prototype.stop = function (time) { if (this.isPlaying) { if (this._streaming) { this._htmlAudioElement.pause(); // Test needed for Firefox or it will generate an Invalid State Error if (this._htmlAudioElement.currentTime > 0) { this._htmlAudioElement.currentTime = 0; } } else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) { var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime; this._soundSource.stop(stopTime); this._soundSource.onended = function () { }; if (!this.isPaused) { this._startOffset = 0; } } this.isPlaying = false; } }; Sound.prototype.pause = function () { if (this.isPlaying) { this.isPaused = true; if (this._streaming) { this._htmlAudioElement.pause(); } else if (BABYLON.Engine.audioEngine.audioContext) { this.stop(0); this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime; } } }; Sound.prototype.setVolume = function (newVolume, time) { if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) { if (time && BABYLON.Engine.audioEngine.audioContext) { this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime); this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime); this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time); } else { this._soundGain.gain.value = newVolume; } } this._volume = newVolume; }; Sound.prototype.setPlaybackRate = function (newPlaybackRate) { this._playbackRate = newPlaybackRate; if (this.isPlaying) { if (this._streaming) { this._htmlAudioElement.playbackRate = this._playbackRate; } else if (this._soundSource) { this._soundSource.playbackRate.value = this._playbackRate; } } }; Sound.prototype.getVolume = function () { return this._volume; }; Sound.prototype.attachToMesh = function (meshToConnectTo) { var _this = this; if (this._connectedMesh && this._registerFunc) { this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc); this._registerFunc = null; } this._connectedMesh = meshToConnectTo; if (!this.spatialSound) { this.spatialSound = true; this._createSpatialParameters(); if (this.isPlaying && this.loop) { this.stop(); this.play(); } } this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh); this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); }; meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc); }; Sound.prototype.detachFromMesh = function () { if (this._connectedMesh && this._registerFunc) { this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc); this._registerFunc = null; this._connectedMesh = null; } }; Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) { var boundingInfo = connectedMesh.getBoundingInfo(); if (!boundingInfo) { return; } this.setPosition(boundingInfo.boundingSphere.centerWorld); if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) { this._updateDirection(); } }; Sound.prototype.clone = function () { var _this = this; if (!this._streaming) { var setBufferAndRun = function () { if (_this._isReadyToPlay) { clonedSound._audioBuffer = _this.getAudioBuffer(); clonedSound._isReadyToPlay = true; if (clonedSound.autoplay) { clonedSound.play(); } } else { window.setTimeout(setBufferAndRun, 300); } }; var currentOptions = { autoplay: this.autoplay, loop: this.loop, volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance, useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor, refDistance: this.refDistance, distanceModel: this.distanceModel }; var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions); if (this.useCustomAttenuation) { clonedSound.setAttenuationFunction(this._customAttenuationFunction); } clonedSound.setPosition(this._position); clonedSound.setPlaybackRate(this._playbackRate); setBufferAndRun(); return clonedSound; } else { return null; } }; Sound.prototype.getAudioBuffer = function () { return this._audioBuffer; }; Sound.prototype.serialize = function () { var serializationObject = { name: this.name, url: this.name, autoplay: this.autoplay, loop: this.loop, volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance, rolloffFactor: this.rolloffFactor, refDistance: this.refDistance, distanceModel: this.distanceModel, playbackRate: this._playbackRate, panningModel: this._panningModel, soundTrackId: this.soundTrackId }; if (this.spatialSound) { if (this._connectedMesh) serializationObject.connectedMeshId = this._connectedMesh.id; serializationObject.position = this._position.asArray(); serializationObject.refDistance = this.refDistance; serializationObject.distanceModel = this.distanceModel; serializationObject.isDirectional = this._isDirectional; serializationObject.localDirectionToMesh = this._localDirection.asArray(); serializationObject.coneInnerAngle = this._coneInnerAngle; serializationObject.coneOuterAngle = this._coneOuterAngle; serializationObject.coneOuterGain = this._coneOuterGain; } return serializationObject; }; Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) { var soundName = parsedSound.name; var soundUrl; if (parsedSound.url) { soundUrl = rootUrl + parsedSound.url; } else { soundUrl = rootUrl + soundName; } var options = { autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume, spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance, rolloffFactor: parsedSound.rolloffFactor, refDistance: parsedSound.refDistance, distanceModel: parsedSound.distanceModel, playbackRate: parsedSound.playbackRate }; var newSound; if (!sourceSound) { newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options); scene._addPendingData(newSound); } else { var setBufferAndRun = function () { if (sourceSound._isReadyToPlay) { newSound._audioBuffer = sourceSound.getAudioBuffer(); newSound._isReadyToPlay = true; if (newSound.autoplay) { newSound.play(); } } else { window.setTimeout(setBufferAndRun, 300); } }; newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options); setBufferAndRun(); } if (parsedSound.position) { var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position); newSound.setPosition(soundPosition); } if (parsedSound.isDirectional) { newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0); if (parsedSound.localDirectionToMesh) { var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh); newSound.setLocalDirectionToMesh(localDirectionToMesh); } } if (parsedSound.connectedMeshId) { var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId); if (connectedMesh) { newSound.attachToMesh(connectedMesh); } } return newSound; }; return Sound; }()); BABYLON.Sound = Sound; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.sound.js.map var BABYLON; (function (BABYLON) { var SoundTrack = /** @class */ (function () { function SoundTrack(scene, options) { this.id = -1; this._isMainTrack = false; this._isInitialized = false; this._scene = scene; this.soundCollection = new Array(); this._options = options; if (!this._isMainTrack) { this._scene.soundTracks.push(this); this.id = this._scene.soundTracks.length - 1; } } SoundTrack.prototype._initializeSoundTrackAudioGraph = function () { if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) { this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain(); this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain); if (this._options) { if (this._options.volume) { this._outputAudioNode.gain.value = this._options.volume; } if (this._options.mainTrack) { this._isMainTrack = this._options.mainTrack; } } this._isInitialized = true; } }; SoundTrack.prototype.dispose = function () { if (BABYLON.Engine.audioEngine.canUseWebAudio) { if (this._connectedAnalyser) { this._connectedAnalyser.stopDebugCanvas(); } while (this.soundCollection.length) { this.soundCollection[0].dispose(); } if (this._outputAudioNode) { this._outputAudioNode.disconnect(); } this._outputAudioNode = null; } }; SoundTrack.prototype.AddSound = function (sound) { if (!this._isInitialized) { this._initializeSoundTrackAudioGraph(); } if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) { sound.connectToSoundTrackAudioNode(this._outputAudioNode); } if (sound.soundTrackId) { if (sound.soundTrackId === -1) { this._scene.mainSoundTrack.RemoveSound(sound); } else { this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound); } } this.soundCollection.push(sound); sound.soundTrackId = this.id; }; SoundTrack.prototype.RemoveSound = function (sound) { var index = this.soundCollection.indexOf(sound); if (index !== -1) { this.soundCollection.splice(index, 1); } }; SoundTrack.prototype.setVolume = function (newVolume) { if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) { this._outputAudioNode.gain.value = newVolume; } }; SoundTrack.prototype.switchPanningModelToHRTF = function () { if (BABYLON.Engine.audioEngine.canUseWebAudio) { for (var i = 0; i < this.soundCollection.length; i++) { this.soundCollection[i].switchPanningModelToHRTF(); } } }; SoundTrack.prototype.switchPanningModelToEqualPower = function () { if (BABYLON.Engine.audioEngine.canUseWebAudio) { for (var i = 0; i < this.soundCollection.length; i++) { this.soundCollection[i].switchPanningModelToEqualPower(); } } }; SoundTrack.prototype.connectToAnalyser = function (analyser) { if (this._connectedAnalyser) { this._connectedAnalyser.stopDebugCanvas(); } this._connectedAnalyser = analyser; if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) { this._outputAudioNode.disconnect(); this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain); } }; return SoundTrack; }()); BABYLON.SoundTrack = SoundTrack; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.soundtrack.js.map var BABYLON; (function (BABYLON) { var Analyser = /** @class */ (function () { function Analyser(scene) { this.SMOOTHING = 0.75; this.FFT_SIZE = 512; this.BARGRAPHAMPLITUDE = 256; this.DEBUGCANVASPOS = { x: 20, y: 20 }; this.DEBUGCANVASSIZE = { width: 320, height: 200 }; this._scene = scene; this._audioEngine = BABYLON.Engine.audioEngine; if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) { this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser(); this._webAudioAnalyser.minDecibels = -140; this._webAudioAnalyser.maxDecibels = 0; this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount); this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount); this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount); } } Analyser.prototype.getFrequencyBinCount = function () { if (this._audioEngine.canUseWebAudio) { return this._webAudioAnalyser.frequencyBinCount; } else { return 0; } }; Analyser.prototype.getByteFrequencyData = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; this._webAudioAnalyser.fftSize = this.FFT_SIZE; this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs); } return this._byteFreqs; }; Analyser.prototype.getByteTimeDomainData = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; this._webAudioAnalyser.fftSize = this.FFT_SIZE; this._webAudioAnalyser.getByteTimeDomainData(this._byteTime); } return this._byteTime; }; Analyser.prototype.getFloatFrequencyData = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; this._webAudioAnalyser.fftSize = this.FFT_SIZE; this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs); } return this._floatFreqs; }; Analyser.prototype.drawDebugCanvas = function () { var _this = this; if (this._audioEngine.canUseWebAudio) { if (!this._debugCanvas) { this._debugCanvas = document.createElement("canvas"); this._debugCanvas.width = this.DEBUGCANVASSIZE.width; this._debugCanvas.height = this.DEBUGCANVASSIZE.height; this._debugCanvas.style.position = "absolute"; this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px"; this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px"; this._debugCanvasContext = this._debugCanvas.getContext("2d"); document.body.appendChild(this._debugCanvas); this._registerFunc = function () { _this.drawDebugCanvas(); }; this._scene.registerBeforeRender(this._registerFunc); } if (this._registerFunc && this._debugCanvasContext) { var workingArray = this.getByteFrequencyData(); this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)'; this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height); // Draw the frequency domain chart. for (var i = 0; i < this.getFrequencyBinCount(); i++) { var value = workingArray[i]; var percent = value / this.BARGRAPHAMPLITUDE; var height = this.DEBUGCANVASSIZE.height * percent; var offset = this.DEBUGCANVASSIZE.height - height - 1; var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount(); var hue = i / this.getFrequencyBinCount() * 360; this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)'; this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height); } } } }; Analyser.prototype.stopDebugCanvas = function () { if (this._debugCanvas) { if (this._registerFunc) { this._scene.unregisterBeforeRender(this._registerFunc); this._registerFunc = null; } document.body.removeChild(this._debugCanvas); this._debugCanvas = null; this._debugCanvasContext = null; } }; Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) { if (this._audioEngine.canUseWebAudio) { inputAudioNode.connect(this._webAudioAnalyser); this._webAudioAnalyser.connect(outputAudioNode); } }; Analyser.prototype.dispose = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.disconnect(); } }; return Analyser; }()); BABYLON.Analyser = Analyser; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.analyser.js.map var BABYLON; (function (BABYLON) { var CubeTexture = /** @class */ (function (_super) { __extends(CubeTexture, _super); function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) { if (extensions === void 0) { extensions = null; } if (noMipmap === void 0) { noMipmap = false; } if (files === void 0) { files = null; } if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; } if (prefiltered === void 0) { prefiltered = false; } if (forcedExtension === void 0) { forcedExtension = null; } var _this = _super.call(this, scene) || this; _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE; _this.name = rootUrl; _this.url = rootUrl; _this._noMipmap = noMipmap; _this.hasAlpha = false; _this._format = format; _this._prefiltered = prefiltered; _this.isCube = true; _this._textureMatrix = BABYLON.Matrix.Identity(); if (prefiltered) { _this.gammaSpace = false; } if (!rootUrl && !files) { return _this; } _this._texture = _this._getFromCache(rootUrl, noMipmap); if (!files) { if (!extensions) { extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"]; } files = []; for (var index = 0; index < extensions.length; index++) { files.push(rootUrl + extensions[index]); } _this._extensions = extensions; } _this._files = files; if (!_this._texture) { if (!scene.useDelayedTextureLoading) { if (prefiltered) { _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension); } else { _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension); } } else { _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED; } } else if (onLoad) { if (_this._texture.isReady) { BABYLON.Tools.SetImmediate(function () { return onLoad(); }); } else { _this._texture.onLoadedObservable.add(onLoad); } } return _this; } CubeTexture.CreateFromImages = function (files, scene, noMipmap) { return new CubeTexture("", scene, null, noMipmap, files); }; CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) { if (forcedExtension === void 0) { forcedExtension = null; } return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension); }; // Methods CubeTexture.prototype.delayLoad = function () { 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); if (!this._texture) { if (this._prefiltered) { this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format); } else { this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format); } } }; CubeTexture.prototype.getReflectionTextureMatrix = function () { return this._textureMatrix; }; CubeTexture.prototype.setReflectionTextureMatrix = function (value) { this._textureMatrix = value; }; CubeTexture.Parse = function (parsedTexture, scene, rootUrl) { var texture = BABYLON.SerializationHelper.Parse(function () { return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions); }, parsedTexture, scene); // 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; }; CubeTexture.prototype.clone = function () { var _this = this; return BABYLON.SerializationHelper.Clone(function () { var scene = _this.getScene(); if (!scene) { return _this; } return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files); }, this); }; return CubeTexture; }(BABYLON.BaseTexture)); BABYLON.CubeTexture = CubeTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.cubeTexture.js.map var BABYLON; (function (BABYLON) { var RenderTargetTexture = /** @class */ (function (_super) { __extends(RenderTargetTexture, _super); function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) { if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; } if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } if (isCube === void 0) { isCube = false; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } if (generateDepthBuffer === void 0) { generateDepthBuffer = true; } if (generateStencilBuffer === void 0) { generateStencilBuffer = false; } if (isMulti === void 0) { isMulti = false; } var _this = _super.call(this, null, scene, !generateMipMaps) || this; _this.isCube = isCube; /** * Use this list to define the list of mesh you want to render. */ _this.renderList = new Array(); _this.renderParticles = true; _this.renderSprites = false; _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE; _this.ignoreCameraViewport = false; // Events /** * An event triggered when the texture is unbind. * @type {BABYLON.Observable} */ _this.onBeforeBindObservable = new BABYLON.Observable(); /** * An event triggered when the texture is unbind. * @type {BABYLON.Observable} */ _this.onAfterUnbindObservable = new BABYLON.Observable(); /** * An event triggered before rendering the texture * @type {BABYLON.Observable} */ _this.onBeforeRenderObservable = new BABYLON.Observable(); /** * An event triggered after rendering the texture * @type {BABYLON.Observable} */ _this.onAfterRenderObservable = new BABYLON.Observable(); /** * An event triggered after the texture clear * @type {BABYLON.Observable} */ _this.onClearObservable = new BABYLON.Observable(); _this._currentRefreshId = -1; _this._refreshRate = 1; _this._samples = 1; scene = _this.getScene(); if (!scene) { return _this; } _this.name = name; _this.isRenderTarget = true; _this._size = size; _this._generateMipMaps = generateMipMaps ? true : false; _this._doNotChangeAspectRatio = doNotChangeAspectRatio; // Rendering groups _this._renderingManager = new BABYLON.RenderingManager(scene); if (isMulti) { return _this; } _this._renderTargetOptions = { generateMipMaps: generateMipMaps, type: type, samplingMode: samplingMode, generateDepthBuffer: generateDepthBuffer, generateStencilBuffer: generateStencilBuffer }; if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) { _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; } if (isCube) { _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions); _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE; _this._textureMatrix = BABYLON.Matrix.Identity(); } else { _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions); } return _this; } Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", { get: function () { return RenderTargetTexture._REFRESHRATE_RENDER_ONCE; }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", { get: function () { return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME; }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", { get: function () { return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES; }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", { set: function (callback) { if (this._onAfterUnbindObserver) { this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver); } this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", { set: function (callback) { if (this._onBeforeRenderObserver) { this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); } this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", { set: function (callback) { if (this._onAfterRenderObserver) { this.onAfterRenderObservable.remove(this._onAfterRenderObserver); } this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture.prototype, "onClear", { set: function (callback) { if (this._onClearObserver) { this.onClearObservable.remove(this._onClearObserver); } this._onClearObserver = this.onClearObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", { get: function () { return this._renderTargetOptions; }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture.prototype, "samples", { get: function () { return this._samples; }, set: function (value) { if (this._samples === value) { return; } var scene = this.getScene(); if (!scene) { return; } this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value); }, enumerable: true, configurable: true }); RenderTargetTexture.prototype.resetRefreshCounter = function () { this._currentRefreshId = -1; }; Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", { get: function () { return this._refreshRate; }, // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on... set: function (value) { this._refreshRate = value; this.resetRefreshCounter(); }, enumerable: true, configurable: true }); RenderTargetTexture.prototype.addPostProcess = function (postProcess) { if (!this._postProcessManager) { var scene = this.getScene(); if (!scene) { return; } this._postProcessManager = new BABYLON.PostProcessManager(scene); this._postProcesses = new Array(); } this._postProcesses.push(postProcess); this._postProcesses[0].autoClear = false; }; RenderTargetTexture.prototype.clearPostProcesses = function (dispose) { if (!this._postProcesses) { return; } if (dispose) { for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) { var postProcess = _a[_i]; postProcess.dispose(); } } this._postProcesses = []; }; RenderTargetTexture.prototype.removePostProcess = function (postProcess) { if (!this._postProcesses) { return; } var index = this._postProcesses.indexOf(postProcess); if (index === -1) { return; } this._postProcesses.splice(index, 1); if (this._postProcesses.length > 0) { this._postProcesses[0].autoClear = false; } }; RenderTargetTexture.prototype._shouldRender = function () { if (this._currentRefreshId === -1) { this._currentRefreshId = 1; return true; } if (this.refreshRate === this._currentRefreshId) { this._currentRefreshId = 1; return true; } this._currentRefreshId++; return false; }; RenderTargetTexture.prototype.getRenderSize = function () { return this._size; }; Object.defineProperty(RenderTargetTexture.prototype, "canRescale", { get: function () { return true; }, enumerable: true, configurable: true }); RenderTargetTexture.prototype.scale = function (ratio) { var newSize = this._size * ratio; this.resize(newSize); }; RenderTargetTexture.prototype.getReflectionTextureMatrix = function () { if (this.isCube) { return this._textureMatrix; } return _super.prototype.getReflectionTextureMatrix.call(this); }; RenderTargetTexture.prototype.resize = function (size) { this.releaseInternalTexture(); var scene = this.getScene(); if (!scene) { return; } if (this.isCube) { this._texture = scene.getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions); } else { this._texture = scene.getEngine().createRenderTargetTexture(size, this._renderTargetOptions); } this._size = size; }; RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) { if (useCameraPostProcess === void 0) { useCameraPostProcess = false; } if (dumpForDebug === void 0) { dumpForDebug = false; } var scene = this.getScene(); if (!scene) { return; } var engine = scene.getEngine(); if (this.useCameraPostProcesses !== undefined) { useCameraPostProcess = this.useCameraPostProcesses; } if (this._waitingRenderList) { this.renderList = []; for (var index = 0; index < this._waitingRenderList.length; index++) { var id = this._waitingRenderList[index]; var mesh_1 = scene.getMeshByID(id); if (mesh_1) { this.renderList.push(mesh_1); } } delete this._waitingRenderList; } // Is predicate defined? if (this.renderListPredicate) { if (this.renderList) { this.renderList.splice(0); // Clear previous renderList } else { this.renderList = []; } var scene = this.getScene(); if (!scene) { return; } var sceneMeshes = scene.meshes; for (var index = 0; index < sceneMeshes.length; index++) { var mesh = sceneMeshes[index]; if (this.renderListPredicate(mesh)) { this.renderList.push(mesh); } } } this.onBeforeBindObservable.notifyObservers(this); // Set custom projection. // Needs to be before binding to prevent changing the aspect ratio. var camera; if (this.activeCamera) { camera = this.activeCamera; engine.setViewport(this.activeCamera.viewport, this._size, this._size); if (this.activeCamera !== scene.activeCamera) { scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true)); } } else { camera = scene.activeCamera; if (camera) { engine.setViewport(camera.viewport, this._size, this._size); } } // Prepare renderingManager this._renderingManager.reset(); var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data; var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length; var sceneRenderId = scene.getRenderId(); for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) { var mesh = currentRenderList[meshIndex]; if (mesh) { if (!mesh.isReady()) { // Reset _currentRefreshId this.resetRefreshCounter(); continue; } mesh._preActivateForIntermediateRendering(sceneRenderId); var isMasked = void 0; if (!this.renderList && camera) { isMasked = ((mesh.layerMask & camera.layerMask) === 0); } else { isMasked = false; } if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) { mesh._activate(sceneRenderId); for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { var subMesh = mesh.subMeshes[subIndex]; scene._activeIndices.addCount(subMesh.indexCount, false); this._renderingManager.dispatch(subMesh); } } } } for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) { var particleSystem = scene.particleSystems[particleIndex]; var emitter = particleSystem.emitter; if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) { continue; } if (currentRenderList.indexOf(emitter) >= 0) { this._renderingManager.dispatchParticles(particleSystem); } } if (this.isCube) { for (var face = 0; face < 6; face++) { this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug); scene.incrementRenderId(); scene.resetCachedMaterial(); } } else { this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug); } this.onAfterUnbindObservable.notifyObservers(this); if (scene.activeCamera) { if (this.activeCamera && this.activeCamera !== scene.activeCamera) { scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true)); } engine.setViewport(scene.activeCamera.viewport); } scene.resetCachedMaterial(); }; RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) { var _this = this; var scene = this.getScene(); if (!scene) { return; } var engine = scene.getEngine(); if (!this._texture) { return; } // Bind if (this._postProcessManager) { this._postProcessManager._prepareFrame(this._texture, this._postProcesses); } else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) { if (this._texture) { engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport); } } this.onBeforeRenderObservable.notifyObservers(faceIndex); // Clear if (this.onClearObservable.hasObservers()) { this.onClearObservable.notifyObservers(engine); } else { engine.clear(this.clearColor || scene.clearColor, true, true, true); } if (!this._doNotChangeAspectRatio) { scene.updateTransformMatrix(true); } // Render this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites); if (this._postProcessManager) { this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport); } else if (useCameraPostProcess) { scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex); } if (!this._doNotChangeAspectRatio) { scene.updateTransformMatrix(true); } // Dump ? if (dumpForDebug) { BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine); } // Unbind if (!this.isCube || faceIndex === 5) { if (this.isCube) { if (faceIndex === 5) { engine.generateMipMapsForCubemap(this._texture); } } engine.unBindFramebuffer(this._texture, this.isCube, function () { _this.onAfterRenderObservable.notifyObservers(faceIndex); }); } else { this.onAfterRenderObservable.notifyObservers(faceIndex); } }; /** * 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. */ RenderTargetTexture.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. */ RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) { this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil); }; RenderTargetTexture.prototype.clone = function () { var textureSize = this.getSize(); var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer); // Base texture newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; // RenderTarget Texture newTexture.coordinatesMode = this.coordinatesMode; if (this.renderList) { newTexture.renderList = this.renderList.slice(0); } return newTexture; }; RenderTargetTexture.prototype.serialize = function () { if (!this.name) { return null; } var serializationObject = _super.prototype.serialize.call(this); serializationObject.renderTargetSize = this.getRenderSize(); serializationObject.renderList = []; if (this.renderList) { for (var index = 0; index < this.renderList.length; index++) { serializationObject.renderList.push(this.renderList[index].id); } } return serializationObject; }; // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore RenderTargetTexture.prototype.disposeFramebufferObjects = function () { var objBuffer = this.getInternalTexture(); var scene = this.getScene(); if (objBuffer && scene) { scene.getEngine()._releaseFramebufferObjects(objBuffer); } }; RenderTargetTexture.prototype.dispose = function () { if (this._postProcessManager) { this._postProcessManager.dispose(); this._postProcessManager = null; } this.clearPostProcesses(true); this.renderList = null; // Remove from custom render targets var scene = this.getScene(); if (!scene) { return; } var index = scene.customRenderTargets.indexOf(this); if (index >= 0) { scene.customRenderTargets.splice(index, 1); } for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) { var camera = _a[_i]; index = camera.customRenderTargets.indexOf(this); if (index >= 0) { camera.customRenderTargets.splice(index, 1); } } _super.prototype.dispose.call(this); }; RenderTargetTexture.prototype._rebuild = function () { if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) { this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE; } if (this._postProcessManager) { this._postProcessManager._rebuild(); } }; RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0; RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1; RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2; return RenderTargetTexture; }(BABYLON.Texture)); BABYLON.RenderTargetTexture = RenderTargetTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.renderTargetTexture.js.map var BABYLON; (function (BABYLON) { ; var MultiRenderTarget = /** @class */ (function (_super) { __extends(MultiRenderTarget, _super); function MultiRenderTarget(name, size, count, scene, options) { var _this = this; options = options || {}; var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false; var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false; var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio; _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this; _this._engine = scene.getEngine(); if (!_this.isSupported) { _this.dispose(); return; } var types = []; var samplingModes = []; for (var i = 0; i < count; i++) { if (options.types && options.types[i]) { types.push(options.types[i]); } else { types.push(BABYLON.Engine.TEXTURETYPE_FLOAT); } if (options.samplingModes && options.samplingModes[i]) { samplingModes.push(options.samplingModes[i]); } else { samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE); } } var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer; _this._count = count; _this._size = size; _this._multiRenderTargetOptions = { samplingModes: samplingModes, generateMipMaps: generateMipMaps, generateDepthBuffer: generateDepthBuffer, generateStencilBuffer: generateStencilBuffer, generateDepthTexture: generateDepthTexture, types: types, textureCount: count }; _this._createInternalTextures(); _this._createTextures(); return _this; } Object.defineProperty(MultiRenderTarget.prototype, "isSupported", { get: function () { return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension; }, enumerable: true, configurable: true }); Object.defineProperty(MultiRenderTarget.prototype, "textures", { get: function () { return this._textures; }, enumerable: true, configurable: true }); Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", { get: function () { return this._textures[this._textures.length - 1]; }, enumerable: true, configurable: true }); Object.defineProperty(MultiRenderTarget.prototype, "wrapU", { set: function (wrap) { if (this._textures) { for (var i = 0; i < this._textures.length; i++) { this._textures[i].wrapU = wrap; } } }, enumerable: true, configurable: true }); Object.defineProperty(MultiRenderTarget.prototype, "wrapV", { set: function (wrap) { if (this._textures) { for (var i = 0; i < this._textures.length; i++) { this._textures[i].wrapV = wrap; } } }, enumerable: true, configurable: true }); MultiRenderTarget.prototype._rebuild = function () { this.releaseInternalTextures(); this._createInternalTextures(); for (var i = 0; i < this._internalTextures.length; i++) { var texture = this._textures[i]; texture._texture = this._internalTextures[i]; } // Keeps references to frame buffer and stencil/depth buffer this._texture = this._internalTextures[0]; }; MultiRenderTarget.prototype._createInternalTextures = function () { this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions); }; MultiRenderTarget.prototype._createTextures = function () { this._textures = []; for (var i = 0; i < this._internalTextures.length; i++) { var texture = new BABYLON.Texture(null, this.getScene()); texture._texture = this._internalTextures[i]; this._textures.push(texture); } // Keeps references to frame buffer and stencil/depth buffer this._texture = this._internalTextures[0]; }; Object.defineProperty(MultiRenderTarget.prototype, "samples", { get: function () { return this._samples; }, set: function (value) { if (this._samples === value) { return; } for (var i = 0; i < this._internalTextures.length; i++) { this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value); } }, enumerable: true, configurable: true }); MultiRenderTarget.prototype.resize = function (size) { this.releaseInternalTextures(); this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions); this._createInternalTextures(); }; MultiRenderTarget.prototype.dispose = function () { this.releaseInternalTextures(); _super.prototype.dispose.call(this); }; MultiRenderTarget.prototype.releaseInternalTextures = function () { if (!this._internalTextures) { return; } for (var i = this._internalTextures.length - 1; i >= 0; i--) { if (this._internalTextures[i] !== undefined) { this._internalTextures[i].dispose(); this._internalTextures.splice(i, 1); } } }; return MultiRenderTarget; }(BABYLON.RenderTargetTexture)); BABYLON.MultiRenderTarget = MultiRenderTarget; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.multiRenderTarget.js.map /// var BABYLON; (function (BABYLON) { var MirrorTexture = /** @class */ (function (_super) { __extends(MirrorTexture, _super); function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) { if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; } if (generateDepthBuffer === void 0) { generateDepthBuffer = true; } var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this; _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1); _this._transformMatrix = BABYLON.Matrix.Zero(); _this._mirrorMatrix = BABYLON.Matrix.Zero(); _this._blurKernelX = 0; _this._blurKernelY = 0; _this._blurRatio = 1.0; _this.ignoreCameraViewport = true; _this.onBeforeRenderObservable.add(function () { BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix); _this._savedViewMatrix = scene.getViewMatrix(); _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix); scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix()); scene.clipPlane = _this.mirrorPlane; scene.getEngine().cullBackFaces = false; scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix); }); _this.onAfterRenderObservable.add(function () { scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix()); scene.getEngine().cullBackFaces = true; scene._mirroredCameraPosition = null; delete scene.clipPlane; }); return _this; } Object.defineProperty(MirrorTexture.prototype, "blurRatio", { get: function () { return this._blurRatio; }, set: function (value) { if (this._blurRatio === value) { return; } this._blurRatio = value; this._preparePostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(MirrorTexture.prototype, "blurKernel", { set: function (value) { this.blurKernelX = value; this.blurKernelY = value; }, enumerable: true, configurable: true }); Object.defineProperty(MirrorTexture.prototype, "blurKernelX", { get: function () { return this._blurKernelX; }, set: function (value) { if (this._blurKernelX === value) { return; } this._blurKernelX = value; this._preparePostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(MirrorTexture.prototype, "blurKernelY", { get: function () { return this._blurKernelY; }, set: function (value) { if (this._blurKernelY === value) { return; } this._blurKernelY = value; this._preparePostProcesses(); }, enumerable: true, configurable: true }); MirrorTexture.prototype._preparePostProcesses = function () { this.clearPostProcesses(true); if (this._blurKernelX && this._blurKernelY) { var engine = this.getScene().getEngine(); var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT; this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType); this._blurX.autoClear = false; if (this._blurRatio === 1 && this.samples < 2 && this._texture) { this._blurX.outputTexture = this._texture; } else { this._blurX.alwaysForcePOT = true; } this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType); this._blurY.autoClear = false; this._blurY.alwaysForcePOT = this._blurRatio !== 1; this.addPostProcess(this._blurX); this.addPostProcess(this._blurY); } }; MirrorTexture.prototype.clone = function () { var scene = this.getScene(); if (!scene) { return this; } var textureSize = this.getSize(); var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer); // Base texture newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; // Mirror Texture newTexture.mirrorPlane = this.mirrorPlane.clone(); if (this.renderList) { newTexture.renderList = this.renderList.slice(0); } return newTexture; }; MirrorTexture.prototype.serialize = function () { if (!this.name) { return null; } var serializationObject = _super.prototype.serialize.call(this); serializationObject.mirrorPlane = this.mirrorPlane.asArray(); return serializationObject; }; return MirrorTexture; }(BABYLON.RenderTargetTexture)); BABYLON.MirrorTexture = MirrorTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.mirrorTexture.js.map /// var BABYLON; (function (BABYLON) { /** * Creates a refraction texture used by refraction channel of the standard material. * @param name the texture name * @param size size of the underlying texture * @param scene root scene */ var RefractionTexture = /** @class */ (function (_super) { __extends(RefractionTexture, _super); function RefractionTexture(name, size, scene, generateMipMaps) { var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this; _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1); _this.depth = 2.0; _this.onBeforeRenderObservable.add(function () { scene.clipPlane = _this.refractionPlane; }); _this.onAfterRenderObservable.add(function () { delete scene.clipPlane; }); return _this; } RefractionTexture.prototype.clone = function () { var scene = this.getScene(); if (!scene) { return this; } var textureSize = this.getSize(); var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps); // Base texture newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; // Refraction Texture newTexture.refractionPlane = this.refractionPlane.clone(); if (this.renderList) { newTexture.renderList = this.renderList.slice(0); } newTexture.depth = this.depth; return newTexture; }; RefractionTexture.prototype.serialize = function () { if (!this.name) { return null; } var serializationObject = _super.prototype.serialize.call(this); serializationObject.mirrorPlane = this.refractionPlane.asArray(); serializationObject.depth = this.depth; return serializationObject; }; return RefractionTexture; }(BABYLON.RenderTargetTexture)); BABYLON.RefractionTexture = RefractionTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.refractionTexture.js.map /// var BABYLON; (function (BABYLON) { var DynamicTexture = /** @class */ (function (_super) { __extends(DynamicTexture, _super); function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) { if (scene === void 0) { scene = null; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; } var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this; _this.name = name; _this._engine = _this.getScene().getEngine(); _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; _this._generateMipMaps = generateMipMaps; if (options.getContext) { _this._canvas = options; _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode); } else { _this._canvas = document.createElement("canvas"); if (options.width) { _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode); } else { _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode); } } var textureSize = _this.getSize(); _this._canvas.width = textureSize.width; _this._canvas.height = textureSize.height; _this._context = _this._canvas.getContext("2d"); return _this; } Object.defineProperty(DynamicTexture.prototype, "canRescale", { get: function () { return true; }, enumerable: true, configurable: true }); DynamicTexture.prototype._recreate = function (textureSize) { this._canvas.width = textureSize.width; this._canvas.height = textureSize.height; this.releaseInternalTexture(); this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode); }; DynamicTexture.prototype.scale = function (ratio) { var textureSize = this.getSize(); textureSize.width *= ratio; textureSize.height *= ratio; this._recreate(textureSize); }; DynamicTexture.prototype.scaleTo = function (width, height) { var textureSize = this.getSize(); textureSize.width = width; textureSize.height = height; this._recreate(textureSize); }; DynamicTexture.prototype.getContext = function () { return this._context; }; DynamicTexture.prototype.clear = function () { var size = this.getSize(); this._context.fillRect(0, 0, size.width, size.height); }; DynamicTexture.prototype.update = function (invertY) { this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined); }; DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) { if (update === void 0) { update = true; } var size = this.getSize(); if (clearColor) { this._context.fillStyle = clearColor; this._context.fillRect(0, 0, size.width, size.height); } this._context.font = font; if (x === null || x === undefined) { var textSize = this._context.measureText(text); x = (size.width - textSize.width) / 2; } if (y === null || y === undefined) { var fontSize = parseInt((font.replace(/\D/g, ''))); ; y = (size.height / 2) + (fontSize / 3.65); } this._context.fillStyle = color; this._context.fillText(text, x, y); if (update) { this.update(invertY); } }; DynamicTexture.prototype.clone = function () { var scene = this.getScene(); if (!scene) { return this; } var textureSize = this.getSize(); var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps); // Base texture newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; // Dynamic Texture newTexture.wrapU = this.wrapU; newTexture.wrapV = this.wrapV; return newTexture; }; DynamicTexture.prototype._rebuild = function () { this.update(); }; return DynamicTexture; }(BABYLON.Texture)); BABYLON.DynamicTexture = DynamicTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.dynamicTexture.js.map var BABYLON; (function (BABYLON) { var VideoTexture = /** @class */ (function (_super) { __extends(VideoTexture, _super); /** * Creates a video texture. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element. * @param {BABYLON.Scene} scene is obviously the current scene. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated). * @param {boolean} invertY is false by default but can be used to invert video on Y axis * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default */ function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) { if (generateMipMaps === void 0) { generateMipMaps = false; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this; _this._autoLaunch = true; var urls = null; _this.name = name; if (urlsOrVideo instanceof HTMLVideoElement) { _this.video = urlsOrVideo; } else { urls = urlsOrVideo; _this.video = document.createElement("video"); _this.video.autoplay = false; _this.video.loop = true; } _this._engine = _this.getScene().getEngine(); _this._generateMipMaps = generateMipMaps; _this._samplingMode = samplingMode; if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) { _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE; _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE; } else { _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; _this._generateMipMaps = false; } if (urls) { _this.video.addEventListener("canplay", function () { _this._createTexture(); }); urls.forEach(function (url) { var source = document.createElement("source"); source.src = url; _this.video.appendChild(source); }); } else { _this._createTexture(); } _this._lastUpdate = BABYLON.Tools.Now; return _this; } VideoTexture.prototype.__setTextureReady = function () { if (this._texture) { this._texture.isReady = true; } }; VideoTexture.prototype._createTexture = function () { this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode); if (this._autoLaunch) { this._autoLaunch = false; this.video.play(); } this._setTextureReady = this.__setTextureReady.bind(this); this.video.addEventListener("playing", this._setTextureReady); }; VideoTexture.prototype._rebuild = function () { this.update(); }; VideoTexture.prototype.update = function () { var now = BABYLON.Tools.Now; if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) { return false; } this._lastUpdate = now; this._engine.updateVideoTexture(this._texture, this.video, this._invertY); return true; }; VideoTexture.prototype.dispose = function () { _super.prototype.dispose.call(this); this.video.removeEventListener("playing", this._setTextureReady); }; VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) { var video = document.createElement("video"); var constraintsDeviceId; if (constraints && constraints.deviceId) { constraintsDeviceId = { exact: constraints.deviceId }; } navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; if (navigator.getUserMedia) { navigator.getUserMedia({ video: { deviceId: constraintsDeviceId, width: { min: (constraints && constraints.minWidth) || 256, max: (constraints && constraints.maxWidth) || 640 }, height: { min: (constraints && constraints.minHeight) || 256, max: (constraints && constraints.maxHeight) || 480 } } }, function (stream) { if (video.mozSrcObject !== undefined) { video.mozSrcObject = stream; } else { video.src = (window.URL && window.URL.createObjectURL(stream)) || stream; } video.play(); if (onReady) { onReady(new BABYLON.VideoTexture("video", video, scene, true, true)); } }, function (e) { BABYLON.Tools.Error(e.name); }); } }; return VideoTexture; }(BABYLON.Texture)); BABYLON.VideoTexture = VideoTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.videoTexture.js.map var BABYLON; (function (BABYLON) { var RawTexture = /** @class */ (function (_super) { __extends(RawTexture, _super); function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this; _this.format = format; _this._engine = scene.getEngine(); _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode); _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; return _this; } RawTexture.prototype.update = function (data) { this._engine.updateRawTexture(this._texture, data, this.format, this._invertY); }; // Statics RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode); }; RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode); }; RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode); }; RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode); }; RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode); }; return RawTexture; }(BABYLON.Texture)); BABYLON.RawTexture = RawTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.rawTexture.js.map var BABYLON; (function (BABYLON) { var PostProcess = /** @class */ (function () { function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; } if (defines === void 0) { defines = null; } if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } if (vertexUrl === void 0) { vertexUrl = "postprocess"; } if (blockCompilation === void 0) { blockCompilation = false; } this.name = name; this.width = -1; this.height = -1; this.autoClear = true; this.alphaMode = BABYLON.Engine.ALPHA_DISABLE; /* Enable Pixel Perfect mode where texture is not scaled to be power of 2. Can only be used on a single postprocess or on the last one of a chain. */ this.enablePixelPerfectMode = false; this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR; this.alwaysForcePOT = false; this.samples = 1; this.adaptScaleToCurrentViewport = false; this._reusable = false; this._textures = new BABYLON.SmartArray(2); this._currentRenderTextureInd = 0; this._scaleRatio = new BABYLON.Vector2(1, 1); this._texelSize = BABYLON.Vector2.Zero(); // Events /** * An event triggered when the postprocess is activated. * @type {BABYLON.Observable} */ this.onActivateObservable = new BABYLON.Observable(); /** * An event triggered when the postprocess changes its size. * @type {BABYLON.Observable} */ this.onSizeChangedObservable = new BABYLON.Observable(); /** * An event triggered when the postprocess applies its effect. * @type {BABYLON.Observable} */ this.onApplyObservable = new BABYLON.Observable(); /** * An event triggered before rendering the postprocess * @type {BABYLON.Observable} */ this.onBeforeRenderObservable = new BABYLON.Observable(); /** * An event triggered after rendering the postprocess * @type {BABYLON.Observable} */ this.onAfterRenderObservable = new BABYLON.Observable(); if (camera != null) { this._camera = camera; this._scene = camera.getScene(); camera.attachPostProcess(this); this._engine = this._scene.getEngine(); this._scene.postProcesses.push(this); } else if (engine) { this._engine = engine; this._engine.postProcesses.push(this); } this._options = options; this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE; this._reusable = reusable || false; this._textureType = textureType; this._samplers = samplers || []; this._samplers.push("textureSampler"); this._fragmentUrl = fragmentUrl; this._vertexUrl = vertexUrl; this._parameters = parameters || []; this._parameters.push("scale"); this._indexParameters = indexParameters; if (!blockCompilation) { this.updateEffect(defines); } } Object.defineProperty(PostProcess.prototype, "onActivate", { set: function (callback) { if (this._onActivateObserver) { this.onActivateObservable.remove(this._onActivateObserver); } if (callback) { this._onActivateObserver = this.onActivateObservable.add(callback); } }, enumerable: true, configurable: true }); Object.defineProperty(PostProcess.prototype, "onSizeChanged", { set: function (callback) { if (this._onSizeChangedObserver) { this.onSizeChangedObservable.remove(this._onSizeChangedObserver); } this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(PostProcess.prototype, "onApply", { set: function (callback) { if (this._onApplyObserver) { this.onApplyObservable.remove(this._onApplyObserver); } this._onApplyObserver = this.onApplyObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(PostProcess.prototype, "onBeforeRender", { set: function (callback) { if (this._onBeforeRenderObserver) { this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); } this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(PostProcess.prototype, "onAfterRender", { set: function (callback) { if (this._onAfterRenderObserver) { this.onAfterRenderObservable.remove(this._onAfterRenderObserver); } this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(PostProcess.prototype, "outputTexture", { get: function () { return this._textures.data[this._currentRenderTextureInd]; }, set: function (value) { this._forcedOutputTexture = value; }, enumerable: true, configurable: true }); PostProcess.prototype.getCamera = function () { return this._camera; }; Object.defineProperty(PostProcess.prototype, "texelSize", { get: function () { if (this._shareOutputWithPostProcess) { return this._shareOutputWithPostProcess.texelSize; } if (this._forcedOutputTexture) { this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height); } return this._texelSize; }, enumerable: true, configurable: true }); PostProcess.prototype.getEngine = function () { return this._engine; }; PostProcess.prototype.getEffect = function () { return this._effect; }; PostProcess.prototype.shareOutputWith = function (postProcess) { this._disposeTextures(); this._shareOutputWithPostProcess = postProcess; return this; }; PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) { if (defines === void 0) { defines = null; } if (uniforms === void 0) { uniforms = null; } if (samplers === void 0) { samplers = null; } this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== null ? defines : "", undefined, onCompiled, onError, indexParameters || this._indexParameters); }; PostProcess.prototype.isReusable = function () { return this._reusable; }; /** invalidate frameBuffer to hint the postprocess to create a depth buffer */ PostProcess.prototype.markTextureDirty = function () { this.width = -1; }; PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) { var _this = this; if (sourceTexture === void 0) { sourceTexture = null; } camera = camera || this._camera; var scene = camera.getScene(); var engine = scene.getEngine(); var maxSize = engine.getCaps().maxTextureSize; var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0; var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0; var desiredWidth = (this._options.width || requiredWidth); var desiredHeight = this._options.height || requiredHeight; if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) { if (this.adaptScaleToCurrentViewport) { var currentViewport = engine.currentViewport; if (currentViewport) { desiredWidth *= currentViewport.width; desiredHeight *= currentViewport.height; } } if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) { if (!this._options.width) { desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth; } if (!this._options.height) { desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight; } } if (this.width !== desiredWidth || this.height !== desiredHeight) { if (this._textures.length > 0) { for (var i = 0; i < this._textures.length; i++) { this._engine._releaseTexture(this._textures.data[i]); } this._textures.reset(); } this.width = desiredWidth; this.height = desiredHeight; var textureSize = { width: this.width, height: this.height }; var textureOptions = { generateMipMaps: false, generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0, generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable, samplingMode: this.renderTargetSamplingMode, type: this._textureType }; this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions)); if (this._reusable) { this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions)); } this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height); this.onSizeChangedObservable.notifyObservers(this); } this._textures.forEach(function (texture) { if (texture.samples !== _this.samples) { _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples); } }); } var target; if (this._shareOutputWithPostProcess) { target = this._shareOutputWithPostProcess.outputTexture; } else if (this._forcedOutputTexture) { target = this._forcedOutputTexture; this.width = this._forcedOutputTexture.width; this.height = this._forcedOutputTexture.height; } else { target = this.outputTexture; } if (this.enablePixelPerfectMode) { this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight); this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true); } else { this._scaleRatio.copyFromFloats(1, 1); this._engine.bindFramebuffer(target, 0, undefined, undefined, true); } this.onActivateObservable.notifyObservers(camera); // Clear if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) { this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true); } if (this._reusable) { this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2; } }; Object.defineProperty(PostProcess.prototype, "isSupported", { get: function () { return this._effect.isSupported; }, enumerable: true, configurable: true }); Object.defineProperty(PostProcess.prototype, "aspectRatio", { get: function () { if (this._shareOutputWithPostProcess) { return this._shareOutputWithPostProcess.aspectRatio; } if (this._forcedOutputTexture) { return this._forcedOutputTexture.width / this._forcedOutputTexture.height; } return this.width / this.height; }, enumerable: true, configurable: true }); PostProcess.prototype.apply = function () { // Check if (!this._effect || !this._effect.isReady()) return null; // States this._engine.enableEffect(this._effect); this._engine.setState(false); this._engine.setDepthBuffer(false); this._engine.setDepthWrite(false); // Alpha this._engine.setAlphaMode(this.alphaMode); if (this.alphaConstants) { this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a); } // Texture var source; if (this._shareOutputWithPostProcess) { source = this._shareOutputWithPostProcess.outputTexture; } else if (this._forcedOutputTexture) { source = this._forcedOutputTexture; } else { source = this.outputTexture; } this._effect._bindTexture("textureSampler", source); // Parameters this._effect.setVector2("scale", this._scaleRatio); this.onApplyObservable.notifyObservers(this._effect); return this._effect; }; PostProcess.prototype._disposeTextures = function () { if (this._shareOutputWithPostProcess || this._forcedOutputTexture) { return; } if (this._textures.length > 0) { for (var i = 0; i < this._textures.length; i++) { this._engine._releaseTexture(this._textures.data[i]); } } this._textures.dispose(); }; PostProcess.prototype.dispose = function (camera) { camera = camera || this._camera; this._disposeTextures(); if (this._scene) { var index_1 = this._scene.postProcesses.indexOf(this); if (index_1 !== -1) { this._scene.postProcesses.splice(index_1, 1); } } else { var index_2 = this._engine.postProcesses.indexOf(this); if (index_2 !== -1) { this._engine.postProcesses.splice(index_2, 1); } } if (!camera) { return; } camera.detachPostProcess(this); var index = camera._postProcesses.indexOf(this); if (index === 0 && camera._postProcesses.length > 0) { this._camera._postProcesses[0].markTextureDirty(); } this.onActivateObservable.clear(); this.onAfterRenderObservable.clear(); this.onApplyObservable.clear(); this.onBeforeRenderObservable.clear(); this.onSizeChangedObservable.clear(); }; return PostProcess; }()); BABYLON.PostProcess = PostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.postProcess.js.map var BABYLON; (function (BABYLON) { var PassPostProcess = /** @class */ (function (_super) { __extends(PassPostProcess, _super); function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) { if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this; } return PassPostProcess; }(BABYLON.PostProcess)); BABYLON.PassPostProcess = PassPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.passPostProcess.js.map var BABYLON; (function (BABYLON) { var ShadowGenerator = /** @class */ (function () { /** * Creates a ShadowGenerator object. * A ShadowGenerator is the required tool to use the shadows. * Each light casting shadows needs to use its own ShadowGenerator. * Required parameters : * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024. * - `light`: the light object generating the shadows. * - `useFullFloatFirst`: by default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture. * Documentation : http://doc.babylonjs.com/tutorials/shadows */ function ShadowGenerator(mapSize, light, useFullFloatFirst) { // Members this._bias = 0.00005; this._blurBoxOffset = 1; this._blurScale = 2; this._blurKernel = 1; this._useKernelBlur = false; this._filter = ShadowGenerator.FILTER_NONE; this._darkness = 0; this._transparencyShadow = false; /** * Controls the extent to which the shadows fade out at the edge of the frustum * Used only by directionals and spots */ this.frustumEdgeFalloff = 0; this.forceBackFacesOnly = false; this._lightDirection = BABYLON.Vector3.Zero(); this._viewMatrix = BABYLON.Matrix.Zero(); this._projectionMatrix = BABYLON.Matrix.Zero(); this._transformMatrix = BABYLON.Matrix.Zero(); this._currentFaceIndex = 0; this._currentFaceIndexCache = 0; this._defaultTextureMatrix = BABYLON.Matrix.Identity(); this._mapSize = mapSize; this._light = light; this._scene = light.getScene(); light._shadowGenerator = this; // Texture type fallback from float to int if not supported. var caps = this._scene.getEngine().getCaps(); if (!useFullFloatFirst) { if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT; } else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT; } else { this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } } else { if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT; } else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT; } else { this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } } this._initializeGenerator(); } Object.defineProperty(ShadowGenerator, "FILTER_NONE", { // Static get: function () { return ShadowGenerator._FILTER_NONE; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", { get: function () { return ShadowGenerator._FILTER_POISSONSAMPLING; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", { get: function () { return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", { get: function () { return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", { get: function () { return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", { get: function () { return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "bias", { get: function () { return this._bias; }, set: function (bias) { this._bias = bias; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", { get: function () { return this._blurBoxOffset; }, set: function (value) { if (this._blurBoxOffset === value) { return; } this._blurBoxOffset = value; this._disposeBlurPostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "blurScale", { get: function () { return this._blurScale; }, set: function (value) { if (this._blurScale === value) { return; } this._blurScale = value; this._disposeBlurPostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "blurKernel", { get: function () { return this._blurKernel; }, set: function (value) { if (this._blurKernel === value) { return; } this._blurKernel = value; this._disposeBlurPostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", { get: function () { return this._useKernelBlur; }, set: function (value) { if (this._useKernelBlur === value) { return; } this._useKernelBlur = value; this._disposeBlurPostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "depthScale", { get: function () { return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale(); }, set: function (value) { this._depthScale = value; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "filter", { get: function () { return this._filter; }, set: function (value) { // Blurring the cubemap is going to be too expensive. Reverting to unblurred version if (this._light.needCube()) { if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { this.useExponentialShadowMap = true; return; } else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { this.useCloseExponentialShadowMap = true; return; } } if (this._filter === value) { return; } this._filter = value; this._disposeBlurPostProcesses(); this._applyFilterValues(); this._light._markMeshesAsLightDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", { get: function () { return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING; }, set: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) { return; } this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", { get: function () { BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead."); return this.useExponentialShadowMap; }, set: function (value) { BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead."); this.useExponentialShadowMap = value; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", { get: function () { BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead."); return this.useBlurExponentialShadowMap; }, set: function (value) { BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead."); this.useBlurExponentialShadowMap = value; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", { get: function () { return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP; }, set: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) { return; } this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", { get: function () { return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP; }, set: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { return; } this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", { get: function () { return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP; }, set: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) { return; } this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", { get: function () { return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP; }, set: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { return; } this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); /** * Returns the darkness value (float). */ ShadowGenerator.prototype.getDarkness = function () { return this._darkness; }; /** * Sets the ShadowGenerator darkness value (float <= 1.0). * Returns the ShadowGenerator. */ ShadowGenerator.prototype.setDarkness = function (darkness) { if (darkness >= 1.0) this._darkness = 1.0; else if (darkness <= 0.0) this._darkness = 0.0; else this._darkness = darkness; return this; }; /** * Sets the ability to have transparent shadow (boolean). * Returns the ShadowGenerator. */ ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) { this._transparencyShadow = hasShadow; return this; }; /** * Returns a RenderTargetTexture object : the shadow map texture. */ ShadowGenerator.prototype.getShadowMap = function () { return this._shadowMap; }; /** * Returns the most ready computed shadow map as a RenderTargetTexture object. */ ShadowGenerator.prototype.getShadowMapForRendering = function () { if (this._shadowMap2) { return this._shadowMap2; } return this._shadowMap; }; /** * Helper function to add a mesh and its descendants to the list of shadow casters * @param mesh Mesh to add * @param includeDescendants boolean indicating if the descendants should be added. Default to true */ ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) { if (includeDescendants === void 0) { includeDescendants = true; } if (!this._shadowMap) { return this; } if (!this._shadowMap.renderList) { this._shadowMap.renderList = []; } this._shadowMap.renderList.push(mesh); if (includeDescendants) { (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes()); } return this; var _a; }; /** * Helper function to remove a mesh and its descendants from the list of shadow casters * @param mesh Mesh to remove * @param includeDescendants boolean indicating if the descendants should be removed. Default to true */ ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) { if (includeDescendants === void 0) { includeDescendants = true; } if (!this._shadowMap || !this._shadowMap.renderList) { return this; } var index = this._shadowMap.renderList.indexOf(mesh); if (index !== -1) { this._shadowMap.renderList.splice(index, 1); } if (includeDescendants) { for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) { var child = _a[_i]; this.removeShadowCaster(child); } } return this; }; /** * Returns the associated light object. */ ShadowGenerator.prototype.getLight = function () { return this._light; }; ShadowGenerator.prototype._initializeGenerator = function () { this._light._markMeshesAsLightDirty(); this._initializeShadowMap(); }; ShadowGenerator.prototype._initializeShadowMap = function () { var _this = this; // Render target this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube()); this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; this._shadowMap.anisotropicFilteringLevel = 1; this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE); this._shadowMap.renderParticles = false; this._shadowMap.ignoreCameraViewport = true; // Record Face Index before render. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) { _this._currentFaceIndex = faceIndex; }); // Custom render function. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this); // Blur if required afer render. this._shadowMap.onAfterUnbindObservable.add(function () { if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) { return; } if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) { _this._initializeBlurRTTAndPostProcesses(); } var shadowMap = _this.getShadowMapForRendering(); if (shadowMap) { _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true); } }); // Clear according to the chosen filter. this._shadowMap.onClearObservable.add(function (engine) { if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) { engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true); } else { engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true); } }); }; ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () { var _this = this; var engine = this._scene.getEngine(); var targetSize = this._mapSize / this.blurScale; if (!this.useKernelBlur || this.blurScale !== 1.0) { this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType); this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE); } if (this.useKernelBlur) { this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType); this._kernelBlurXPostprocess.width = targetSize; this._kernelBlurXPostprocess.height = targetSize; this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) { effect.setTexture("textureSampler", _this._shadowMap); }); this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType); this._kernelBlurXPostprocess.autoClear = false; this._kernelBlurYPostprocess.autoClear = false; if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) { this._kernelBlurXPostprocess.packedFloat = true; this._kernelBlurYPostprocess.packedFloat = true; } this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess]; } else { this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType); this._boxBlurPostprocess.onApplyObservable.add(function (effect) { effect.setFloat2("screenSize", targetSize, targetSize); effect.setTexture("textureSampler", _this._shadowMap); }); this._boxBlurPostprocess.autoClear = false; this._blurPostProcesses = [this._boxBlurPostprocess]; } }; ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { var index; var engine = this._scene.getEngine(); if (depthOnlySubMeshes.length) { engine.setColorWrite(false); for (index = 0; index < depthOnlySubMeshes.length; index++) { this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]); } engine.setColorWrite(true); } for (index = 0; index < opaqueSubMeshes.length; index++) { this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]); } for (index = 0; index < alphaTestSubMeshes.length; index++) { this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]); } if (this._transparencyShadow) { for (index = 0; index < transparentSubMeshes.length; index++) { this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]); } } }; ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) { var _this = this; var mesh = subMesh.getRenderingMesh(); var scene = this._scene; var engine = scene.getEngine(); var material = subMesh.getMaterial(); if (!material) { return; } // Culling engine.setState(material.backFaceCulling); // Managing instances var batch = mesh._getInstancesRenderList(subMesh._id); if (batch.mustReturn) { return; } var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined); if (this.isReady(subMesh, hardwareInstancedRendering)) { engine.enableEffect(this._effect); mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode); this._effect.setFloat2("biasAndScale", this.bias, this.depthScale); this._effect.setMatrix("viewProjection", this.getTransformMatrix()); this._effect.setVector3("lightPosition", this.getLight().position); if (scene.activeCamera) { this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera)); } // Alpha test if (material && material.needAlphaTesting()) { var alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { this._effect.setTexture("diffuseSampler", alphaTexture); this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix); } } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders) { this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh))); } if (this.forceBackFacesOnly) { engine.setState(true, 0, false, true); } // Draw mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); }); if (this.forceBackFacesOnly) { engine.setState(true, 0, false, false); } } else { // Need to reset refresh rate of the shadowMap if (this._shadowMap) { this._shadowMap.resetRefreshCounter(); } } }; ShadowGenerator.prototype._applyFilterValues = function () { if (!this._shadowMap) { return; } if (this.filter === ShadowGenerator.FILTER_NONE) { this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE); } else { this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE); } }; /** * Force shader compilation including textures ready check */ ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) { var _this = this; var shadowMap = this.getShadowMap(); if (!shadowMap) { return; } var subMeshes = new Array(); var currentIndex = 0; var renderList = shadowMap.renderList; if (!renderList) { return; } for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) { var mesh = renderList_1[_i]; subMeshes.push.apply(subMeshes, mesh.subMeshes); } var checkReady = function () { if (!_this._scene || !_this._scene.getEngine()) { return; } var subMesh = subMeshes[currentIndex]; if (_this.isReady(subMesh, options ? options.useInstances : false)) { currentIndex++; if (currentIndex >= subMeshes.length) { if (onCompiled) { onCompiled(_this); } return; } } setTimeout(checkReady, 16); }; if (subMeshes.length > 0) { checkReady(); } }; /** * Boolean : true when the ShadowGenerator is finally computed. */ ShadowGenerator.prototype.isReady = function (subMesh, useInstances) { var defines = []; if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) { defines.push("#define FLOAT"); } if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { defines.push("#define ESM"); } var attribs = [BABYLON.VertexBuffer.PositionKind]; var mesh = subMesh.getMesh(); var material = subMesh.getMaterial(); // Alpha test if (material && material.needAlphaTesting()) { var alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { defines.push("#define ALPHATEST"); if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) { attribs.push(BABYLON.VertexBuffer.UVKind); defines.push("#define UV1"); } if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) { if (alphaTexture.coordinatesIndex === 1) { attribs.push(BABYLON.VertexBuffer.UV2Kind); defines.push("#define UV2"); } } } } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1)); } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } // Instances if (useInstances) { defines.push("#define INSTANCES"); attribs.push("world0"); attribs.push("world1"); attribs.push("world2"); attribs.push("world3"); } // Get correct effect var join = defines.join("\n"); if (this._cachedDefines !== join) { this._cachedDefines = join; this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join); } return this._effect.isReady(); }; /** * This creates the defines related to the standard BJS materials. */ ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) { var scene = this._scene; var light = this._light; if (!scene.shadowsEnabled || !light.shadowEnabled) { return; } defines["SHADOW" + lightIndex] = true; if (this.usePoissonSampling) { defines["SHADOWPCF" + lightIndex] = true; } else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { defines["SHADOWESM" + lightIndex] = true; } else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) { defines["SHADOWCLOSEESM" + lightIndex] = true; } if (light.needCube()) { defines["SHADOWCUBE" + lightIndex] = true; } }; /** * This binds shadow lights related to the standard BJS materials. * It implies the unifroms available on the materials are the standard BJS ones. */ ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) { var light = this._light; var scene = this._scene; if (!scene.shadowsEnabled || !light.shadowEnabled) { return; } var camera = scene.activeCamera; if (!camera) { return; } var shadowMap = this.getShadowMap(); if (!shadowMap) { return; } if (!light.needCube()) { effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix()); } effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering()); light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex); light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex); }; // Methods /** * Returns a Matrix object : the updated transformation matrix. */ ShadowGenerator.prototype.getTransformMatrix = function () { var scene = this._scene; if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) { return this._transformMatrix; } this._currentRenderID = scene.getRenderId(); this._currentFaceIndexCache = this._currentFaceIndex; var lightPosition = this._light.position; if (this._light.computeTransformedInformation()) { lightPosition = this._light.transformedPosition; } BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection); if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) { this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light } if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) { this._cachedPosition = lightPosition.clone(); this._cachedDirection = this._lightDirection.clone(); BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix); var shadowMap = this.getShadowMap(); if (shadowMap) { var renderList = shadowMap.renderList; if (renderList) { this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList); } } this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); } return this._transformMatrix; }; ShadowGenerator.prototype.recreateShadowMap = function () { var shadowMap = this._shadowMap; if (!shadowMap) { return; } // Track render list. var renderList = shadowMap.renderList; // Clean up existing data. this._disposeRTTandPostProcesses(); // Reinitializes. this._initializeGenerator(); // Reaffect the filter to ensure a correct fallback if necessary. this.filter = this.filter; // Reaffect the filter. this._applyFilterValues(); // Reaffect Render List. shadowMap.renderList = renderList; }; ShadowGenerator.prototype._disposeBlurPostProcesses = function () { if (this._shadowMap2) { this._shadowMap2.dispose(); this._shadowMap2 = null; } if (this._downSamplePostprocess) { this._downSamplePostprocess.dispose(); this._downSamplePostprocess = null; } if (this._boxBlurPostprocess) { this._boxBlurPostprocess.dispose(); this._boxBlurPostprocess = null; } if (this._kernelBlurXPostprocess) { this._kernelBlurXPostprocess.dispose(); this._kernelBlurXPostprocess = null; } if (this._kernelBlurYPostprocess) { this._kernelBlurYPostprocess.dispose(); this._kernelBlurYPostprocess = null; } this._blurPostProcesses = []; }; ShadowGenerator.prototype._disposeRTTandPostProcesses = function () { if (this._shadowMap) { this._shadowMap.dispose(); this._shadowMap = null; } this._disposeBlurPostProcesses(); }; /** * Disposes the ShadowGenerator. * Returns nothing. */ ShadowGenerator.prototype.dispose = function () { this._disposeRTTandPostProcesses(); if (this._light) { this._light._shadowGenerator = null; this._light._markMeshesAsLightDirty(); } }; /** * Serializes the ShadowGenerator and returns a serializationObject. */ ShadowGenerator.prototype.serialize = function () { var serializationObject = {}; var shadowMap = this.getShadowMap(); if (!shadowMap) { return serializationObject; } serializationObject.lightId = this._light.id; serializationObject.mapSize = shadowMap.getRenderSize(); serializationObject.useExponentialShadowMap = this.useExponentialShadowMap; serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap; serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap; serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap; serializationObject.usePoissonSampling = this.usePoissonSampling; serializationObject.forceBackFacesOnly = this.forceBackFacesOnly; serializationObject.depthScale = this.depthScale; serializationObject.darkness = this.getDarkness(); serializationObject.blurBoxOffset = this.blurBoxOffset; serializationObject.blurKernel = this.blurKernel; serializationObject.blurScale = this.blurScale; serializationObject.useKernelBlur = this.useKernelBlur; serializationObject.transparencyShadow = this._transparencyShadow; serializationObject.renderList = []; if (shadowMap.renderList) { for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) { var mesh = shadowMap.renderList[meshIndex]; serializationObject.renderList.push(mesh.id); } } return serializationObject; }; /** * Parses a serialized ShadowGenerator and returns a new ShadowGenerator. */ ShadowGenerator.Parse = function (parsedShadowGenerator, scene) { //casting to point light, as light is missing the position attr and typescript complains. var light = scene.getLightByID(parsedShadowGenerator.lightId); var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light); var shadowMap = shadowGenerator.getShadowMap(); for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) { var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]); meshes.forEach(function (mesh) { if (!shadowMap) { return; } if (!shadowMap.renderList) { shadowMap.renderList = []; } shadowMap.renderList.push(mesh); }); } if (parsedShadowGenerator.usePoissonSampling) { shadowGenerator.usePoissonSampling = true; } else if (parsedShadowGenerator.useExponentialShadowMap) { shadowGenerator.useExponentialShadowMap = true; } else if (parsedShadowGenerator.useBlurExponentialShadowMap) { shadowGenerator.useBlurExponentialShadowMap = true; } else if (parsedShadowGenerator.useCloseExponentialShadowMap) { shadowGenerator.useCloseExponentialShadowMap = true; } else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) { shadowGenerator.useBlurCloseExponentialShadowMap = true; } else if (parsedShadowGenerator.useVarianceShadowMap) { shadowGenerator.useExponentialShadowMap = true; } else if (parsedShadowGenerator.useBlurVarianceShadowMap) { shadowGenerator.useBlurExponentialShadowMap = true; } if (parsedShadowGenerator.depthScale) { shadowGenerator.depthScale = parsedShadowGenerator.depthScale; } if (parsedShadowGenerator.blurScale) { shadowGenerator.blurScale = parsedShadowGenerator.blurScale; } if (parsedShadowGenerator.blurBoxOffset) { shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset; } if (parsedShadowGenerator.useKernelBlur) { shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur; } if (parsedShadowGenerator.blurKernel) { shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel; } if (parsedShadowGenerator.bias !== undefined) { shadowGenerator.bias = parsedShadowGenerator.bias; } if (parsedShadowGenerator.darkness) { shadowGenerator.setDarkness(parsedShadowGenerator.darkness); } if (parsedShadowGenerator.transparencyShadow) { shadowGenerator.setTransparencyShadow(true); } shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly; return shadowGenerator; }; ShadowGenerator._FILTER_NONE = 0; ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1; ShadowGenerator._FILTER_POISSONSAMPLING = 2; ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3; ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4; ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5; return ShadowGenerator; }()); BABYLON.ShadowGenerator = ShadowGenerator; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.shadowGenerator.js.map var BABYLON; (function (BABYLON) { var DefaultLoadingScreen = /** @class */ (function () { function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) { if (_loadingText === void 0) { _loadingText = ""; } if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; } var _this = this; this._renderingCanvas = _renderingCanvas; this._loadingText = _loadingText; this._loadingDivBackgroundColor = _loadingDivBackgroundColor; // Resize this._resizeLoadingUI = function () { var canvasRect = _this._renderingCanvas.getBoundingClientRect(); var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position; if (!_this._loadingDiv) { return; } _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute"; _this._loadingDiv.style.left = canvasRect.left + "px"; _this._loadingDiv.style.top = canvasRect.top + "px"; _this._loadingDiv.style.width = canvasRect.width + "px"; _this._loadingDiv.style.height = canvasRect.height + "px"; }; } DefaultLoadingScreen.prototype.displayLoadingUI = function () { if (this._loadingDiv) { // Do not add a loading screen if there is already one return; } this._loadingDiv = document.createElement("div"); this._loadingDiv.id = "babylonjsLoadingDiv"; this._loadingDiv.style.opacity = "0"; this._loadingDiv.style.transition = "opacity 1.5s ease"; this._loadingDiv.style.pointerEvents = "none"; // Loading text this._loadingTextDiv = document.createElement("div"); this._loadingTextDiv.style.position = "absolute"; this._loadingTextDiv.style.left = "0"; this._loadingTextDiv.style.top = "50%"; this._loadingTextDiv.style.marginTop = "80px"; this._loadingTextDiv.style.width = "100%"; this._loadingTextDiv.style.height = "20px"; this._loadingTextDiv.style.fontFamily = "Arial"; this._loadingTextDiv.style.fontSize = "14px"; this._loadingTextDiv.style.color = "white"; this._loadingTextDiv.style.textAlign = "center"; this._loadingTextDiv.innerHTML = "Loading"; this._loadingDiv.appendChild(this._loadingTextDiv); //set the predefined text this._loadingTextDiv.innerHTML = this._loadingText; // Generating keyframes var style = document.createElement('style'); style.type = 'text/css'; var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }"; style.innerHTML = keyFrames; document.getElementsByTagName('head')[0].appendChild(style); // Loading img var imgBack = new Image(); imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC"; imgBack.style.position = "absolute"; imgBack.style.left = "50%"; imgBack.style.top = "50%"; imgBack.style.marginLeft = "-60px"; imgBack.style.marginTop = "-60px"; imgBack.style.animation = "spin1 2s infinite ease-in-out"; imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out"; imgBack.style.transformOrigin = "50% 50%"; imgBack.style.webkitTransformOrigin = "50% 50%"; this._loadingDiv.appendChild(imgBack); this._resizeLoadingUI(); window.addEventListener("resize", this._resizeLoadingUI); this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor; document.body.appendChild(this._loadingDiv); this._loadingDiv.style.opacity = "1"; }; DefaultLoadingScreen.prototype.hideLoadingUI = function () { var _this = this; if (!this._loadingDiv) { return; } var onTransitionEnd = function () { if (!_this._loadingDiv) { return; } document.body.removeChild(_this._loadingDiv); window.removeEventListener("resize", _this._resizeLoadingUI); _this._loadingDiv = null; }; this._loadingDiv.style.opacity = "0"; this._loadingDiv.addEventListener("transitionend", onTransitionEnd); }; Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", { set: function (text) { this._loadingText = text; if (this._loadingTextDiv) { this._loadingTextDiv.innerHTML = this._loadingText; } }, enumerable: true, configurable: true }); Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", { get: function () { return this._loadingDivBackgroundColor; }, set: function (color) { this._loadingDivBackgroundColor = color; if (!this._loadingDiv) { return; } this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor; }, enumerable: true, configurable: true }); return DefaultLoadingScreen; }()); BABYLON.DefaultLoadingScreen = DefaultLoadingScreen; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.loadingScreen.js.map var BABYLON; (function (BABYLON) { var SceneLoader = /** @class */ (function () { function SceneLoader() { } Object.defineProperty(SceneLoader, "NO_LOGGING", { get: function () { return 0; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", { get: function () { return 1; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", { get: function () { return 2; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoader, "DETAILED_LOGGING", { get: function () { return 3; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", { get: function () { return SceneLoader._ForceFullSceneLoadingForIncremental; }, set: function (value) { SceneLoader._ForceFullSceneLoadingForIncremental = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoader, "ShowLoadingScreen", { get: function () { return SceneLoader._ShowLoadingScreen; }, set: function (value) { SceneLoader._ShowLoadingScreen = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoader, "loggingLevel", { get: function () { return SceneLoader._loggingLevel; }, set: function (value) { SceneLoader._loggingLevel = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", { get: function () { return SceneLoader._CleanBoneMatrixWeights; }, set: function (value) { SceneLoader._CleanBoneMatrixWeights = value; }, enumerable: true, configurable: true }); SceneLoader._getDefaultPlugin = function () { return SceneLoader._registeredPlugins[".babylon"]; }; SceneLoader._getPluginForExtension = function (extension) { var registeredPlugin = SceneLoader._registeredPlugins[extension]; if (registeredPlugin) { return registeredPlugin; } return SceneLoader._getDefaultPlugin(); }; SceneLoader._getPluginForDirectLoad = function (data) { for (var extension in SceneLoader._registeredPlugins) { var plugin = SceneLoader._registeredPlugins[extension].plugin; if (plugin.canDirectLoad && plugin.canDirectLoad(data)) { return SceneLoader._registeredPlugins[extension]; } } return SceneLoader._getDefaultPlugin(); }; SceneLoader._getPluginForFilename = function (sceneFilename) { if (sceneFilename.name) { sceneFilename = sceneFilename.name; } var dotPosition = sceneFilename.lastIndexOf("."); var queryStringPosition = sceneFilename.indexOf("?"); if (queryStringPosition === -1) { queryStringPosition = sceneFilename.length; } var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase(); return SceneLoader._getPluginForExtension(extension); }; // use babylon file loader directly if sceneFilename is prefixed with "data:" SceneLoader._getDirectLoad = function (sceneFilename) { if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") { return sceneFilename.substr(5); } return null; }; SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) { var directLoad = SceneLoader._getDirectLoad(sceneFilename); var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename); var plugin = registeredPlugin.plugin; var useArrayBuffer = registeredPlugin.isBinary; var database; SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin); var dataCallback = function (data) { if (scene.isDisposed) { onError("Scene has been disposed"); return; } scene.database = database; try { onSuccess(plugin, data); } catch (e) { onError(null, e); } }; var manifestChecked = function (success) { BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) { if (request) { onError(request.status + " " + request.statusText); } }); }; if (directLoad) { dataCallback(directLoad); return; } if (rootUrl.indexOf("file:") === -1) { if (scene.getEngine().enableOfflineSupport) { // Checking if a manifest file has been set for this scene and if offline mode has been requested database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked); } else { manifestChecked(true); } } else { var fileOrString = sceneFilename; if (fileOrString.name) { BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer); } else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) { BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer); } else { onError("Unable to find file named " + sceneFilename); return; } } }; // Public functions SceneLoader.GetPluginForExtension = function (extension) { return SceneLoader._getPluginForExtension(extension).plugin; }; SceneLoader.RegisterPlugin = function (plugin) { if (typeof plugin.extensions === "string") { var extension = plugin.extensions; SceneLoader._registeredPlugins[extension.toLowerCase()] = { plugin: plugin, isBinary: false }; } else { var extensions = plugin.extensions; Object.keys(extensions).forEach(function (extension) { SceneLoader._registeredPlugins[extension.toLowerCase()] = { plugin: plugin, isBinary: extensions[extension].isBinary }; }); } }; /** * Import meshes into a scene * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported * @param rootUrl a string that defines the root url for scene and resources * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene * @param scene the instance of BABYLON.Scene to append to * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds * @param onProgress a callback with a progress event for each file being loaded * @param onError a callback with the scene, a message, and possibly an exception when import fails */ SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) { if (onSuccess === void 0) { onSuccess = null; } if (onProgress === void 0) { onProgress = null; } if (onError === void 0) { onError = null; } if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") { BABYLON.Tools.Error("Wrong sceneFilename parameter"); return; } var loadingToken = {}; scene._addPendingData(loadingToken); var errorHandler = function (message, exception) { var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""); if (onError) { onError(scene, errorMessage, exception); } else { BABYLON.Tools.Error(errorMessage); // should the exception be thrown? } scene._removePendingData(loadingToken); }; var progressHandler = function (event) { if (onProgress) { onProgress(event); } }; SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) { if (plugin.importMesh) { var syncedPlugin = plugin; var meshes = new Array(); var particleSystems = new Array(); var skeletons = new Array(); if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) { return; } if (onSuccess) { // wrap onSuccess with try-catch to know if something went wrong. try { scene.importedMeshesFiles.push(rootUrl + sceneFilename); onSuccess(meshes, particleSystems, skeletons); scene._removePendingData(loadingToken); } catch (e) { var message = 'Error in onSuccess callback.'; errorHandler(message, e); } } } else { var asyncedPlugin = plugin; asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) { if (onSuccess) { try { scene.importedMeshesFiles.push(rootUrl + sceneFilename); onSuccess(meshes, particleSystems, skeletons); scene._removePendingData(loadingToken); } catch (e) { var message = 'Error in onSuccess callback.'; errorHandler(message, e); } } }, progressHandler, errorHandler); } }, progressHandler, errorHandler); }; /** * Load a scene * @param rootUrl a string that defines the root url for scene and resources * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene * @param engine is the instance of BABYLON.Engine to use to create the scene * @param onSuccess a callback with the scene when import succeeds * @param onProgress a callback with a progress event for each file being loaded * @param onError a callback with the scene, a message, and possibly an exception when import fails */ SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) { SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError); }; /** * Append a scene * @param rootUrl a string that defines the root url for scene and resources * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene * @param scene is the instance of BABYLON.Scene to append to * @param onSuccess a callback with the scene when import succeeds * @param onProgress a callback with a progress event for each file being loaded * @param onError a callback with the scene, a message, and possibly an exception when import fails */ SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) { if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") { BABYLON.Tools.Error("Wrong sceneFilename parameter"); return; } if (SceneLoader.ShowLoadingScreen) { scene.getEngine().displayLoadingUI(); } var loadingToken = {}; scene._addPendingData(loadingToken); var errorHandler = function (message, exception) { var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""); if (onError) { onError(scene, errorMessage, exception); } else { BABYLON.Tools.Error(errorMessage); // should the exception be thrown? } scene._removePendingData(loadingToken); scene.getEngine().hideLoadingUI(); }; var progressHandler = function (event) { if (onProgress) { onProgress(event); } }; SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) { if (plugin.load) { var syncedPlugin = plugin; if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) { return; } if (onSuccess) { try { onSuccess(scene); } catch (e) { errorHandler("Error in onSuccess callback", e); } } scene.loadingPluginName = plugin.name; scene._removePendingData(loadingToken); } else { var asyncedPlugin = plugin; asyncedPlugin.loadAsync(scene, data, rootUrl, function () { if (onSuccess) { onSuccess(scene); } scene.loadingPluginName = plugin.name; scene._removePendingData(loadingToken); }, progressHandler, errorHandler); } if (SceneLoader.ShowLoadingScreen) { scene.executeWhenReady(function () { scene.getEngine().hideLoadingUI(); }); } }, progressHandler, errorHandler); }; // Flags SceneLoader._ForceFullSceneLoadingForIncremental = false; SceneLoader._ShowLoadingScreen = true; SceneLoader._CleanBoneMatrixWeights = false; SceneLoader._loggingLevel = SceneLoader.NO_LOGGING; // Members SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable(); SceneLoader._registeredPlugins = {}; return SceneLoader; }()); BABYLON.SceneLoader = SceneLoader; ; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.sceneLoader.js.map var BABYLON; (function (BABYLON) { var Internals; (function (Internals) { var parseMaterialById = function (id, parsedData, scene, rootUrl) { for (var index = 0, cache = parsedData.materials.length; index < cache; index++) { var parsedMaterial = parsedData.materials[index]; if (parsedMaterial.id === id) { return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl); } } return null; }; var isDescendantOf = function (mesh, names, hierarchyIds) { for (var i in names) { if (mesh.name === names[i]) { hierarchyIds.push(mesh.id); return true; } } if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) { hierarchyIds.push(mesh.id); return true; } return false; }; var logOperation = function (operation, producer) { return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown"); }; BABYLON.SceneLoader.RegisterPlugin({ name: "babylon.js", extensions: ".babylon", canDirectLoad: function (data) { if (data.indexOf("babylon") !== -1) { return true; } return false; }, importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) { // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details // when SceneLoader.debugLogging = true (default), or exception encountered. // Everything stored in var log instead of writing separate lines to support only writing in exception, // and avoid problems with multiple concurrent .babylon loads. var log = "importMesh has failed JSON parse"; try { var parsedData = JSON.parse(data); log = ""; var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING; if (!meshesNames) { meshesNames = null; } else if (!Array.isArray(meshesNames)) { meshesNames = [meshesNames]; } var hierarchyIds = new Array(); if (parsedData.meshes !== undefined && parsedData.meshes !== null) { var loadedSkeletonsIds = []; var loadedMaterialsIds = []; var index; var cache; for (index = 0, cache = parsedData.meshes.length; index < cache; index++) { var parsedMesh = parsedData.meshes[index]; if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) { if (meshesNames !== null) { // Remove found mesh name from list. delete meshesNames[meshesNames.indexOf(parsedMesh.name)]; } //Geometry? if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) { //does the file contain geometries? if (parsedData.geometries !== undefined && parsedData.geometries !== null) { //find the correct geometry and add it to the scene var found = false; ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) { if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) { return; } else { parsedData.geometries[geometryType].forEach(function (parsedGeometryData) { if (parsedGeometryData.id === parsedMesh.geometryId) { switch (geometryType) { case "boxes": BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene); break; case "spheres": BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene); break; case "cylinders": BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene); break; case "toruses": BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene); break; case "grounds": BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene); break; case "planes": BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene); break; case "torusKnots": BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene); break; case "vertexData": BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl); break; } found = true; } }); } }); if (found === false) { BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id); } } } // Material ? if (parsedMesh.materialId) { var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1); if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) { for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) { var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex]; if (parsedMultiMaterial.id === parsedMesh.materialId) { for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) { var subMatId = parsedMultiMaterial.materials[matIndex]; loadedMaterialsIds.push(subMatId); var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl); log += "\n\tMaterial " + mat.toString(fullDetails); } loadedMaterialsIds.push(parsedMultiMaterial.id); var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene); materialFound = true; log += "\n\tMulti-Material " + mmat.toString(fullDetails); break; } } } if (materialFound === false) { loadedMaterialsIds.push(parsedMesh.materialId); var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl); if (!mat) { BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id); } else { log += "\n\tMaterial " + mat.toString(fullDetails); } } } // Skeleton ? if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) { var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1); if (skeletonAlreadyLoaded === false) { for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) { var parsedSkeleton = parsedData.skeletons[skeletonIndex]; if (parsedSkeleton.id === parsedMesh.skeletonId) { var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene); skeletons.push(skeleton); loadedSkeletonsIds.push(parsedSkeleton.id); log += "\n\tSkeleton " + skeleton.toString(fullDetails); } } } } var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl); meshes.push(mesh); log += "\n\tMesh " + mesh.toString(fullDetails); } } // Connecting parents var currentMesh; for (index = 0, cache = scene.meshes.length; index < cache; index++) { currentMesh = scene.meshes[index]; if (currentMesh._waitingParentId) { currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId); currentMesh._waitingParentId = null; } } // freeze and compute world matrix application for (index = 0, cache = scene.meshes.length; index < cache; index++) { currentMesh = scene.meshes[index]; if (currentMesh._waitingFreezeWorldMatrix) { currentMesh.freezeWorldMatrix(); currentMesh._waitingFreezeWorldMatrix = null; } else { currentMesh.computeWorldMatrix(true); } } } // Particles if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) { for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) { var parsedParticleSystem = parsedData.particleSystems[index]; if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) { particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl)); } } } return true; } catch (err) { var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log; if (onError) { onError(msg, err); } else { BABYLON.Tools.Log(msg); throw err; } } finally { if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) { BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : "")); } } return false; }, load: function (scene, data, rootUrl, onError) { // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details // when SceneLoader.debugLogging = true (default), or exception encountered. // Everything stored in var log instead of writing separate lines to support only writing in exception, // and avoid problems with multiple concurrent .babylon loads. var log = "importScene has failed JSON parse"; try { var parsedData = JSON.parse(data); log = ""; var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING; // Scene if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) { scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental; } if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) { scene.autoClear = parsedData.autoClear; } if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) { scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor); } if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) { scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor); } if (parsedData.gravity !== undefined && parsedData.gravity !== null) { scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity); } // Fog if (parsedData.fogMode && parsedData.fogMode !== 0) { scene.fogMode = parsedData.fogMode; scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor); scene.fogStart = parsedData.fogStart; scene.fogEnd = parsedData.fogEnd; scene.fogDensity = parsedData.fogDensity; log += "\tFog mode for scene: "; switch (scene.fogMode) { // getters not compiling, so using hardcoded case 1: log += "exp\n"; break; case 2: log += "exp2\n"; break; case 3: log += "linear\n"; break; } } //Physics if (parsedData.physicsEnabled) { var physicsPlugin; if (parsedData.physicsEngine === "cannon") { physicsPlugin = new BABYLON.CannonJSPlugin(); } else if (parsedData.physicsEngine === "oimo") { physicsPlugin = new BABYLON.OimoJSPlugin(); } log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n"; //else - default engine, which is currently oimo var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null; scene.enablePhysics(physicsGravity, physicsPlugin); } // Metadata if (parsedData.metadata !== undefined && parsedData.metadata !== null) { scene.metadata = parsedData.metadata; } //collisions, if defined. otherwise, default is true if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) { scene.collisionsEnabled = parsedData.collisionsEnabled; } scene.workerCollisions = !!parsedData.workerCollisions; var index; var cache; // Lights if (parsedData.lights !== undefined && parsedData.lights !== null) { for (index = 0, cache = parsedData.lights.length; index < cache; index++) { var parsedLight = parsedData.lights[index]; var light = BABYLON.Light.Parse(parsedLight, scene); if (light) { log += (index === 0 ? "\n\tLights:" : ""); log += "\n\t\t" + light.toString(fullDetails); } } } // Animations if (parsedData.animations !== undefined && parsedData.animations !== null) { for (index = 0, cache = parsedData.animations.length; index < cache; index++) { var parsedAnimation = parsedData.animations[index]; var animation = BABYLON.Animation.Parse(parsedAnimation); scene.animations.push(animation); log += (index === 0 ? "\n\tAnimations:" : ""); log += "\n\t\t" + animation.toString(fullDetails); } } if (parsedData.autoAnimate) { scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0); } // Materials if (parsedData.materials !== undefined && parsedData.materials !== null) { for (index = 0, cache = parsedData.materials.length; index < cache; index++) { var parsedMaterial = parsedData.materials[index]; var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl); log += (index === 0 ? "\n\tMaterials:" : ""); log += "\n\t\t" + mat.toString(fullDetails); } } if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) { for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) { var parsedMultiMaterial = parsedData.multiMaterials[index]; var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene); log += (index === 0 ? "\n\tMultiMaterials:" : ""); log += "\n\t\t" + mmat.toString(fullDetails); } } // Morph targets if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) { for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) { var managerData = _a[_i]; BABYLON.MorphTargetManager.Parse(managerData, scene); } } // Skeletons if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) { for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) { var parsedSkeleton = parsedData.skeletons[index]; var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene); log += (index === 0 ? "\n\tSkeletons:" : ""); log += "\n\t\t" + skeleton.toString(fullDetails); } } // Geometries var geometries = parsedData.geometries; if (geometries !== undefined && geometries !== null) { // Boxes var boxes = geometries.boxes; if (boxes !== undefined && boxes !== null) { for (index = 0, cache = boxes.length; index < cache; index++) { var parsedBox = boxes[index]; BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene); } } // Spheres var spheres = geometries.spheres; if (spheres !== undefined && spheres !== null) { for (index = 0, cache = spheres.length; index < cache; index++) { var parsedSphere = spheres[index]; BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene); } } // Cylinders var cylinders = geometries.cylinders; if (cylinders !== undefined && cylinders !== null) { for (index = 0, cache = cylinders.length; index < cache; index++) { var parsedCylinder = cylinders[index]; BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene); } } // Toruses var toruses = geometries.toruses; if (toruses !== undefined && toruses !== null) { for (index = 0, cache = toruses.length; index < cache; index++) { var parsedTorus = toruses[index]; BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene); } } // Grounds var grounds = geometries.grounds; if (grounds !== undefined && grounds !== null) { for (index = 0, cache = grounds.length; index < cache; index++) { var parsedGround = grounds[index]; BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene); } } // Planes var planes = geometries.planes; if (planes !== undefined && planes !== null) { for (index = 0, cache = planes.length; index < cache; index++) { var parsedPlane = planes[index]; BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene); } } // TorusKnots var torusKnots = geometries.torusKnots; if (torusKnots !== undefined && torusKnots !== null) { for (index = 0, cache = torusKnots.length; index < cache; index++) { var parsedTorusKnot = torusKnots[index]; BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene); } } // VertexData var vertexData = geometries.vertexData; if (vertexData !== undefined && vertexData !== null) { for (index = 0, cache = vertexData.length; index < cache; index++) { var parsedVertexData = vertexData[index]; BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl); } } } // Meshes if (parsedData.meshes !== undefined && parsedData.meshes !== null) { for (index = 0, cache = parsedData.meshes.length; index < cache; index++) { var parsedMesh = parsedData.meshes[index]; var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl); log += (index === 0 ? "\n\tMeshes:" : ""); log += "\n\t\t" + mesh.toString(fullDetails); } } // Cameras if (parsedData.cameras !== undefined && parsedData.cameras !== null) { for (index = 0, cache = parsedData.cameras.length; index < cache; index++) { var parsedCamera = parsedData.cameras[index]; var camera = BABYLON.Camera.Parse(parsedCamera, scene); log += (index === 0 ? "\n\tCameras:" : ""); log += "\n\t\t" + camera.toString(fullDetails); } } if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) { scene.setActiveCameraByID(parsedData.activeCameraID); } // Browsing all the graph to connect the dots for (index = 0, cache = scene.cameras.length; index < cache; index++) { var camera = scene.cameras[index]; if (camera._waitingParentId) { camera.parent = scene.getLastEntryByID(camera._waitingParentId); camera._waitingParentId = null; } } for (index = 0, cache = scene.lights.length; index < cache; index++) { var light_1 = scene.lights[index]; if (light_1 && light_1._waitingParentId) { light_1.parent = scene.getLastEntryByID(light_1._waitingParentId); light_1._waitingParentId = null; } } // Sounds var loadedSounds = []; var loadedSound; if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) { for (index = 0, cache = parsedData.sounds.length; index < cache; index++) { var parsedSound = parsedData.sounds[index]; if (BABYLON.Engine.audioEngine.canUseWebAudio) { if (!parsedSound.url) parsedSound.url = parsedSound.name; if (!loadedSounds[parsedSound.url]) { loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl); loadedSounds[parsedSound.url] = loadedSound; } else { BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]); } } else { new BABYLON.Sound(parsedSound.name, null, scene); } } } loadedSounds = []; // Connect parents & children and parse actions for (index = 0, cache = scene.meshes.length; index < cache; index++) { var mesh = scene.meshes[index]; if (mesh._waitingParentId) { mesh.parent = scene.getLastEntryByID(mesh._waitingParentId); mesh._waitingParentId = null; } if (mesh._waitingActions) { BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene); mesh._waitingActions = null; } } // freeze world matrix application for (index = 0, cache = scene.meshes.length; index < cache; index++) { var currentMesh = scene.meshes[index]; if (currentMesh._waitingFreezeWorldMatrix) { currentMesh.freezeWorldMatrix(); currentMesh._waitingFreezeWorldMatrix = null; } else { currentMesh.computeWorldMatrix(true); } } // Particles Systems if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) { for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) { var parsedParticleSystem = parsedData.particleSystems[index]; BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl); } } // Environment texture if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) { scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene); if (parsedData.createDefaultSkybox === true) { var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000; var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0; scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel); } } // Lens flares if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) { for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) { var parsedLensFlareSystem = parsedData.lensFlareSystems[index]; BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl); } } // Shadows if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) { for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) { var parsedShadowGenerator = parsedData.shadowGenerators[index]; BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene); } } // Lights exclusions / inclusions for (index = 0, cache = scene.lights.length; index < cache; index++) { var light_2 = scene.lights[index]; // Excluded check if (light_2._excludedMeshesIds.length > 0) { for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) { var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]); if (excludedMesh) { light_2.excludedMeshes.push(excludedMesh); } } light_2._excludedMeshesIds = []; } // Included check if (light_2._includedOnlyMeshesIds.length > 0) { for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) { var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]); if (includedOnlyMesh) { light_2.includedOnlyMeshes.push(includedOnlyMesh); } } light_2._includedOnlyMeshesIds = []; } } // Actions (scene) if (parsedData.actions !== undefined && parsedData.actions !== null) { BABYLON.ActionManager.Parse(parsedData.actions, null, scene); } // Finish return true; } catch (err) { var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log; if (onError) { onError(msg, err); } else { BABYLON.Tools.Log(msg); throw err; } } finally { if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) { BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : "")); } } return false; } }); })(Internals = BABYLON.Internals || (BABYLON.Internals = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.babylonFileLoader.js.map var BABYLON; (function (BABYLON) { var FilesInput = /** @class */ (function () { function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) { this.onProcessFileCallback = function () { return true; }; this._engine = engine; this._currentScene = scene; this._sceneLoadedCallback = sceneLoadedCallback; this._progressCallback = progressCallback; this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback; this._textureLoadingCallback = textureLoadingCallback; this._startingProcessingFilesCallback = startingProcessingFilesCallback; this._onReloadCallback = onReloadCallback; this._errorCallback = errorCallback; } FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) { var _this = this; if (elementToMonitor) { this._elementToMonitor = elementToMonitor; this._dragEnterHandler = function (e) { _this.drag(e); }; this._dragOverHandler = function (e) { _this.drag(e); }; this._dropHandler = function (e) { _this.drop(e); }; this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false); this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false); this._elementToMonitor.addEventListener("drop", this._dropHandler, false); } }; FilesInput.prototype.dispose = function () { if (!this._elementToMonitor) { return; } this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler); this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler); this._elementToMonitor.removeEventListener("drop", this._dropHandler); }; FilesInput.prototype.renderFunction = function () { if (this._additionalRenderLoopLogicCallback) { this._additionalRenderLoopLogicCallback(); } if (this._currentScene) { if (this._textureLoadingCallback) { var remaining = this._currentScene.getWaitingItemsCount(); if (remaining > 0) { this._textureLoadingCallback(remaining); } } this._currentScene.render(); } }; FilesInput.prototype.drag = function (e) { e.stopPropagation(); e.preventDefault(); }; FilesInput.prototype.drop = function (eventDrop) { eventDrop.stopPropagation(); eventDrop.preventDefault(); this.loadFiles(eventDrop); }; FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) { var _this = this; var reader = folder.createReader(); var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/"); reader.readEntries(function (entries) { remaining.count += entries.length; for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { var entry = entries_1[_i]; if (entry.isFile) { entry.file(function (file) { file.correctName = relativePath + file.name; files.push(file); if (--remaining.count === 0) { callback(); } }); } else if (entry.isDirectory) { _this._traverseFolder(entry, files, remaining, callback); } } if (--remaining.count) { callback(); } }); }; FilesInput.prototype._processFiles = function (files) { var skippedFiles = 0; for (var i = 0; i < files.length; i++) { var name = files[i].correctName.toLowerCase(); var extension = name.split('.').pop(); if (!this.onProcessFileCallback(files[i], name, extension)) { skippedFiles++; continue; } if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb") && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) { this._sceneFileToLoad = files[i]; } else { FilesInput.FilesToLoad[name] = files[i]; } } if (this._onReloadCallback) { this._onReloadCallback(this._sceneFileToLoad); } else if (skippedFiles < files.length) { this.reload(); } }; FilesInput.prototype.loadFiles = function (event) { var _this = this; if (this._startingProcessingFilesCallback) this._startingProcessingFilesCallback(); // Handling data transfer via drag'n'drop if (event && event.dataTransfer && event.dataTransfer.files) { this._filesToLoad = event.dataTransfer.files; } // Handling files from input files if (event && event.target && event.target.files) { this._filesToLoad = event.target.files; } if (this._filesToLoad && this._filesToLoad.length > 0) { var files_1 = new Array(); var folders = []; var items = event.dataTransfer ? event.dataTransfer.items : null; for (var i = 0; i < this._filesToLoad.length; i++) { var fileToLoad = this._filesToLoad[i]; var name_1 = fileToLoad.name.toLowerCase(); var entry = void 0; fileToLoad.correctName = name_1; if (items) { var item = items[i]; if (item.getAsEntry) { entry = item.getAsEntry(); } else if (item.webkitGetAsEntry) { entry = item.webkitGetAsEntry(); } } if (!entry) { files_1.push(fileToLoad); } else { if (entry.isDirectory) { folders.push(entry); } else { files_1.push(fileToLoad); } } } if (folders.length === 0) { this._processFiles(files_1); } else { var remaining = { count: folders.length }; for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) { var folder = folders_1[_i]; this._traverseFolder(folder, files_1, remaining, function () { _this._processFiles(files_1); }); } } } }; FilesInput.prototype.reload = function () { var _this = this; // If a ".babylon" file has been provided if (this._sceneFileToLoad) { if (this._currentScene) { if (BABYLON.Tools.errorsCount > 0) { BABYLON.Tools.ClearLogCache(); BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched"); } this._engine.stopRenderLoop(); this._currentScene.dispose(); } BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) { _this._currentScene = newScene; if (_this._sceneLoadedCallback) { _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene); } // Wait for textures and shaders to be ready _this._currentScene.executeWhenReady(function () { _this._engine.runRenderLoop(function () { _this.renderFunction(); }); }); }, function (progress) { if (_this._progressCallback) { _this._progressCallback(progress); } }, function (scene, message) { _this._currentScene = scene; if (_this._errorCallback) { _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message); } }); } else { BABYLON.Tools.Error("Please provide a valid .babylon file."); } }; FilesInput.FilesToLoad = {}; return FilesInput; }()); BABYLON.FilesInput = FilesInput; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.filesInput.js.map var BABYLON; (function (BABYLON) { /** * This class implement a typical dictionary using a string as key and the generic type T as value. * The underlying implementation relies on an associative array to ensure the best performances. * The value can be anything including 'null' but except 'undefined' */ var StringDictionary = /** @class */ (function () { function StringDictionary() { this._count = 0; this._data = {}; } /** * This will clear this dictionary and copy the content from the 'source' one. * If the T value is a custom object, it won't be copied/cloned, the same object will be used * @param source the dictionary to take the content from and copy to this dictionary */ StringDictionary.prototype.copyFrom = function (source) { var _this = this; this.clear(); source.forEach(function (t, v) { return _this.add(t, v); }); }; /** * Get a value based from its key * @param key the given key to get the matching value from * @return the value if found, otherwise undefined is returned */ StringDictionary.prototype.get = function (key) { var val = this._data[key]; if (val !== undefined) { return val; } return undefined; }; /** * Get a value from its key or add it if it doesn't exist. * This method will ensure you that a given key/data will be present in the dictionary. * @param key the given key to get the matching value from * @param factory the factory that will create the value if the key is not present in the dictionary. * The factory will only be invoked if there's no data for the given key. * @return the value corresponding to the key. */ StringDictionary.prototype.getOrAddWithFactory = function (key, factory) { var val = this.get(key); if (val !== undefined) { return val; } val = factory(key); if (val) { this.add(key, val); } return val; }; /** * Get a value from its key if present in the dictionary otherwise add it * @param key the key to get the value from * @param val if there's no such key/value pair in the dictionary add it with this value * @return the value corresponding to the key */ StringDictionary.prototype.getOrAdd = function (key, val) { var curVal = this.get(key); if (curVal !== undefined) { return curVal; } this.add(key, val); return val; }; /** * Check if there's a given key in the dictionary * @param key the key to check for * @return true if the key is present, false otherwise */ StringDictionary.prototype.contains = function (key) { return this._data[key] !== undefined; }; /** * Add a new key and its corresponding value * @param key the key to add * @param value the value corresponding to the key * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary */ StringDictionary.prototype.add = function (key, value) { if (this._data[key] !== undefined) { return false; } this._data[key] = value; ++this._count; return true; }; StringDictionary.prototype.set = function (key, value) { if (this._data[key] === undefined) { return false; } this._data[key] = value; return true; }; /** * Get the element of the given key and remove it from the dictionary * @param key */ StringDictionary.prototype.getAndRemove = function (key) { var val = this.get(key); if (val !== undefined) { delete this._data[key]; --this._count; return val; } return null; }; /** * Remove a key/value from the dictionary. * @param key the key to remove * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary */ StringDictionary.prototype.remove = function (key) { if (this.contains(key)) { delete this._data[key]; --this._count; return true; } return false; }; /** * Clear the whole content of the dictionary */ StringDictionary.prototype.clear = function () { this._data = {}; this._count = 0; }; Object.defineProperty(StringDictionary.prototype, "count", { get: function () { return this._count; }, enumerable: true, configurable: true }); /** * Execute a callback on each key/val of the dictionary. * Note that you can remove any element in this dictionary in the callback implementation * @param callback the callback to execute on a given key/value pair */ StringDictionary.prototype.forEach = function (callback) { for (var cur in this._data) { var val = this._data[cur]; callback(cur, val); } }; /** * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object. * If the callback returns null or undefined the method will iterate to the next key/value pair * Note that you can remove any element in this dictionary in the callback implementation * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned */ StringDictionary.prototype.first = function (callback) { for (var cur in this._data) { var val = this._data[cur]; var res = callback(cur, val); if (res) { return res; } } return null; }; return StringDictionary; }()); BABYLON.StringDictionary = StringDictionary; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.stringDictionary.js.map var BABYLON; (function (BABYLON) { var Tags = /** @class */ (function () { function Tags() { } Tags.EnableFor = function (obj) { obj._tags = obj._tags || {}; obj.hasTags = function () { return Tags.HasTags(obj); }; obj.addTags = function (tagsString) { return Tags.AddTagsTo(obj, tagsString); }; obj.removeTags = function (tagsString) { return Tags.RemoveTagsFrom(obj, tagsString); }; obj.matchesTagsQuery = function (tagsQuery) { return Tags.MatchesQuery(obj, tagsQuery); }; }; Tags.DisableFor = function (obj) { delete obj._tags; delete obj.hasTags; delete obj.addTags; delete obj.removeTags; delete obj.matchesTagsQuery; }; Tags.HasTags = function (obj) { if (!obj._tags) { return false; } return !BABYLON.Tools.IsEmpty(obj._tags); }; Tags.GetTags = function (obj, asString) { if (asString === void 0) { asString = true; } if (!obj._tags) { return null; } if (asString) { var tagsArray = []; for (var tag in obj._tags) { if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) { tagsArray.push(tag); } } return tagsArray.join(" "); } else { return obj._tags; } }; // the tags 'true' and 'false' are reserved and cannot be used as tags // a tag cannot start with '||', '&&', and '!' // it cannot contain whitespaces Tags.AddTagsTo = function (obj, tagsString) { if (!tagsString) { return; } if (typeof tagsString !== "string") { return; } var tags = tagsString.split(" "); tags.forEach(function (tag, index, array) { Tags._AddTagTo(obj, tag); }); }; Tags._AddTagTo = function (obj, tag) { tag = tag.trim(); if (tag === "" || tag === "true" || tag === "false") { return; } if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) { return; } Tags.EnableFor(obj); obj._tags[tag] = true; }; Tags.RemoveTagsFrom = function (obj, tagsString) { if (!Tags.HasTags(obj)) { return; } var tags = tagsString.split(" "); for (var t in tags) { Tags._RemoveTagFrom(obj, tags[t]); } }; Tags._RemoveTagFrom = function (obj, tag) { delete obj._tags[tag]; }; Tags.MatchesQuery = function (obj, tagsQuery) { if (tagsQuery === undefined) { return true; } if (tagsQuery === "") { return Tags.HasTags(obj); } return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; }); }; return Tags; }()); BABYLON.Tags = Tags; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.tags.js.map var BABYLON; (function (BABYLON) { var Internals; (function (Internals) { var AndOrNotEvaluator = /** @class */ (function () { function AndOrNotEvaluator() { } AndOrNotEvaluator.Eval = function (query, evaluateCallback) { if (!query.match(/\([^\(\)]*\)/g)) { query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback); } else { query = query.replace(/\([^\(\)]*\)/g, function (r) { // remove parenthesis r = r.slice(1, r.length - 1); return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback); }); } if (query === "true") { return true; } if (query === "false") { return false; } return AndOrNotEvaluator.Eval(query, evaluateCallback); }; AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) { evaluateCallback = evaluateCallback || (function (r) { return r === "true" ? true : false; }); var result; var or = parenthesisContent.split("||"); for (var i in or) { if (or.hasOwnProperty(i)) { var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim()); var and = ori.split("&&"); if (and.length > 1) { for (var j = 0; j < and.length; ++j) { var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim()); if (andj !== "true" && andj !== "false") { if (andj[0] === "!") { result = !evaluateCallback(andj.substring(1)); } else { result = evaluateCallback(andj); } } else { result = andj === "true" ? true : false; } if (!result) { ori = "false"; break; } } } if (result || ori === "true") { result = true; break; } // result equals false (or undefined) if (ori !== "true" && ori !== "false") { if (ori[0] === "!") { result = !evaluateCallback(ori.substring(1)); } else { result = evaluateCallback(ori); } } else { result = ori === "true" ? true : false; } } } // the whole parenthesis scope is replaced by 'true' or 'false' return result ? "true" : "false"; }; AndOrNotEvaluator._SimplifyNegation = function (booleanString) { booleanString = booleanString.replace(/^[\s!]+/, function (r) { // remove whitespaces r = r.replace(/[\s]/g, function () { return ""; }); return r.length % 2 ? "!" : ""; }); booleanString = booleanString.trim(); if (booleanString === "!true") { booleanString = "false"; } else if (booleanString === "!false") { booleanString = "true"; } return booleanString; }; return AndOrNotEvaluator; }()); Internals.AndOrNotEvaluator = AndOrNotEvaluator; })(Internals = BABYLON.Internals || (BABYLON.Internals = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.andOrNotEvaluator.js.map var BABYLON; (function (BABYLON) { var Database = /** @class */ (function () { function Database(urlToScene, callbackManifestChecked) { // Handling various flavors of prefixed version of IndexedDB this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB); this.callbackManifestChecked = callbackManifestChecked; this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene); this.db = null; this._enableSceneOffline = false; this._enableTexturesOffline = false; this.manifestVersionFound = 0; this.mustUpdateRessources = false; this.hasReachedQuota = false; if (!Database.IDBStorageEnabled) { this.callbackManifestChecked(true); } else { this.checkManifestFile(); } } Object.defineProperty(Database.prototype, "enableSceneOffline", { get: function () { return this._enableSceneOffline; }, enumerable: true, configurable: true }); Object.defineProperty(Database.prototype, "enableTexturesOffline", { get: function () { return this._enableTexturesOffline; }, enumerable: true, configurable: true }); Database.prototype.checkManifestFile = function () { var _this = this; var noManifestFile = function () { _this._enableSceneOffline = false; _this._enableTexturesOffline = false; _this.callbackManifestChecked(false); }; var timeStampUsed = false; var manifestURL = this.currentSceneUrl + ".manifest"; var xhr = new XMLHttpRequest(); if (navigator.onLine) { // Adding a timestamp to by-pass browsers' cache timeStampUsed = true; manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime(); } xhr.open("GET", manifestURL, true); xhr.addEventListener("load", function () { if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) { try { var manifestFile = JSON.parse(xhr.response); _this._enableSceneOffline = manifestFile.enableSceneOffline; _this._enableTexturesOffline = manifestFile.enableTexturesOffline; if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) { _this.manifestVersionFound = manifestFile.version; } if (_this.callbackManifestChecked) { _this.callbackManifestChecked(true); } } catch (ex) { noManifestFile(); } } else { noManifestFile(); } }, false); xhr.addEventListener("error", function (event) { if (timeStampUsed) { timeStampUsed = false; // Let's retry without the timeStamp // It could fail when coupled with HTML5 Offline API var retryManifestURL = _this.currentSceneUrl + ".manifest"; xhr.open("GET", retryManifestURL, true); xhr.send(); } else { noManifestFile(); } }, false); try { xhr.send(); } catch (ex) { BABYLON.Tools.Error("Error on XHR send request."); this.callbackManifestChecked(false); } }; Database.prototype.openAsync = function (successCallback, errorCallback) { var _this = this; function handleError() { that.isSupported = false; if (errorCallback) errorCallback(); } var that = this; if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) { // Your browser doesn't support IndexedDB this.isSupported = false; if (errorCallback) errorCallback(); } else { // If the DB hasn't been opened or created yet if (!this.db) { this.hasReachedQuota = false; this.isSupported = true; var request = this.idbFactory.open("babylonjs", 1); // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB request.onerror = function (event) { handleError(); }; // executes when a version change transaction cannot complete due to other active transactions request.onblocked = function (event) { BABYLON.Tools.Error("IDB request blocked. Please reload the page."); handleError(); }; // DB has been opened successfully request.onsuccess = function (event) { _this.db = request.result; successCallback(); }; // Initialization of the DB. Creating Scenes & Textures stores request.onupgradeneeded = function (event) { _this.db = (event.target).result; if (_this.db) { try { _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" }); _this.db.createObjectStore("versions", { keyPath: "sceneUrl" }); _this.db.createObjectStore("textures", { keyPath: "textureUrl" }); } catch (ex) { BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message); handleError(); } } }; } else { if (successCallback) successCallback(); } } }; Database.prototype.loadImageFromDB = function (url, image) { var _this = this; var completeURL = Database.ReturnFullUrlLocation(url); var saveAndLoadImage = function () { if (!_this.hasReachedQuota && _this.db !== null) { // the texture is not yet in the DB, let's try to save it _this._saveImageIntoDBAsync(completeURL, image); } else { image.src = url; } }; if (!this.mustUpdateRessources) { this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage); } else { saveAndLoadImage(); } }; Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) { if (this.isSupported && this.db !== null) { var texture; var transaction = this.db.transaction(["textures"]); transaction.onabort = function (event) { image.src = url; }; transaction.oncomplete = function (event) { var blobTextureURL; if (texture) { var URL = window.URL || window.webkitURL; blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true }); image.onerror = function () { BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url); image.src = url; }; image.src = blobTextureURL; } else { notInDBCallback(); } }; var getRequest = transaction.objectStore("textures").get(url); getRequest.onsuccess = function (event) { texture = (event.target).result; }; getRequest.onerror = function (event) { BABYLON.Tools.Error("Error loading texture " + url + " from DB."); image.src = url; }; } else { BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."); image.src = url; } }; Database.prototype._saveImageIntoDBAsync = function (url, image) { var _this = this; if (this.isSupported) { // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on var generateBlobUrl = function () { var blobTextureURL; if (blob) { var URL = window.URL || window.webkitURL; try { blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true }); } // Chrome is raising a type error if we're setting the oneTimeOnly parameter catch (ex) { blobTextureURL = URL.createObjectURL(blob); } } if (blobTextureURL) { image.src = blobTextureURL; } }; if (Database.IsUASupportingBlobStorage) { var xhr = new XMLHttpRequest(), blob; xhr.open("GET", url, true); xhr.responseType = "blob"; xhr.addEventListener("load", function () { if (xhr.status === 200 && _this.db) { // Blob as response (XHR2) blob = xhr.response; var transaction = _this.db.transaction(["textures"], "readwrite"); // the transaction could abort because of a QuotaExceededError error transaction.onabort = function (event) { try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3 var srcElement = (event.srcElement || event.target); var error = srcElement.error; if (error && error.name === "QuotaExceededError") { _this.hasReachedQuota = true; } } catch (ex) { } generateBlobUrl(); }; transaction.oncomplete = function (event) { generateBlobUrl(); }; var newTexture = { textureUrl: url, data: blob }; try { // Put the blob into the dabase var addRequest = transaction.objectStore("textures").put(newTexture); addRequest.onsuccess = function (event) { }; addRequest.onerror = function (event) { generateBlobUrl(); }; } catch (ex) { // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB if (ex.code === 25) { Database.IsUASupportingBlobStorage = false; } image.src = url; } } else { image.src = url; } }, false); xhr.addEventListener("error", function (event) { BABYLON.Tools.Error("Error in XHR request in BABYLON.Database."); image.src = url; }, false); xhr.send(); } else { image.src = url; } } else { BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."); image.src = url; } }; Database.prototype._checkVersionFromDB = function (url, versionLoaded) { var _this = this; var updateVersion = function () { // the version is not yet in the DB or we need to update it _this._saveVersionIntoDBAsync(url, versionLoaded); }; this._loadVersionFromDBAsync(url, versionLoaded, updateVersion); }; Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) { var _this = this; if (this.isSupported && this.db) { var version; try { var transaction = this.db.transaction(["versions"]); transaction.oncomplete = function (event) { if (version) { // If the version in the JSON file is > than the version in DB if (_this.manifestVersionFound > version.data) { _this.mustUpdateRessources = true; updateInDBCallback(); } else { callback(version.data); } } else { _this.mustUpdateRessources = true; updateInDBCallback(); } }; transaction.onabort = function (event) { callback(-1); }; var getRequest = transaction.objectStore("versions").get(url); getRequest.onsuccess = function (event) { version = (event.target).result; }; getRequest.onerror = function (event) { BABYLON.Tools.Error("Error loading version for scene " + url + " from DB."); callback(-1); }; } catch (ex) { BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message); callback(-1); } } else { BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."); callback(-1); } }; Database.prototype._saveVersionIntoDBAsync = function (url, callback) { var _this = this; if (this.isSupported && !this.hasReachedQuota && this.db) { try { // Open a transaction to the database var transaction = this.db.transaction(["versions"], "readwrite"); // the transaction could abort because of a QuotaExceededError error transaction.onabort = function (event) { try { var error = event.srcElement['error']; if (error && error.name === "QuotaExceededError") { _this.hasReachedQuota = true; } } catch (ex) { } callback(-1); }; transaction.oncomplete = function (event) { callback(_this.manifestVersionFound); }; var newVersion = { sceneUrl: url, data: this.manifestVersionFound }; // Put the scene into the database var addRequest = transaction.objectStore("versions").put(newVersion); addRequest.onsuccess = function (event) { }; addRequest.onerror = function (event) { BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database."); }; } catch (ex) { BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message); callback(-1); } } else { callback(-1); } }; Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) { var _this = this; var completeUrl = Database.ReturnFullUrlLocation(url); var saveAndLoadFile = function () { // the scene is not yet in the DB, let's try to save it _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack); }; this._checkVersionFromDB(completeUrl, function (version) { if (version !== -1) { if (!_this.mustUpdateRessources) { _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer); } else { _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer); } } else { if (errorCallback) { errorCallback(); } } }); }; Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) { if (this.isSupported && this.db) { var targetStore; if (url.indexOf(".babylon") !== -1) { targetStore = "scenes"; } else { targetStore = "textures"; } var file; var transaction = this.db.transaction([targetStore]); transaction.oncomplete = function (event) { if (file) { callback(file.data); } else { notInDBCallback(); } }; transaction.onabort = function (event) { notInDBCallback(); }; var getRequest = transaction.objectStore(targetStore).get(url); getRequest.onsuccess = function (event) { file = (event.target).result; }; getRequest.onerror = function (event) { BABYLON.Tools.Error("Error loading file " + url + " from DB."); notInDBCallback(); }; } else { BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."); callback(); } }; Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) { var _this = this; if (this.isSupported) { var targetStore; if (url.indexOf(".babylon") !== -1) { targetStore = "scenes"; } else { targetStore = "textures"; } // Create XHR var xhr = new XMLHttpRequest(); var fileData; xhr.open("GET", url, true); if (useArrayBuffer) { xhr.responseType = "arraybuffer"; } if (progressCallback) { xhr.onprogress = progressCallback; } xhr.addEventListener("load", function () { if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) { // Blob as response (XHR2) //fileData = xhr.responseText; fileData = !useArrayBuffer ? xhr.responseText : xhr.response; if (!_this.hasReachedQuota && _this.db) { // Open a transaction to the database var transaction = _this.db.transaction([targetStore], "readwrite"); // the transaction could abort because of a QuotaExceededError error transaction.onabort = function (event) { try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3 var error = event.srcElement['error']; if (error && error.name === "QuotaExceededError") { _this.hasReachedQuota = true; } } catch (ex) { } callback(fileData); }; transaction.oncomplete = function (event) { callback(fileData); }; var newFile; if (targetStore === "scenes") { newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound }; } else { newFile = { textureUrl: url, data: fileData }; } try { // Put the scene into the database var addRequest = transaction.objectStore(targetStore).put(newFile); addRequest.onsuccess = function (event) { }; addRequest.onerror = function (event) { BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database."); }; } catch (ex) { callback(fileData); } } else { callback(fileData); } } else { callback(); } }, false); xhr.addEventListener("error", function (event) { BABYLON.Tools.Error("error on XHR request."); callback(); }, false); xhr.send(); } else { BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."); callback(); } }; Database.IsUASupportingBlobStorage = true; Database.IDBStorageEnabled = true; Database.parseURL = function (url) { var a = document.createElement('a'); a.href = url; var urlWithoutHash = url.substring(0, url.lastIndexOf("#")); var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length); var absLocation = url.substring(0, url.indexOf(fileName, 0)); return absLocation; }; Database.ReturnFullUrlLocation = function (url) { if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) { return (Database.parseURL(window.location.href) + url); } else { return url; } }; return Database; }()); BABYLON.Database = Database; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.database.js.map var BABYLON; (function (BABYLON) { var FresnelParameters = /** @class */ (function () { function FresnelParameters() { this._isEnabled = true; this.leftColor = BABYLON.Color3.White(); this.rightColor = BABYLON.Color3.Black(); this.bias = 0; this.power = 1; } Object.defineProperty(FresnelParameters.prototype, "isEnabled", { get: function () { return this._isEnabled; }, set: function (value) { if (this._isEnabled === value) { return; } this._isEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag); }, enumerable: true, configurable: true }); FresnelParameters.prototype.clone = function () { var newFresnelParameters = new FresnelParameters(); BABYLON.Tools.DeepCopy(this, newFresnelParameters); return newFresnelParameters; }; FresnelParameters.prototype.serialize = function () { var serializationObject = {}; serializationObject.isEnabled = this.isEnabled; serializationObject.leftColor = this.leftColor; serializationObject.rightColor = this.rightColor; serializationObject.bias = this.bias; serializationObject.power = this.power; return serializationObject; }; FresnelParameters.Parse = function (parsedFresnelParameters) { var fresnelParameters = new FresnelParameters(); fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled; fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor); fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor); fresnelParameters.bias = parsedFresnelParameters.bias; fresnelParameters.power = parsedFresnelParameters.power || 1.0; return fresnelParameters; }; return FresnelParameters; }()); BABYLON.FresnelParameters = FresnelParameters; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.fresnelParameters.js.map var BABYLON; (function (BABYLON) { var MultiMaterial = /** @class */ (function (_super) { __extends(MultiMaterial, _super); function MultiMaterial(name, scene) { var _this = _super.call(this, name, scene, true) || this; scene.multiMaterials.push(_this); _this.subMaterials = new Array(); _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material return _this; } Object.defineProperty(MultiMaterial.prototype, "subMaterials", { get: function () { return this._subMaterials; }, set: function (value) { this._subMaterials = value; this._hookArray(value); }, enumerable: true, configurable: true }); MultiMaterial.prototype._hookArray = 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._markAllSubMeshesAsTexturesDirty(); return result; }; var oldSplice = array.splice; array.splice = function (index, deleteCount) { var deleted = oldSplice.apply(array, [index, deleteCount]); _this._markAllSubMeshesAsTexturesDirty(); return deleted; }; }; // Properties MultiMaterial.prototype.getSubMaterial = function (index) { if (index < 0 || index >= this.subMaterials.length) { return this.getScene().defaultMaterial; } return this.subMaterials[index]; }; MultiMaterial.prototype.getActiveTextures = function () { return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { if (subMaterial) { return subMaterial.getActiveTextures(); } else { return []; } })); var _a; }; // Methods MultiMaterial.prototype.getClassName = function () { return "MultiMaterial"; }; MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { for (var index = 0; index < this.subMaterials.length; index++) { var subMaterial = this.subMaterials[index]; if (subMaterial) { if (subMaterial.storeEffectOnSubMeshes) { if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) { return false; } continue; } if (!subMaterial.isReady(mesh)) { return false; } } } return true; }; MultiMaterial.prototype.clone = function (name, cloneChildren) { var newMultiMaterial = new MultiMaterial(name, this.getScene()); for (var index = 0; index < this.subMaterials.length; index++) { var subMaterial = null; var current = this.subMaterials[index]; if (cloneChildren && current) { subMaterial = current.clone(name + "-" + current.name); } else { subMaterial = this.subMaterials[index]; } newMultiMaterial.subMaterials.push(subMaterial); } return newMultiMaterial; }; MultiMaterial.prototype.serialize = function () { var serializationObject = {}; serializationObject.name = this.name; serializationObject.id = this.id; serializationObject.tags = BABYLON.Tags.GetTags(this); serializationObject.materials = []; for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) { var subMat = this.subMaterials[matIndex]; if (subMat) { serializationObject.materials.push(subMat.id); } else { serializationObject.materials.push(null); } } return serializationObject; }; MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) { var scene = this.getScene(); if (!scene) { return; } var index = scene.multiMaterials.indexOf(this); if (index >= 0) { scene.multiMaterials.splice(index, 1); } _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures); }; return MultiMaterial; }(BABYLON.Material)); BABYLON.MultiMaterial = MultiMaterial; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.multiMaterial.js.map var BABYLON; (function (BABYLON) { var FreeCameraTouchInput = /** @class */ (function () { function FreeCameraTouchInput() { this._offsetX = null; this._offsetY = null; this._pointerCount = 0; this._pointerPressed = new Array(); this.touchAngularSensibility = 200000.0; this.touchMoveSensibility = 250.0; } FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var previousPosition = null; if (this._pointerInput === undefined) { this._onLostFocus = function (evt) { _this._offsetX = null; _this._offsetY = null; }; this._pointerInput = function (p, s) { var evt = p.event; if (evt.pointerType === "mouse") { return; } if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) { if (!noPreventDefault) { evt.preventDefault(); } _this._pointerPressed.push(evt.pointerId); if (_this._pointerPressed.length !== 1) { return; } previousPosition = { x: evt.clientX, y: evt.clientY }; } else if (p.type === BABYLON.PointerEventTypes.POINTERUP) { if (!noPreventDefault) { evt.preventDefault(); } var index = _this._pointerPressed.indexOf(evt.pointerId); if (index === -1) { return; } _this._pointerPressed.splice(index, 1); if (index != 0) { return; } previousPosition = null; _this._offsetX = null; _this._offsetY = null; } else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) { if (!noPreventDefault) { evt.preventDefault(); } if (!previousPosition) { return; } var index = _this._pointerPressed.indexOf(evt.pointerId); if (index != 0) { return; } _this._offsetX = evt.clientX - previousPosition.x; _this._offsetY = -(evt.clientY - previousPosition.y); } }; } this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE); if (this._onLostFocus) { element.addEventListener("blur", this._onLostFocus); } }; FreeCameraTouchInput.prototype.detachControl = function (element) { if (this._pointerInput && element) { if (this._observer) { this.camera.getScene().onPointerObservable.remove(this._observer); this._observer = null; } if (this._onLostFocus) { element.removeEventListener("blur", this._onLostFocus); this._onLostFocus = null; } this._pointerPressed = []; this._offsetX = null; this._offsetY = null; this._pointerCount = 0; } }; FreeCameraTouchInput.prototype.checkInputs = function () { if (this._offsetX && this._offsetY) { var camera = this.camera; camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility; if (this._pointerPressed.length > 1) { camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility; } else { var speed = camera._computeLocalCameraSpeed(); var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility); BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix); camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix)); } } }; FreeCameraTouchInput.prototype.getClassName = function () { return "FreeCameraTouchInput"; }; FreeCameraTouchInput.prototype.getSimpleName = function () { return "touch"; }; __decorate([ BABYLON.serialize() ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0); __decorate([ BABYLON.serialize() ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0); return FreeCameraTouchInput; }()); BABYLON.FreeCameraTouchInput = FreeCameraTouchInput; BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.freeCameraTouchInput.js.map /// var BABYLON; (function (BABYLON) { // We're mainly based on the logic defined into the FreeCamera code var TouchCamera = /** @class */ (function (_super) { __extends(TouchCamera, _super); //-- end properties for backward compatibility for inputs function TouchCamera(name, position, scene) { var _this = _super.call(this, name, position, scene) || this; _this.inputs.addTouch(); _this._setupInputs(); return _this; } Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", { //-- Begin properties for backward compatibility for inputs get: function () { var touch = this.inputs.attached["touch"]; if (touch) return touch.touchAngularSensibility; return 0; }, set: function (value) { var touch = this.inputs.attached["touch"]; if (touch) touch.touchAngularSensibility = value; }, enumerable: true, configurable: true }); Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", { get: function () { var touch = this.inputs.attached["touch"]; if (touch) return touch.touchMoveSensibility; return 0; }, set: function (value) { var touch = this.inputs.attached["touch"]; if (touch) touch.touchMoveSensibility = value; }, enumerable: true, configurable: true }); TouchCamera.prototype.getClassName = function () { return "TouchCamera"; }; TouchCamera.prototype._setupInputs = function () { var mouse = this.inputs.attached["mouse"]; if (mouse) { mouse.touchEnabled = false; } }; return TouchCamera; }(BABYLON.FreeCamera)); BABYLON.TouchCamera = TouchCamera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.touchCamera.js.map var BABYLON; (function (BABYLON) { var ProceduralTexture = /** @class */ (function (_super) { __extends(ProceduralTexture, _super); function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) { if (fallbackTexture === void 0) { fallbackTexture = null; } if (generateMipMaps === void 0) { generateMipMaps = true; } if (isCube === void 0) { isCube = false; } var _this = _super.call(this, null, scene, !generateMipMaps) || this; _this.isCube = isCube; _this.isEnabled = true; _this._currentRefreshId = -1; _this._refreshRate = 1; _this._vertexBuffers = {}; _this._uniforms = new Array(); _this._samplers = new Array(); _this._textures = {}; _this._floats = {}; _this._floatsArrays = {}; _this._colors3 = {}; _this._colors4 = {}; _this._vectors2 = {}; _this._vectors3 = {}; _this._matrices = {}; _this._fallbackTextureUsed = false; scene._proceduralTextures.push(_this); _this._engine = scene.getEngine(); _this.name = name; _this.isRenderTarget = true; _this._size = size; _this._generateMipMaps = generateMipMaps; _this.setFragment(fragment); _this._fallbackTexture = fallbackTexture; if (isCube) { _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps }); _this.setFloat("face", 0); } else { _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps); } // 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._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2); _this._createIndexBuffer(); return _this; } ProceduralTexture.prototype._createIndexBuffer = function () { var engine = this._engine; // Indices var indices = []; indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); this._indexBuffer = engine.createIndexBuffer(indices); }; ProceduralTexture.prototype._rebuild = function () { var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]; if (vb) { vb._rebuild(); } this._createIndexBuffer(); if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) { this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE; } }; ProceduralTexture.prototype.reset = function () { if (this._effect === undefined) { return; } var engine = this._engine; engine._releaseEffect(this._effect); }; ProceduralTexture.prototype.isReady = function () { var _this = this; var engine = this._engine; var shaders; if (!this._fragment) { return false; } if (this._fallbackTextureUsed) { return true; } if (this._fragment.fragmentElement !== undefined) { shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement }; } else { shaders = { vertex: "procedural", fragment: this._fragment }; } this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () { _this.releaseInternalTexture(); if (_this._fallbackTexture) { _this._texture = _this._fallbackTexture._texture; if (_this._texture) { _this._texture.incrementReferences(); } } _this._fallbackTextureUsed = true; }); return this._effect.isReady(); }; ProceduralTexture.prototype.resetRefreshCounter = function () { this._currentRefreshId = -1; }; ProceduralTexture.prototype.setFragment = function (fragment) { this._fragment = fragment; }; Object.defineProperty(ProceduralTexture.prototype, "refreshRate", { get: function () { return this._refreshRate; }, // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on... set: function (value) { this._refreshRate = value; this.resetRefreshCounter(); }, enumerable: true, configurable: true }); ProceduralTexture.prototype._shouldRender = function () { if (!this.isEnabled || !this.isReady() || !this._texture) { return false; } if (this._fallbackTextureUsed) { return false; } if (this._currentRefreshId === -1) { this._currentRefreshId = 1; return true; } if (this.refreshRate === this._currentRefreshId) { this._currentRefreshId = 1; return true; } this._currentRefreshId++; return false; }; ProceduralTexture.prototype.getRenderSize = function () { return this._size; }; ProceduralTexture.prototype.resize = function (size, generateMipMaps) { if (this._fallbackTextureUsed) { return; } this.releaseInternalTexture(); this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps); }; ProceduralTexture.prototype._checkUniform = function (uniformName) { if (this._uniforms.indexOf(uniformName) === -1) { this._uniforms.push(uniformName); } }; ProceduralTexture.prototype.setTexture = function (name, texture) { if (this._samplers.indexOf(name) === -1) { this._samplers.push(name); } this._textures[name] = texture; return this; }; ProceduralTexture.prototype.setFloat = function (name, value) { this._checkUniform(name); this._floats[name] = value; return this; }; ProceduralTexture.prototype.setFloats = function (name, value) { this._checkUniform(name); this._floatsArrays[name] = value; return this; }; ProceduralTexture.prototype.setColor3 = function (name, value) { this._checkUniform(name); this._colors3[name] = value; return this; }; ProceduralTexture.prototype.setColor4 = function (name, value) { this._checkUniform(name); this._colors4[name] = value; return this; }; ProceduralTexture.prototype.setVector2 = function (name, value) { this._checkUniform(name); this._vectors2[name] = value; return this; }; ProceduralTexture.prototype.setVector3 = function (name, value) { this._checkUniform(name); this._vectors3[name] = value; return this; }; ProceduralTexture.prototype.setMatrix = function (name, value) { this._checkUniform(name); this._matrices[name] = value; return this; }; ProceduralTexture.prototype.render = function (useCameraPostProcess) { var scene = this.getScene(); if (!scene) { return; } var engine = this._engine; // Render engine.enableEffect(this._effect); engine.setState(false); // Texture for (var name in this._textures) { this._effect.setTexture(name, this._textures[name]); } // Float for (name in this._floats) { this._effect.setFloat(name, this._floats[name]); } // Floats for (name in this._floatsArrays) { this._effect.setArray(name, this._floatsArrays[name]); } // Color3 for (name in this._colors3) { this._effect.setColor3(name, this._colors3[name]); } // Color4 for (name in this._colors4) { var color = this._colors4[name]; this._effect.setFloat4(name, color.r, color.g, color.b, color.a); } // Vector2 for (name in this._vectors2) { this._effect.setVector2(name, this._vectors2[name]); } // Vector3 for (name in this._vectors3) { this._effect.setVector3(name, this._vectors3[name]); } // Matrix for (name in this._matrices) { this._effect.setMatrix(name, this._matrices[name]); } if (!this._texture) { return; } if (this.isCube) { for (var face = 0; face < 6; face++) { engine.bindFramebuffer(this._texture, face, undefined, undefined, true); // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect); this._effect.setFloat("face", face); // Clear engine.clear(scene.clearColor, true, true, true); // Draw order engine.draw(true, 0, 6); // Mipmaps if (face === 5) { engine.generateMipMapsForCubemap(this._texture); } } } else { engine.bindFramebuffer(this._texture, 0, undefined, undefined, true); // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect); // Clear engine.clear(scene.clearColor, true, true, true); // Draw order engine.draw(true, 0, 6); } // Unbind engine.unBindFramebuffer(this._texture, this.isCube); if (this.onGenerated) { this.onGenerated(); } }; ProceduralTexture.prototype.clone = function () { var textureSize = this.getSize(); var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps); // Base texture newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; // RenderTarget Texture newTexture.coordinatesMode = this.coordinatesMode; return newTexture; }; ProceduralTexture.prototype.dispose = function () { var scene = this.getScene(); if (!scene) { return; } var index = scene._proceduralTextures.indexOf(this); if (index >= 0) { scene._proceduralTextures.splice(index, 1); } var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]; if (vertexBuffer) { vertexBuffer.dispose(); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null; } if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) { this._indexBuffer = null; } _super.prototype.dispose.call(this); }; return ProceduralTexture; }(BABYLON.Texture)); BABYLON.ProceduralTexture = ProceduralTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.proceduralTexture.js.map /// var BABYLON; (function (BABYLON) { var CustomProceduralTexture = /** @class */ (function (_super) { __extends(CustomProceduralTexture, _super); function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) { var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this; _this._animate = true; _this._time = 0; _this._texturePath = texturePath; //Try to load json _this.loadJson(texturePath); _this.refreshRate = 1; return _this; } CustomProceduralTexture.prototype.loadJson = function (jsonUrl) { var _this = this; var that = this; function noConfigFile() { BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element"); try { that.setFragment(that._texturePath); } catch (ex) { BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture"); } } var configFileUrl = jsonUrl + "/config.json"; var xhr = new XMLHttpRequest(); xhr.open("GET", configFileUrl, true); xhr.addEventListener("load", function () { if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) { try { _this._config = JSON.parse(xhr.response); _this.updateShaderUniforms(); _this.updateTextures(); _this.setFragment(_this._texturePath + "/custom"); _this._animate = _this._config.animate; _this.refreshRate = _this._config.refreshrate; } catch (ex) { noConfigFile(); } } else { noConfigFile(); } }, false); xhr.addEventListener("error", function () { noConfigFile(); }, false); try { xhr.send(); } catch (ex) { BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request."); } }; CustomProceduralTexture.prototype.isReady = function () { if (!_super.prototype.isReady.call(this)) { return false; } for (var name in this._textures) { var texture = this._textures[name]; if (!texture.isReady()) { return false; } } return true; }; CustomProceduralTexture.prototype.render = function (useCameraPostProcess) { var scene = this.getScene(); if (this._animate && scene) { this._time += scene.getAnimationRatio() * 0.03; this.updateShaderUniforms(); } _super.prototype.render.call(this, useCameraPostProcess); }; CustomProceduralTexture.prototype.updateTextures = function () { for (var i = 0; i < this._config.sampler2Ds.length; i++) { this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene())); } }; CustomProceduralTexture.prototype.updateShaderUniforms = function () { if (this._config) { for (var j = 0; j < this._config.uniforms.length; j++) { var uniform = this._config.uniforms[j]; switch (uniform.type) { case "float": this.setFloat(uniform.name, uniform.value); break; case "color3": this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b)); break; case "color4": this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a)); break; case "vector2": this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y)); break; case "vector3": this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z)); break; } } } this.setFloat("time", this._time); }; Object.defineProperty(CustomProceduralTexture.prototype, "animate", { get: function () { return this._animate; }, set: function (value) { this._animate = value; }, enumerable: true, configurable: true }); return CustomProceduralTexture; }(BABYLON.ProceduralTexture)); BABYLON.CustomProceduralTexture = CustomProceduralTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.customProceduralTexture.js.map var BABYLON; (function (BABYLON) { var FreeCameraGamepadInput = /** @class */ (function () { function FreeCameraGamepadInput() { this.gamepadAngularSensibility = 200; this.gamepadMoveSensibility = 40; // private members this._cameraTransform = BABYLON.Matrix.Identity(); this._deltaTransform = BABYLON.Vector3.Zero(); this._vector3 = BABYLON.Vector3.Zero(); this._vector2 = BABYLON.Vector2.Zero(); } FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var manager = this.camera.getScene().gamepadManager; this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) { if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) { // prioritize XBOX gamepads. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) { _this.gamepad = gamepad; } } }); this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) { if (_this.gamepad === gamepad) { _this.gamepad = null; } }); this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX); }; FreeCameraGamepadInput.prototype.detachControl = function (element) { this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); this.gamepad = null; }; FreeCameraGamepadInput.prototype.checkInputs = function () { if (this.gamepad && this.gamepad.leftStick) { var camera = this.camera; var LSValues = this.gamepad.leftStick; var normalizedLX = LSValues.x / this.gamepadMoveSensibility; var normalizedLY = LSValues.y / this.gamepadMoveSensibility; LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0; LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0; var RSValues = this.gamepad.rightStick; if (RSValues) { var normalizedRX = RSValues.x / this.gamepadAngularSensibility; var normalizedRY = RSValues.y / this.gamepadAngularSensibility; RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0; RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0; } else { RSValues = { x: 0, y: 0 }; } if (!camera.rotationQuaternion) { BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform); } else { camera.rotationQuaternion.toRotationMatrix(this._cameraTransform); } var speed = camera._computeLocalCameraSpeed() * 50.0; this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed); BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform); camera.cameraDirection.addInPlace(this._deltaTransform); this._vector2.copyFromFloats(RSValues.y, RSValues.x); camera.cameraRotation.addInPlace(this._vector2); } }; FreeCameraGamepadInput.prototype.getClassName = function () { return "FreeCameraGamepadInput"; }; FreeCameraGamepadInput.prototype.getSimpleName = function () { return "gamepad"; }; __decorate([ BABYLON.serialize() ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0); __decorate([ BABYLON.serialize() ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); return FreeCameraGamepadInput; }()); BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput; BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map var BABYLON; (function (BABYLON) { var ArcRotateCameraGamepadInput = /** @class */ (function () { function ArcRotateCameraGamepadInput() { this.gamepadRotationSensibility = 80; this.gamepadMoveSensibility = 40; } ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var manager = this.camera.getScene().gamepadManager; this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) { if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) { // prioritize XBOX gamepads. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) { _this.gamepad = gamepad; } } }); this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) { if (_this.gamepad === gamepad) { _this.gamepad = null; } }); this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX); }; ArcRotateCameraGamepadInput.prototype.detachControl = function (element) { this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); this.gamepad = null; }; ArcRotateCameraGamepadInput.prototype.checkInputs = function () { if (this.gamepad) { var camera = this.camera; var RSValues = this.gamepad.rightStick; if (RSValues) { if (RSValues.x != 0) { var normalizedRX = RSValues.x / this.gamepadRotationSensibility; if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) { camera.inertialAlphaOffset += normalizedRX; } } if (RSValues.y != 0) { var normalizedRY = RSValues.y / this.gamepadRotationSensibility; if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) { camera.inertialBetaOffset += normalizedRY; } } } var LSValues = this.gamepad.leftStick; if (LSValues && LSValues.y != 0) { var normalizedLY = LSValues.y / this.gamepadMoveSensibility; if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) { this.camera.inertialRadiusOffset -= normalizedLY; } } } }; ArcRotateCameraGamepadInput.prototype.getClassName = function () { return "ArcRotateCameraGamepadInput"; }; ArcRotateCameraGamepadInput.prototype.getSimpleName = function () { return "gamepad"; }; __decorate([ BABYLON.serialize() ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0); __decorate([ BABYLON.serialize() ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); return ArcRotateCameraGamepadInput; }()); BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput; BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map var BABYLON; (function (BABYLON) { var GamepadManager = /** @class */ (function () { function GamepadManager() { var _this = this; this._babylonGamepads = []; this._oneGamepadConnected = false; this._isMonitoring = false; this.onGamepadDisconnectedObservable = new BABYLON.Observable(); if (!BABYLON.Tools.IsWindowObjectExist()) { this._gamepadEventSupported = false; } else { this._gamepadEventSupported = 'GamepadEvent' in window; this._gamepadSupport = (navigator.getGamepads || navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads); } this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) { // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected for (var i in _this._babylonGamepads) { var gamepad = _this._babylonGamepads[i]; if (gamepad && gamepad._isConnected) { _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad); } } }); this._onGamepadConnectedEvent = function (evt) { var gamepad = evt.gamepad; if (gamepad.index in _this._babylonGamepads) { if (_this._babylonGamepads[gamepad.index].isConnected) { return; } } var newGamepad; if (_this._babylonGamepads[gamepad.index]) { newGamepad = _this._babylonGamepads[gamepad.index]; newGamepad.browserGamepad = gamepad; newGamepad._isConnected = true; } else { newGamepad = _this._addNewGamepad(gamepad); } _this.onGamepadConnectedObservable.notifyObservers(newGamepad); _this._startMonitoringGamepads(); }; this._onGamepadDisconnectedEvent = function (evt) { var gamepad = evt.gamepad; // Remove the gamepad from the list of gamepads to monitor. for (var i in _this._babylonGamepads) { if (_this._babylonGamepads[i].index === gamepad.index) { var disconnectedGamepad = _this._babylonGamepads[i]; disconnectedGamepad._isConnected = false; _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad); break; } } }; if (this._gamepadSupport) { //first add already-connected gamepads this._updateGamepadObjects(); if (this._babylonGamepads.length) { this._startMonitoringGamepads(); } // Checking if the gamepad connected event is supported (like in Firefox) if (this._gamepadEventSupported) { window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false); window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false); } else { this._startMonitoringGamepads(); } } } Object.defineProperty(GamepadManager.prototype, "gamepads", { get: function () { return this._babylonGamepads; }, enumerable: true, configurable: true }); GamepadManager.prototype.getGamepadByType = function (type) { if (type === void 0) { type = BABYLON.Gamepad.XBOX; } for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) { var gamepad = _a[_i]; if (gamepad && gamepad.type === type) { return gamepad; } } return null; }; GamepadManager.prototype.dispose = function () { if (this._gamepadEventSupported) { if (this._onGamepadConnectedEvent) { window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent); } if (this._onGamepadDisconnectedEvent) { window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent); } this._onGamepadConnectedEvent = null; this._onGamepadDisconnectedEvent = null; } this._babylonGamepads.forEach(function (gamepad) { gamepad.dispose(); }); this.onGamepadConnectedObservable.clear(); this.onGamepadDisconnectedObservable.clear(); this._oneGamepadConnected = false; this._stopMonitoringGamepads(); this._babylonGamepads = []; }; GamepadManager.prototype._addNewGamepad = function (gamepad) { if (!this._oneGamepadConnected) { this._oneGamepadConnected = true; } var newGamepad; var xboxOne = (gamepad.id.search("Xbox One") !== -1); if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) { newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne); } else if (gamepad.pose) { newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad); } else { newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad); } this._babylonGamepads[newGamepad.index] = newGamepad; return newGamepad; }; GamepadManager.prototype._startMonitoringGamepads = function () { if (!this._isMonitoring) { this._isMonitoring = true; this._checkGamepadsStatus(); } }; GamepadManager.prototype._stopMonitoringGamepads = function () { this._isMonitoring = false; }; GamepadManager.prototype._checkGamepadsStatus = function () { var _this = this; // Hack to be compatible Chrome this._updateGamepadObjects(); for (var i in this._babylonGamepads) { var gamepad = this._babylonGamepads[i]; if (!gamepad || !gamepad.isConnected) { continue; } gamepad.update(); } if (this._isMonitoring) { BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); }); } }; // This function is called only on Chrome, which does not properly support // connection/disconnection events and forces you to recopy again the gamepad object GamepadManager.prototype._updateGamepadObjects = function () { var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []); for (var i = 0; i < gamepads.length; i++) { if (gamepads[i]) { if (!this._babylonGamepads[gamepads[i].index]) { var newGamepad = this._addNewGamepad(gamepads[i]); this.onGamepadConnectedObservable.notifyObservers(newGamepad); } else { // Forced to copy again this object for Chrome for unknown reason this._babylonGamepads[i].browserGamepad = gamepads[i]; if (!this._babylonGamepads[i].isConnected) { this._babylonGamepads[i]._isConnected = true; this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]); } } } } }; return GamepadManager; }()); BABYLON.GamepadManager = GamepadManager; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.gamepadManager.js.map var BABYLON; (function (BABYLON) { var StickValues = /** @class */ (function () { function StickValues(x, y) { this.x = x; this.y = y; } return StickValues; }()); BABYLON.StickValues = StickValues; var Gamepad = /** @class */ (function () { function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) { if (leftStickX === void 0) { leftStickX = 0; } if (leftStickY === void 0) { leftStickY = 1; } if (rightStickX === void 0) { rightStickX = 2; } if (rightStickY === void 0) { rightStickY = 3; } this.id = id; this.index = index; this.browserGamepad = browserGamepad; this._isConnected = true; this.type = Gamepad.GAMEPAD; this._leftStickAxisX = leftStickX; this._leftStickAxisY = leftStickY; this._rightStickAxisX = rightStickX; this._rightStickAxisY = rightStickY; if (this.browserGamepad.axes.length >= 2) { this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] }; } if (this.browserGamepad.axes.length >= 4) { this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] }; } } Object.defineProperty(Gamepad.prototype, "isConnected", { get: function () { return this._isConnected; }, enumerable: true, configurable: true }); Gamepad.prototype.onleftstickchanged = function (callback) { this._onleftstickchanged = callback; }; Gamepad.prototype.onrightstickchanged = function (callback) { this._onrightstickchanged = callback; }; Object.defineProperty(Gamepad.prototype, "leftStick", { get: function () { return this._leftStick; }, set: function (newValues) { if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) { this._onleftstickchanged(newValues); } this._leftStick = newValues; }, enumerable: true, configurable: true }); Object.defineProperty(Gamepad.prototype, "rightStick", { get: function () { return this._rightStick; }, set: function (newValues) { if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) { this._onrightstickchanged(newValues); } this._rightStick = newValues; }, enumerable: true, configurable: true }); Gamepad.prototype.update = function () { if (this._leftStick) { this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] }; } if (this._rightStick) { this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] }; } }; Gamepad.prototype.dispose = function () { }; Gamepad.GAMEPAD = 0; Gamepad.GENERIC = 1; Gamepad.XBOX = 2; Gamepad.POSE_ENABLED = 3; return Gamepad; }()); BABYLON.Gamepad = Gamepad; var GenericPad = /** @class */ (function (_super) { __extends(GenericPad, _super); function GenericPad(id, index, browserGamepad) { var _this = _super.call(this, id, index, browserGamepad) || this; _this.onButtonDownObservable = new BABYLON.Observable(); _this.onButtonUpObservable = new BABYLON.Observable(); _this.type = Gamepad.GENERIC; _this._buttons = new Array(browserGamepad.buttons.length); return _this; } GenericPad.prototype.onbuttondown = function (callback) { this._onbuttondown = callback; }; GenericPad.prototype.onbuttonup = function (callback) { this._onbuttonup = callback; }; GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) { if (newValue !== currentValue) { if (newValue === 1) { if (this._onbuttondown) { this._onbuttondown(buttonIndex); } this.onButtonDownObservable.notifyObservers(buttonIndex); } if (newValue === 0) { if (this._onbuttonup) { this._onbuttonup(buttonIndex); } this.onButtonUpObservable.notifyObservers(buttonIndex); } } return newValue; }; GenericPad.prototype.update = function () { _super.prototype.update.call(this); for (var index = 0; index < this._buttons.length; index++) { this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index); } }; return GenericPad; }(Gamepad)); BABYLON.GenericPad = GenericPad; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.gamepad.js.map var BABYLON; (function (BABYLON) { var Xbox360Button; (function (Xbox360Button) { Xbox360Button[Xbox360Button["A"] = 0] = "A"; Xbox360Button[Xbox360Button["B"] = 1] = "B"; Xbox360Button[Xbox360Button["X"] = 2] = "X"; Xbox360Button[Xbox360Button["Y"] = 3] = "Y"; Xbox360Button[Xbox360Button["Start"] = 4] = "Start"; Xbox360Button[Xbox360Button["Back"] = 5] = "Back"; Xbox360Button[Xbox360Button["LB"] = 6] = "LB"; Xbox360Button[Xbox360Button["RB"] = 7] = "RB"; Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick"; Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick"; })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {})); var Xbox360Dpad; (function (Xbox360Dpad) { Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up"; Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down"; Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left"; Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right"; })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {})); var Xbox360Pad = /** @class */ (function (_super) { __extends(Xbox360Pad, _super); function Xbox360Pad(id, index, gamepad, xboxOne) { if (xboxOne === void 0) { xboxOne = false; } var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this; _this._leftTrigger = 0; _this._rightTrigger = 0; _this.onButtonDownObservable = new BABYLON.Observable(); _this.onButtonUpObservable = new BABYLON.Observable(); _this.onPadDownObservable = new BABYLON.Observable(); _this.onPadUpObservable = new BABYLON.Observable(); _this._buttonA = 0; _this._buttonB = 0; _this._buttonX = 0; _this._buttonY = 0; _this._buttonBack = 0; _this._buttonStart = 0; _this._buttonLB = 0; _this._buttonRB = 0; _this._buttonLeftStick = 0; _this._buttonRightStick = 0; _this._dPadUp = 0; _this._dPadDown = 0; _this._dPadLeft = 0; _this._dPadRight = 0; _this._isXboxOnePad = false; _this.type = BABYLON.Gamepad.XBOX; _this._isXboxOnePad = xboxOne; return _this; } Xbox360Pad.prototype.onlefttriggerchanged = function (callback) { this._onlefttriggerchanged = callback; }; Xbox360Pad.prototype.onrighttriggerchanged = function (callback) { this._onrighttriggerchanged = callback; }; Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", { get: function () { return this._leftTrigger; }, set: function (newValue) { if (this._onlefttriggerchanged && this._leftTrigger !== newValue) { this._onlefttriggerchanged(newValue); } this._leftTrigger = newValue; }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", { get: function () { return this._rightTrigger; }, set: function (newValue) { if (this._onrighttriggerchanged && this._rightTrigger !== newValue) { this._onrighttriggerchanged(newValue); } this._rightTrigger = newValue; }, enumerable: true, configurable: true }); Xbox360Pad.prototype.onbuttondown = function (callback) { this._onbuttondown = callback; }; Xbox360Pad.prototype.onbuttonup = function (callback) { this._onbuttonup = callback; }; Xbox360Pad.prototype.ondpaddown = function (callback) { this._ondpaddown = callback; }; Xbox360Pad.prototype.ondpadup = function (callback) { this._ondpadup = callback; }; Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) { if (newValue !== currentValue) { if (newValue === 1) { if (this._onbuttondown) { this._onbuttondown(buttonType); } this.onButtonDownObservable.notifyObservers(buttonType); } if (newValue === 0) { if (this._onbuttonup) { this._onbuttonup(buttonType); } this.onButtonUpObservable.notifyObservers(buttonType); } } return newValue; }; Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) { if (newValue !== currentValue) { if (newValue === 1) { if (this._ondpaddown) { this._ondpaddown(buttonType); } this.onPadDownObservable.notifyObservers(buttonType); } if (newValue === 0) { if (this._ondpadup) { this._ondpadup(buttonType); } this.onPadUpObservable.notifyObservers(buttonType); } } return newValue; }; Object.defineProperty(Xbox360Pad.prototype, "buttonA", { get: function () { return this._buttonA; }, set: function (value) { this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonB", { get: function () { return this._buttonB; }, set: function (value) { this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonX", { get: function () { return this._buttonX; }, set: function (value) { this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonY", { get: function () { return this._buttonY; }, set: function (value) { this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonStart", { get: function () { return this._buttonStart; }, set: function (value) { this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonBack", { get: function () { return this._buttonBack; }, set: function (value) { this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonLB", { get: function () { return this._buttonLB; }, set: function (value) { this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonRB", { get: function () { return this._buttonRB; }, set: function (value) { this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", { get: function () { return this._buttonLeftStick; }, set: function (value) { this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", { get: function () { return this._buttonRightStick; }, set: function (value) { this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "dPadUp", { get: function () { return this._dPadUp; }, set: function (value) { this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "dPadDown", { get: function () { return this._dPadDown; }, set: function (value) { this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", { get: function () { return this._dPadLeft; }, set: function (value) { this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "dPadRight", { get: function () { return this._dPadRight; }, set: function (value) { this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right); }, enumerable: true, configurable: true }); Xbox360Pad.prototype.update = function () { _super.prototype.update.call(this); if (this._isXboxOnePad) { this.buttonA = this.browserGamepad.buttons[0].value; this.buttonB = this.browserGamepad.buttons[1].value; this.buttonX = this.browserGamepad.buttons[2].value; this.buttonY = this.browserGamepad.buttons[3].value; this.buttonLB = this.browserGamepad.buttons[4].value; this.buttonRB = this.browserGamepad.buttons[5].value; this.leftTrigger = this.browserGamepad.axes[2]; this.rightTrigger = this.browserGamepad.axes[5]; this.buttonBack = this.browserGamepad.buttons[9].value; this.buttonStart = this.browserGamepad.buttons[8].value; this.buttonLeftStick = this.browserGamepad.buttons[6].value; this.buttonRightStick = this.browserGamepad.buttons[7].value; this.dPadUp = this.browserGamepad.buttons[11].value; this.dPadDown = this.browserGamepad.buttons[12].value; this.dPadLeft = this.browserGamepad.buttons[13].value; this.dPadRight = this.browserGamepad.buttons[14].value; } else { this.buttonA = this.browserGamepad.buttons[0].value; this.buttonB = this.browserGamepad.buttons[1].value; this.buttonX = this.browserGamepad.buttons[2].value; this.buttonY = this.browserGamepad.buttons[3].value; this.buttonLB = this.browserGamepad.buttons[4].value; this.buttonRB = this.browserGamepad.buttons[5].value; this.leftTrigger = this.browserGamepad.buttons[6].value; this.rightTrigger = this.browserGamepad.buttons[7].value; this.buttonBack = this.browserGamepad.buttons[8].value; this.buttonStart = this.browserGamepad.buttons[9].value; this.buttonLeftStick = this.browserGamepad.buttons[10].value; this.buttonRightStick = this.browserGamepad.buttons[11].value; this.dPadUp = this.browserGamepad.buttons[12].value; this.dPadDown = this.browserGamepad.buttons[13].value; this.dPadLeft = this.browserGamepad.buttons[14].value; this.dPadRight = this.browserGamepad.buttons[15].value; } }; return Xbox360Pad; }(BABYLON.Gamepad)); BABYLON.Xbox360Pad = Xbox360Pad; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.xboxGamepad.js.map var BABYLON; (function (BABYLON) { var PoseEnabledControllerType; (function (PoseEnabledControllerType) { PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE"; PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS"; PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS"; PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC"; })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {})); var PoseEnabledControllerHelper = /** @class */ (function () { function PoseEnabledControllerHelper() { } PoseEnabledControllerHelper.InitiateController = function (vrGamepad) { // Oculus Touch if (vrGamepad.id.indexOf('Oculus Touch') !== -1) { return new BABYLON.OculusTouchController(vrGamepad); } else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) { return new BABYLON.WindowsMotionController(vrGamepad); } else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) { return new BABYLON.ViveController(vrGamepad); } else { return new BABYLON.GenericController(vrGamepad); } }; return PoseEnabledControllerHelper; }()); BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper; var PoseEnabledController = /** @class */ (function (_super) { __extends(PoseEnabledController, _super); function PoseEnabledController(browserGamepad) { var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this; _this.deviceScaleFactor = 1; _this._leftHandSystemQuaternion = new BABYLON.Quaternion(); _this.type = BABYLON.Gamepad.POSE_ENABLED; _this.controllerType = PoseEnabledControllerType.GENERIC; _this.position = BABYLON.Vector3.Zero(); _this.rotationQuaternion = new BABYLON.Quaternion(); _this.devicePosition = BABYLON.Vector3.Zero(); _this.deviceRotationQuaternion = new BABYLON.Quaternion(); _this._calculatedPosition = BABYLON.Vector3.Zero(); _this._calculatedRotation = new BABYLON.Quaternion(); BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion); return _this; } PoseEnabledController.prototype.update = function () { _super.prototype.update.call(this); var pose = this.browserGamepad.pose; this.updateFromDevice(pose); if (this._mesh) { this._mesh.position.copyFrom(this._calculatedPosition); if (this._mesh.rotationQuaternion) { this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation); } } }; PoseEnabledController.prototype.updateFromDevice = function (poseData) { if (poseData) { this.rawPose = poseData; if (poseData.position) { this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]); if (this._mesh && this._mesh.getScene().useRightHandedSystem) { this.devicePosition.z *= -1; } this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition); this._calculatedPosition.addInPlace(this.position); } var pose = this.rawPose; if (poseData.orientation && pose.orientation) { this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]); if (this._mesh) { if (this._mesh.getScene().useRightHandedSystem) { this.deviceRotationQuaternion.z *= -1; this.deviceRotationQuaternion.w *= -1; } else { this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion); } } // if the camera is set, rotate to the camera's rotation this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation); } } }; PoseEnabledController.prototype.attachToMesh = function (mesh) { if (this._mesh) { this._mesh.parent = null; } this._mesh = mesh; if (this._poseControlledCamera) { this._mesh.parent = this._poseControlledCamera; } if (!this._mesh.rotationQuaternion) { this._mesh.rotationQuaternion = new BABYLON.Quaternion(); } }; PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) { this._poseControlledCamera = camera; if (this._mesh) { this._mesh.parent = this._poseControlledCamera; } }; PoseEnabledController.prototype.dispose = function () { if (this._mesh) { this._mesh.dispose(); } this._mesh = null; _super.prototype.dispose.call(this); }; Object.defineProperty(PoseEnabledController.prototype, "mesh", { get: function () { return this._mesh; }, enumerable: true, configurable: true }); PoseEnabledController.prototype.getForwardRay = function (length) { if (length === void 0) { length = 100; } if (!this.mesh) { return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length); } var m = this.mesh.getWorldMatrix(); var origin = m.getTranslation(); var forward = new BABYLON.Vector3(0, 0, -1); var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m); var direction = BABYLON.Vector3.Normalize(forwardWorld); return new BABYLON.Ray(origin, direction, length); }; return PoseEnabledController; }(BABYLON.Gamepad)); BABYLON.PoseEnabledController = PoseEnabledController; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.poseEnabledController.js.map var BABYLON; (function (BABYLON) { var WebVRController = /** @class */ (function (_super) { __extends(WebVRController, _super); function WebVRController(vrGamepad) { var _this = _super.call(this, vrGamepad) || this; // Observables _this.onTriggerStateChangedObservable = new BABYLON.Observable(); _this.onMainButtonStateChangedObservable = new BABYLON.Observable(); _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable(); _this.onPadStateChangedObservable = new BABYLON.Observable(); _this.onPadValuesChangedObservable = new BABYLON.Observable(); _this.pad = { x: 0, y: 0 }; // avoid GC, store state in a tmp object _this._changes = { pressChanged: false, touchChanged: false, valueChanged: false, changed: false }; _this._buttons = new Array(vrGamepad.buttons.length); _this.hand = vrGamepad.hand; return _this; } WebVRController.prototype.onButtonStateChange = function (callback) { this._onButtonStateChange = callback; }; Object.defineProperty(WebVRController.prototype, "defaultModel", { get: function () { return this._defaultModel; }, enumerable: true, configurable: true }); WebVRController.prototype.update = function () { _super.prototype.update.call(this); for (var index = 0; index < this._buttons.length; index++) { this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index); } ; if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) { this.pad.x = this.leftStick.x; this.pad.y = this.leftStick.y; this.onPadValuesChangedObservable.notifyObservers(this.pad); } }; WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) { if (!newState) { newState = { pressed: false, touched: false, value: 0 }; } if (!currentState) { this._buttons[buttonIndex] = { pressed: newState.pressed, touched: newState.touched, value: newState.value }; return; } this._checkChanges(newState, currentState); if (this._changes.changed) { this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState); this.handleButtonChange(buttonIndex, newState, this._changes); } this._buttons[buttonIndex].pressed = newState.pressed; this._buttons[buttonIndex].touched = newState.touched; // oculus triggers are never 0, thou not touched. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value; }; WebVRController.prototype._checkChanges = function (newState, currentState) { this._changes.pressChanged = newState.pressed !== currentState.pressed; this._changes.touchChanged = newState.touched !== currentState.touched; this._changes.valueChanged = newState.value !== currentState.value; this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged; return this._changes; }; WebVRController.prototype.dispose = function () { _super.prototype.dispose.call(this); this.onTriggerStateChangedObservable.clear(); this.onMainButtonStateChangedObservable.clear(); this.onSecondaryButtonStateChangedObservable.clear(); this.onPadStateChangedObservable.clear(); this.onPadValuesChangedObservable.clear(); }; return WebVRController; }(BABYLON.PoseEnabledController)); BABYLON.WebVRController = WebVRController; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.webVRController.js.map var BABYLON; (function (BABYLON) { var OculusTouchController = /** @class */ (function (_super) { __extends(OculusTouchController, _super); function OculusTouchController(vrGamepad) { var _this = _super.call(this, vrGamepad) || this; _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable(); _this.onThumbRestChangedObservable = new BABYLON.Observable(); _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS; return _this; } OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) { var _this = this; var meshName; // Hand if (this.hand === 'left') { meshName = OculusTouchController.MODEL_LEFT_FILENAME; } else { meshName = OculusTouchController.MODEL_RIGHT_FILENAME; } BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) { /* Parent Mesh name: oculus_touch_left - body - trigger - thumbstick - grip - button_y - button_x - button_enter */ _this._defaultModel = newMeshes[1]; _this.attachToMesh(_this._defaultModel); if (meshLoaded) { meshLoaded(_this._defaultModel); } }); }; Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", { // helper getters for left and right hand. get: function () { if (this.hand === 'right') { return this.onMainButtonStateChangedObservable; } else { throw new Error('No A button on left hand'); } }, enumerable: true, configurable: true }); Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", { get: function () { if (this.hand === 'right') { return this.onSecondaryButtonStateChangedObservable; } else { throw new Error('No B button on left hand'); } }, enumerable: true, configurable: true }); Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", { get: function () { if (this.hand === 'left') { return this.onMainButtonStateChangedObservable; } else { throw new Error('No X button on right hand'); } }, enumerable: true, configurable: true }); Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", { get: function () { if (this.hand === 'left') { return this.onSecondaryButtonStateChangedObservable; } else { throw new Error('No Y button on right hand'); } }, enumerable: true, configurable: true }); /* 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1) 2) secondary trigger (same) 3) A (right) X (left), touch, pressed = value 4) B / Y 5) thumb rest */ OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) { var notifyObject = state; //{ state: state, changes: changes }; var triggerDirection = this.hand === 'right' ? -1 : 1; switch (buttonIdx) { case 0: this.onPadStateChangedObservable.notifyObservers(notifyObject); return; case 1:// index trigger if (this._defaultModel) { (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20; (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005; (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005; } this.onTriggerStateChangedObservable.notifyObservers(notifyObject); return; case 2:// secondary trigger if (this._defaultModel) { (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035; } this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject); return; case 3: if (this._defaultModel) { if (notifyObject.pressed) { (this._defaultModel.getChildren()[1]).position.y = -0.001; } else { (this._defaultModel.getChildren()[1]).position.y = 0; } } this.onMainButtonStateChangedObservable.notifyObservers(notifyObject); return; case 4: if (this._defaultModel) { if (notifyObject.pressed) { (this._defaultModel.getChildren()[2]).position.y = -0.001; } else { (this._defaultModel.getChildren()[2]).position.y = 0; } } this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject); return; case 5: this.onThumbRestChangedObservable.notifyObservers(notifyObject); return; } }; OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/'; OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon'; OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon'; return OculusTouchController; }(BABYLON.WebVRController)); BABYLON.OculusTouchController = OculusTouchController; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.oculusTouchController.js.map var BABYLON; (function (BABYLON) { var ViveController = /** @class */ (function (_super) { __extends(ViveController, _super); function ViveController(vrGamepad) { var _this = _super.call(this, vrGamepad) || this; _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE; return _this; } ViveController.prototype.initControllerMesh = function (scene, meshLoaded) { var _this = this; BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) { /* Parent Mesh name: ViveWand - body - r_gripper - l_gripper - menu_button - system_button - trackpad - trigger - LED */ _this._defaultModel = newMeshes[1]; _this.attachToMesh(_this._defaultModel); if (meshLoaded) { meshLoaded(_this._defaultModel); } }); }; Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", { get: function () { return this.onMainButtonStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", { get: function () { return this.onMainButtonStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", { get: function () { return this.onSecondaryButtonStateChangedObservable; }, enumerable: true, configurable: true }); /** * Vive mapping: * 0: touchpad * 1: trigger * 2: left AND right buttons * 3: menu button */ ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) { var notifyObject = state; //{ state: state, changes: changes }; switch (buttonIdx) { case 0: this.onPadStateChangedObservable.notifyObservers(notifyObject); return; case 1:// index trigger if (this._defaultModel) { (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15; } this.onTriggerStateChangedObservable.notifyObservers(notifyObject); return; case 2:// left AND right button this.onMainButtonStateChangedObservable.notifyObservers(notifyObject); return; case 3: if (this._defaultModel) { if (notifyObject.pressed) { (this._defaultModel.getChildren()[2]).position.y = -0.001; } else { (this._defaultModel.getChildren()[2]).position.y = 0; } } this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject); return; } }; ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/'; ViveController.MODEL_FILENAME = 'wand.babylon'; return ViveController; }(BABYLON.WebVRController)); BABYLON.ViveController = ViveController; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.viveController.js.map var BABYLON; (function (BABYLON) { var GenericController = /** @class */ (function (_super) { __extends(GenericController, _super); function GenericController(vrGamepad) { return _super.call(this, vrGamepad) || this; } GenericController.prototype.initControllerMesh = function (scene, meshLoaded) { var _this = this; BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) { _this._defaultModel = newMeshes[1]; _this.attachToMesh(_this._defaultModel); if (meshLoaded) { meshLoaded(_this._defaultModel); } }); }; GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) { console.log("Button id: " + buttonIdx + "state: "); console.dir(state); }; GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/'; GenericController.MODEL_FILENAME = 'generic.babylon'; return GenericController; }(BABYLON.WebVRController)); BABYLON.GenericController = GenericController; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.genericController.js.map var BABYLON; (function (BABYLON) { var LoadedMeshInfo = /** @class */ (function () { function LoadedMeshInfo() { this.buttonMeshes = {}; this.axisMeshes = {}; } return LoadedMeshInfo; }()); var WindowsMotionController = /** @class */ (function (_super) { __extends(WindowsMotionController, _super); function WindowsMotionController(vrGamepad) { var _this = _super.call(this, vrGamepad) || this; _this._mapping = { // Semantic button names buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'], // A mapping of the button name to glTF model node name // that should be transformed by button value. buttonMeshNames: { 'trigger': 'SELECT', 'menu': 'MENU', 'grip': 'GRASP', 'thumbstick': 'THUMBSTICK_PRESS', 'trackpad': 'TOUCHPAD_PRESS' }, // This mapping is used to translate from the Motion Controller to Babylon semantics buttonObservableNames: { 'trigger': 'onTriggerStateChangedObservable', 'menu': 'onSecondaryButtonStateChangedObservable', 'grip': 'onMainButtonStateChangedObservable', 'thumbstick': 'onPadStateChangedObservable', 'trackpad': 'onTrackpadChangedObservable' }, // A mapping of the axis name to glTF model node name // that should be transformed by axis value. // This array mirrors the browserGamepad.axes array, such that // the mesh corresponding to axis 0 is in this array index 0. axisMeshNames: [ 'THUMBSTICK_X', 'THUMBSTICK_Y', 'TOUCHPAD_TOUCH_X', 'TOUCHPAD_TOUCH_Y' ], pointingPoseMeshName: 'POINTING_POSE' }; _this.onTrackpadChangedObservable = new BABYLON.Observable(); _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS; _this._loadedMeshInfo = null; return _this; } Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", { get: function () { return this.onTriggerStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", { get: function () { return this.onSecondaryButtonStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", { get: function () { return this.onMainButtonStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", { get: function () { return this.onPadStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", { get: function () { return this.onTrackpadChangedObservable; }, enumerable: true, configurable: true }); /** * Called once per frame by the engine. */ WindowsMotionController.prototype.update = function () { _super.prototype.update.call(this); // Only need to animate axes if there is a loaded mesh if (this._loadedMeshInfo) { if (this.browserGamepad.axes) { for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) { this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]); } } } }; /** * Called once for each button that changed state since the last frame * @param buttonIdx Which button index changed * @param state New state of the button * @param changes Which properties on the state changed since last frame */ WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) { var buttonName = this._mapping.buttons[buttonIdx]; if (!buttonName) { return; } // Only emit events for buttons that we know how to map from index to name var observable = this[(this._mapping.buttonObservableNames)[buttonName]]; if (observable) { observable.notifyObservers(state); } this.lerpButtonTransform(buttonName, state.value); }; WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) { // If there is no loaded mesh, there is nothing to transform. if (!this._loadedMeshInfo) { return; } var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName]; if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) { return; } BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion); BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position); }; WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) { if (!this._loadedMeshInfo) { return; } var meshInfo = this._loadedMeshInfo.axisMeshes[axis]; if (!meshInfo) { return; } if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) { return; } // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1) var lerpValue = axisValue * 0.5 + 0.5; BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion); BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position); }; /** * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. * @param scene scene in which to add meshes * @param meshLoaded optional callback function that will be called if the mesh loads successfully. */ WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) { var _this = this; if (forceDefault === void 0) { forceDefault = false; } var path; var filename; // Checking if GLB loader is present if (BABYLON.SceneLoader.GetPluginForExtension("glb")) { // Determine the device specific folder based on the ID suffix var device = 'default'; if (this.id && !forceDefault) { var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN); device = ((match && match[0]) || device); } // Hand if (this.hand === 'left') { filename = WindowsMotionController.MODEL_LEFT_FILENAME; } else { filename = WindowsMotionController.MODEL_RIGHT_FILENAME; } path = WindowsMotionController.MODEL_BASE_URL + device + '/'; } else { BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models"); path = BABYLON.GenericController.MODEL_BASE_URL; filename = BABYLON.GenericController.MODEL_FILENAME; } BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) { // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format. _this._loadedMeshInfo = _this.processModel(scene, meshes); if (!_this._loadedMeshInfo) { return; } _this._defaultModel = _this._loadedMeshInfo.rootNode; _this.attachToMesh(_this._defaultModel); if (meshLoaded) { meshLoaded(_this._defaultModel); } }, null, function (scene, message) { BABYLON.Tools.Log(message); BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename); if (!forceDefault) { _this.initControllerMesh(scene, meshLoaded, true); } }); }; /** * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that * can be transformed by button presses and axes values, based on this._mapping. * * @param scene scene in which the meshes exist * @param meshes list of meshes that make up the controller model to process * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed. */ WindowsMotionController.prototype.processModel = function (scene, meshes) { var loadedMeshInfo = null; // Create a new mesh to contain the glTF hierarchy var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene); // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh' var childMesh = null; for (var i = 0; i < meshes.length; i++) { var mesh = meshes[i]; if (!mesh.parent) { // Exclude controller meshes from picking results mesh.isPickable = false; // Handle root node, attach to the new parentMesh childMesh = mesh; break; } } if (childMesh) { childMesh.setParent(parentMesh); // Create our mesh info. Note that this method will always return non-null. loadedMeshInfo = this.createMeshInfo(parentMesh); } else { BABYLON.Tools.Warn('Could not find root node in model file.'); } return loadedMeshInfo; }; WindowsMotionController.prototype.createMeshInfo = function (rootNode) { var loadedMeshInfo = new LoadedMeshInfo(); var i; loadedMeshInfo.rootNode = rootNode; // Reset the caches loadedMeshInfo.buttonMeshes = {}; loadedMeshInfo.axisMeshes = {}; // Button Meshes for (i = 0; i < this._mapping.buttons.length; i++) { var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]]; if (!buttonMeshName) { BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]); continue; } var buttonMesh = getChildByName(rootNode, buttonMeshName); if (!buttonMesh) { BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName); continue; } var buttonMeshInfo = { index: i, value: getImmediateChildByName(buttonMesh, 'VALUE'), pressed: getImmediateChildByName(buttonMesh, 'PRESSED'), unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED') }; if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) { loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo; } else { // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName + '(VALUE: ' + !!buttonMeshInfo.value + ', PRESSED: ' + !!buttonMeshInfo.pressed + ', UNPRESSED:' + !!buttonMeshInfo.unpressed + ')'); } } // Axis Meshes for (i = 0; i < this._mapping.axisMeshNames.length; i++) { var axisMeshName = this._mapping.axisMeshNames[i]; if (!axisMeshName) { BABYLON.Tools.Log('Skipping unknown axis at index: ' + i); continue; } var axisMesh = getChildByName(rootNode, axisMeshName); if (!axisMesh) { BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName); continue; } var axisMeshInfo = { index: i, value: getImmediateChildByName(axisMesh, 'VALUE'), min: getImmediateChildByName(axisMesh, 'MIN'), max: getImmediateChildByName(axisMesh, 'MAX') }; if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) { loadedMeshInfo.axisMeshes[i] = axisMeshInfo; } else { // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName + '(VALUE: ' + !!axisMeshInfo.value + ', MIN: ' + !!axisMeshInfo.min + ', MAX:' + !!axisMeshInfo.max + ')'); } } // Pointing Ray loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName); if (!loadedMeshInfo.pointingPoseNode) { BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName); } return loadedMeshInfo; // Look through all children recursively. This will return null if no mesh exists with the given name. function getChildByName(node, name) { return node.getChildMeshes(false, function (n) { return n.name === name; })[0]; } // Look through only immediate children. This will return null if no mesh exists with the given name. function getImmediateChildByName(node, name) { return node.getChildMeshes(true, function (n) { return n.name == name; })[0]; } }; WindowsMotionController.prototype.getForwardRay = function (length) { if (length === void 0) { length = 100; } if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) { return _super.prototype.getForwardRay.call(this, length); } var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix(); var origin = m.getTranslation(); var forward = new BABYLON.Vector3(0, 0, -1); var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m); var direction = BABYLON.Vector3.Normalize(forwardWorld); return new BABYLON.Ray(origin, direction, length); }; WindowsMotionController.prototype.dispose = function () { _super.prototype.dispose.call(this); this.onTrackpadChangedObservable.clear(); }; WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/'; WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb'; WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb'; WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) '; WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/; return WindowsMotionController; }(BABYLON.WebVRController)); BABYLON.WindowsMotionController = WindowsMotionController; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.windowsMotionController.js.map /// var BABYLON; (function (BABYLON) { var FollowCamera = /** @class */ (function (_super) { __extends(FollowCamera, _super); function FollowCamera(name, position, scene, lockedTarget) { if (lockedTarget === void 0) { lockedTarget = null; } var _this = _super.call(this, name, position, scene) || this; _this.radius = 12; _this.rotationOffset = 0; _this.heightOffset = 4; _this.cameraAcceleration = 0.05; _this.maxCameraSpeed = 20; _this.lockedTarget = lockedTarget; return _this; } FollowCamera.prototype.getRadians = function (degrees) { return degrees * Math.PI / 180; }; FollowCamera.prototype.follow = function (cameraTarget) { if (!cameraTarget) return; var yRotation; if (cameraTarget.rotationQuaternion) { var rotMatrix = new BABYLON.Matrix(); cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix); yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]); } else { yRotation = cameraTarget.rotation.y; } var radians = this.getRadians(this.rotationOffset) + yRotation; var targetPosition = cameraTarget.getAbsolutePosition(); var targetX = targetPosition.x + Math.sin(radians) * this.radius; var targetZ = targetPosition.z + Math.cos(radians) * this.radius; var dx = targetX - this.position.x; var dy = (targetPosition.y + this.heightOffset) - this.position.y; var dz = (targetZ) - this.position.z; var vx = dx * this.cameraAcceleration * 2; //this is set to .05 var vy = dy * this.cameraAcceleration; var vz = dz * this.cameraAcceleration * 2; if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) { vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; } if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) { vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; } if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) { vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; } this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz); this.setTarget(targetPosition); }; FollowCamera.prototype._checkInputs = function () { _super.prototype._checkInputs.call(this); if (this.lockedTarget) { this.follow(this.lockedTarget); } }; FollowCamera.prototype.getClassName = function () { return "FollowCamera"; }; __decorate([ BABYLON.serialize() ], FollowCamera.prototype, "radius", void 0); __decorate([ BABYLON.serialize() ], FollowCamera.prototype, "rotationOffset", void 0); __decorate([ BABYLON.serialize() ], FollowCamera.prototype, "heightOffset", void 0); __decorate([ BABYLON.serialize() ], FollowCamera.prototype, "cameraAcceleration", void 0); __decorate([ BABYLON.serialize() ], FollowCamera.prototype, "maxCameraSpeed", void 0); __decorate([ BABYLON.serializeAsMeshReference("lockedTargetId") ], FollowCamera.prototype, "lockedTarget", void 0); return FollowCamera; }(BABYLON.TargetCamera)); BABYLON.FollowCamera = FollowCamera; var ArcFollowCamera = /** @class */ (function (_super) { __extends(ArcFollowCamera, _super); function ArcFollowCamera(name, alpha, beta, radius, target, scene) { var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this; _this.alpha = alpha; _this.beta = beta; _this.radius = radius; _this.target = target; _this._cartesianCoordinates = BABYLON.Vector3.Zero(); _this.follow(); return _this; } ArcFollowCamera.prototype.follow = function () { if (!this.target) { return; } this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta); this._cartesianCoordinates.y = this.radius * Math.sin(this.beta); this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta); var targetPosition = this.target.getAbsolutePosition(); this.position = targetPosition.add(this._cartesianCoordinates); this.setTarget(targetPosition); }; ArcFollowCamera.prototype._checkInputs = function () { _super.prototype._checkInputs.call(this); this.follow(); }; ArcFollowCamera.prototype.getClassName = function () { return "ArcFollowCamera"; }; return ArcFollowCamera; }(BABYLON.TargetCamera)); BABYLON.ArcFollowCamera = ArcFollowCamera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.followCamera.js.map /// var BABYLON; (function (BABYLON) { // We're mainly based on the logic defined into the FreeCamera code var UniversalCamera = /** @class */ (function (_super) { __extends(UniversalCamera, _super); //-- end properties for backward compatibility for inputs function UniversalCamera(name, position, scene) { var _this = _super.call(this, name, position, scene) || this; _this.inputs.addGamepad(); return _this; } Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", { //-- Begin properties for backward compatibility for inputs get: function () { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) return gamepad.gamepadAngularSensibility; return 0; }, set: function (value) { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) gamepad.gamepadAngularSensibility = value; }, enumerable: true, configurable: true }); Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", { get: function () { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) return gamepad.gamepadMoveSensibility; return 0; }, set: function (value) { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) gamepad.gamepadMoveSensibility = value; }, enumerable: true, configurable: true }); UniversalCamera.prototype.getClassName = function () { return "UniversalCamera"; }; return UniversalCamera; }(BABYLON.TouchCamera)); BABYLON.UniversalCamera = UniversalCamera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.universalCamera.js.map /// var BABYLON; (function (BABYLON) { // We're mainly based on the logic defined into the FreeCamera code var GamepadCamera = /** @class */ (function (_super) { __extends(GamepadCamera, _super); //-- end properties for backward compatibility for inputs function GamepadCamera(name, position, scene) { return _super.call(this, name, position, scene) || this; } Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", { //-- Begin properties for backward compatibility for inputs get: function () { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) return gamepad.gamepadAngularSensibility; return 0; }, set: function (value) { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) gamepad.gamepadAngularSensibility = value; }, enumerable: true, configurable: true }); Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", { get: function () { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) return gamepad.gamepadMoveSensibility; return 0; }, set: function (value) { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) gamepad.gamepadMoveSensibility = value; }, enumerable: true, configurable: true }); GamepadCamera.prototype.getClassName = function () { return "GamepadCamera"; }; return GamepadCamera; }(BABYLON.UniversalCamera)); BABYLON.GamepadCamera = GamepadCamera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.gamepadCamera.js.map var BABYLON; (function (BABYLON) { var PostProcessRenderPipelineManager = /** @class */ (function () { function PostProcessRenderPipelineManager() { this._renderPipelines = {}; } PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) { this._renderPipelines[renderPipeline._name] = renderPipeline; }; PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) { if (unique === void 0) { unique = false; } var renderPipeline = this._renderPipelines[renderPipelineName]; if (!renderPipeline) { return; } renderPipeline._attachCameras(cameras, unique); }; PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) { var renderPipeline = this._renderPipelines[renderPipelineName]; if (!renderPipeline) { return; } renderPipeline._detachCameras(cameras); }; PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) { var renderPipeline = this._renderPipelines[renderPipelineName]; if (!renderPipeline) { return; } renderPipeline._enableEffect(renderEffectName, cameras); }; PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) { var renderPipeline = this._renderPipelines[renderPipelineName]; if (!renderPipeline) { return; } renderPipeline._disableEffect(renderEffectName, cameras); }; PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) { var renderPipeline = this._renderPipelines[renderPipelineName]; if (!renderPipeline) { return; } renderPipeline._enableDisplayOnlyPass(passName, cameras); }; PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) { var renderPipeline = this._renderPipelines[renderPipelineName]; if (!renderPipeline) { return; } renderPipeline._disableDisplayOnlyPass(cameras); }; PostProcessRenderPipelineManager.prototype.update = function () { for (var renderPipelineName in this._renderPipelines) { if (this._renderPipelines.hasOwnProperty(renderPipelineName)) { var pipeline = this._renderPipelines[renderPipelineName]; if (!pipeline.isSupported) { pipeline.dispose(); delete this._renderPipelines[renderPipelineName]; } else { pipeline._update(); } } } }; PostProcessRenderPipelineManager.prototype._rebuild = function () { for (var renderPipelineName in this._renderPipelines) { if (this._renderPipelines.hasOwnProperty(renderPipelineName)) { var pipeline = this._renderPipelines[renderPipelineName]; pipeline._rebuild(); } } }; PostProcessRenderPipelineManager.prototype.dispose = function () { for (var renderPipelineName in this._renderPipelines) { if (this._renderPipelines.hasOwnProperty(renderPipelineName)) { var pipeline = this._renderPipelines[renderPipelineName]; pipeline.dispose(); } } }; return PostProcessRenderPipelineManager; }()); BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map var BABYLON; (function (BABYLON) { var PostProcessRenderPass = /** @class */ (function () { function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) { this._refCount = 0; this._name = name; this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene); this.setRenderList(renderList); this._renderTexture.onBeforeRenderObservable.add(beforeRender); this._renderTexture.onAfterRenderObservable.add(afterRender); this._scene = scene; this._renderList = renderList; } // private PostProcessRenderPass.prototype._incRefCount = function () { if (this._refCount === 0) { this._scene.customRenderTargets.push(this._renderTexture); } return ++this._refCount; }; PostProcessRenderPass.prototype._decRefCount = function () { this._refCount--; if (this._refCount <= 0) { this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1); } return this._refCount; }; PostProcessRenderPass.prototype._update = function () { this.setRenderList(this._renderList); }; // public PostProcessRenderPass.prototype.setRenderList = function (renderList) { this._renderTexture.renderList = renderList; }; PostProcessRenderPass.prototype.getRenderTexture = function () { return this._renderTexture; }; return PostProcessRenderPass; }()); BABYLON.PostProcessRenderPass = PostProcessRenderPass; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.postProcessRenderPass.js.map var BABYLON; (function (BABYLON) { var PostProcessRenderEffect = /** @class */ (function () { function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) { this._engine = engine; this._name = name; this._singleInstance = singleInstance || true; this._getPostProcess = getPostProcess; this._cameras = {}; this._indicesForCamera = {}; this._postProcesses = {}; this._renderPasses = {}; this._renderEffectAsPasses = {}; } Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", { get: function () { for (var index in this._postProcesses) { if (!this._postProcesses[index].isSupported) { return false; } } return true; }, enumerable: true, configurable: true }); PostProcessRenderEffect.prototype._update = function () { for (var renderPassName in this._renderPasses) { this._renderPasses[renderPassName]._update(); } }; PostProcessRenderEffect.prototype.addPass = function (renderPass) { this._renderPasses[renderPass._name] = renderPass; this._linkParameters(); }; PostProcessRenderEffect.prototype.removePass = function (renderPass) { delete this._renderPasses[renderPass._name]; this._linkParameters(); }; PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) { this._renderEffectAsPasses[renderEffect._name] = renderEffect; this._linkParameters(); }; PostProcessRenderEffect.prototype.getPass = function (passName) { for (var renderPassName in this._renderPasses) { if (renderPassName === passName) { return this._renderPasses[passName]; } } return null; }; PostProcessRenderEffect.prototype.emptyPasses = function () { this._renderPasses = {}; this._linkParameters(); }; PostProcessRenderEffect.prototype._attachCameras = function (cameras) { var cameraKey; var cams = BABYLON.Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } for (var i = 0; i < cams.length; i++) { var camera = cams[i]; var cameraName = camera.name; if (this._singleInstance) { cameraKey = 0; } else { cameraKey = cameraName; } this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess(); var index = camera.attachPostProcess(this._postProcesses[cameraKey]); if (!this._indicesForCamera[cameraName]) { this._indicesForCamera[cameraName] = []; } this._indicesForCamera[cameraName].push(index); if (!this._cameras[cameraName]) { this._cameras[cameraName] = camera; } for (var passName in this._renderPasses) { this._renderPasses[passName]._incRefCount(); } } this._linkParameters(); }; PostProcessRenderEffect.prototype._detachCameras = function (cameras) { var cams = BABYLON.Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } for (var i = 0; i < cams.length; i++) { var camera = cams[i]; var cameraName = camera.name; camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]); if (this._cameras[cameraName]) { //this._indicesForCamera.splice(index, 1); this._cameras[cameraName] = null; } for (var passName in this._renderPasses) { this._renderPasses[passName]._decRefCount(); } } }; PostProcessRenderEffect.prototype._enable = function (cameras) { var cams = BABYLON.Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } for (var i = 0; i < cams.length; i++) { var camera = cams[i]; var cameraName = camera.name; for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) { if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) { cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]); } } for (var passName in this._renderPasses) { this._renderPasses[passName]._incRefCount(); } } }; PostProcessRenderEffect.prototype._disable = function (cameras) { var cams = BABYLON.Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } for (var i = 0; i < cams.length; i++) { var camera = cams[i]; var cameraName = camera.Name; camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]); for (var passName in this._renderPasses) { this._renderPasses[passName]._decRefCount(); } } }; PostProcessRenderEffect.prototype.getPostProcess = function (camera) { if (this._singleInstance) { return this._postProcesses[0]; } else { if (!camera) { return null; } return this._postProcesses[camera.name]; } }; PostProcessRenderEffect.prototype._linkParameters = function () { var _this = this; for (var index in this._postProcesses) { if (this.applyParameters) { this.applyParameters(this._postProcesses[index]); } this._postProcesses[index].onBeforeRenderObservable.add(function (effect) { _this._linkTextures(effect); }); } }; PostProcessRenderEffect.prototype._linkTextures = function (effect) { for (var renderPassName in this._renderPasses) { effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture()); } for (var renderEffectName in this._renderEffectAsPasses) { effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess()); } }; return PostProcessRenderEffect; }()); BABYLON.PostProcessRenderEffect = PostProcessRenderEffect; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.postProcessRenderEffect.js.map var BABYLON; (function (BABYLON) { var PostProcessRenderPipeline = /** @class */ (function () { function PostProcessRenderPipeline(engine, name) { this._engine = engine; this._name = name; this._renderEffects = {}; this._renderEffectsForIsolatedPass = new Array(); this._cameras = []; } PostProcessRenderPipeline.prototype.getClassName = function () { return "PostProcessRenderPipeline"; }; Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", { get: function () { for (var renderEffectName in this._renderEffects) { if (this._renderEffects.hasOwnProperty(renderEffectName)) { if (!this._renderEffects[renderEffectName].isSupported) { return false; } } } return true; }, enumerable: true, configurable: true }); PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) { this._renderEffects[renderEffect._name] = renderEffect; }; // private PostProcessRenderPipeline.prototype._rebuild = function () { }; PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) { var renderEffects = this._renderEffects[renderEffectName]; if (!renderEffects) { return; } renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras)); }; PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) { var renderEffects = this._renderEffects[renderEffectName]; if (!renderEffects) { return; } renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras)); }; PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) { var cams = BABYLON.Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } var indicesToDelete = []; var i; for (i = 0; i < cams.length; i++) { var camera = cams[i]; var cameraName = camera.name; if (this._cameras.indexOf(camera) === -1) { this._cameras[cameraName] = camera; } else if (unique) { indicesToDelete.push(i); } } for (i = 0; i < indicesToDelete.length; i++) { cameras.splice(indicesToDelete[i], 1); } for (var renderEffectName in this._renderEffects) { if (this._renderEffects.hasOwnProperty(renderEffectName)) { this._renderEffects[renderEffectName]._attachCameras(cams); } } }; PostProcessRenderPipeline.prototype._detachCameras = function (cameras) { var cams = BABYLON.Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } for (var renderEffectName in this._renderEffects) { if (this._renderEffects.hasOwnProperty(renderEffectName)) { this._renderEffects[renderEffectName]._detachCameras(cams); } } for (var i = 0; i < cams.length; i++) { this._cameras.splice(this._cameras.indexOf(cams[i]), 1); } }; PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) { var _this = this; var cams = BABYLON.Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } var pass = null; var renderEffectName; for (renderEffectName in this._renderEffects) { if (this._renderEffects.hasOwnProperty(renderEffectName)) { pass = this._renderEffects[renderEffectName].getPass(passName); if (pass != null) { break; } } } if (pass === null) { return; } for (renderEffectName in this._renderEffects) { if (this._renderEffects.hasOwnProperty(renderEffectName)) { this._renderEffects[renderEffectName]._disable(cams); } } pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME; for (var i = 0; i < cams.length; i++) { var camera = cams[i]; var cameraName = camera.name; this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); }); this._renderEffectsForIsolatedPass[cameraName].emptyPasses(); this._renderEffectsForIsolatedPass[cameraName].addPass(pass); this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera); } }; PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) { var _this = this; var cams = BABYLON.Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } for (var i = 0; i < cams.length; i++) { var camera = cams[i]; var cameraName = camera.name; this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); }); this._renderEffectsForIsolatedPass[cameraName]._disable(camera); } for (var renderEffectName in this._renderEffects) { if (this._renderEffects.hasOwnProperty(renderEffectName)) { this._renderEffects[renderEffectName]._enable(cams); } } }; PostProcessRenderPipeline.prototype._update = function () { for (var renderEffectName in this._renderEffects) { if (this._renderEffects.hasOwnProperty(renderEffectName)) { this._renderEffects[renderEffectName]._update(); } } for (var i = 0; i < this._cameras.length; i++) { var cameraName = this._cameras[i].name; if (this._renderEffectsForIsolatedPass[cameraName]) { this._renderEffectsForIsolatedPass[cameraName]._update(); } } }; PostProcessRenderPipeline.prototype._reset = function () { this._renderEffects = {}; this._renderEffectsForIsolatedPass = new Array(); }; PostProcessRenderPipeline.prototype.dispose = function () { // Must be implemented by children }; PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect"; PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler"; __decorate([ BABYLON.serialize() ], PostProcessRenderPipeline.prototype, "_name", void 0); return PostProcessRenderPipeline; }()); BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map var BABYLON; (function (BABYLON) { var DepthRenderer = /** @class */ (function () { function DepthRenderer(scene, type) { if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; } var _this = this; this._scene = scene; var engine = scene.getEngine(); // Render target this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type); this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; this._depthMap.refreshRate = 1; this._depthMap.renderParticles = false; this._depthMap.renderList = null; // set default depth value to 1.0 (far away) this._depthMap.onClearObservable.add(function (engine) { engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true); }); // Custom render function var renderSubMesh = function (subMesh) { var mesh = subMesh.getRenderingMesh(); var scene = _this._scene; var engine = scene.getEngine(); var material = subMesh.getMaterial(); if (!material) { return; } // Culling engine.setState(material.backFaceCulling); // Managing instances var batch = mesh._getInstancesRenderList(subMesh._id); if (batch.mustReturn) { return; } var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null); if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) { engine.enableEffect(_this._effect); mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode); _this._effect.setMatrix("viewProjection", scene.getTransformMatrix()); _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ); // Alpha test if (material && material.needAlphaTesting()) { var alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { _this._effect.setTexture("diffuseSampler", alphaTexture); _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); } } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh)); } // Draw mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); }); } }; this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { var index; if (depthOnlySubMeshes.length) { engine.setColorWrite(false); for (index = 0; index < depthOnlySubMeshes.length; index++) { renderSubMesh(depthOnlySubMeshes.data[index]); } engine.setColorWrite(true); } for (index = 0; index < opaqueSubMeshes.length; index++) { renderSubMesh(opaqueSubMeshes.data[index]); } for (index = 0; index < alphaTestSubMeshes.length; index++) { renderSubMesh(alphaTestSubMeshes.data[index]); } }; } DepthRenderer.prototype.isReady = function (subMesh, useInstances) { var material = subMesh.getMaterial(); if (material.disableDepthWrite) { return false; } var defines = []; var attribs = [BABYLON.VertexBuffer.PositionKind]; var mesh = subMesh.getMesh(); // Alpha test if (material && material.needAlphaTesting()) { defines.push("#define ALPHATEST"); if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) { attribs.push(BABYLON.VertexBuffer.UVKind); defines.push("#define UV1"); } if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) { attribs.push(BABYLON.VertexBuffer.UV2Kind); defines.push("#define UV2"); } } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0)); } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } // Instances if (useInstances) { defines.push("#define INSTANCES"); attribs.push("world0"); attribs.push("world1"); attribs.push("world2"); attribs.push("world3"); } // Get correct effect var join = defines.join("\n"); if (this._cachedDefines !== join) { this._cachedDefines = join; this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join); } return this._effect.isReady(); }; DepthRenderer.prototype.getDepthMap = function () { return this._depthMap; }; // Methods DepthRenderer.prototype.dispose = function () { this._depthMap.dispose(); }; return DepthRenderer; }()); BABYLON.DepthRenderer = DepthRenderer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.depthRenderer.js.map var BABYLON; (function (BABYLON) { var SSAORenderingPipeline = /** @class */ (function (_super) { __extends(SSAORenderingPipeline, _super); /** * @constructor * @param {string} name - The rendering pipeline name * @param {BABYLON.Scene} scene - The scene linked to this pipeline * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 } * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to */ function SSAORenderingPipeline(name, scene, ratio, cameras) { var _this = _super.call(this, scene.getEngine(), name) || this; // Members /** * The PassPostProcess id in the pipeline that contains the original scene color * @type {string} */ _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect"; /** * The SSAO PostProcess id in the pipeline * @type {string} */ _this.SSAORenderEffect = "SSAORenderEffect"; /** * The horizontal blur PostProcess id in the pipeline * @type {string} */ _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect"; /** * The vertical blur PostProcess id in the pipeline * @type {string} */ _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect"; /** * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect) * @type {string} */ _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect"; /** * The output strength of the SSAO post-process. Default value is 1.0. * @type {number} */ _this.totalStrength = 1.0; /** * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006 * @type {number} */ _this.radius = 0.0001; /** * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel * Must not be equal to fallOff and superior to fallOff. * Default value is 0.975 * @type {number} */ _this.area = 0.0075; /** * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel * Must not be equal to area and inferior to area. * Default value is 0.0 * @type {number} */ _this.fallOff = 0.000001; /** * The base color of the SSAO post-process * The final result is "base + ssao" between [0, 1] * @type {number} */ _this.base = 0.5; _this._firstUpdate = true; _this._scene = scene; // Set up assets _this._createRandomTexture(); _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on" var ssaoRatio = ratio.ssaoRatio || ratio; var combineRatio = ratio.combineRatio || ratio; _this._ratio = { ssaoRatio: ssaoRatio, combineRatio: combineRatio }; _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false); _this._createSSAOPostProcess(ssaoRatio); _this._createBlurPostProcess(ssaoRatio); _this._createSSAOCombinePostProcess(combineRatio); // Set up pipeline _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true)); _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true)); _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true)); _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true)); _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true)); // Finish scene.postProcessRenderPipelineManager.addPipeline(_this); if (cameras) scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras); return _this; } // Public Methods /** * Removes the internal pipeline assets and detatches the pipeline from the scene cameras */ SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) { if (disableDepthRender === void 0) { disableDepthRender = false; } for (var i = 0; i < this._scene.cameras.length; i++) { var camera = this._scene.cameras[i]; this._originalColorPostProcess.dispose(camera); this._ssaoPostProcess.dispose(camera); this._blurHPostProcess.dispose(camera); this._blurVPostProcess.dispose(camera); this._ssaoCombinePostProcess.dispose(camera); } this._randomTexture.dispose(); if (disableDepthRender) this._scene.disableDepthRenderer(); this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras); _super.prototype.dispose.call(this); }; // Private Methods SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) { var _this = this; /* var samplerOffsets = [ -8.0, -6.0, -4.0, -2.0, 0.0, 2.0, 4.0, 6.0, 8.0 ]; */ var samplerOffsets = new Array(); for (var i = -8; i < 8; i++) { samplerOffsets.push(i * 2); } this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16"); this._blurHPostProcess.onApply = function (effect) { effect.setFloat("outSize", _this._ssaoCombinePostProcess.width); effect.setTexture("depthSampler", _this._depthTexture); if (_this._firstUpdate) { effect.setArray("samplerOffsets", samplerOffsets); } }; this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16"); this._blurVPostProcess.onApply = function (effect) { effect.setFloat("outSize", _this._ssaoCombinePostProcess.height); effect.setTexture("depthSampler", _this._depthTexture); if (_this._firstUpdate) { effect.setArray("samplerOffsets", samplerOffsets); _this._firstUpdate = false; } }; }; SSAORenderingPipeline.prototype._rebuild = function () { this._firstUpdate = true; _super.prototype._rebuild.call(this); }; SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) { var _this = this; var numSamples = 16; var sampleSphere = [ 0.5381, 0.1856, -0.4319, 0.1379, 0.2486, 0.4430, 0.3371, 0.5679, -0.0057, -0.6999, -0.0451, -0.0019, 0.0689, -0.1598, -0.8547, 0.0560, 0.0069, -0.1843, -0.0146, 0.1402, 0.0762, 0.0100, -0.1924, -0.0344, -0.3577, -0.5301, -0.4358, -0.3169, 0.1063, 0.0158, 0.0103, -0.5869, 0.0046, -0.0897, -0.4940, 0.3287, 0.7119, -0.0154, -0.0918, -0.0533, 0.0596, -0.5411, 0.0352, -0.0631, 0.5460, -0.4776, 0.2847, -0.0271 ]; var samplesFactor = 1.0 / numSamples; this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [ "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff", "base", "range", "viewport" ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO"); this._ssaoPostProcess.onApply = function (effect) { if (_this._firstUpdate) { effect.setArray3("sampleSphere", sampleSphere); effect.setFloat("samplesFactor", samplesFactor); effect.setFloat("randTextureTiles", 4.0); } effect.setFloat("totalStrength", _this.totalStrength); effect.setFloat("radius", _this.radius); effect.setFloat("area", _this.area); effect.setFloat("fallOff", _this.fallOff); effect.setFloat("base", _this.base); effect.setTexture("textureSampler", _this._depthTexture); effect.setTexture("randomSampler", _this._randomTexture); }; }; SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) { var _this = this; this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false); this._ssaoCombinePostProcess.onApply = function (effect) { effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess); }; }; SSAORenderingPipeline.prototype._createRandomTexture = function () { var size = 512; this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE); this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE; this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE; var context = this._randomTexture.getContext(); var rand = function (min, max) { return Math.random() * (max - min) + min; }; var randVector = BABYLON.Vector3.Zero(); for (var x = 0; x < size; x++) { for (var y = 0; y < size; y++) { randVector.x = Math.floor(rand(-1.0, 1.0) * 255); randVector.y = Math.floor(rand(-1.0, 1.0) * 255); randVector.z = Math.floor(rand(-1.0, 1.0) * 255); context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')'; context.fillRect(x, y, 1, 1); } } this._randomTexture.update(false); }; __decorate([ BABYLON.serialize() ], SSAORenderingPipeline.prototype, "totalStrength", void 0); __decorate([ BABYLON.serialize() ], SSAORenderingPipeline.prototype, "radius", void 0); __decorate([ BABYLON.serialize() ], SSAORenderingPipeline.prototype, "area", void 0); __decorate([ BABYLON.serialize() ], SSAORenderingPipeline.prototype, "fallOff", void 0); __decorate([ BABYLON.serialize() ], SSAORenderingPipeline.prototype, "base", void 0); __decorate([ BABYLON.serialize() ], SSAORenderingPipeline.prototype, "_ratio", void 0); return SSAORenderingPipeline; }(BABYLON.PostProcessRenderPipeline)); BABYLON.SSAORenderingPipeline = SSAORenderingPipeline; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map var BABYLON; (function (BABYLON) { var SSAO2RenderingPipeline = /** @class */ (function (_super) { __extends(SSAO2RenderingPipeline, _super); /** * @constructor * @param {string} name - The rendering pipeline name * @param {BABYLON.Scene} scene - The scene linked to this pipeline * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 } * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to */ function SSAO2RenderingPipeline(name, scene, ratio, cameras) { var _this = _super.call(this, scene.getEngine(), name) || this; // Members /** * The PassPostProcess id in the pipeline that contains the original scene color * @type {string} */ _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect"; /** * The SSAO PostProcess id in the pipeline * @type {string} */ _this.SSAORenderEffect = "SSAORenderEffect"; /** * The horizontal blur PostProcess id in the pipeline * @type {string} */ _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect"; /** * The vertical blur PostProcess id in the pipeline * @type {string} */ _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect"; /** * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect) * @type {string} */ _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect"; /** * The output strength of the SSAO post-process. Default value is 1.0. * @type {number} */ _this.totalStrength = 1.0; /** * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change. * @type {number} */ _this.maxZ = 100.0; /** * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much * @type {number} */ _this.minZAspect = 0.2; /** * Number of samples used for the SSAO calculations. Default value is 8 * @type {number} */ _this._samples = 8; /** * Are we using bilateral blur ? * @type {boolean} */ _this._expensiveBlur = true; /** * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0 * @type {number} */ _this.radius = 2.0; /** * The base color of the SSAO post-process * The final result is "base + ssao" between [0, 1] * @type {number} */ _this.base = 0.1; _this._firstUpdate = true; _this._scene = scene; if (!_this.isSupported) { BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support."); return _this; } var ssaoRatio = ratio.ssaoRatio || ratio; var blurRatio = ratio.blurRatio || ratio; _this._ratio = { ssaoRatio: ssaoRatio, blurRatio: blurRatio }; // Set up assets var geometryBufferRenderer = scene.enableGeometryBufferRenderer(); _this._createRandomTexture(); _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0]; _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1]; _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false); _this._createSSAOPostProcess(1.0); _this._createBlurPostProcess(ssaoRatio, blurRatio); _this._createSSAOCombinePostProcess(blurRatio); // Set up pipeline _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true)); _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true)); _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true)); _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true)); _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true)); // Finish scene.postProcessRenderPipelineManager.addPipeline(_this); if (cameras) scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras); return _this; } Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", { get: function () { return this._samples; }, set: function (n) { this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO"); this._samples = n; this._sampleSphere = this._generateHemisphere(); this._firstUpdate = true; }, enumerable: true, configurable: true }); Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", { get: function () { return this._expensiveBlur; }, set: function (b) { this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]); this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]); this._expensiveBlur = b; this._firstUpdate = true; }, enumerable: true, configurable: true }); Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", { /** * Support test. * @type {boolean} */ get: function () { var engine = BABYLON.Engine.LastCreatedEngine; if (!engine) { return false; } return engine.getCaps().drawBuffersExtension; }, enumerable: true, configurable: true }); // Public Methods /** * Removes the internal pipeline assets and detatches the pipeline from the scene cameras */ SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) { if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; } for (var i = 0; i < this._scene.cameras.length; i++) { var camera = this._scene.cameras[i]; this._originalColorPostProcess.dispose(camera); this._ssaoPostProcess.dispose(camera); this._blurHPostProcess.dispose(camera); this._blurVPostProcess.dispose(camera); this._ssaoCombinePostProcess.dispose(camera); } this._randomTexture.dispose(); if (disableGeometryBufferRenderer) this._scene.disableGeometryBufferRenderer(); this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras); _super.prototype.dispose.call(this); }; // Private Methods SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) { var _this = this; this._samplerOffsets = []; var expensive = this.expensiveBlur; for (var i = -8; i < 8; i++) { this._samplerOffsets.push(i * 2 + 0.5); } this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n"); this._blurHPostProcess.onApply = function (effect) { if (!_this._scene.activeCamera) { return; } effect.setFloat("outSize", _this._ssaoCombinePostProcess.width); effect.setFloat("near", _this._scene.activeCamera.minZ); effect.setFloat("far", _this._scene.activeCamera.maxZ); effect.setFloat("radius", _this.radius); effect.setTexture("depthSampler", _this._depthTexture); if (_this._firstUpdate) { effect.setArray("samplerOffsets", _this._samplerOffsets); } }; this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n"); this._blurVPostProcess.onApply = function (effect) { if (!_this._scene.activeCamera) { return; } effect.setFloat("outSize", _this._ssaoCombinePostProcess.height); effect.setFloat("near", _this._scene.activeCamera.minZ); effect.setFloat("far", _this._scene.activeCamera.maxZ); effect.setFloat("radius", _this.radius); effect.setTexture("depthSampler", _this._depthTexture); if (_this._firstUpdate) { effect.setArray("samplerOffsets", _this._samplerOffsets); _this._firstUpdate = false; } }; }; SSAO2RenderingPipeline.prototype._rebuild = function () { this._firstUpdate = true; _super.prototype._rebuild.call(this); }; SSAO2RenderingPipeline.prototype._generateHemisphere = function () { var numSamples = this.samples; var result = []; var vector, scale; var rand = function (min, max) { return Math.random() * (max - min) + min; }; var i = 0; while (i < numSamples) { vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0)); vector.normalize(); scale = i / numSamples; scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale); vector.scaleInPlace(scale); result.push(vector.x, vector.y, vector.z); i++; } return result; }; SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) { var _this = this; var numSamples = this.samples; this._sampleSphere = this._generateHemisphere(); this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [ "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "base", "range", "projection", "near", "far", "texelSize", "xViewport", "yViewport", "maxZ", "minZAspect" ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO"); this._ssaoPostProcess.onApply = function (effect) { if (_this._firstUpdate) { effect.setArray3("sampleSphere", _this._sampleSphere); effect.setFloat("randTextureTiles", 4.0); } if (!_this._scene.activeCamera) { return; } effect.setFloat("samplesFactor", 1 / _this.samples); effect.setFloat("totalStrength", _this.totalStrength); effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height); effect.setFloat("radius", _this.radius); effect.setFloat("maxZ", _this.maxZ); effect.setFloat("minZAspect", _this.minZAspect); effect.setFloat("base", _this.base); effect.setFloat("near", _this._scene.activeCamera.minZ); effect.setFloat("far", _this._scene.activeCamera.maxZ); effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true)); effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2)); effect.setMatrix("projection", _this._scene.getProjectionMatrix()); effect.setTexture("textureSampler", _this._depthTexture); effect.setTexture("normalSampler", _this._normalTexture); effect.setTexture("randomSampler", _this._randomTexture); }; }; SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) { var _this = this; this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false); this._ssaoCombinePostProcess.onApply = function (effect) { effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess); }; }; SSAO2RenderingPipeline.prototype._createRandomTexture = function () { var size = 512; this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE); this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE; this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE; var context = this._randomTexture.getContext(); var rand = function (min, max) { return Math.random() * (max - min) + min; }; var randVector = BABYLON.Vector3.Zero(); for (var x = 0; x < size; x++) { for (var y = 0; y < size; y++) { randVector.x = rand(0.0, 1.0); randVector.y = rand(0.0, 1.0); randVector.z = 0.0; randVector.normalize(); randVector.scaleInPlace(255); randVector.x = Math.floor(randVector.x); randVector.y = Math.floor(randVector.y); context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')'; context.fillRect(x, y, 1, 1); } } this._randomTexture.update(false); }; __decorate([ BABYLON.serialize() ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0); __decorate([ BABYLON.serialize() ], SSAO2RenderingPipeline.prototype, "maxZ", void 0); __decorate([ BABYLON.serialize() ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0); __decorate([ BABYLON.serialize("samples") ], SSAO2RenderingPipeline.prototype, "_samples", void 0); __decorate([ BABYLON.serialize("expensiveBlur") ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0); __decorate([ BABYLON.serialize() ], SSAO2RenderingPipeline.prototype, "radius", void 0); __decorate([ BABYLON.serialize() ], SSAO2RenderingPipeline.prototype, "base", void 0); __decorate([ BABYLON.serialize() ], SSAO2RenderingPipeline.prototype, "_ratio", void 0); return SSAO2RenderingPipeline; }(BABYLON.PostProcessRenderPipeline)); BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map // BABYLON.JS Chromatic Aberration GLSL Shader // Author: Olivier Guyot // Separates very slightly R, G and B colors on the edges of the screen // Inspired by Francois Tarlier & Martins Upitis var BABYLON; (function (BABYLON) { var LensRenderingPipeline = /** @class */ (function (_super) { __extends(LensRenderingPipeline, _super); /** * @constructor * * Effect parameters are as follow: * { * chromatic_aberration: number; // from 0 to x (1 for realism) * edge_blur: number; // from 0 to x (1 for realism) * distortion: number; // from 0 to x (1 for realism) * grain_amount: number; // from 0 to 1 * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default) * dof_aperture: number; // depth-of-field: focus blur bias (default: 1) * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default) * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default) * dof_threshold: number; // depth-of-field: highlights threshold (default: 1) * blur_noise: boolean; // add a little bit of noise to the blur (default: true) * } * Note: if an effect parameter is unset, effect is disabled * * @param {string} name - The rendering pipeline name * @param {object} parameters - An object containing all parameters (see above) * @param {BABYLON.Scene} scene - The scene linked to this pipeline * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to */ function LensRenderingPipeline(name, parameters, scene, ratio, cameras) { if (ratio === void 0) { ratio = 1.0; } var _this = _super.call(this, scene.getEngine(), name) || this; // Lens effects can be of the following: // - chromatic aberration (slight shift of RGB colors) // - blur on the edge of the lens // - lens distortion // - depth-of-field blur & highlights enhancing // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas) // - grain effect (noise or custom texture) // Two additional texture samplers are needed: // - depth map (for depth-of-field) // - grain texture /** * The chromatic aberration PostProcess id in the pipeline * @type {string} */ _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect"; /** * The highlights enhancing PostProcess id in the pipeline * @type {string} */ _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect"; /** * The depth-of-field PostProcess id in the pipeline * @type {string} */ _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect"; _this._scene = scene; // Fetch texture samplers _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on" if (parameters.grain_texture) { _this._grainTexture = parameters.grain_texture; } else { _this._createGrainTexture(); } // save parameters _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0; _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0; _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0; _this._distortion = parameters.distortion ? parameters.distortion : 0; _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1; _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1; _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1; _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1; _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0; _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true; _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true; // Create effects _this._createChromaticAberrationPostProcess(ratio); _this._createHighlightsPostProcess(ratio); _this._createDepthOfFieldPostProcess(ratio / 4); // Set up pipeline _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true)); _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true)); _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true)); if (_this._highlightsGain === -1) { _this._disableEffect(_this.HighlightsEnhancingEffect, null); } // Finish scene.postProcessRenderPipelineManager.addPipeline(_this); if (cameras) { scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras); } return _this; } // public methods (self explanatory) LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; }; LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; }; LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; }; LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; }; LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; }; LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; }; LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; }; LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; }; LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; }; LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; }; LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; }; LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; }; LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._highlightsPostProcess.updateEffect("#define PENTAGON\n"); }; LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._highlightsPostProcess.updateEffect(); }; LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; }; LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; }; LensRenderingPipeline.prototype.setHighlightsGain = function (amount) { this._highlightsGain = amount; }; LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) { if (this._highlightsGain === -1) { this._highlightsGain = 1.0; } this._highlightsThreshold = amount; }; LensRenderingPipeline.prototype.disableHighlights = function () { this._highlightsGain = -1; }; /** * Removes the internal pipeline assets and detaches the pipeline from the scene cameras */ LensRenderingPipeline.prototype.dispose = function (disableDepthRender) { if (disableDepthRender === void 0) { disableDepthRender = false; } this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras); this._chromaticAberrationPostProcess = null; this._highlightsPostProcess = null; this._depthOfFieldPostProcess = null; this._grainTexture.dispose(); if (disableDepthRender) this._scene.disableDepthRenderer(); }; // colors shifting and distortion LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) { var _this = this; this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms [], // samplers ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false); this._chromaticAberrationPostProcess.onApply = function (effect) { effect.setFloat('chromatic_aberration', _this._chromaticAberration); effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth()); effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight()); }; }; // highlights enhancing LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) { var _this = this; this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms [], // samplers ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : ""); this._highlightsPostProcess.onApply = function (effect) { effect.setFloat('gain', _this._highlightsGain); effect.setFloat('threshold', _this._highlightsThreshold); effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess); effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth()); effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight()); }; }; // colors shifting and distortion LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) { var _this = this; this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [ "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled", "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far" ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false); this._depthOfFieldPostProcess.onApply = function (effect) { effect.setTexture("depthSampler", _this._depthTexture); effect.setTexture("grainSampler", _this._grainTexture); effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess); effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess); effect.setFloat('grain_amount', _this._grainAmount); effect.setBool('blur_noise', _this._blurNoise); effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth()); effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight()); effect.setFloat('distortion', _this._distortion); effect.setBool('dof_enabled', (_this._dofDistance !== -1)); effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance)); effect.setFloat('aperture', _this._dofAperture); effect.setFloat('darken', _this._dofDarken); effect.setFloat('edge_blur', _this._edgeBlur); effect.setBool('highlights', (_this._highlightsGain !== -1)); if (_this._scene.activeCamera) { effect.setFloat('near', _this._scene.activeCamera.minZ); effect.setFloat('far', _this._scene.activeCamera.maxZ); } }; }; // creates a black and white random noise texture, 512x512 LensRenderingPipeline.prototype._createGrainTexture = function () { var size = 512; this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE); this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE; this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE; var context = this._grainTexture.getContext(); var rand = function (min, max) { return Math.random() * (max - min) + min; }; var value; for (var x = 0; x < size; x++) { for (var y = 0; y < size; y++) { value = Math.floor(rand(0.42, 0.58) * 255); context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')'; context.fillRect(x, y, 1, 1); } } this._grainTexture.update(false); }; return LensRenderingPipeline; }(BABYLON.PostProcessRenderPipeline)); BABYLON.LensRenderingPipeline = LensRenderingPipeline; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.lensRenderingPipeline.js.map var BABYLON; (function (BABYLON) { var StandardRenderingPipeline = /** @class */ (function (_super) { __extends(StandardRenderingPipeline, _super); /** * @constructor * @param {string} name - The rendering pipeline name * @param {BABYLON.Scene} scene - The scene linked to this pipeline * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to */ function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) { if (originalPostProcess === void 0) { originalPostProcess = null; } var _this = _super.call(this, scene.getEngine(), name) || this; _this.downSampleX4PostProcess = null; _this.brightPassPostProcess = null; _this.blurHPostProcesses = []; _this.blurVPostProcesses = []; _this.textureAdderPostProcess = null; _this.volumetricLightPostProcess = null; _this.volumetricLightSmoothXPostProcess = null; _this.volumetricLightSmoothYPostProcess = null; _this.volumetricLightMergePostProces = null; _this.volumetricLightFinalPostProcess = null; _this.luminancePostProcess = null; _this.luminanceDownSamplePostProcesses = []; _this.hdrPostProcess = null; _this.textureAdderFinalPostProcess = null; _this.lensFlareFinalPostProcess = null; _this.hdrFinalPostProcess = null; _this.lensFlarePostProcess = null; _this.lensFlareComposePostProcess = null; _this.motionBlurPostProcess = null; _this.depthOfFieldPostProcess = null; // Values _this.brightThreshold = 1.0; _this.blurWidth = 512.0; _this.horizontalBlur = false; _this.exposure = 1.0; _this.lensTexture = null; _this.volumetricLightCoefficient = 0.2; _this.volumetricLightPower = 4.0; _this.volumetricLightBlurScale = 64.0; _this.sourceLight = null; _this.hdrMinimumLuminance = 1.0; _this.hdrDecreaseRate = 0.5; _this.hdrIncreaseRate = 0.5; _this.lensColorTexture = null; _this.lensFlareStrength = 20.0; _this.lensFlareGhostDispersal = 1.4; _this.lensFlareHaloWidth = 0.7; _this.lensFlareDistortionStrength = 16.0; _this.lensStarTexture = null; _this.lensFlareDirtTexture = null; _this.depthOfFieldDistance = 10.0; _this.depthOfFieldBlurWidth = 64.0; _this.motionStrength = 1.0; // IAnimatable _this.animations = []; _this._currentDepthOfFieldSource = null; _this._hdrCurrentLuminance = 1.0; // Getters and setters _this._bloomEnabled = true; _this._depthOfFieldEnabled = false; _this._vlsEnabled = false; _this._lensFlareEnabled = false; _this._hdrEnabled = false; _this._motionBlurEnabled = false; _this._motionBlurSamples = 64.0; _this._volumetricLightStepsCount = 50.0; _this._cameras = cameras || []; // Initialize _this._scene = scene; _this._basePostProcess = originalPostProcess; _this._ratio = ratio; // Misc _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT; // Finish scene.postProcessRenderPipelineManager.addPipeline(_this); _this._buildPipeline(); return _this; } Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", { get: function () { return this._bloomEnabled; }, set: function (enabled) { if (this._bloomEnabled === enabled) { return; } this._bloomEnabled = enabled; this._buildPipeline(); }, enumerable: true, configurable: true }); Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", { get: function () { return this._depthOfFieldEnabled; }, set: function (enabled) { if (this._depthOfFieldEnabled === enabled) { return; } this._depthOfFieldEnabled = enabled; this._buildPipeline(); }, enumerable: true, configurable: true }); Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", { get: function () { return this._lensFlareEnabled; }, set: function (enabled) { if (this._lensFlareEnabled === enabled) { return; } this._lensFlareEnabled = enabled; this._buildPipeline(); }, enumerable: true, configurable: true }); Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", { get: function () { return this._hdrEnabled; }, set: function (enabled) { if (this._hdrEnabled === enabled) { return; } this._hdrEnabled = enabled; this._buildPipeline(); }, enumerable: true, configurable: true }); Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", { get: function () { return this._vlsEnabled; }, set: function (enabled) { if (this._vlsEnabled === enabled) { return; } if (enabled) { var geometry = this._scene.enableGeometryBufferRenderer(); if (!geometry) { BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline"); return; } } this._vlsEnabled = enabled; this._buildPipeline(); }, enumerable: true, configurable: true }); Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", { get: function () { return this._motionBlurEnabled; }, set: function (enabled) { if (this._motionBlurEnabled === enabled) { return; } this._motionBlurEnabled = enabled; this._buildPipeline(); }, enumerable: true, configurable: true }); Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", { get: function () { return this._volumetricLightStepsCount; }, set: function (count) { if (this.volumetricLightPostProcess) { this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1)); } this._volumetricLightStepsCount = count; }, enumerable: true, configurable: true }); Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", { get: function () { return this._motionBlurSamples; }, set: function (samples) { if (this.motionBlurPostProcess) { this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1)); } this._motionBlurSamples = samples; }, enumerable: true, configurable: true }); StandardRenderingPipeline.prototype._buildPipeline = function () { var _this = this; var ratio = this._ratio; var scene = this._scene; this._disposePostProcesses(); this._reset(); // Create pass post-process if (!this._basePostProcess) { this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType); this.originalPostProcess.onApply = function (effect) { _this._currentDepthOfFieldSource = _this.originalPostProcess; }; } else { this.originalPostProcess = this._basePostProcess; } this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true)); this._currentDepthOfFieldSource = this.originalPostProcess; if (this._vlsEnabled) { // Create volumetric light this._createVolumetricLightPostProcess(scene, ratio); // Create volumetric light final post-process this.volumetricLightFinalPostProcess = new BABYLON.PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true)); } if (this._bloomEnabled) { // Create down sample X4 post-process this._createDownSampleX4PostProcess(scene, ratio / 2); // Create bright pass post-process this._createBrightPassPostProcess(scene, ratio / 2); // Create gaussian blur post-processes (down sampling blurs) this._createBlurPostProcesses(scene, ratio / 4, 1); // Create texture adder post-process this._createTextureAdderPostProcess(scene, ratio); // Create depth-of-field source post-process this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true)); } if (this._lensFlareEnabled) { // Create lens flare post-process this._createLensFlarePostProcess(scene, ratio); // Create depth-of-field source post-process post lens-flare and disable it now this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true)); } if (this._hdrEnabled) { // Create luminance this._createLuminancePostProcesses(scene, this._floatTextureType); // Create HDR this._createHdrPostProcess(scene, ratio); // Create depth-of-field source post-process post hdr and disable it now this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true)); } if (this._depthOfFieldEnabled) { // Create gaussian blur used by depth-of-field this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth"); // Create depth-of-field post-process this._createDepthOfFieldPostProcess(scene, ratio); } if (this._motionBlurEnabled) { // Create motion blur post-process this._createMotionBlurPostProcess(scene, ratio); } if (this._cameras !== null) { this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); } }; // Down Sample X4 Post-Processs StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) { var _this = this; var downSampleX4Offsets = new Array(32); this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this.downSampleX4PostProcess.onApply = function (effect) { var id = 0; var width = _this.downSampleX4PostProcess.width; var height = _this.downSampleX4PostProcess.height; for (var i = -2; i < 2; i++) { for (var j = -2; j < 2; j++) { downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width); downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height); id += 2; } } effect.setArray2("dsOffsets", downSampleX4Offsets); }; // Add to pipeline this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true)); }; // Brightpass Post-Process StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) { var _this = this; var brightOffsets = new Array(8); this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this.brightPassPostProcess.onApply = function (effect) { var sU = (1.0 / _this.brightPassPostProcess.width); var sV = (1.0 / _this.brightPassPostProcess.height); brightOffsets[0] = -0.5 * sU; brightOffsets[1] = 0.5 * sV; brightOffsets[2] = 0.5 * sU; brightOffsets[3] = 0.5 * sV; brightOffsets[4] = -0.5 * sU; brightOffsets[5] = -0.5 * sV; brightOffsets[6] = 0.5 * sU; brightOffsets[7] = -0.5 * sV; effect.setArray2("dsOffsets", brightOffsets); effect.setFloat("brightThreshold", _this.brightThreshold); }; // Add to pipeline this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true)); }; // Create blur H&V post-processes StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) { var _this = this; if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; } var engine = scene.getEngine(); var blurX = new BABYLON.BlurPostProcess("HDRBlurH" + "_" + indice, new BABYLON.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); var blurY = new BABYLON.BlurPostProcess("HDRBlurV" + "_" + indice, new BABYLON.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); blurX.onActivateObservable.add(function () { var dw = blurX.width / engine.getRenderWidth(); blurX.kernel = _this[blurWidthKey] * dw; }); blurY.onActivateObservable.add(function () { var dw = blurY.height / engine.getRenderHeight(); blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw; }); this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true)); this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true)); this.blurHPostProcesses.push(blurX); this.blurVPostProcesses.push(blurY); }; // Create texture adder post-process StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) { var _this = this; this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this.textureAdderPostProcess.onApply = function (effect) { effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess); effect.setTexture("lensSampler", _this.lensTexture); effect.setFloat("exposure", _this.exposure); _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess; }; // Add to pipeline this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true)); }; StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) { var _this = this; var geometryRenderer = scene.enableGeometryBufferRenderer(); geometryRenderer.enablePosition = true; var geometry = geometryRenderer.getGBuffer(); // Base post-process this.volumetricLightPostProcess = new BABYLON.PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1)); var depthValues = BABYLON.Vector2.Zero(); this.volumetricLightPostProcess.onApply = function (effect) { if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) { var generator = _this.sourceLight.getShadowGenerator(); effect.setTexture("shadowMapSampler", generator.getShadowMap()); effect.setTexture("positionSampler", geometry.textures[2]); effect.setColor3("sunColor", _this.sourceLight.diffuse); effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection()); effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition); effect.setMatrix("shadowViewProjection", generator.getTransformMatrix()); effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient); effect.setFloat("scatteringPower", _this.volumetricLightPower); depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera); depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera); effect.setVector2("depthValues", depthValues); } }; this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true)); // Smooth this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale"); // Merge this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE"); this.volumetricLightMergePostProces.onApply = function (effect) { effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess); _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess; }; this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true)); }; // Create luminance StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) { var _this = this; // Create luminance var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps); this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType); var offsets = []; this.luminancePostProcess.onApply = function (effect) { var sU = (1.0 / _this.luminancePostProcess.width); var sV = (1.0 / _this.luminancePostProcess.height); offsets[0] = -0.5 * sU; offsets[1] = 0.5 * sV; offsets[2] = 0.5 * sU; offsets[3] = 0.5 * sV; offsets[4] = -0.5 * sU; offsets[5] = -0.5 * sV; offsets[6] = 0.5 * sU; offsets[7] = -0.5 * sV; effect.setArray2("lumOffsets", offsets); }; // Add to pipeline this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true)); // Create down sample luminance for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) { var size = Math.pow(3, i); var defines = "#define LUMINANCE_DOWN_SAMPLE\n"; if (i === 0) { defines += "#define FINAL_DOWN_SAMPLER"; } var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType); this.luminanceDownSamplePostProcesses.push(postProcess); } // Create callbacks and add effects var lastLuminance = this.luminancePostProcess; this.luminanceDownSamplePostProcesses.forEach(function (pp, index) { var downSampleOffsets = new Array(18); pp.onApply = function (effect) { if (!lastLuminance) { return; } var id = 0; for (var x = -1; x < 2; x++) { for (var y = -1; y < 2; y++) { downSampleOffsets[id] = x / lastLuminance.width; downSampleOffsets[id + 1] = y / lastLuminance.height; id += 2; } } effect.setArray2("dsOffsets", downSampleOffsets); effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width); if (index === _this.luminanceDownSamplePostProcesses.length - 1) { lastLuminance = _this.luminancePostProcess; } else { lastLuminance = pp; } }; if (index === _this.luminanceDownSamplePostProcesses.length - 1) { pp.onAfterRender = function (effect) { var pixel = scene.getEngine().readPixels(0, 0, 1, 1); var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0); _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0; }; } _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true)); }); }; // Create HDR post-process StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) { var _this = this; this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); var outputLiminance = 1; var time = 0; var lastTime = 0; this.hdrPostProcess.onApply = function (effect) { effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource); time += scene.getEngine().getDeltaTime(); if (outputLiminance < 0) { outputLiminance = _this._hdrCurrentLuminance; } else { var dt = (lastTime - time) / 1000.0; if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) { outputLiminance += _this.hdrDecreaseRate * dt; } else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) { outputLiminance -= _this.hdrIncreaseRate * dt; } else { outputLiminance = _this._hdrCurrentLuminance; } } outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20); effect.setFloat("averageLuminance", outputLiminance); lastTime = time; _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess; }; this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true)); }; // Create lens flare post-process StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) { var _this = this; this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true)); this._createBlurPostProcesses(scene, ratio / 4, 2); this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true)); var resolution = new BABYLON.Vector2(0, 0); // Lens flare this.lensFlarePostProcess.onApply = function (effect) { effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess); effect.setTexture("lensColorSampler", _this.lensColorTexture); effect.setFloat("strength", _this.lensFlareStrength); effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal); effect.setFloat("haloWidth", _this.lensFlareHaloWidth); // Shift resolution.x = _this.lensFlarePostProcess.width; resolution.y = _this.lensFlarePostProcess.height; effect.setVector2("resolution", resolution); effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength); }; // Compose var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); this.lensFlareComposePostProcess.onApply = function (effect) { if (!_this._scene.activeCamera) { return; } effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource); effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture); effect.setTexture("lensStarSampler", _this.lensStarTexture); // Lens start rotation matrix var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0); var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2); var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0)); camRot *= 4.0; var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1); effect.setMatrix("lensStarMatrix", lensStarMatrix); _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess; }; }; // Create depth-of-field post-process StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) { var _this = this; this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this.depthOfFieldPostProcess.onApply = function (effect) { effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource); effect.setTexture("depthSampler", _this._getDepthTexture()); effect.setFloat("distance", _this.depthOfFieldDistance); }; // Add to pipeline this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true)); }; // Create motion blur post-process StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) { var _this = this; this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); var motionScale = 0; var prevViewProjection = BABYLON.Matrix.Identity(); var invViewProjection = BABYLON.Matrix.Identity(); var viewProjection = BABYLON.Matrix.Identity(); var screenSize = BABYLON.Vector2.Zero(); this.motionBlurPostProcess.onApply = function (effect) { viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix()); viewProjection.invertToRef(invViewProjection); effect.setMatrix("inverseViewProjection", invViewProjection); effect.setMatrix("prevViewProjection", prevViewProjection); prevViewProjection = viewProjection; screenSize.x = _this.motionBlurPostProcess.width; screenSize.y = _this.motionBlurPostProcess.height; effect.setVector2("screenSize", screenSize); motionScale = scene.getEngine().getFps() / 60.0; effect.setFloat("motionScale", motionScale); effect.setFloat("motionStrength", _this.motionStrength); effect.setTexture("depthSampler", _this._getDepthTexture()); }; this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true)); }; StandardRenderingPipeline.prototype._getDepthTexture = function () { if (this._scene.getEngine().getCaps().drawBuffersExtension) { var renderer = this._scene.enableGeometryBufferRenderer(); return renderer.getGBuffer().textures[0]; } return this._scene.enableDepthRenderer().getDepthMap(); }; StandardRenderingPipeline.prototype._disposePostProcesses = function () { for (var i = 0; i < this._cameras.length; i++) { var camera = this._cameras[i]; if (this.originalPostProcess) { this.originalPostProcess.dispose(camera); } if (this.downSampleX4PostProcess) { this.downSampleX4PostProcess.dispose(camera); } if (this.brightPassPostProcess) { this.brightPassPostProcess.dispose(camera); } if (this.textureAdderPostProcess) { this.textureAdderPostProcess.dispose(camera); } if (this.textureAdderFinalPostProcess) { this.textureAdderFinalPostProcess.dispose(camera); } if (this.volumetricLightPostProcess) { this.volumetricLightPostProcess.dispose(camera); } if (this.volumetricLightSmoothXPostProcess) { this.volumetricLightSmoothXPostProcess.dispose(camera); } if (this.volumetricLightSmoothYPostProcess) { this.volumetricLightSmoothYPostProcess.dispose(camera); } if (this.volumetricLightMergePostProces) { this.volumetricLightMergePostProces.dispose(camera); } if (this.volumetricLightFinalPostProcess) { this.volumetricLightFinalPostProcess.dispose(camera); } if (this.lensFlarePostProcess) { this.lensFlarePostProcess.dispose(camera); } if (this.lensFlareComposePostProcess) { this.lensFlareComposePostProcess.dispose(camera); } for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) { this.luminanceDownSamplePostProcesses[j].dispose(camera); } if (this.luminancePostProcess) { this.luminancePostProcess.dispose(camera); } if (this.hdrPostProcess) { this.hdrPostProcess.dispose(camera); } if (this.hdrFinalPostProcess) { this.hdrFinalPostProcess.dispose(camera); } if (this.depthOfFieldPostProcess) { this.depthOfFieldPostProcess.dispose(camera); } if (this.motionBlurPostProcess) { this.motionBlurPostProcess.dispose(camera); } for (var j = 0; j < this.blurHPostProcesses.length; j++) { this.blurHPostProcesses[j].dispose(camera); } for (var j = 0; j < this.blurVPostProcesses.length; j++) { this.blurVPostProcesses[j].dispose(camera); } } this.originalPostProcess = null; this.downSampleX4PostProcess = null; this.brightPassPostProcess = null; this.textureAdderPostProcess = null; this.textureAdderFinalPostProcess = null; this.volumetricLightPostProcess = null; this.volumetricLightSmoothXPostProcess = null; this.volumetricLightSmoothYPostProcess = null; this.volumetricLightMergePostProces = null; this.volumetricLightFinalPostProcess = null; this.lensFlarePostProcess = null; this.lensFlareComposePostProcess = null; this.luminancePostProcess = null; this.hdrPostProcess = null; this.hdrFinalPostProcess = null; this.depthOfFieldPostProcess = null; this.motionBlurPostProcess = null; this.luminanceDownSamplePostProcesses = []; this.blurHPostProcesses = []; this.blurVPostProcesses = []; }; // Dispose StandardRenderingPipeline.prototype.dispose = function () { this._disposePostProcesses(); this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); _super.prototype.dispose.call(this); }; // Serialize rendering pipeline StandardRenderingPipeline.prototype.serialize = function () { var serializationObject = BABYLON.SerializationHelper.Serialize(this); serializationObject.customType = "StandardRenderingPipeline"; return serializationObject; }; /** * Static members */ // Parse serialized pipeline StandardRenderingPipeline.Parse = function (source, scene, rootUrl) { return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl); }; // Luminance steps StandardRenderingPipeline.LuminanceSteps = 6; __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "brightThreshold", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "blurWidth", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "exposure", void 0); __decorate([ BABYLON.serializeAsTexture("lensTexture") ], StandardRenderingPipeline.prototype, "lensTexture", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0); __decorate([ BABYLON.serializeAsTexture("lensColorTexture") ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0); __decorate([ BABYLON.serializeAsTexture("lensStarTexture") ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0); __decorate([ BABYLON.serializeAsTexture("lensFlareDirtTexture") ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "motionStrength", void 0); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "BloomEnabled", null); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "HDREnabled", null); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "VLSEnabled", null); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null); __decorate([ BABYLON.serialize() ], StandardRenderingPipeline.prototype, "motionBlurSamples", null); return StandardRenderingPipeline; }(BABYLON.PostProcessRenderPipeline)); BABYLON.StandardRenderingPipeline = StandardRenderingPipeline; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.standardRenderingPipeline.js.map var BABYLON; (function (BABYLON) { var FxaaPostProcess = /** @class */ (function (_super) { __extends(FxaaPostProcess, _super); function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) { if (camera === void 0) { camera = null; } if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this; _this.onApplyObservable.add(function (effect) { var texelSize = _this.texelSize; effect.setFloat2("texelSize", texelSize.x, texelSize.y); }); return _this; } return FxaaPostProcess; }(BABYLON.PostProcess)); BABYLON.FxaaPostProcess = FxaaPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.fxaaPostProcess.js.map var BABYLON; (function (BABYLON) { var DefaultRenderingPipeline = /** @class */ (function (_super) { __extends(DefaultRenderingPipeline, _super); /** * @constructor * @param {string} name - The rendering pipeline name * @param {BABYLON.Scene} scene - The scene linked to this pipeline * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline */ function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) { if (automaticBuild === void 0) { automaticBuild = true; } var _this = _super.call(this, scene.getEngine(), name) || this; _this.PassPostProcessId = "PassPostProcessEffect"; _this.HighLightsPostProcessId = "HighLightsPostProcessEffect"; _this.BlurXPostProcessId = "BlurXPostProcessEffect"; _this.BlurYPostProcessId = "BlurYPostProcessEffect"; _this.CopyBackPostProcessId = "CopyBackPostProcessEffect"; _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect"; _this.FxaaPostProcessId = "FxaaPostProcessEffect"; _this.FinalMergePostProcessId = "FinalMergePostProcessEffect"; // IAnimatable _this.animations = []; // Values _this._bloomEnabled = false; _this._fxaaEnabled = false; _this._imageProcessingEnabled = true; _this._bloomScale = 0.6; _this._buildAllowed = true; /** * Specifies the size of the bloom blur kernel, relative to the final output size */ _this.bloomKernel = 64; /** * Specifies the weight of the bloom in the final rendering */ _this._bloomWeight = 0.15; _this._cameras = cameras || []; _this._buildAllowed = automaticBuild; // Initialize _this._scene = scene; var caps = _this._scene.getEngine().getCaps(); _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender); // Misc if (_this._hdr) { if (caps.textureHalfFloatRender) { _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT; } else if (caps.textureFloatRender) { _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT; } } else { _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } // Attach scene.postProcessRenderPipelineManager.addPipeline(_this); _this._buildPipeline(); return _this; } Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", { get: function () { return this._bloomWeight; }, set: function (value) { if (this._bloomWeight === value) { return; } this._bloomWeight = value; if (this._hdr && this.copyBack) { this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value); } }, enumerable: true, configurable: true }); Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", { get: function () { return this._bloomScale; }, set: function (value) { if (this._bloomScale === value) { return; } this._bloomScale = value; this._buildPipeline(); }, enumerable: true, configurable: true }); Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", { get: function () { return this._bloomEnabled; }, set: function (enabled) { if (this._bloomEnabled === enabled) { return; } this._bloomEnabled = enabled; this._buildPipeline(); }, enumerable: true, configurable: true }); Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", { get: function () { return this._fxaaEnabled; }, set: function (enabled) { if (this._fxaaEnabled === enabled) { return; } this._fxaaEnabled = enabled; this._buildPipeline(); }, enumerable: true, configurable: true }); Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", { get: function () { return this._imageProcessingEnabled; }, set: function (enabled) { if (this._imageProcessingEnabled === enabled) { return; } this._imageProcessingEnabled = enabled; this._buildPipeline(); }, enumerable: true, configurable: true }); /** * Force the compilation of the entire pipeline. */ DefaultRenderingPipeline.prototype.prepare = function () { var previousState = this._buildAllowed; this._buildAllowed = true; this._buildPipeline(); this._buildAllowed = previousState; }; DefaultRenderingPipeline.prototype._buildPipeline = function () { var _this = this; if (!this._buildAllowed) { return; } var engine = this._scene.getEngine(); this._disposePostProcesses(); this._reset(); if (this.bloomEnabled) { this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType); this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true)); if (!this._hdr) { this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType); this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true)); this.highlights.autoClear = false; this.highlights.alwaysForcePOT = true; } this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType); this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true)); this.blurX.alwaysForcePOT = true; this.blurX.autoClear = false; this.blurX.onActivateObservable.add(function () { var dw = _this.blurX.width / engine.getRenderWidth(true); _this.blurX.kernel = _this.bloomKernel * dw; }); this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType); this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true)); this.blurY.alwaysForcePOT = true; this.blurY.autoClear = false; this.blurY.onActivateObservable.add(function () { var dh = _this.blurY.height / engine.getRenderHeight(true); _this.blurY.kernel = _this.bloomKernel * dh; }); this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType); this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true)); this.copyBack.alwaysForcePOT = true; if (this._hdr) { this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE; var w = this.bloomWeight; this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w); } else { this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE; } this.copyBack.autoClear = false; } if (this._imageProcessingEnabled) { this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType); if (this._hdr) { this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true)); } else { this._scene.imageProcessingConfiguration.applyByPostProcess = false; } } if (this.fxaaEnabled) { this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType); this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true)); this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing); } else { this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType); this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true)); this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing); } if (this.bloomEnabled) { if (this._hdr) { this.copyBack.shareOutputWith(this.blurX); if (this.imageProcessing) { this.imageProcessing.shareOutputWith(this.pass); this.imageProcessing.autoClear = false; } else if (this.fxaa) { this.fxaa.shareOutputWith(this.pass); } else { this.finalMerge.shareOutputWith(this.pass); } } else { if (this.fxaa) { this.fxaa.shareOutputWith(this.pass); } else { this.finalMerge.shareOutputWith(this.pass); } } } if (this._cameras !== null) { this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); } }; DefaultRenderingPipeline.prototype._disposePostProcesses = function () { for (var i = 0; i < this._cameras.length; i++) { var camera = this._cameras[i]; if (this.pass) { this.pass.dispose(camera); } if (this.highlights) { this.highlights.dispose(camera); } if (this.blurX) { this.blurX.dispose(camera); } if (this.blurY) { this.blurY.dispose(camera); } if (this.copyBack) { this.copyBack.dispose(camera); } if (this.imageProcessing) { this.imageProcessing.dispose(camera); } if (this.fxaa) { this.fxaa.dispose(camera); } if (this.finalMerge) { this.finalMerge.dispose(camera); } } this.pass = null; this.highlights = null; this.blurX = null; this.blurY = null; this.copyBack = null; this.imageProcessing = null; this.fxaa = null; this.finalMerge = null; }; // Dispose DefaultRenderingPipeline.prototype.dispose = function () { this._disposePostProcesses(); this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); _super.prototype.dispose.call(this); }; // Serialize rendering pipeline DefaultRenderingPipeline.prototype.serialize = function () { var serializationObject = BABYLON.SerializationHelper.Serialize(this); serializationObject.customType = "DefaultRenderingPipeline"; return serializationObject; }; // Parse serialized pipeline DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) { return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl); }; __decorate([ BABYLON.serialize() ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0); __decorate([ BABYLON.serialize() ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0); __decorate([ BABYLON.serialize() ], DefaultRenderingPipeline.prototype, "_hdr", void 0); __decorate([ BABYLON.serialize() ], DefaultRenderingPipeline.prototype, "bloomWeight", null); __decorate([ BABYLON.serialize() ], DefaultRenderingPipeline.prototype, "bloomScale", null); __decorate([ BABYLON.serialize() ], DefaultRenderingPipeline.prototype, "bloomEnabled", null); __decorate([ BABYLON.serialize() ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null); __decorate([ BABYLON.serialize() ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null); return DefaultRenderingPipeline; }(BABYLON.PostProcessRenderPipeline)); BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map var BABYLON; (function (BABYLON) { var GeometryBufferRenderer = /** @class */ (function () { function GeometryBufferRenderer(scene, ratio) { if (ratio === void 0) { ratio = 1; } this._enablePosition = false; this._scene = scene; this._ratio = ratio; // Render target this._createRenderTargets(); } Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", { set: function (meshes) { this._multiRenderTarget.renderList = meshes; }, enumerable: true, configurable: true }); Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", { get: function () { return this._multiRenderTarget.isSupported; }, enumerable: true, configurable: true }); Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", { get: function () { return this._enablePosition; }, set: function (enable) { this._enablePosition = enable; this.dispose(); this._createRenderTargets(); }, enumerable: true, configurable: true }); GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) { var material = subMesh.getMaterial(); if (material && material.disableDepthWrite) { return false; } var defines = []; var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind]; var mesh = subMesh.getMesh(); // Alpha test if (material && material.needAlphaTesting()) { defines.push("#define ALPHATEST"); if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) { attribs.push(BABYLON.VertexBuffer.UVKind); defines.push("#define UV1"); } if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) { attribs.push(BABYLON.VertexBuffer.UV2Kind); defines.push("#define UV2"); } } // Buffers if (this._enablePosition) { defines.push("#define POSITION"); } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0)); } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } // Instances if (useInstances) { defines.push("#define INSTANCES"); attribs.push("world0"); attribs.push("world1"); attribs.push("world2"); attribs.push("world3"); } // Get correct effect var join = defines.join("\n"); if (this._cachedDefines !== join) { this._cachedDefines = join; this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 }); } return this._effect.isReady(); }; GeometryBufferRenderer.prototype.getGBuffer = function () { return this._multiRenderTarget; }; // Methods GeometryBufferRenderer.prototype.dispose = function () { this.getGBuffer().dispose(); }; GeometryBufferRenderer.prototype._createRenderTargets = function () { var _this = this; var engine = this._scene.getEngine(); var count = this._enablePosition ? 3 : 2; this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true }); if (!this.isSupported) { return; } this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; this._multiRenderTarget.refreshRate = 1; this._multiRenderTarget.renderParticles = false; this._multiRenderTarget.renderList = null; // set default depth value to 1.0 (far away) this._multiRenderTarget.onClearObservable.add(function (engine) { engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true); }); // Custom render function var renderSubMesh = function (subMesh) { var mesh = subMesh.getRenderingMesh(); var scene = _this._scene; var engine = scene.getEngine(); var material = subMesh.getMaterial(); if (!material) { return; } // Culling engine.setState(material.backFaceCulling); // Managing instances var batch = mesh._getInstancesRenderList(subMesh._id); if (batch.mustReturn) { return; } var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null); if (_this.isReady(subMesh, hardwareInstancedRendering)) { engine.enableEffect(_this._effect); mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode); _this._effect.setMatrix("viewProjection", scene.getTransformMatrix()); _this._effect.setMatrix("view", scene.getViewMatrix()); // Alpha test if (material && material.needAlphaTesting()) { var alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { _this._effect.setTexture("diffuseSampler", alphaTexture); _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); } } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh)); } // Draw mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); }); } }; this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { var index; if (depthOnlySubMeshes.length) { engine.setColorWrite(false); for (index = 0; index < depthOnlySubMeshes.length; index++) { renderSubMesh(depthOnlySubMeshes.data[index]); } engine.setColorWrite(true); } for (index = 0; index < opaqueSubMeshes.length; index++) { renderSubMesh(opaqueSubMeshes.data[index]); } for (index = 0; index < alphaTestSubMeshes.length; index++) { renderSubMesh(alphaTestSubMeshes.data[index]); } }; }; return GeometryBufferRenderer; }()); BABYLON.GeometryBufferRenderer = GeometryBufferRenderer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.geometryBufferRenderer.js.map var BABYLON; (function (BABYLON) { var RefractionPostProcess = /** @class */ (function (_super) { __extends(RefractionPostProcess, _super); function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) { var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this; _this.color = color; _this.depth = depth; _this.colorLevel = colorLevel; _this.onActivateObservable.add(function (cam) { _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene()); }); _this.onApplyObservable.add(function (effect) { effect.setColor3("baseColor", _this.color); effect.setFloat("depth", _this.depth); effect.setFloat("colorLevel", _this.colorLevel); effect.setTexture("refractionSampler", _this._refRexture); }); return _this; } // Methods RefractionPostProcess.prototype.dispose = function (camera) { if (this._refRexture) { this._refRexture.dispose(); } _super.prototype.dispose.call(this, camera); }; return RefractionPostProcess; }(BABYLON.PostProcess)); BABYLON.RefractionPostProcess = RefractionPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.refractionPostProcess.js.map var BABYLON; (function (BABYLON) { var BlackAndWhitePostProcess = /** @class */ (function (_super) { __extends(BlackAndWhitePostProcess, _super); function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) { var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this; _this.degree = 1; _this.onApplyObservable.add(function (effect) { effect.setFloat("degree", _this.degree); }); return _this; } return BlackAndWhitePostProcess; }(BABYLON.PostProcess)); BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map var BABYLON; (function (BABYLON) { var ConvolutionPostProcess = /** @class */ (function (_super) { __extends(ConvolutionPostProcess, _super); function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) { var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this; _this.kernel = kernel; _this.onApply = function (effect) { effect.setFloat2("screenSize", _this.width, _this.height); effect.setArray("kernel", _this.kernel); }; return _this; } // Statics // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing) ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1]; ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0]; ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1]; ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0]; ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2]; ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0]; return ConvolutionPostProcess; }(BABYLON.PostProcess)); BABYLON.ConvolutionPostProcess = ConvolutionPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.convolutionPostProcess.js.map var BABYLON; (function (BABYLON) { var FilterPostProcess = /** @class */ (function (_super) { __extends(FilterPostProcess, _super); function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) { var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this; _this.kernelMatrix = kernelMatrix; _this.onApply = function (effect) { effect.setMatrix("kernelMatrix", _this.kernelMatrix); }; return _this; } return FilterPostProcess; }(BABYLON.PostProcess)); BABYLON.FilterPostProcess = FilterPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.filterPostProcess.js.map var BABYLON; (function (BABYLON) { // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) { __extends(VolumetricLightScatteringPostProcess, _super); /** * @constructor * @param {string} name - The post-process name * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering * @param {number} samples - The post-process quality, default 100 * @param {number} samplingMode - The post-process filtering mode * @param {BABYLON.Engine} engine - The babylon engine * @param {boolean} reusable - If the post-process is reusable * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided */ function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) { if (samples === void 0) { samples = 100; } if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; } var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this; _this._screenCoordinates = BABYLON.Vector2.Zero(); /** * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true" * @type {Vector3} */ _this.customMeshPosition = BABYLON.Vector3.Zero(); /** * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false) * @type {boolean} */ _this.useCustomMeshPosition = false; /** * If the post-process should inverse the light scattering direction * @type {boolean} */ _this.invert = true; /** * Array containing the excluded meshes not rendered in the internal pass */ _this.excludedMeshes = new Array(); /** * Controls the overall intensity of the post-process * @type {number} */ _this.exposure = 0.3; /** * Dissipates each sample's contribution in range [0, 1] * @type {number} */ _this.decay = 0.96815; /** * Controls the overall intensity of each sample * @type {number} */ _this.weight = 0.58767; /** * Controls the density of each sample * @type {number} */ _this.density = 0.926; scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null. engine = scene.getEngine(); _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight()); // Configure mesh _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene)); // Configure _this._createPass(scene, ratio.passRatio || ratio); _this.onActivate = function (camera) { if (!_this.isSupported) { _this.dispose(camera); } _this.onActivate = null; }; _this.onApplyObservable.add(function (effect) { _this._updateMeshScreenCoordinates(scene); effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT); effect.setFloat("exposure", _this.exposure); effect.setFloat("decay", _this.decay); effect.setFloat("weight", _this.weight); effect.setFloat("density", _this.density); effect.setVector2("meshPositionOnScreen", _this._screenCoordinates); }); return _this; } Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", { get: function () { BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"); return false; }, set: function (useDiffuseColor) { BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"); }, enumerable: true, configurable: true }); VolumetricLightScatteringPostProcess.prototype.getClassName = function () { return "VolumetricLightScatteringPostProcess"; }; VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) { var mesh = subMesh.getMesh(); // Render this.mesh as default if (mesh === this.mesh && mesh.material) { return mesh.material.isReady(mesh); } var defines = []; var attribs = [BABYLON.VertexBuffer.PositionKind]; var material = subMesh.getMaterial(); // Alpha test if (material) { if (material.needAlphaTesting()) { defines.push("#define ALPHATEST"); } if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) { attribs.push(BABYLON.VertexBuffer.UVKind); defines.push("#define UV1"); } if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) { attribs.push(BABYLON.VertexBuffer.UV2Kind); defines.push("#define UV2"); } } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind); defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0)); } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } // Instances if (useInstances) { defines.push("#define INSTANCES"); attribs.push("world0"); attribs.push("world1"); attribs.push("world2"); attribs.push("world3"); } // Get correct effect var join = defines.join("\n"); if (this._cachedDefines !== join) { this._cachedDefines = join; this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join); } return this._volumetricLightScatteringPass.isReady(); }; /** * Sets the new light position for light scattering effect * @param {BABYLON.Vector3} The new custom light position */ VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) { this.customMeshPosition = position; }; /** * Returns the light position for light scattering effect * @return {BABYLON.Vector3} The custom light position */ VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () { return this.customMeshPosition; }; /** * Disposes the internal assets and detaches the post-process from the camera */ VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) { var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT); if (rttIndex !== -1) { camera.getScene().customRenderTargets.splice(rttIndex, 1); } this._volumetricLightScatteringRTT.dispose(); _super.prototype.dispose.call(this, camera); }; /** * Returns the render target texture used by the post-process * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process */ VolumetricLightScatteringPostProcess.prototype.getPass = function () { return this._volumetricLightScatteringRTT; }; // Private methods VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) { if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) { return true; } return false; }; VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) { var _this = this; var engine = scene.getEngine(); this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; this._volumetricLightScatteringRTT.renderList = null; this._volumetricLightScatteringRTT.renderParticles = false; var camera = this.getCamera(); if (camera) { camera.customRenderTargets.push(this._volumetricLightScatteringRTT); } else { scene.customRenderTargets.push(this._volumetricLightScatteringRTT); } // Custom render function for submeshes var renderSubMesh = function (subMesh) { var mesh = subMesh.getRenderingMesh(); if (_this._meshExcluded(mesh)) { return; } var material = subMesh.getMaterial(); if (!material) { return; } var scene = mesh.getScene(); var engine = scene.getEngine(); // Culling engine.setState(material.backFaceCulling); // Managing instances var batch = mesh._getInstancesRenderList(subMesh._id); if (batch.mustReturn) { return; } var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null); if (_this.isReady(subMesh, hardwareInstancedRendering)) { var effect = _this._volumetricLightScatteringPass; if (mesh === _this.mesh) { if (subMesh.effect) { effect = subMesh.effect; } else { effect = material.getEffect(); } } engine.enableEffect(effect); mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode); if (mesh === _this.mesh) { material.bind(mesh.getWorldMatrix(), mesh); } else { _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix()); // Alpha test if (material && material.needAlphaTesting()) { var alphaTexture = material.getAlphaTestTexture(); _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture); if (alphaTexture) { _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); } } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh)); } } // Draw mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); }); } }; // Render target texture callbacks var savedSceneClearColor; var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0); this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () { savedSceneClearColor = scene.clearColor; scene.clearColor = sceneClearColor; }); this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () { scene.clearColor = savedSceneClearColor; }); this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { var engine = scene.getEngine(); var index; if (depthOnlySubMeshes.length) { engine.setColorWrite(false); for (index = 0; index < depthOnlySubMeshes.length; index++) { renderSubMesh(depthOnlySubMeshes.data[index]); } engine.setColorWrite(true); } for (index = 0; index < opaqueSubMeshes.length; index++) { renderSubMesh(opaqueSubMeshes.data[index]); } engine.setAlphaTesting(true); for (index = 0; index < alphaTestSubMeshes.length; index++) { renderSubMesh(alphaTestSubMeshes.data[index]); } engine.setAlphaTesting(false); if (transparentSubMeshes.length) { // Sort sub meshes for (index = 0; index < transparentSubMeshes.length; index++) { var submesh = transparentSubMeshes.data[index]; var boundingInfo = submesh.getBoundingInfo(); if (boundingInfo && scene.activeCamera) { submesh._alphaIndex = submesh.getMesh().alphaIndex; submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length(); } } var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length); sortedArray.sort(function (a, b) { // Alpha index first if (a._alphaIndex > b._alphaIndex) { return 1; } if (a._alphaIndex < b._alphaIndex) { return -1; } // Then distance to camera if (a._distanceToCamera < b._distanceToCamera) { return 1; } if (a._distanceToCamera > b._distanceToCamera) { return -1; } return 0; }); // Render sub meshes engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE); for (index = 0; index < sortedArray.length; index++) { renderSubMesh(sortedArray[index]); } engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE); } }; }; VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) { var transform = scene.getTransformMatrix(); var meshPosition; if (this.useCustomMeshPosition) { meshPosition = this.customMeshPosition; } else if (this.attachedNode) { meshPosition = this.attachedNode.position; } else { meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position; } var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort); this._screenCoordinates.x = pos.x / this._viewPort.width; this._screenCoordinates.y = pos.y / this._viewPort.height; if (this.invert) this._screenCoordinates.y = 1.0 - this._screenCoordinates.y; }; // Static methods /** * Creates a default mesh for the Volumeric Light Scattering post-process * @param {string} The mesh name * @param {BABYLON.Scene} The scene where to create the mesh * @return {BABYLON.Mesh} the default mesh */ VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) { var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene); mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL; var material = new BABYLON.StandardMaterial(name + "Material", scene); material.emissiveColor = new BABYLON.Color3(1, 1, 1); mesh.material = material; return mesh; }; __decorate([ BABYLON.serializeAsVector3() ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0); __decorate([ BABYLON.serialize() ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0); __decorate([ BABYLON.serialize() ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0); __decorate([ BABYLON.serializeAsMeshReference() ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0); __decorate([ BABYLON.serialize() ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0); __decorate([ BABYLON.serialize() ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0); __decorate([ BABYLON.serialize() ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0); __decorate([ BABYLON.serialize() ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0); __decorate([ BABYLON.serialize() ], VolumetricLightScatteringPostProcess.prototype, "density", void 0); return VolumetricLightScatteringPostProcess; }(BABYLON.PostProcess)); BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map // // This post-process allows the modification of rendered colors by using // a 'look-up table' (LUT). This effect is also called Color Grading. // // The object needs to be provided an url to a texture containing the color // look-up table: the texture must be 256 pixels wide and 16 pixels high. // Use an image editing software to tweak the LUT to match your needs. // // For an example of a color LUT, see here: // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png // For explanations on color grading, see here: // http://udn.epicgames.com/Three/ColorGrading.html // var BABYLON; (function (BABYLON) { var ColorCorrectionPostProcess = /** @class */ (function (_super) { __extends(ColorCorrectionPostProcess, _super); function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) { var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this; _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE); _this._colorTableTexture.anisotropicFilteringLevel = 1; _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; _this.onApply = function (effect) { effect.setTexture("colorTable", _this._colorTableTexture); }; return _this; } return ColorCorrectionPostProcess; }(BABYLON.PostProcess)); BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map var BABYLON; (function (BABYLON) { var TonemappingOperator; (function (TonemappingOperator) { TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable"; TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard"; TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson"; TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic"; })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {})); ; var TonemapPostProcess = /** @class */ (function (_super) { __extends(TonemapPostProcess, _super); function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; } if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this; _this._operator = _operator; _this.exposureAdjustment = exposureAdjustment; var defines = "#define "; if (_this._operator === TonemappingOperator.Hable) defines += "HABLE_TONEMAPPING"; else if (_this._operator === TonemappingOperator.Reinhard) defines += "REINHARD_TONEMAPPING"; else if (_this._operator === TonemappingOperator.HejiDawson) defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING"; else if (_this._operator === TonemappingOperator.Photographic) defines += "PHOTOGRAPHIC_TONEMAPPING"; //sadly a second call to create the effect. _this.updateEffect(defines); _this.onApply = function (effect) { effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment); }; return _this; } return TonemapPostProcess; }(BABYLON.PostProcess)); BABYLON.TonemapPostProcess = TonemapPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.tonemapPostProcess.js.map var BABYLON; (function (BABYLON) { var DisplayPassPostProcess = /** @class */ (function (_super) { __extends(DisplayPassPostProcess, _super); function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) { return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this; } return DisplayPassPostProcess; }(BABYLON.PostProcess)); BABYLON.DisplayPassPostProcess = DisplayPassPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.displayPassPostProcess.js.map var BABYLON; (function (BABYLON) { var HighlightsPostProcess = /** @class */ (function (_super) { __extends(HighlightsPostProcess, _super); function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) { if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this; } return HighlightsPostProcess; }(BABYLON.PostProcess)); BABYLON.HighlightsPostProcess = HighlightsPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.highlightsPostProcess.js.map var BABYLON; (function (BABYLON) { var ImageProcessingPostProcess = /** @class */ (function (_super) { __extends(ImageProcessingPostProcess, _super); function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) { if (camera === void 0) { camera = null; } if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this; _this._fromLinearSpace = true; /** * Defines cache preventing GC. */ _this._defines = { IMAGEPROCESSING: false, VIGNETTE: false, VIGNETTEBLENDMODEMULTIPLY: false, VIGNETTEBLENDMODEOPAQUE: false, TONEMAPPING: false, CONTRAST: false, COLORCURVES: false, COLORGRADING: false, COLORGRADING3D: false, FROMLINEARSPACE: false, SAMPLER3DGREENDEPTH: false, SAMPLER3DBGRMAP: false, IMAGEPROCESSINGPOSTPROCESS: false, EXPOSURE: false, }; // Setup the default processing configuration to the scene. _this._attachImageProcessingConfiguration(null, true); _this.imageProcessingConfiguration.applyByPostProcess = true; _this.onApply = function (effect) { _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio); }; return _this; } Object.defineProperty(ImageProcessingPostProcess.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); }, enumerable: true, configurable: true }); /** * Attaches a new image processing configuration to the PBR Material. * @param configuration */ ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) { var _this = this; if (doNotBuild === void 0) { doNotBuild = false; } 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) { var scene = null; var engine = this.getEngine(); var camera = this.getCamera(); if (camera) { scene = camera.getScene(); } else if (engine && engine.scenes) { var scenes = engine.scenes; scene = scenes[scenes.length - 1]; } else { scene = BABYLON.Engine.LastCreatedScene; } this._imageProcessingConfiguration = scene.imageProcessingConfiguration; } else { this._imageProcessingConfiguration = configuration; } // Attaches observer. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) { _this._updateParameters(); }); // Ensure the effect will be rebuilt. if (!doNotBuild) { this._updateParameters(); } }; Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", { /** * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true . */ get: function () { return this.imageProcessingConfiguration.colorCurves; }, /** * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true . */ set: function (value) { this.imageProcessingConfiguration.colorCurves = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", { /** * 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(ImageProcessingPostProcess.prototype, "colorGradingTexture", { /** * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. */ get: function () { return this.imageProcessingConfiguration.colorGradingTexture; }, /** * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. */ set: function (value) { this.imageProcessingConfiguration.colorGradingTexture = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", { /** * 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(ImageProcessingPostProcess.prototype, "exposure", { /** * Gets exposure used in the effect. */ get: function () { return this.imageProcessingConfiguration.exposure; }, /** * Sets exposure used in the effect. */ set: function (value) { this.imageProcessingConfiguration.exposure = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", { /** * 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(ImageProcessingPostProcess.prototype, "contrast", { /** * Gets contrast used in the effect. */ get: function () { return this.imageProcessingConfiguration.contrast; }, /** * Sets contrast used in the effect. */ set: function (value) { this.imageProcessingConfiguration.contrast = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", { /** * Gets Vignette stretch size. */ get: function () { return this.imageProcessingConfiguration.vignetteStretch; }, /** * Sets Vignette stretch size. */ set: function (value) { this.imageProcessingConfiguration.vignetteStretch = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", { /** * Gets Vignette centre X Offset. */ get: function () { return this.imageProcessingConfiguration.vignetteCentreX; }, /** * Sets Vignette centre X Offset. */ set: function (value) { this.imageProcessingConfiguration.vignetteCentreX = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", { /** * Gets Vignette centre Y Offset. */ get: function () { return this.imageProcessingConfiguration.vignetteCentreY; }, /** * Sets Vignette centre Y Offset. */ set: function (value) { this.imageProcessingConfiguration.vignetteCentreY = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", { /** * Gets Vignette weight or intensity of the vignette effect. */ get: function () { return this.imageProcessingConfiguration.vignetteWeight; }, /** * Sets Vignette weight or intensity of the vignette effect. */ set: function (value) { this.imageProcessingConfiguration.vignetteWeight = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", { /** * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) * if vignetteEnabled is set to true. */ get: function () { return this.imageProcessingConfiguration.vignetteColor; }, /** * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) * if vignetteEnabled is set to true. */ set: function (value) { this.imageProcessingConfiguration.vignetteColor = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", { /** * Gets Camera field of view used by the Vignette effect. */ get: function () { return this.imageProcessingConfiguration.vignetteCameraFov; }, /** * Sets Camera field of view used by the Vignette effect. */ set: function (value) { this.imageProcessingConfiguration.vignetteCameraFov = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", { /** * Gets the vignette blend mode allowing different kind of effect. */ get: function () { return this.imageProcessingConfiguration.vignetteBlendMode; }, /** * Sets the vignette blend mode allowing different kind of effect. */ set: function (value) { this.imageProcessingConfiguration.vignetteBlendMode = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", { /** * Gets wether the vignette effect is enabled. */ get: function () { return this.imageProcessingConfiguration.vignetteEnabled; }, /** * Sets wether the vignette effect is enabled. */ set: function (value) { this.imageProcessingConfiguration.vignetteEnabled = value; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", { /** * Gets wether the input of the processing is in Gamma or Linear Space. */ get: function () { return this._fromLinearSpace; }, /** * Sets wether the input of the processing is in Gamma or Linear Space. */ set: function (value) { if (this._fromLinearSpace === value) { return; } this._fromLinearSpace = value; this._updateParameters(); }, enumerable: true, configurable: true }); ImageProcessingPostProcess.prototype.getClassName = function () { return "ImageProcessingPostProcess"; }; ImageProcessingPostProcess.prototype._updateParameters = function () { this._defines.FROMLINEARSPACE = this._fromLinearSpace; this.imageProcessingConfiguration.prepareDefines(this._defines, true); var defines = ""; for (var define in this._defines) { if (this._defines[define]) { defines += "#define " + define + ";\r\n"; } } var samplers = ["textureSampler"]; BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines); var uniforms = ["scale"]; BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines); this.updateEffect(defines, uniforms, samplers); }; ImageProcessingPostProcess.prototype.dispose = function (camera) { _super.prototype.dispose.call(this, camera); if (this._imageProcessingConfiguration && this._imageProcessingObserver) { this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); } this.imageProcessingConfiguration.applyByPostProcess = false; }; __decorate([ BABYLON.serialize() ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0); return ImageProcessingPostProcess; }(BABYLON.PostProcess)); BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map var BABYLON; (function (BABYLON) { var BlurPostProcess = /** @class */ (function (_super) { __extends(BlurPostProcess, _super); function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; } if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this; _this.direction = direction; _this._packedFloat = false; _this.onApplyObservable.add(function (effect) { effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y); }); _this.kernel = kernel; return _this; } Object.defineProperty(BlurPostProcess.prototype, "kernel", { /** * Gets the length in pixels of the blur sample region */ get: function () { return this._idealKernel; }, /** * Sets the length in pixels of the blur sample region */ set: function (v) { if (this._idealKernel === v) { return; } v = Math.max(v, 1); this._idealKernel = v; this._kernel = this._nearestBestKernel(v); this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(BlurPostProcess.prototype, "packedFloat", { /** * Gets wether or not the blur is unpacking/repacking floats */ get: function () { return this._packedFloat; }, /** * Sets wether or not the blur needs to unpack/repack floats */ set: function (v) { if (this._packedFloat === v) { return; } this._packedFloat = v; this._updateParameters(); }, enumerable: true, configurable: true }); BlurPostProcess.prototype._updateParameters = function () { // Generate sampling offsets and weights var N = this._kernel; var centerIndex = (N - 1) / 2; // Generate Gaussian sampling weights over kernel var offsets = []; var weights = []; var totalWeight = 0; for (var i = 0; i < N; i++) { var u = i / (N - 1); var w = this._gaussianWeight(u * 2.0 - 1); offsets[i] = (i - centerIndex); weights[i] = w; totalWeight += w; } // Normalize weights for (var i = 0; i < weights.length; i++) { weights[i] /= totalWeight; } // Optimize: combine samples to take advantage of hardware linear sampling // Walk from left to center, combining pairs (symmetrically) var linearSamplingWeights = []; var linearSamplingOffsets = []; var linearSamplingMap = []; for (var i = 0; i <= centerIndex; i += 2) { var j = Math.min(i + 1, Math.floor(centerIndex)); var singleCenterSample = i === j; if (singleCenterSample) { linearSamplingMap.push({ o: offsets[i], w: weights[i] }); } else { var sharedCell = j === centerIndex; var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.)); var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]); if (offsetLinear === 0) { linearSamplingMap.push({ o: offsets[i], w: weights[i] }); linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] }); } else { linearSamplingMap.push({ o: offsetLinear, w: weightLinear }); linearSamplingMap.push({ o: -offsetLinear, w: weightLinear }); } } } for (var i = 0; i < linearSamplingMap.length; i++) { linearSamplingOffsets[i] = linearSamplingMap[i].o; linearSamplingWeights[i] = linearSamplingMap[i].w; } // Replace with optimized offsets = linearSamplingOffsets; weights = linearSamplingWeights; // Generate shaders var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors; var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter var varyingCount = Math.min(offsets.length, freeVaryingVec2); var defines = ""; for (var i = 0; i < varyingCount; i++) { defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n"; defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n"; } var depCount = 0; for (var i = freeVaryingVec2; i < offsets.length; i++) { defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n"; defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n"; depCount++; } if (this.packedFloat) { defines += "#define PACKEDFLOAT 1"; } this.updateEffect(defines, null, null, { varyingCount: varyingCount, depCount: depCount }); }; /** * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard. * The gaps between physical kernels are compensated for in the weighting of the samples * @param idealKernel Ideal blur kernel. * @return Nearest best kernel. */ BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) { var v = Math.round(idealKernel); for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) { var k = _a[_i]; if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) { return Math.max(k, 3); } } return Math.max(v, 3); }; /** * Calculates the value of a Gaussian distribution with sigma 3 at a given point. * @param x The point on the Gaussian distribution to sample. * @return the value of the Gaussian function at x. */ BlurPostProcess.prototype._gaussianWeight = function (x) { //reference: Engine/ImageProcessingBlur.cpp #dcc760 // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1], // so we truncate at three standard deviations by setting stddev (sigma) to 1/3. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is // truncated at around 1.3% of peak strength. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size var sigma = (1 / 3); var denominator = Math.sqrt(2.0 * Math.PI) * sigma; var exponent = -((x * x) / (2.0 * sigma * sigma)); var weight = (1.0 / denominator) * Math.exp(exponent); return weight; }; /** * Generates a string that can be used as a floating point number in GLSL. * @param x Value to print. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s). * @return GLSL float string. */ BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) { if (decimalFigures === void 0) { decimalFigures = 8; } return x.toFixed(decimalFigures).replace(/0+$/, ''); }; return BlurPostProcess; }(BABYLON.PostProcess)); BABYLON.BlurPostProcess = BlurPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.blurPostProcess.js.map /// var BABYLON; (function (BABYLON) { var Bone = /** @class */ (function (_super) { __extends(Bone, _super); function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) { if (parentBone === void 0) { parentBone = null; } if (localMatrix === void 0) { localMatrix = null; } if (restPose === void 0) { restPose = null; } if (baseMatrix === void 0) { baseMatrix = null; } if (index === void 0) { index = null; } var _this = _super.call(this, name, skeleton.getScene()) || this; _this.name = name; _this.children = new Array(); _this.animations = new Array(); // Set this value to map this bone to a different index in the transform matrices. // Set this value to -1 to exclude the bone from the transform matrices. _this._index = null; _this._worldTransform = new BABYLON.Matrix(); _this._absoluteTransform = new BABYLON.Matrix(); _this._invertedAbsoluteTransform = new BABYLON.Matrix(); _this._scaleMatrix = BABYLON.Matrix.Identity(); _this._scaleVector = BABYLON.Vector3.One(); _this._negateScaleChildren = BABYLON.Vector3.One(); _this._scalingDeterminant = 1; _this._skeleton = skeleton; _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity(); _this._restPose = restPose ? restPose : _this._localMatrix.clone(); _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone(); _this._index = index; skeleton.bones.push(_this); _this.setParent(parentBone, false); _this._updateDifferenceMatrix(); return _this; } Object.defineProperty(Bone.prototype, "_matrix", { get: function () { return this._localMatrix; }, set: function (val) { if (this._localMatrix) { this._localMatrix.copyFrom(val); } else { this._localMatrix = val; } }, enumerable: true, configurable: true }); // Members Bone.prototype.getSkeleton = function () { return this._skeleton; }; Bone.prototype.getParent = function () { return this._parent; }; Bone.prototype.setParent = function (parent, updateDifferenceMatrix) { if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; } if (this._parent === parent) { return; } if (this._parent) { var index = this._parent.children.indexOf(this); if (index !== -1) { this._parent.children.splice(index, 1); } } this._parent = parent; if (this._parent) { this._parent.children.push(this); } if (updateDifferenceMatrix) { this._updateDifferenceMatrix(); } }; Bone.prototype.getLocalMatrix = function () { return this._localMatrix; }; Bone.prototype.getBaseMatrix = function () { return this._baseMatrix; }; Bone.prototype.getRestPose = function () { return this._restPose; }; Bone.prototype.returnToRest = function () { this.updateMatrix(this._restPose.clone()); }; Bone.prototype.getWorldMatrix = function () { return this._worldTransform; }; Bone.prototype.getInvertedAbsoluteTransform = function () { return this._invertedAbsoluteTransform; }; Bone.prototype.getAbsoluteTransform = function () { return this._absoluteTransform; }; Object.defineProperty(Bone.prototype, "position", { // Properties (matches AbstractMesh properties) get: function () { return this.getPosition(); }, set: function (newPosition) { this.setPosition(newPosition); }, enumerable: true, configurable: true }); Object.defineProperty(Bone.prototype, "rotation", { get: function () { return this.getRotation(); }, set: function (newRotation) { this.setRotation(newRotation); }, enumerable: true, configurable: true }); Object.defineProperty(Bone.prototype, "rotationQuaternion", { get: function () { return this.getRotationQuaternion(); }, set: function (newRotation) { this.setRotationQuaternion(newRotation); }, enumerable: true, configurable: true }); Object.defineProperty(Bone.prototype, "scaling", { get: function () { return this.getScale(); }, set: function (newScaling) { this.setScale(newScaling.x, newScaling.y, newScaling.z); }, enumerable: true, configurable: true }); // Methods Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) { if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; } this._baseMatrix = matrix.clone(); this._localMatrix = matrix.clone(); this._skeleton._markAsDirty(); if (updateDifferenceMatrix) { this._updateDifferenceMatrix(); } }; Bone.prototype._updateDifferenceMatrix = function (rootMatrix) { if (!rootMatrix) { rootMatrix = this._baseMatrix; } if (this._parent) { rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform); } else { this._absoluteTransform.copyFrom(rootMatrix); } this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform); for (var index = 0; index < this.children.length; index++) { this.children[index]._updateDifferenceMatrix(); } this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1); }; Bone.prototype.markAsDirty = function () { this._currentRenderId++; this._skeleton._markAsDirty(); }; Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) { if (rescaleAsRequired === void 0) { rescaleAsRequired = false; } if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; } // all animation may be coming from a library skeleton, so may need to create animation if (this.animations.length === 0) { this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0)); this.animations[0].setKeys([]); } // get animation info / verify there is such a range from the source bone var sourceRange = source.animations[0].getRange(rangeName); if (!sourceRange) { return false; } var from = sourceRange.from; var to = sourceRange.to; var sourceKeys = source.animations[0].getKeys(); // rescaling prep var sourceBoneLength = source.length; var sourceParent = source.getParent(); var parent = this.getParent(); var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length; var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1; var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1); var destKeys = this.animations[0].getKeys(); // loop vars declaration var orig; var origTranslation; var mat; for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) { orig = sourceKeys[key]; if (orig.frame >= from && orig.frame <= to) { if (rescaleAsRequired) { mat = orig.value.clone(); // scale based on parent ratio, when bone has parent if (parentScalingReqd) { origTranslation = mat.getTranslation(); mat.setTranslation(origTranslation.scaleInPlace(parentRatio)); // scale based on skeleton dimension ratio when root bone, and value is passed } else if (dimensionsScalingReqd && skelDimensionsRatio) { origTranslation = mat.getTranslation(); mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio)); // use original when root bone, and no data for skelDimensionsRatio } else { mat = orig.value; } } else { mat = orig.value; } destKeys.push({ frame: orig.frame + frameOffset, value: mat }); } } this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset); return true; }; /** * Translate the bone in local or world space. * @param vec The amount to translate the bone. * @param space The space that the translation is in. * @param mesh The mesh that this bone is attached to. This is only used in world space. */ Bone.prototype.translate = function (vec, space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } var lm = this.getLocalMatrix(); if (space == BABYLON.Space.LOCAL) { lm.m[12] += vec.x; lm.m[13] += vec.y; lm.m[14] += vec.z; } else { var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; var tvec = Bone._tmpVecs[0]; if (this._parent) { if (mesh && wm) { tmat.copyFrom(this._parent.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat.copyFrom(this._parent.getAbsoluteTransform()); } } tmat.m[12] = 0; tmat.m[13] = 0; tmat.m[14] = 0; tmat.invert(); BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec); lm.m[12] += tvec.x; lm.m[13] += tvec.y; lm.m[14] += tvec.z; } this.markAsDirty(); }; /** * Set the postion of the bone in local or world space. * @param position The position to set the bone. * @param space The space that the position is in. * @param mesh The mesh that this bone is attached to. This is only used in world space. */ Bone.prototype.setPosition = function (position, space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } var lm = this.getLocalMatrix(); if (space == BABYLON.Space.LOCAL) { lm.m[12] = position.x; lm.m[13] = position.y; lm.m[14] = position.z; } else { var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; var vec = Bone._tmpVecs[0]; if (this._parent) { if (mesh && wm) { tmat.copyFrom(this._parent.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat.copyFrom(this._parent.getAbsoluteTransform()); } } tmat.invert(); BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec); lm.m[12] = vec.x; lm.m[13] = vec.y; lm.m[14] = vec.z; } this.markAsDirty(); }; /** * Set the absolute postion of the bone (world space). * @param position The position to set the bone. * @param mesh The mesh that this bone is attached to. */ Bone.prototype.setAbsolutePosition = function (position, mesh) { this.setPosition(position, BABYLON.Space.WORLD, mesh); }; /** * Set the scale of the bone on the x, y and z axes. * @param x The scale of the bone on the x axis. * @param x The scale of the bone on the y axis. * @param z The scale of the bone on the z axis. * @param scaleChildren Set this to true if children of the bone should be scaled. */ Bone.prototype.setScale = function (x, y, z, scaleChildren) { if (scaleChildren === void 0) { scaleChildren = false; } if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) { if (!scaleChildren) { this._negateScaleChildren.x = 1 / x; this._negateScaleChildren.y = 1 / y; this._negateScaleChildren.z = 1 / z; } this._syncScaleVector(); } this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren); }; /** * Scale the bone on the x, y and z axes. * @param x The amount to scale the bone on the x axis. * @param x The amount to scale the bone on the y axis. * @param z The amount to scale the bone on the z axis. * @param scaleChildren Set this to true if children of the bone should be scaled. */ Bone.prototype.scale = function (x, y, z, scaleChildren) { if (scaleChildren === void 0) { scaleChildren = false; } var locMat = this.getLocalMatrix(); var origLocMat = Bone._tmpMats[0]; origLocMat.copyFrom(locMat); var origLocMatInv = Bone._tmpMats[1]; origLocMatInv.copyFrom(origLocMat); origLocMatInv.invert(); var scaleMat = Bone._tmpMats[2]; BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat); this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix); this._scaleVector.x *= x; this._scaleVector.y *= y; this._scaleVector.z *= z; locMat.multiplyToRef(origLocMatInv, locMat); locMat.multiplyToRef(scaleMat, locMat); locMat.multiplyToRef(origLocMat, locMat); var parent = this.getParent(); if (parent) { locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform()); } else { this.getAbsoluteTransform().copyFrom(locMat); } var len = this.children.length; scaleMat.invert(); for (var i = 0; i < len; i++) { var child = this.children[i]; var cm = child.getLocalMatrix(); cm.multiplyToRef(scaleMat, cm); var lm = child.getLocalMatrix(); lm.m[12] *= x; lm.m[13] *= y; lm.m[14] *= z; } this.computeAbsoluteTransforms(); if (scaleChildren) { for (var i = 0; i < len; i++) { this.children[i].scale(x, y, z, scaleChildren); } } this.markAsDirty(); }; /** * Set the yaw, pitch, and roll of the bone in local or world space. * @param yaw The rotation of the bone on the y axis. * @param pitch The rotation of the bone on the x axis. * @param roll The rotation of the bone on the z axis. * @param space The space that the axes of rotation are in. * @param mesh The mesh that this bone is attached to. This is only used in world space. */ Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } var rotMat = Bone._tmpMats[0]; BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat); var rotMatInv = Bone._tmpMats[1]; this._getNegativeRotationToRef(rotMatInv, space, mesh); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, mesh); }; /** * Rotate the bone on an axis in local or world space. * @param axis The axis to rotate the bone on. * @param amount The amount to rotate the bone. * @param space The space that the axis is in. * @param mesh The mesh that this bone is attached to. This is only used in world space. */ Bone.prototype.rotate = function (axis, amount, space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } var rmat = Bone._tmpMats[0]; rmat.m[12] = 0; rmat.m[13] = 0; rmat.m[14] = 0; BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat); this._rotateWithMatrix(rmat, space, mesh); }; /** * Set the rotation of the bone to a particular axis angle in local or world space. * @param axis The axis to rotate the bone on. * @param angle The angle that the bone should be rotated to. * @param space The space that the axis is in. * @param mesh The mesh that this bone is attached to. This is only used in world space. */ Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } var rotMat = Bone._tmpMats[0]; BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat); var rotMatInv = Bone._tmpMats[1]; this._getNegativeRotationToRef(rotMatInv, space, mesh); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, mesh); }; /** * Set the euler rotation of the bone in local of world space. * @param rotation The euler rotation that the bone should be set to. * @param space The space that the rotation is in. * @param mesh The mesh that this bone is attached to. This is only used in world space. */ Bone.prototype.setRotation = function (rotation, space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh); }; /** * Set the quaternion rotation of the bone in local of world space. * @param quat The quaternion rotation that the bone should be set to. * @param space The space that the rotation is in. * @param mesh The mesh that this bone is attached to. This is only used in world space. */ Bone.prototype.setRotationQuaternion = function (quat, space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } var rotMatInv = Bone._tmpMats[0]; this._getNegativeRotationToRef(rotMatInv, space, mesh); var rotMat = Bone._tmpMats[1]; BABYLON.Matrix.FromQuaternionToRef(quat, rotMat); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, mesh); }; /** * Set the rotation matrix of the bone in local of world space. * @param rotMat The rotation matrix that the bone should be set to. * @param space The space that the rotation is in. * @param mesh The mesh that this bone is attached to. This is only used in world space. */ Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } var rotMatInv = Bone._tmpMats[0]; this._getNegativeRotationToRef(rotMatInv, space, mesh); var rotMat2 = Bone._tmpMats[1]; rotMat2.copyFrom(rotMat); rotMatInv.multiplyToRef(rotMat, rotMat2); this._rotateWithMatrix(rotMat2, space, mesh); }; Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } var lmat = this.getLocalMatrix(); var lx = lmat.m[12]; var ly = lmat.m[13]; var lz = lmat.m[14]; var parent = this.getParent(); var parentScale = Bone._tmpMats[3]; var parentScaleInv = Bone._tmpMats[4]; if (parent) { if (space == BABYLON.Space.WORLD) { if (mesh) { parentScale.copyFrom(mesh.getWorldMatrix()); parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale); } else { parentScale.copyFrom(parent.getAbsoluteTransform()); } } else { parentScale = parent._scaleMatrix; } parentScaleInv.copyFrom(parentScale); parentScaleInv.invert(); lmat.multiplyToRef(parentScale, lmat); lmat.multiplyToRef(rmat, lmat); lmat.multiplyToRef(parentScaleInv, lmat); } else { if (space == BABYLON.Space.WORLD && mesh) { parentScale.copyFrom(mesh.getWorldMatrix()); parentScaleInv.copyFrom(parentScale); parentScaleInv.invert(); lmat.multiplyToRef(parentScale, lmat); lmat.multiplyToRef(rmat, lmat); lmat.multiplyToRef(parentScaleInv, lmat); } else { lmat.multiplyToRef(rmat, lmat); } } lmat.m[12] = lx; lmat.m[13] = ly; lmat.m[14] = lz; this.computeAbsoluteTransforms(); this.markAsDirty(); }; Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } if (space == BABYLON.Space.WORLD) { var scaleMatrix = Bone._tmpMats[2]; scaleMatrix.copyFrom(this._scaleMatrix); rotMatInv.copyFrom(this.getAbsoluteTransform()); if (mesh) { rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv); var meshScale = Bone._tmpMats[3]; BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale); scaleMatrix.multiplyToRef(meshScale, scaleMatrix); } rotMatInv.invert(); scaleMatrix.m[0] *= this._scalingDeterminant; rotMatInv.multiplyToRef(scaleMatrix, rotMatInv); } else { rotMatInv.copyFrom(this.getLocalMatrix()); rotMatInv.invert(); var scaleMatrix = Bone._tmpMats[2]; scaleMatrix.copyFrom(this._scaleMatrix); if (this._parent) { var pscaleMatrix = Bone._tmpMats[3]; pscaleMatrix.copyFrom(this._parent._scaleMatrix); pscaleMatrix.invert(); pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv); } else { scaleMatrix.m[0] *= this._scalingDeterminant; } rotMatInv.multiplyToRef(scaleMatrix, rotMatInv); } }; /** * Get the scale of the bone * @returns the scale of the bone */ Bone.prototype.getScale = function () { return this._scaleVector.clone(); }; /** * Copy the scale of the bone to a vector3. * @param result The vector3 to copy the scale to */ Bone.prototype.getScaleToRef = function (result) { result.copyFrom(this._scaleVector); }; /** * Get the position of the bone in local or world space. * @param space The space that the returned position is in. * @param mesh The mesh that this bone is attached to. This is only used in world space. * @returns The position of the bone */ Bone.prototype.getPosition = function (space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } if (mesh === void 0) { mesh = null; } var pos = BABYLON.Vector3.Zero(); this.getPositionToRef(space, mesh, pos); return pos; }; /** * Copy the position of the bone to a vector3 in local or world space. * @param space The space that the returned position is in. * @param mesh The mesh that this bone is attached to. This is only used in world space. * @param result The vector3 to copy the position to. */ Bone.prototype.getPositionToRef = function (space, mesh, result) { if (space === void 0) { space = BABYLON.Space.LOCAL; } if (space == BABYLON.Space.LOCAL) { var lm = this.getLocalMatrix(); result.x = lm.m[12]; result.y = lm.m[13]; result.z = lm.m[14]; } else { var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; if (mesh && wm) { tmat.copyFrom(this.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat = this.getAbsoluteTransform(); } result.x = tmat.m[12]; result.y = tmat.m[13]; result.z = tmat.m[14]; } }; /** * Get the absolute position of the bone (world space). * @param mesh The mesh that this bone is attached to. * @returns The absolute position of the bone */ Bone.prototype.getAbsolutePosition = function (mesh) { if (mesh === void 0) { mesh = null; } var pos = BABYLON.Vector3.Zero(); this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos); return pos; }; /** * Copy the absolute position of the bone (world space) to the result param. * @param mesh The mesh that this bone is attached to. * @param result The vector3 to copy the absolute position to. */ Bone.prototype.getAbsolutePositionToRef = function (mesh, result) { this.getPositionToRef(BABYLON.Space.WORLD, mesh, result); }; /** * Compute the absolute transforms of this bone and its children. */ Bone.prototype.computeAbsoluteTransforms = function () { if (this._parent) { this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform); } else { this._absoluteTransform.copyFrom(this._localMatrix); var poseMatrix = this._skeleton.getPoseMatrix(); if (poseMatrix) { this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform); } } var children = this.children; var len = children.length; for (var i = 0; i < len; i++) { children[i].computeAbsoluteTransforms(); } }; Bone.prototype._syncScaleVector = function () { var lm = this.getLocalMatrix(); var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]); var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]); var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]); var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1; var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1; var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1; this._scaleVector.x = xs * Math.sqrt(xsq); this._scaleVector.y = ys * Math.sqrt(ysq); this._scaleVector.z = zs * Math.sqrt(zsq); if (this._parent) { this._scaleVector.x /= this._parent._negateScaleChildren.x; this._scaleVector.y /= this._parent._negateScaleChildren.y; this._scaleVector.z /= this._parent._negateScaleChildren.z; } BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix); }; /** * Get the world direction from an axis that is in the local space of the bone. * @param localAxis The local direction that is used to compute the world direction. * @param mesh The mesh that this bone is attached to. * @returns The world direction */ Bone.prototype.getDirection = function (localAxis, mesh) { if (mesh === void 0) { mesh = null; } var result = BABYLON.Vector3.Zero(); this.getDirectionToRef(localAxis, mesh, result); return result; }; /** * Copy the world direction to a vector3 from an axis that is in the local space of the bone. * @param localAxis The local direction that is used to compute the world direction. * @param mesh The mesh that this bone is attached to. * @param result The vector3 that the world direction will be copied to. */ Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) { if (mesh === void 0) { mesh = null; } var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var mat = Bone._tmpMats[0]; mat.copyFrom(this.getAbsoluteTransform()); if (mesh && wm) { mat.multiplyToRef(wm, mat); } BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result); result.normalize(); }; /** * Get the euler rotation of the bone in local or world space. * @param space The space that the rotation should be in. * @param mesh The mesh that this bone is attached to. This is only used in world space. * @returns The euler rotation */ Bone.prototype.getRotation = function (space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } if (mesh === void 0) { mesh = null; } var result = BABYLON.Vector3.Zero(); this.getRotationToRef(space, mesh, result); return result; }; /** * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space. * @param space The space that the rotation should be in. * @param mesh The mesh that this bone is attached to. This is only used in world space. * @param result The vector3 that the rotation should be copied to. */ Bone.prototype.getRotationToRef = function (space, mesh, result) { if (space === void 0) { space = BABYLON.Space.LOCAL; } if (mesh === void 0) { mesh = null; } var quat = Bone._tmpQuat; this.getRotationQuaternionToRef(space, mesh, quat); quat.toEulerAnglesToRef(result); }; /** * Get the quaternion rotation of the bone in either local or world space. * @param space The space that the rotation should be in. * @param mesh The mesh that this bone is attached to. This is only used in world space. * @returns The quaternion rotation */ Bone.prototype.getRotationQuaternion = function (space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } if (mesh === void 0) { mesh = null; } var result = BABYLON.Quaternion.Identity(); this.getRotationQuaternionToRef(space, mesh, result); return result; }; /** * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space. * @param space The space that the rotation should be in. * @param mesh The mesh that this bone is attached to. This is only used in world space. * @param result The quaternion that the rotation should be copied to. */ Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) { if (space === void 0) { space = BABYLON.Space.LOCAL; } if (mesh === void 0) { mesh = null; } if (space == BABYLON.Space.LOCAL) { this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]); } else { var mat = Bone._tmpMats[0]; var amat = this.getAbsoluteTransform(); if (mesh) { amat.multiplyToRef(mesh.getWorldMatrix(), mat); } else { mat.copyFrom(amat); } mat.m[0] *= this._scalingDeterminant; mat.m[1] *= this._scalingDeterminant; mat.m[2] *= this._scalingDeterminant; mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]); } }; /** * Get the rotation matrix of the bone in local or world space. * @param space The space that the rotation should be in. * @param mesh The mesh that this bone is attached to. This is only used in world space. * @returns The rotation matrix */ Bone.prototype.getRotationMatrix = function (space, mesh) { if (space === void 0) { space = BABYLON.Space.LOCAL; } var result = BABYLON.Matrix.Identity(); this.getRotationMatrixToRef(space, mesh, result); return result; }; /** * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space. * @param space The space that the rotation should be in. * @param mesh The mesh that this bone is attached to. This is only used in world space. * @param result The quaternion that the rotation should be copied to. */ Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) { if (space === void 0) { space = BABYLON.Space.LOCAL; } if (space == BABYLON.Space.LOCAL) { this.getLocalMatrix().getRotationMatrixToRef(result); } else { var mat = Bone._tmpMats[0]; var amat = this.getAbsoluteTransform(); if (mesh) { amat.multiplyToRef(mesh.getWorldMatrix(), mat); } else { mat.copyFrom(amat); } mat.m[0] *= this._scalingDeterminant; mat.m[1] *= this._scalingDeterminant; mat.m[2] *= this._scalingDeterminant; mat.getRotationMatrixToRef(result); } }; /** * Get the world position of a point that is in the local space of the bone. * @param position The local position * @param mesh The mesh that this bone is attached to. * @returns The world position */ Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) { if (mesh === void 0) { mesh = null; } var result = BABYLON.Vector3.Zero(); this.getAbsolutePositionFromLocalToRef(position, mesh, result); return result; }; /** * Get the world position of a point that is in the local space of the bone and copy it to the result param. * @param position The local position * @param mesh The mesh that this bone is attached to. * @param result The vector3 that the world position should be copied to. */ Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) { if (mesh === void 0) { mesh = null; } var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; if (mesh && wm) { tmat.copyFrom(this.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat = this.getAbsoluteTransform(); } BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result); }; /** * Get the local position of a point that is in world space. * @param position The world position * @param mesh The mesh that this bone is attached to. * @returns The local position */ Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) { if (mesh === void 0) { mesh = null; } var result = BABYLON.Vector3.Zero(); this.getLocalPositionFromAbsoluteToRef(position, mesh, result); return result; }; /** * Get the local position of a point that is in world space and copy it to the result param. * @param position The world position * @param mesh The mesh that this bone is attached to. * @param result The vector3 that the local position should be copied to. */ Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) { if (mesh === void 0) { mesh = null; } var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; tmat.copyFrom(this.getAbsoluteTransform()); if (mesh && wm) { tmat.multiplyToRef(wm, tmat); } tmat.invert(); BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result); }; Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()]; Bone._tmpQuat = BABYLON.Quaternion.Identity(); Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()]; return Bone; }(BABYLON.Node)); BABYLON.Bone = Bone; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.bone.js.map var BABYLON; (function (BABYLON) { var BoneIKController = /** @class */ (function () { function BoneIKController(mesh, bone, options) { this.targetPosition = BABYLON.Vector3.Zero(); this.poleTargetPosition = BABYLON.Vector3.Zero(); this.poleTargetLocalOffset = BABYLON.Vector3.Zero(); this.poleAngle = 0; this.slerpAmount = 1; this._bone1Quat = BABYLON.Quaternion.Identity(); this._bone1Mat = BABYLON.Matrix.Identity(); this._bone2Ang = Math.PI; this._maxAngle = Math.PI; this._rightHandedSystem = false; this._bendAxis = BABYLON.Vector3.Right(); this._slerping = false; this._adjustRoll = 0; this._bone2 = bone; this._bone1 = bone.getParent(); if (!this._bone1) { return; } this.mesh = mesh; var bonePos = bone.getPosition(); if (bone.getAbsoluteTransform().determinant() > 0) { this._rightHandedSystem = true; this._bendAxis.x = 0; this._bendAxis.y = 0; this._bendAxis.z = -1; if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) { this._adjustRoll = Math.PI * .5; this._bendAxis.z = 1; } } if (this._bone1.length) { var boneScale1 = this._bone1.getScale(); var boneScale2 = this._bone2.getScale(); this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y; this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y; } else if (this._bone1.children[0]) { mesh.computeWorldMatrix(true); var pos1 = this._bone2.children[0].getAbsolutePosition(mesh); var pos2 = this._bone2.getAbsolutePosition(mesh); var pos3 = this._bone1.getAbsolutePosition(mesh); this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2); this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3); } this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat); this.maxAngle = Math.PI; if (options) { if (options.targetMesh) { this.targetMesh = options.targetMesh; this.targetMesh.computeWorldMatrix(true); } if (options.poleTargetMesh) { this.poleTargetMesh = options.poleTargetMesh; this.poleTargetMesh.computeWorldMatrix(true); } else if (options.poleTargetBone) { this.poleTargetBone = options.poleTargetBone; } else if (this._bone1.getParent()) { this.poleTargetBone = this._bone1.getParent(); } if (options.poleTargetLocalOffset) { this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset); } if (options.poleAngle) { this.poleAngle = options.poleAngle; } if (options.bendAxis) { this._bendAxis.copyFrom(options.bendAxis); } if (options.maxAngle) { this.maxAngle = options.maxAngle; } if (options.slerpAmount) { this.slerpAmount = options.slerpAmount; } } } Object.defineProperty(BoneIKController.prototype, "maxAngle", { get: function () { return this._maxAngle; }, set: function (value) { this._setMaxAngle(value); }, enumerable: true, configurable: true }); BoneIKController.prototype._setMaxAngle = function (ang) { if (ang < 0) { ang = 0; } if (ang > Math.PI || ang == undefined) { ang = Math.PI; } this._maxAngle = ang; var a = this._bone1Length; var b = this._bone2Length; this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang)); }; BoneIKController.prototype.update = function () { var bone1 = this._bone1; if (!bone1) { return; } var target = this.targetPosition; var poleTarget = this.poleTargetPosition; var mat1 = BoneIKController._tmpMats[0]; var mat2 = BoneIKController._tmpMats[1]; if (this.targetMesh) { target.copyFrom(this.targetMesh.getAbsolutePosition()); } if (this.poleTargetBone) { this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget); } else if (this.poleTargetMesh) { BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget); } var bonePos = BoneIKController._tmpVecs[0]; var zaxis = BoneIKController._tmpVecs[1]; var xaxis = BoneIKController._tmpVecs[2]; var yaxis = BoneIKController._tmpVecs[3]; var upAxis = BoneIKController._tmpVecs[4]; var _tmpQuat = BoneIKController._tmpQuat; bone1.getAbsolutePositionToRef(this.mesh, bonePos); poleTarget.subtractToRef(bonePos, upAxis); if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) { upAxis.y = 1; } else { upAxis.normalize(); } target.subtractToRef(bonePos, yaxis); yaxis.normalize(); BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis); zaxis.normalize(); BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis); xaxis.normalize(); BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1); var a = this._bone1Length; var b = this._bone2Length; var c = BABYLON.Vector3.Distance(bonePos, target); if (this._maxReach > 0) { c = Math.min(this._maxReach, c); } var acosa = (b * b + c * c - a * a) / (2 * b * c); var acosb = (c * c + a * a - b * b) / (2 * c * a); if (acosa > 1) { acosa = 1; } if (acosb > 1) { acosb = 1; } if (acosa < -1) { acosa = -1; } if (acosb < -1) { acosb = -1; } var angA = Math.acos(acosa); var angB = Math.acos(acosb); var angC = -angA - angB; if (this._rightHandedSystem) { BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2); mat2.multiplyToRef(mat1, mat1); BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2); mat2.multiplyToRef(mat1, mat1); } else { var _tmpVec = BoneIKController._tmpVecs[5]; _tmpVec.copyFrom(this._bendAxis); _tmpVec.x *= -1; BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2); mat2.multiplyToRef(mat1, mat1); } if (this.poleAngle) { BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2); mat1.multiplyToRef(mat2, mat1); } if (this._bone1) { if (this.slerpAmount < 1) { if (!this._slerping) { BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat); } BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat); BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat); angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount; this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh); this._slerping = true; } else { this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh); this._bone1Mat.copyFrom(mat1); this._slerping = false; } } this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL); this._bone2Ang = angC; }; BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()]; BoneIKController._tmpQuat = BABYLON.Quaternion.Identity(); BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()]; return BoneIKController; }()); BABYLON.BoneIKController = BoneIKController; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.boneIKController.js.map var BABYLON; (function (BABYLON) { var BoneLookController = /** @class */ (function () { /** * Create a BoneLookController * @param mesh the mesh that the bone belongs to * @param bone the bone that will be looking to the target * @param target the target Vector3 to look at * @param settings optional settings: * - maxYaw: the maximum angle the bone will yaw to * - minYaw: the minimum angle the bone will yaw to * - maxPitch: the maximum angle the bone will pitch to * - minPitch: the minimum angle the bone will yaw to * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target. * - upAxis: the up axis of the coordinate system * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD. * - yawAxis: set yawAxis if the bone does not yaw on the y axis * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis * - adjustYaw: used to make an adjustment to the yaw of the bone * - adjustPitch: used to make an adjustment to the pitch of the bone * - adjustRoll: used to make an adjustment to the roll of the bone **/ function BoneLookController(mesh, bone, target, options) { /** * The up axis of the coordinate system that is used when the bone is rotated. */ this.upAxis = BABYLON.Vector3.Up(); /** * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD. */ this.upAxisSpace = BABYLON.Space.LOCAL; /** * Used to make an adjustment to the yaw of the bone. */ this.adjustYaw = 0; /** * Used to make an adjustment to the pitch of the bone. */ this.adjustPitch = 0; /** * Used to make an adjustment to the roll of the bone. */ this.adjustRoll = 0; /** * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp). */ this.slerpAmount = 1; this._boneQuat = BABYLON.Quaternion.Identity(); this._slerping = false; this._firstFrameSkipped = false; this._fowardAxis = BABYLON.Vector3.Forward(); this.mesh = mesh; this.bone = bone; this.target = target; if (options) { if (options.adjustYaw) { this.adjustYaw = options.adjustYaw; } if (options.adjustPitch) { this.adjustPitch = options.adjustPitch; } if (options.adjustRoll) { this.adjustRoll = options.adjustRoll; } if (options.maxYaw != null) { this.maxYaw = options.maxYaw; } else { this.maxYaw = Math.PI; } if (options.minYaw != null) { this.minYaw = options.minYaw; } else { this.minYaw = -Math.PI; } if (options.maxPitch != null) { this.maxPitch = options.maxPitch; } else { this.maxPitch = Math.PI; } if (options.minPitch != null) { this.minPitch = options.minPitch; } else { this.minPitch = -Math.PI; } if (options.slerpAmount != null) { this.slerpAmount = options.slerpAmount; } if (options.upAxis != null) { this.upAxis = options.upAxis; } if (options.upAxisSpace != null) { this.upAxisSpace = options.upAxisSpace; } if (options.yawAxis != null || options.pitchAxis != null) { var newYawAxis = BABYLON.Axis.Y; var newPitchAxis = BABYLON.Axis.X; if (options.yawAxis != null) { newYawAxis = options.yawAxis.clone(); newYawAxis.normalize(); } if (options.pitchAxis != null) { newPitchAxis = options.pitchAxis.clone(); newPitchAxis.normalize(); } var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis); this._transformYawPitch = BABYLON.Matrix.Identity(); BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch); this._transformYawPitchInv = this._transformYawPitch.clone(); this._transformYawPitch.invert(); } } if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) { this.upAxisSpace = BABYLON.Space.LOCAL; } } Object.defineProperty(BoneLookController.prototype, "minYaw", { /** * Get/set the minimum yaw angle that the bone can look to. */ get: function () { return this._minYaw; }, set: function (value) { this._minYaw = value; this._minYawSin = Math.sin(value); this._minYawCos = Math.cos(value); if (this._maxYaw != null) { this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw; this._yawRange = this._maxYaw - this._minYaw; } }, enumerable: true, configurable: true }); Object.defineProperty(BoneLookController.prototype, "maxYaw", { /** * Get/set the maximum yaw angle that the bone can look to. */ get: function () { return this._maxYaw; }, set: function (value) { this._maxYaw = value; this._maxYawSin = Math.sin(value); this._maxYawCos = Math.cos(value); if (this._minYaw != null) { this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw; this._yawRange = this._maxYaw - this._minYaw; } }, enumerable: true, configurable: true }); Object.defineProperty(BoneLookController.prototype, "minPitch", { /** * Get/set the minimum pitch angle that the bone can look to. */ get: function () { return this._minPitch; }, set: function (value) { this._minPitch = value; this._minPitchTan = Math.tan(value); }, enumerable: true, configurable: true }); Object.defineProperty(BoneLookController.prototype, "maxPitch", { /** * Get/set the maximum pitch angle that the bone can look to. */ get: function () { return this._maxPitch; }, set: function (value) { this._maxPitch = value; this._maxPitchTan = Math.tan(value); }, enumerable: true, configurable: true }); /** * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()). */ BoneLookController.prototype.update = function () { //skip the first frame when slerping so that the mesh rotation is correct if (this.slerpAmount < 1 && !this._firstFrameSkipped) { this._firstFrameSkipped = true; return; } var bone = this.bone; var bonePos = BoneLookController._tmpVecs[0]; bone.getAbsolutePositionToRef(this.mesh, bonePos); var target = this.target; var _tmpMat1 = BoneLookController._tmpMats[0]; var _tmpMat2 = BoneLookController._tmpMats[1]; var mesh = this.mesh; var parentBone = bone.getParent(); var upAxis = BoneLookController._tmpVecs[1]; upAxis.copyFrom(this.upAxis); if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) { if (this._transformYawPitch) { BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis); } parentBone.getDirectionToRef(upAxis, this.mesh, upAxis); } else if (this.upAxisSpace == BABYLON.Space.LOCAL) { mesh.getDirectionToRef(upAxis, upAxis); if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) { upAxis.normalize(); } } var checkYaw = false; var checkPitch = false; if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) { checkYaw = true; } if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) { checkPitch = true; } if (checkYaw || checkPitch) { var spaceMat = BoneLookController._tmpMats[2]; var spaceMatInv = BoneLookController._tmpMats[3]; if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) { parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat); } else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) { spaceMat.copyFrom(mesh.getWorldMatrix()); } else { var forwardAxis = BoneLookController._tmpVecs[2]; forwardAxis.copyFrom(this._fowardAxis); if (this._transformYawPitch) { BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis); } if (parentBone) { parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis); } else { mesh.getDirectionToRef(forwardAxis, forwardAxis); } var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis); rightAxis.normalize(); var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis); BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat); } spaceMat.invertToRef(spaceMatInv); var xzlen = null; if (checkPitch) { var localTarget = BoneLookController._tmpVecs[3]; target.subtractToRef(bonePos, localTarget); BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget); xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); var pitch = Math.atan2(localTarget.y, xzlen); var newPitch = pitch; if (pitch > this._maxPitch) { localTarget.y = this._maxPitchTan * xzlen; newPitch = this._maxPitch; } else if (pitch < this._minPitch) { localTarget.y = this._minPitchTan * xzlen; newPitch = this._minPitch; } if (pitch != newPitch) { BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget); localTarget.addInPlace(bonePos); target = localTarget; } } if (checkYaw) { var localTarget = BoneLookController._tmpVecs[4]; target.subtractToRef(bonePos, localTarget); BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget); var yaw = Math.atan2(localTarget.x, localTarget.z); var newYaw = yaw; if (yaw > this._maxYaw || yaw < this._minYaw) { if (xzlen == null) { xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); } if (this._yawRange > Math.PI) { if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) { localTarget.z = this._maxYawCos * xzlen; localTarget.x = this._maxYawSin * xzlen; newYaw = this._maxYaw; } else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) { localTarget.z = this._minYawCos * xzlen; localTarget.x = this._minYawSin * xzlen; newYaw = this._minYaw; } } else { if (yaw > this._maxYaw) { localTarget.z = this._maxYawCos * xzlen; localTarget.x = this._maxYawSin * xzlen; newYaw = this._maxYaw; } else if (yaw < this._minYaw) { localTarget.z = this._minYawCos * xzlen; localTarget.x = this._minYawSin * xzlen; newYaw = this._minYaw; } } } if (this._slerping && this._yawRange > Math.PI) { //are we going to be crossing into the min/max region? var boneFwd = BoneLookController._tmpVecs[8]; boneFwd.copyFrom(BABYLON.Axis.Z); if (this._transformYawPitch) { BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd); } var boneRotMat = BABYLON.BoneLookController._tmpMats[4]; this._boneQuat.toRotationMatrix(boneRotMat); this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat); BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd); BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd); var boneYaw = Math.atan2(boneFwd.x, boneFwd.z); var angBtwTar = this._getAngleBetween(boneYaw, yaw); var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint); if (angBtwTar > angBtwMidYaw) { if (xzlen == null) { xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); } var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw); var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw); if (angBtwMin < angBtwMax) { newYaw = boneYaw + Math.PI * .75; localTarget.z = Math.cos(newYaw) * xzlen; localTarget.x = Math.sin(newYaw) * xzlen; } else { newYaw = boneYaw - Math.PI * .75; localTarget.z = Math.cos(newYaw) * xzlen; localTarget.x = Math.sin(newYaw) * xzlen; } } } if (yaw != newYaw) { BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget); localTarget.addInPlace(bonePos); target = localTarget; } } } var zaxis = BoneLookController._tmpVecs[5]; var xaxis = BoneLookController._tmpVecs[6]; var yaxis = BoneLookController._tmpVecs[7]; var _tmpQuat = BoneLookController._tmpQuat; target.subtractToRef(bonePos, zaxis); zaxis.normalize(); BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis); xaxis.normalize(); BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis); yaxis.normalize(); BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1); if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) { return; } if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) { return; } if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) { return; } if (this.adjustYaw || this.adjustPitch || this.adjustRoll) { BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2); _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1); } if (this.slerpAmount < 1) { if (!this._slerping) { this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat); } if (this._transformYawPitch) { this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1); } BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat); BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat); this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh); this._slerping = true; } else { if (this._transformYawPitch) { this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1); } this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh); this._slerping = false; } }; BoneLookController.prototype._getAngleDiff = function (ang1, ang2) { var angDiff = ang2 - ang1; angDiff %= Math.PI * 2; if (angDiff > Math.PI) { angDiff -= Math.PI * 2; } else if (angDiff < -Math.PI) { angDiff += Math.PI * 2; } return angDiff; }; BoneLookController.prototype._getAngleBetween = function (ang1, ang2) { ang1 %= (2 * Math.PI); ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1; ang2 %= (2 * Math.PI); ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2; var ab = 0; if (ang1 < ang2) { ab = ang2 - ang1; } else { ab = ang1 - ang2; } if (ab > Math.PI) { ab = Math.PI * 2 - ab; } return ab; }; BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) { ang %= (2 * Math.PI); ang = (ang < 0) ? ang + (2 * Math.PI) : ang; ang1 %= (2 * Math.PI); ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1; ang2 %= (2 * Math.PI); ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2; if (ang1 < ang2) { if (ang > ang1 && ang < ang2) { return true; } } else { if (ang > ang2 && ang < ang1) { return true; } } return false; }; BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()]; BoneLookController._tmpQuat = BABYLON.Quaternion.Identity(); BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()]; return BoneLookController; }()); BABYLON.BoneLookController = BoneLookController; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.boneLookController.js.map var BABYLON; (function (BABYLON) { var Skeleton = /** @class */ (function () { function Skeleton(name, id, scene) { this.name = name; this.id = id; this.bones = new Array(); this.needInitialSkinMatrix = false; this._isDirty = true; this._meshesWithPoseMatrix = new Array(); this._identity = BABYLON.Matrix.Identity(); this._ranges = {}; this._lastAbsoluteTransformsUpdateId = -1; // Events /** * An event triggered before computing the skeleton's matrices * @type {BABYLON.Observable} */ this.onBeforeComputeObservable = new BABYLON.Observable(); this.bones = []; this._scene = scene || BABYLON.Engine.LastCreatedScene; scene.skeletons.push(this); //make sure it will recalculate the matrix next time prepare is called. this._isDirty = true; } // Members Skeleton.prototype.getTransformMatrices = function (mesh) { if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) { return mesh._bonesTransformMatrices; } if (!this._transformMatrices) { this.prepare(); } return this._transformMatrices; }; Skeleton.prototype.getScene = function () { return this._scene; }; // Methods /** * @param {boolean} fullDetails - support for multiple levels of logging within scene loading */ Skeleton.prototype.toString = function (fullDetails) { var ret = "Name: " + this.name + ", nBones: " + this.bones.length; ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"); if (fullDetails) { ret += ", Ranges: {"; var first = true; for (var name_1 in this._ranges) { if (first) { ret += ", "; first = false; } ret += name_1; } ret += "}"; } return ret; }; /** * Get bone's index searching by name * @param {string} name is bone's name to search for * @return {number} Indice of the bone. Returns -1 if not found */ Skeleton.prototype.getBoneIndexByName = function (name) { for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) { if (this.bones[boneIndex].name === name) { return boneIndex; } } return -1; }; Skeleton.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, nBones = this.bones.length; i < nBones; i++) { if (this.bones[i].animations[0]) { this.bones[i].animations[0].createRange(name, from, to); } } } }; Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) { if (deleteFrames === void 0) { deleteFrames = true; } for (var i = 0, nBones = this.bones.length; i < nBones; i++) { if (this.bones[i].animations[0]) { this.bones[i].animations[0].deleteRange(name, deleteFrames); } } this._ranges[name] = null; // said much faster than 'delete this._range[name]' }; Skeleton.prototype.getAnimationRange = function (name) { return this._ranges[name]; }; /** * Returns as an Array, all AnimationRanges defined on this skeleton */ Skeleton.prototype.getAnimationRanges = function () { var animationRanges = []; var name; var i = 0; for (name in this._ranges) { animationRanges[i] = this._ranges[name]; i++; } return animationRanges; }; /** * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences */ Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) { if (rescaleAsRequired === void 0) { rescaleAsRequired = false; } if (this._ranges[name] || !source.getAnimationRange(name)) { return false; } var ret = true; var frameOffset = this._getHighestAnimationFrame() + 1; // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required var boneDict = {}; var sourceBones = source.bones; var nBones; var i; for (i = 0, nBones = sourceBones.length; i < nBones; i++) { boneDict[sourceBones[i].name] = sourceBones[i]; } if (this.bones.length !== sourceBones.length) { BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length); ret = false; } var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null; for (i = 0, nBones = this.bones.length; i < nBones; i++) { var boneName = this.bones[i].name; var sourceBone = boneDict[boneName]; if (sourceBone) { ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio); } else { BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName); ret = false; } } // do not call createAnimationRange(), since it also is done to bones, which was already done var range = source.getAnimationRange(name); if (range) { this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset); } return ret; }; Skeleton.prototype.returnToRest = function () { for (var index = 0; index < this.bones.length; index++) { this.bones[index].returnToRest(); } }; Skeleton.prototype._getHighestAnimationFrame = function () { var ret = 0; for (var i = 0, nBones = this.bones.length; i < nBones; i++) { if (this.bones[i].animations[0]) { var highest = this.bones[i].animations[0].getHighestFrame(); if (ret < highest) { ret = highest; } } } return ret; }; Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) { var range = this.getAnimationRange(name); if (!range) { return null; } return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd); }; Skeleton.prototype._markAsDirty = function () { this._isDirty = true; }; Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) { this._meshesWithPoseMatrix.push(mesh); }; Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) { var index = this._meshesWithPoseMatrix.indexOf(mesh); if (index > -1) { this._meshesWithPoseMatrix.splice(index, 1); } }; Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) { this.onBeforeComputeObservable.notifyObservers(this); for (var index = 0; index < this.bones.length; index++) { var bone = this.bones[index]; var parentBone = bone.getParent(); if (parentBone) { bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix()); } else { if (initialSkinMatrix) { bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix()); } else { bone.getWorldMatrix().copyFrom(bone.getLocalMatrix()); } } if (bone._index !== -1) { var mappedIndex = bone._index === null ? index : bone._index; bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16); } } this._identity.copyToArray(targetMatrix, this.bones.length * 16); }; Skeleton.prototype.prepare = function () { if (!this._isDirty) { return; } if (this.needInitialSkinMatrix) { for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) { var mesh = this._meshesWithPoseMatrix[index]; var poseMatrix = mesh.getPoseMatrix(); if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) { mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1)); } if (this._synchronizedWithMesh !== mesh) { this._synchronizedWithMesh = mesh; // Prepare bones for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) { var bone = this.bones[boneIndex]; if (!bone.getParent()) { var matrix = bone.getBaseMatrix(); matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]); bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]); } } } this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix); } } else { if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) { this._transformMatrices = new Float32Array(16 * (this.bones.length + 1)); } this._computeTransformMatrices(this._transformMatrices, null); } this._isDirty = false; this._scene._activeBones.addCount(this.bones.length, false); }; Skeleton.prototype.getAnimatables = function () { if (!this._animatables || this._animatables.length !== this.bones.length) { this._animatables = []; for (var index = 0; index < this.bones.length; index++) { this._animatables.push(this.bones[index]); } } return this._animatables; }; Skeleton.prototype.clone = function (name, id) { var result = new Skeleton(name, id || name, this._scene); result.needInitialSkinMatrix = this.needInitialSkinMatrix; for (var index = 0; index < this.bones.length; index++) { var source = this.bones[index]; var parentBone = null; var parent_1 = source.getParent(); if (parent_1) { var parentIndex = this.bones.indexOf(parent_1); parentBone = result.bones[parentIndex]; } var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone()); BABYLON.Tools.DeepCopy(source.animations, bone.animations); } if (this._ranges) { result._ranges = {}; for (var rangeName in this._ranges) { var range = this._ranges[rangeName]; if (range) { result._ranges[rangeName] = range.clone(); } } } this._isDirty = true; return result; }; Skeleton.prototype.enableBlending = function (blendingSpeed) { if (blendingSpeed === void 0) { blendingSpeed = 0.01; } this.bones.forEach(function (bone) { bone.animations.forEach(function (animation) { animation.enableBlending = true; animation.blendingSpeed = blendingSpeed; }); }); }; Skeleton.prototype.dispose = function () { this._meshesWithPoseMatrix = []; // Animations this.getScene().stopAnimation(this); // Remove from scene this.getScene().removeSkeleton(this); }; Skeleton.prototype.serialize = function () { var serializationObject = {}; serializationObject.name = this.name; serializationObject.id = this.id; serializationObject.dimensionsAtRest = this.dimensionsAtRest; serializationObject.bones = []; serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix; for (var index = 0; index < this.bones.length; index++) { var bone = this.bones[index]; var parent_2 = bone.getParent(); var serializedBone = { parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1, name: bone.name, matrix: bone.getBaseMatrix().toArray(), rest: bone.getRestPose().toArray() }; serializationObject.bones.push(serializedBone); if (bone.length) { serializedBone.length = bone.length; } if (bone.animations && bone.animations.length > 0) { serializedBone.animation = bone.animations[0].serialize(); } 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; }; Skeleton.Parse = function (parsedSkeleton, scene) { var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene); if (parsedSkeleton.dimensionsAtRest) { skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest); } skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix; var index; for (index = 0; index < parsedSkeleton.bones.length; index++) { var parsedBone = parsedSkeleton.bones[index]; var parentBone = null; if (parsedBone.parentBoneIndex > -1) { parentBone = skeleton.bones[parsedBone.parentBoneIndex]; } var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null; var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest); if (parsedBone.length) { bone.length = parsedBone.length; } if (parsedBone.animation) { bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation)); } } // placed after bones, so createAnimationRange can cascade down if (parsedSkeleton.ranges) { for (index = 0; index < parsedSkeleton.ranges.length; index++) { var data = parsedSkeleton.ranges[index]; skeleton.createAnimationRange(data.name, data.from, data.to); } } return skeleton; }; Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) { if (forceUpdate === void 0) { forceUpdate = false; } var renderId = this._scene.getRenderId(); if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) { this.bones[0].computeAbsoluteTransforms(); this._lastAbsoluteTransformsUpdateId = renderId; } }; Skeleton.prototype.getPoseMatrix = function () { var poseMatrix = null; if (this._meshesWithPoseMatrix.length > 0) { poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix(); } return poseMatrix; }; Skeleton.prototype.sortBones = function () { var bones = new Array(); var visited = new Array(this.bones.length); for (var index = 0; index < this.bones.length; index++) { this._sortBones(index, bones, visited); } this.bones = bones; }; Skeleton.prototype._sortBones = function (index, bones, visited) { if (visited[index]) { return; } visited[index] = true; var bone = this.bones[index]; if (bone._index === undefined) { bone._index = index; } var parentBone = bone.getParent(); if (parentBone) { this._sortBones(this.bones.indexOf(parentBone), bones, visited); } bones.push(bone); }; return Skeleton; }()); BABYLON.Skeleton = Skeleton; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.skeleton.js.map var BABYLON; (function (BABYLON) { var SphericalPolynomial = /** @class */ (function () { function SphericalPolynomial() { this.x = BABYLON.Vector3.Zero(); this.y = BABYLON.Vector3.Zero(); this.z = BABYLON.Vector3.Zero(); this.xx = BABYLON.Vector3.Zero(); this.yy = BABYLON.Vector3.Zero(); this.zz = BABYLON.Vector3.Zero(); this.xy = BABYLON.Vector3.Zero(); this.yz = BABYLON.Vector3.Zero(); this.zx = BABYLON.Vector3.Zero(); } SphericalPolynomial.prototype.addAmbient = function (color) { var colorVector = new BABYLON.Vector3(color.r, color.g, color.b); this.xx = this.xx.add(colorVector); this.yy = this.yy.add(colorVector); this.zz = this.zz.add(colorVector); }; SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) { var result = new SphericalPolynomial(); result.x = harmonics.L11.scale(1.02333); result.y = harmonics.L1_1.scale(1.02333); result.z = harmonics.L10.scale(1.02333); result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043)); result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043)); result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417)); result.yz = harmonics.L2_1.scale(0.858086); result.zx = harmonics.L21.scale(0.858086); result.xy = harmonics.L2_2.scale(0.858086); result.scale(1.0 / Math.PI); return result; }; SphericalPolynomial.prototype.scale = function (scale) { this.x = this.x.scale(scale); this.y = this.y.scale(scale); this.z = this.z.scale(scale); this.xx = this.xx.scale(scale); this.yy = this.yy.scale(scale); this.zz = this.zz.scale(scale); this.yz = this.yz.scale(scale); this.zx = this.zx.scale(scale); this.xy = this.xy.scale(scale); }; return SphericalPolynomial; }()); BABYLON.SphericalPolynomial = SphericalPolynomial; var SphericalHarmonics = /** @class */ (function () { function SphericalHarmonics() { this.L00 = BABYLON.Vector3.Zero(); this.L1_1 = BABYLON.Vector3.Zero(); this.L10 = BABYLON.Vector3.Zero(); this.L11 = BABYLON.Vector3.Zero(); this.L2_2 = BABYLON.Vector3.Zero(); this.L2_1 = BABYLON.Vector3.Zero(); this.L20 = BABYLON.Vector3.Zero(); this.L21 = BABYLON.Vector3.Zero(); this.L22 = BABYLON.Vector3.Zero(); } SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) { var colorVector = new BABYLON.Vector3(color.r, color.g, color.b); var c = colorVector.scale(deltaSolidAngle); this.L00 = this.L00.add(c.scale(0.282095)); this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y)); this.L10 = this.L10.add(c.scale(0.488603 * direction.z)); this.L11 = this.L11.add(c.scale(0.488603 * direction.x)); this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y)); this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z)); this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z)); this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0))); this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y))); }; SphericalHarmonics.prototype.scale = function (scale) { this.L00 = this.L00.scale(scale); this.L1_1 = this.L1_1.scale(scale); this.L10 = this.L10.scale(scale); this.L11 = this.L11.scale(scale); this.L2_2 = this.L2_2.scale(scale); this.L2_1 = this.L2_1.scale(scale); this.L20 = this.L20.scale(scale); this.L21 = this.L21.scale(scale); this.L22 = this.L22.scale(scale); }; SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () { // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere. // // E_lm = A_l * L_lm // // In spherical harmonics this convolution amounts to scaling factors for each frequency band. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where // the scaling factors are given in equation 9. // Constant (Band 0) this.L00 = this.L00.scale(3.141593); // Linear (Band 1) this.L1_1 = this.L1_1.scale(2.094395); this.L10 = this.L10.scale(2.094395); this.L11 = this.L11.scale(2.094395); // Quadratic (Band 2) this.L2_2 = this.L2_2.scale(0.785398); this.L2_1 = this.L2_1.scale(0.785398); this.L20 = this.L20.scale(0.785398); this.L21 = this.L21.scale(0.785398); this.L22 = this.L22.scale(0.785398); }; SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () { // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation. // L = (1/pi) * E * rho // // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually. this.scale(1.0 / Math.PI); // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied // (The pixel shader must apply albedo after texture fetches, etc). }; SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) { var result = new SphericalHarmonics(); result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126)); result.L1_1 = polynomial.y.scale(0.977204); result.L10 = polynomial.z.scale(0.977204); result.L11 = polynomial.x.scale(0.977204); result.L2_2 = polynomial.xy.scale(1.16538); result.L2_1 = polynomial.yz.scale(1.16538); result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834)); result.L21 = polynomial.zx.scale(1.16538); result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538)); result.scale(Math.PI); return result; }; return SphericalHarmonics; }()); BABYLON.SphericalHarmonics = SphericalHarmonics; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.sphericalPolynomial.js.map var BABYLON; (function (BABYLON) { var Internals; (function (Internals) { var FileFaceOrientation = /** @class */ (function () { function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) { this.name = name; this.worldAxisForNormal = worldAxisForNormal; this.worldAxisForFileX = worldAxisForFileX; this.worldAxisForFileY = worldAxisForFileY; } return FileFaceOrientation; }()); ; /** * Helper class dealing with the extraction of spherical polynomial dataArray * from a cube map. */ var CubeMapToSphericalPolynomialTools = /** @class */ (function () { function CubeMapToSphericalPolynomialTools() { } /** * Converts a texture to the according Spherical Polynomial data. * This extracts the first 3 orders only as they are the only one used in the lighting. * * @param texture The texture to extract the information from. * @return The Spherical Polynomial data. */ CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) { if (!texture.isCube) { // Only supports cube Textures currently. return null; } var size = texture.getSize().width; var right = texture.readPixels(0); var left = texture.readPixels(1); var up; var down; if (texture.isRenderTarget) { up = texture.readPixels(3); down = texture.readPixels(2); } else { up = texture.readPixels(2); down = texture.readPixels(3); } var front = texture.readPixels(4); var back = texture.readPixels(5); var gammaSpace = texture.gammaSpace; // Always read as RGBA. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA; var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; } var cubeInfo = { size: size, right: right, left: left, up: up, down: down, front: front, back: back, format: format, type: type, gammaSpace: gammaSpace, }; return this.ConvertCubeMapToSphericalPolynomial(cubeInfo); }; /** * Converts a cubemap to the according Spherical Polynomial data. * This extracts the first 3 orders only as they are the only one used in the lighting. * * @param cubeInfo The Cube map to extract the information from. * @return The Spherical Polynomial data. */ CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) { var sphericalHarmonics = new BABYLON.SphericalHarmonics(); var totalSolidAngle = 0.0; // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size. var du = 2.0 / cubeInfo.size; var dv = du; // The (u,v) of the first texel is half a texel from the corner (-1,-1). var minUV = du * 0.5 - 1.0; for (var faceIndex = 0; faceIndex < 6; faceIndex++) { var fileFace = this.FileFaces[faceIndex]; var dataArray = cubeInfo[fileFace.name]; var v = minUV; // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH). // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality. // Because SP is still linear, so summation is fine in that basis. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3; for (var y = 0; y < cubeInfo.size; y++) { var u = minUV; for (var x = 0; x < cubeInfo.size; x++) { // World direction (not normalised) var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal); worldDirection.normalize(); var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0); var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0]; var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1]; var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2]; // Handle Integer types. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) { r /= 255; g /= 255; b /= 255; } // Handle Gamma space textures. if (cubeInfo.gammaSpace) { r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace); g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace); b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace); } var color = new BABYLON.Color3(r, g, b); sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle); totalSolidAngle += deltaSolidAngle; u += du; } v += dv; } } // Solid angle for entire sphere is 4*pi var sphereSolidAngle = 4.0 * Math.PI; // Adjust the solid angle to allow for how many faces we processed. var facesProcessed = 6.0; var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0; // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle. // This is needed because the numerical integration over the cube uses a // small angle approximation of solid angle for each texel (see deltaSolidAngle), // and also to compensate for accumulative error due to float precision in the summation. var correctionFactor = expectedSolidAngle / totalSolidAngle; sphericalHarmonics.scale(correctionFactor); sphericalHarmonics.convertIncidentRadianceToIrradiance(); sphericalHarmonics.convertIrradianceToLambertianRadiance(); return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics); }; CubeMapToSphericalPolynomialTools.FileFaces = [ new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)), new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)), new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)), new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)), new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)), new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom ]; return CubeMapToSphericalPolynomialTools; }()); Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools; })(Internals = BABYLON.Internals || (BABYLON.Internals = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map var BABYLON; (function (BABYLON) { var Internals; (function (Internals) { /** * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces. */ var PanoramaToCubeMapTools = /** @class */ (function () { function PanoramaToCubeMapTools() { } /** * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces). * * @param float32Array The source data. * @param inputWidth The width of the input panorama. * @param inputhHeight The height of the input panorama. * @param size The willing size of the generated cubemap (each faces will be size * size pixels) * @return The cubemap data */ PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) { if (!float32Array) { throw "ConvertPanoramaToCubemap: input cannot be null"; } if (float32Array.length != inputWidth * inputHeight * 3) { throw "ConvertPanoramaToCubemap: input size is wrong"; } var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight); var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight); var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight); var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight); var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight); var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight); return { front: textureFront, back: textureBack, left: textureLeft, right: textureRight, up: textureUp, down: textureDown, size: size, type: BABYLON.Engine.TEXTURETYPE_FLOAT, format: BABYLON.Engine.TEXTUREFORMAT_RGB, gammaSpace: false, }; }; PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) { var buffer = new ArrayBuffer(texSize * texSize * 4 * 3); var textureArray = new Float32Array(buffer); var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize); var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize); var dy = 1 / texSize; var fy = 0; for (var y = 0; y < texSize; y++) { var xv1 = faceData[0]; var xv2 = faceData[2]; for (var x = 0; x < texSize; x++) { var v = xv2.subtract(xv1).scale(fy).add(xv1); v.normalize(); var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight); // 3 channels per pixels textureArray[y * texSize * 3 + (x * 3) + 0] = color.r; textureArray[y * texSize * 3 + (x * 3) + 1] = color.g; textureArray[y * texSize * 3 + (x * 3) + 2] = color.b; xv1 = xv1.add(rotDX1); xv2 = xv2.add(rotDX2); } fy += dy; } return textureArray; }; PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) { var theta = Math.atan2(vDir.z, vDir.x); var phi = Math.acos(vDir.y); while (theta < -Math.PI) theta += 2 * Math.PI; while (theta > Math.PI) theta -= 2 * Math.PI; var dx = theta / Math.PI; var dy = phi / Math.PI; // recenter. dx = dx * 0.5 + 0.5; var px = Math.round(dx * inputWidth); if (px < 0) px = 0; else if (px >= inputWidth) px = inputWidth - 1; var py = Math.round(dy * inputHeight); if (py < 0) py = 0; else if (py >= inputHeight) py = inputHeight - 1; var inputY = (inputHeight - py - 1); var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0]; var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1]; var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2]; return { r: r, g: g, b: b }; }; PanoramaToCubeMapTools.FACE_FRONT = [ new BABYLON.Vector3(-1.0, -1.0, -1.0), new BABYLON.Vector3(1.0, -1.0, -1.0), new BABYLON.Vector3(-1.0, 1.0, -1.0), new BABYLON.Vector3(1.0, 1.0, -1.0) ]; PanoramaToCubeMapTools.FACE_BACK = [ new BABYLON.Vector3(1.0, -1.0, 1.0), new BABYLON.Vector3(-1.0, -1.0, 1.0), new BABYLON.Vector3(1.0, 1.0, 1.0), new BABYLON.Vector3(-1.0, 1.0, 1.0) ]; PanoramaToCubeMapTools.FACE_RIGHT = [ new BABYLON.Vector3(1.0, -1.0, -1.0), new BABYLON.Vector3(1.0, -1.0, 1.0), new BABYLON.Vector3(1.0, 1.0, -1.0), new BABYLON.Vector3(1.0, 1.0, 1.0) ]; PanoramaToCubeMapTools.FACE_LEFT = [ new BABYLON.Vector3(-1.0, -1.0, 1.0), new BABYLON.Vector3(-1.0, -1.0, -1.0), new BABYLON.Vector3(-1.0, 1.0, 1.0), new BABYLON.Vector3(-1.0, 1.0, -1.0) ]; PanoramaToCubeMapTools.FACE_DOWN = [ new BABYLON.Vector3(-1.0, 1.0, -1.0), new BABYLON.Vector3(1.0, 1.0, -1.0), new BABYLON.Vector3(-1.0, 1.0, 1.0), new BABYLON.Vector3(1.0, 1.0, 1.0) ]; PanoramaToCubeMapTools.FACE_UP = [ new BABYLON.Vector3(-1.0, -1.0, 1.0), new BABYLON.Vector3(1.0, -1.0, 1.0), new BABYLON.Vector3(-1.0, -1.0, -1.0), new BABYLON.Vector3(1.0, -1.0, -1.0) ]; return PanoramaToCubeMapTools; }()); Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools; })(Internals = BABYLON.Internals || (BABYLON.Internals = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.panoramaToCubemap.js.map var BABYLON; (function (BABYLON) { var Internals; (function (Internals) { ; /** * This groups tools to convert HDR texture to native colors array. */ var HDRTools = /** @class */ (function () { function HDRTools() { } HDRTools.Ldexp = function (mantissa, exponent) { if (exponent > 1023) { return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023); } if (exponent < -1074) { return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074); } return mantissa * Math.pow(2, exponent); }; HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) { if (exponent > 0) { exponent = this.Ldexp(1.0, exponent - (128 + 8)); float32array[index + 0] = red * exponent; float32array[index + 1] = green * exponent; float32array[index + 2] = blue * exponent; } else { float32array[index + 0] = 0; float32array[index + 1] = 0; float32array[index + 2] = 0; } }; HDRTools.readStringLine = function (uint8array, startIndex) { var line = ""; var character = ""; for (var i = startIndex; i < uint8array.length - startIndex; i++) { character = String.fromCharCode(uint8array[i]); if (character == "\n") { break; } line += character; } return line; }; /** * Reads header information from an RGBE texture stored in a native array. * More information on this format are available here: * https://en.wikipedia.org/wiki/RGBE_image_format * * @param uint8array The binary file stored in native array. * @return The header information. */ HDRTools.RGBE_ReadHeader = function (uint8array) { var height = 0; var width = 0; var line = this.readStringLine(uint8array, 0); if (line[0] != '#' || line[1] != '?') { throw "Bad HDR Format."; } var endOfHeader = false; var findFormat = false; var lineIndex = 0; do { lineIndex += (line.length + 1); line = this.readStringLine(uint8array, lineIndex); if (line == "FORMAT=32-bit_rle_rgbe") { findFormat = true; } else if (line.length == 0) { endOfHeader = true; } } while (!endOfHeader); if (!findFormat) { throw "HDR Bad header format, unsupported FORMAT"; } lineIndex += (line.length + 1); line = this.readStringLine(uint8array, lineIndex); var sizeRegexp = /^\-Y (.*) \+X (.*)$/g; var match = sizeRegexp.exec(line); // TODO. Support +Y and -X if needed. if (!match || match.length < 3) { throw "HDR Bad header format, no size"; } width = parseInt(match[2]); height = parseInt(match[1]); if (width < 8 || width > 0x7fff) { throw "HDR Bad header format, unsupported size"; } lineIndex += (line.length + 1); return { height: height, width: width, dataPosition: lineIndex }; }; /** * Returns the cubemap information (each faces texture data) extracted from an RGBE texture. * This RGBE texture needs to store the information as a panorama. * * More information on this format are available here: * https://en.wikipedia.org/wiki/RGBE_image_format * * @param buffer The binary file stored in an array buffer. * @param size The expected size of the extracted cubemap. * @return The Cube Map information. */ HDRTools.GetCubeMapTextureData = function (buffer, size) { var uint8array = new Uint8Array(buffer); var hdrInfo = this.RGBE_ReadHeader(uint8array); var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo); var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size); return cubeMapData; }; /** * Returns the pixels data extracted from an RGBE texture. * This pixels will be stored left to right up to down in the R G B order in one array. * * More information on this format are available here: * https://en.wikipedia.org/wiki/RGBE_image_format * * @param uint8array The binary file stored in an array buffer. * @param hdrInfo The header information of the file. * @return The pixels data in RGB right to left up to down order. */ HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) { // Keep for multi format supports. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo); }; HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) { var num_scanlines = hdrInfo.height; var scanline_width = hdrInfo.width; var a, b, c, d, count; var dataIndex = hdrInfo.dataPosition; var index = 0, endIndex = 0, i = 0; var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E var scanLineArray = new Uint8Array(scanLineArrayBuffer); // 3 channels of 4 bytes per pixel in float. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3); var resultArray = new Float32Array(resultBuffer); // read in each successive scanline while (num_scanlines > 0) { a = uint8array[dataIndex++]; b = uint8array[dataIndex++]; c = uint8array[dataIndex++]; d = uint8array[dataIndex++]; if (a != 2 || b != 2 || (c & 0x80)) { // this file is not run length encoded throw "HDR Bad header format, not RLE"; } if (((c << 8) | d) != scanline_width) { throw "HDR Bad header format, wrong scan line width"; } index = 0; // read each of the four channels for the scanline into the buffer for (i = 0; i < 4; i++) { endIndex = (i + 1) * scanline_width; while (index < endIndex) { a = uint8array[dataIndex++]; b = uint8array[dataIndex++]; if (a > 128) { // a run of the same value count = a - 128; if ((count == 0) || (count > endIndex - index)) { throw "HDR Bad Format, bad scanline data (run)"; } while (count-- > 0) { scanLineArray[index++] = b; } } else { // a non-run count = a; if ((count == 0) || (count > endIndex - index)) { throw "HDR Bad Format, bad scanline data (non-run)"; } scanLineArray[index++] = b; if (--count > 0) { for (var j = 0; j < count; j++) { scanLineArray[index++] = uint8array[dataIndex++]; } } } } } // now convert data from buffer into floats for (i = 0; i < scanline_width; i++) { a = scanLineArray[i]; b = scanLineArray[i + scanline_width]; c = scanLineArray[i + 2 * scanline_width]; d = scanLineArray[i + 3 * scanline_width]; this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3); } num_scanlines--; } return resultArray; }; return HDRTools; }()); Internals.HDRTools = HDRTools; })(Internals = BABYLON.Internals || (BABYLON.Internals = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.hdr.js.map var BABYLON; (function (BABYLON) { /** * This represents a texture coming from an HDR input. * * The only supported format is currently panorama picture stored in RGBE format. * Example of such files can be found on HDRLib: http://hdrlib.com/ */ var HDRCubeTexture = /** @class */ (function (_super) { __extends(HDRCubeTexture, _super); /** * Instantiates an HDRTexture from the following parameters. * * @param url The location of the HDR raw data (Panorama stored in RGBE format) * @param scene The scene the texture will be used in * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap. * @param noMipmap Forces to not generate the mipmap if true * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time. */ function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) { if (noMipmap === void 0) { noMipmap = false; } if (generateHarmonics === void 0) { generateHarmonics = true; } if (useInGammaSpace === void 0) { useInGammaSpace = false; } if (usePMREMGenerator === void 0) { usePMREMGenerator = false; } if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } var _this = _super.call(this, scene) || this; _this._useInGammaSpace = false; _this._generateHarmonics = true; _this._isBABYLONPreprocessed = false; _this._onLoad = null; _this._onError = null; /** * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully. */ _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE; /** * Specifies wether the texture has been generated through the PMREMGenerator tool. * This is usefull at run time to apply the good shader. */ _this.isPMREM = false; _this._isBlocking = true; if (!url) { return _this; } _this.name = url; _this.url = url; _this.hasAlpha = false; _this.isCube = true; _this._textureMatrix = BABYLON.Matrix.Identity(); _this._onLoad = onLoad; _this._onError = onError; _this.gammaSpace = false; var caps = scene.getEngine().getCaps(); if (size) { _this._isBABYLONPreprocessed = false; _this._noMipmap = noMipmap; _this._size = size; _this._useInGammaSpace = useInGammaSpace; _this._usePMREMGenerator = usePMREMGenerator && caps.textureLOD && caps.textureFloat && !_this._useInGammaSpace; } else { _this._isBABYLONPreprocessed = true; _this._noMipmap = false; _this._useInGammaSpace = false; _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat && !_this._useInGammaSpace; } _this.isPMREM = _this._usePMREMGenerator; _this._texture = _this._getFromCache(url, _this._noMipmap); if (!_this._texture) { if (!scene.useDelayedTextureLoading) { _this.loadTexture(); } else { _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED; } } return _this; } Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", { /** * Gets wether or not the texture is blocking during loading. */ get: function () { return this._isBlocking; }, /** * Sets wether or not the texture is blocking during loading. */ set: function (value) { this._isBlocking = value; }, enumerable: true, configurable: true }); /** * Occurs when the file is a preprocessed .babylon.hdr file. */ HDRCubeTexture.prototype.loadBabylonTexture = function () { var _this = this; var mipLevels = 0; var floatArrayView = null; var scene = this.getScene(); var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) { var mips = new Array(); if (!floatArrayView) { return mips; } var startIndex = 30; for (var level = 0; level < mipLevels; level++) { mips.push([]); // Fill each pixel of the mip level. var faceSize = Math.pow(_this._size >> level, 2) * 3; for (var faceIndex = 0; faceIndex < 6; faceIndex++) { var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize); mips[level].push(faceData); startIndex += faceSize; } } return mips; } : null; var callback = function (buffer) { var scene = _this.getScene(); if (!scene) { return null; } // Create Native Array Views var intArrayView = new Int32Array(buffer); floatArrayView = new Float32Array(buffer); // Fill header. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility) _this._size = intArrayView[1]; // CubeMap max mip face size. // Update Texture Information. if (!_this._texture) { return null; } _this._texture.updateSize(_this._size, _this._size); // Fill polynomial information. var sphericalPolynomial = new BABYLON.SphericalPolynomial(); sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]); sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]); sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]); sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]); sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]); sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]); sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]); sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]); sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]); _this.sphericalPolynomial = sphericalPolynomial; // Fill pixel data. mipLevels = intArrayView[29]; // Number of mip levels. var startIndex = 30; var data = []; var faceSize = Math.pow(_this._size, 2) * 3; for (var faceIndex = 0; faceIndex < 6; faceIndex++) { data.push(floatArrayView.subarray(startIndex, startIndex + faceSize)); startIndex += faceSize; } var results = []; var byteArray = null; // Push each faces. for (var k = 0; k < 6; k++) { var dataFace = null; // To be deprecated. if (version === 1) { var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... dataFace = data[j]; } // If special cases. if (!mipmapGenerator && dataFace) { if (!scene.getEngine().getCaps().textureFloat) { // 3 channels of 1 bytes per pixel in bytes. var byteBuffer = new ArrayBuffer(faceSize); byteArray = new Uint8Array(byteBuffer); } for (var i = 0; i < _this._size * _this._size; i++) { // Put in gamma space if requested. if (_this._useInGammaSpace) { dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace); dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace); dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace); } // Convert to int texture for fallback. if (byteArray) { var r = Math.max(dataFace[(i * 3) + 0] * 255, 0); var g = Math.max(dataFace[(i * 3) + 1] * 255, 0); var b = Math.max(dataFace[(i * 3) + 2] * 255, 0); // May use luminance instead if the result is not accurate. var max = Math.max(Math.max(r, g), b); if (max > 255) { var scale = 255 / max; r *= scale; g *= scale; b *= scale; } byteArray[(i * 3) + 0] = r; byteArray[(i * 3) + 1] = g; byteArray[(i * 3) + 2] = b; } } } // Fill the array accordingly. if (byteArray) { results.push(byteArray); } else { results.push(dataFace); } } return results; }; if (scene) { this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError); } }; /** * Occurs when the file is raw .hdr file. */ HDRCubeTexture.prototype.loadHDRTexture = function () { var _this = this; var callback = function (buffer) { var scene = _this.getScene(); if (!scene) { return null; } // Extract the raw linear data. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size); // Generate harmonics if needed. if (_this._generateHarmonics) { var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data); _this.sphericalPolynomial = sphericalPolynomial; } var results = []; var byteArray = null; // Push each faces. for (var j = 0; j < 6; j++) { // Create uintarray fallback. if (!scene.getEngine().getCaps().textureFloat) { // 3 channels of 1 bytes per pixel in bytes. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3); byteArray = new Uint8Array(byteBuffer); } var dataFace = (data[HDRCubeTexture._facesMapping[j]]); // If special cases. if (_this._useInGammaSpace || byteArray) { for (var i = 0; i < _this._size * _this._size; i++) { // Put in gamma space if requested. if (_this._useInGammaSpace) { dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace); dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace); dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace); } // Convert to int texture for fallback. if (byteArray) { var r = Math.max(dataFace[(i * 3) + 0] * 255, 0); var g = Math.max(dataFace[(i * 3) + 1] * 255, 0); var b = Math.max(dataFace[(i * 3) + 2] * 255, 0); // May use luminance instead if the result is not accurate. var max = Math.max(Math.max(r, g), b); if (max > 255) { var scale = 255 / max; r *= scale; g *= scale; b *= scale; } byteArray[(i * 3) + 0] = r; byteArray[(i * 3) + 1] = g; byteArray[(i * 3) + 2] = b; } } } if (byteArray) { results.push(byteArray); } else { results.push(dataFace); } } return results; }; var mipmapGenerator = null; // TODO. Implement In code PMREM Generator following the LYS toolset generation. // if (!this._noMipmap && // this._usePMREMGenerator) { // mipmapGenerator = (data: ArrayBufferView[]) => { // // Custom setup of the generator matching with the PBR shader values. // var generator = new BABYLON.Internals.PMREMGenerator(data, // this._size, // this._size, // 0, // 3, // this.getScene().getEngine().getCaps().textureFloat, // 2048, // 0.25, // false, // true); // return generator.filterCubeMap(); // }; // } var scene = this.getScene(); if (scene) { this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError); } }; /** * Starts the loading process of the texture. */ HDRCubeTexture.prototype.loadTexture = function () { if (this._isBABYLONPreprocessed) { this.loadBabylonTexture(); } else { this.loadHDRTexture(); } }; HDRCubeTexture.prototype.clone = function () { var scene = this.getScene(); if (!scene) { return this; } var size = (this._isBABYLONPreprocessed ? null : this._size); var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator); // Base texture newTexture.level = this.level; newTexture.wrapU = this.wrapU; newTexture.wrapV = this.wrapV; newTexture.coordinatesIndex = this.coordinatesIndex; newTexture.coordinatesMode = this.coordinatesMode; return newTexture; }; // Methods HDRCubeTexture.prototype.delayLoad = function () { if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { return; } this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED; this._texture = this._getFromCache(this.url, this._noMipmap); if (!this._texture) { this.loadTexture(); } }; HDRCubeTexture.prototype.getReflectionTextureMatrix = function () { return this._textureMatrix; }; HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) { this._textureMatrix = value; }; HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) { var texture = null; if (parsedTexture.name && !parsedTexture.isRenderTarget) { var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size; texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator); texture.name = parsedTexture.name; texture.hasAlpha = parsedTexture.hasAlpha; texture.level = parsedTexture.level; texture.coordinatesMode = parsedTexture.coordinatesMode; texture.isBlocking = parsedTexture.isBlocking; } return texture; }; HDRCubeTexture.prototype.serialize = function () { if (!this.name) { return null; } var serializationObject = {}; serializationObject.name = this.name; serializationObject.hasAlpha = this.hasAlpha; serializationObject.isCube = true; serializationObject.level = this.level; serializationObject.size = this._size; serializationObject.coordinatesMode = this.coordinatesMode; serializationObject.useInGammaSpace = this._useInGammaSpace; serializationObject.generateHarmonics = this._generateHarmonics; serializationObject.usePMREMGenerator = this._usePMREMGenerator; serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed; serializationObject.customType = "BABYLON.HDRCubeTexture"; serializationObject.noMipmap = this._noMipmap; serializationObject.isBlocking = this._isBlocking; return serializationObject; }; /** * Saves as a file the data contained in the texture in a binary format. * This can be used to prevent the long loading tie associated with creating the seamless texture as well * as the spherical used in the lighting. * @param url The HDR file url. * @param size The size of the texture data to generate (one of the cubemap face desired width). * @param onError Method called if any error happens during download. * @return The packed binary data. */ HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) { if (onError === void 0) { onError = null; } var callback = function (buffer) { var data = new Blob([buffer], { type: 'application/octet-stream' }); // Returns a URL you can use as a href. var objUrl = window.URL.createObjectURL(data); // Simulates a link to it and click to dowload. var a = document.createElement("a"); document.body.appendChild(a); a.style.display = "none"; a.href = objUrl; a.download = "envmap.babylon.hdr"; a.click(); }; HDRCubeTexture.generateBabylonHDR(url, size, callback, onError); }; /** * Serializes the data contained in the texture in a binary format. * This can be used to prevent the long loading tie associated with creating the seamless texture as well * as the spherical used in the lighting. * @param url The HDR file url. * @param size The size of the texture data to generate (one of the cubemap face desired width). * @param onError Method called if any error happens during download. * @return The packed binary data. */ HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) { if (onError === void 0) { onError = null; } // Needs the url tho create the texture. if (!url) { return; } // Check Power of two size. if (!BABYLON.Tools.IsExponentOfTwo(size)) { return; } // Coming Back in 3.x. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1."); }; HDRCubeTexture._facesMapping = [ "right", "left", "up", "down", "front", "back" ]; return HDRCubeTexture; }(BABYLON.BaseTexture)); BABYLON.HDRCubeTexture = HDRCubeTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.hdrCubeTexture.js.map // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut // Huge respect for a such great lib. // Earcut license: // Copyright (c) 2016, Mapbox // // Permission to use, copy, modify, and/or distribute this software for any purpose // with or without fee is hereby granted, provided that the above copyright notice // and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF // THIS SOFTWARE. var Earcut; (function (Earcut) { /** * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...]. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11). * @param dim is the number of coordinates per vertice in the input array (2 by default). */ function earcut(data, holeIndices, dim) { dim = dim || 2; var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array(); if (!outerNode) return triangles; var minX = 0, minY = 0, maxX, maxY, x, y, size = 0; if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox if (data.length > 80 * dim) { minX = maxX = data[0]; minY = maxY = data[1]; for (var i = dim; i < outerLen; i += dim) { x = data[i]; y = data[i + 1]; if (x < minX) minX = x; if (y < minY) minY = y; if (x > maxX) maxX = x; if (y > maxY) maxY = y; } // minX, minY and size are later used to transform coords into integers for z-order calculation size = Math.max(maxX - minX, maxY - minY); } earcutLinked(outerNode, triangles, dim, minX, minY, size, 0); return triangles; } Earcut.earcut = earcut; var Node = /** @class */ (function () { function Node(i, x, y) { this.i = i; this.x = x; this.y = y; this.prev = null; this.next = null; this.z = null; this.prevZ = null; this.nextZ = null; this.steiner = false; } return Node; }()); // create a circular doubly linked list from polygon points in the specified winding order function linkedList(data, start, end, dim, clockwise) { var i, last = null; if (clockwise === (signedArea(data, start, end, dim) > 0)) { for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); } else { for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); } if (last && equals(last, last.next)) { removeNode(last); last = last.next; } return last; } // eliminate colinear or duplicate points function filterPoints(start, end) { if (!start) return start; if (!end) end = start; var p = start, again; do { again = false; if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { removeNode(p); p = end = p.prev; if (p === p.next) return undefined; again = true; } else { p = p.next; } } while (again || p !== end); return end; } // main ear slicing loop which triangulates a polygon (given as a linked list) function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { if (!ear) return; // interlink polygon nodes in z-order if (!pass && size) indexCurve(ear, minX, minY, size); var stop = ear, prev, next; // iterate through ears, slicing them one by one while (ear.prev !== ear.next) { prev = ear.prev; next = ear.next; if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { // cut off the triangle triangles.push(prev.i / dim); triangles.push(ear.i / dim); triangles.push(next.i / dim); removeNode(ear); // skipping the next vertice leads to less sliver triangles ear = next.next; stop = next.next; continue; } ear = next; // if we looped through the whole remaining polygon and can't find any more ears if (ear === stop) { // try filtering points and slicing again if (!pass) { earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1); // if this didn't work, try curing all small self-intersections locally } else if (pass === 1) { ear = cureLocalIntersections(ear, triangles, dim); earcutLinked(ear, triangles, dim, minX, minY, size, 2); // as a last resort, try splitting the remaining polygon into two } else if (pass === 2) { splitEarcut(ear, triangles, dim, minX, minY, size); } break; } } } // check whether a polygon node forms a valid ear with adjacent nodes function isEar(ear) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; // reflex, can't be an ear // now make sure we don't have other points inside the potential ear var p = ear.next.next; while (p !== ear.prev) { if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.next; } return true; } function isEarHashed(ear, minX, minY, size) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; // reflex, can't be an ear // triangle bbox; min & max are calculated like this for speed var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); // z-order range for the current triangle bbox; var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size); // first look for points inside the triangle in increasing z-order var p = ear.nextZ; while (p && p.z <= maxZ) { if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.nextZ; } // then look for points in decreasing z-order p = ear.prevZ; while (p && p.z >= minZ) { if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.prevZ; } return true; } // go through all polygon nodes and cure small local self-intersections function cureLocalIntersections(start, triangles, dim) { var p = start; do { var a = p.prev, b = p.next.next; if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { triangles.push(a.i / dim); triangles.push(p.i / dim); triangles.push(b.i / dim); // remove two nodes involved removeNode(p); removeNode(p.next); p = start = b; } p = p.next; } while (p !== start); return p; } // try splitting polygon into two and triangulate them independently function splitEarcut(start, triangles, dim, minX, minY, size) { // look for a valid diagonal that divides the polygon into two var a = start; do { var b = a.next.next; while (b !== a.prev) { if (a.i !== b.i && isValidDiagonal(a, b)) { // split the polygon in two by the diagonal var c = splitPolygon(a, b); // filter colinear points around the cuts a = filterPoints(a, a.next); c = filterPoints(c, c.next); // run earcut on each half earcutLinked(a, triangles, dim, minX, minY, size, undefined); earcutLinked(c, triangles, dim, minX, minY, size, undefined); return; } b = b.next; } a = a.next; } while (a !== start); } // link every hole into the outer loop, producing a single-ring polygon without holes function eliminateHoles(data, holeIndices, outerNode, dim) { var queue = [], i, len, start, end, list; for (i = 0, len = holeIndices.length; i < len; i++) { start = holeIndices[i] * dim; end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; list = linkedList(data, start, end, dim, false); if (list === list.next) list.steiner = true; queue.push(getLeftmost(list)); } queue.sort(compareX); // process holes from left to right for (i = 0; i < queue.length; i++) { eliminateHole(queue[i], outerNode); outerNode = filterPoints(outerNode, outerNode.next); } return outerNode; } function compareX(a, b) { return a.x - b.x; } // find a bridge between vertices that connects hole with an outer ring and and link it function eliminateHole(hole, outerNode) { outerNode = findHoleBridge(hole, outerNode); if (outerNode) { var b = splitPolygon(outerNode, hole); filterPoints(b, b.next); } } // David Eberly's algorithm for finding a bridge between hole and outer polygon function findHoleBridge(hole, outerNode) { var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m; // find a segment intersected by a ray from the hole's leftmost point to the left; // segment's endpoint with lesser x will be potential connection point do { if (hy <= p.y && hy >= p.next.y) { var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); if (x <= hx && x > qx) { qx = x; if (x === hx) { if (hy === p.y) return p; if (hy === p.next.y) return p.next; } m = p.x < p.next.x ? p : p.next; } } p = p.next; } while (p !== outerNode); if (!m) return null; if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint // look for points inside the triangle of hole point, segment intersection and endpoint; // if there are no points found, we have a valid connection; // otherwise choose the point of the minimum angle with the ray as connection point var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan; p = m.next; while (p !== stop) { if (hx >= p.x && p.x >= mx && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { tan = Math.abs(hy - p.y) / (hx - p.x); // tangential if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { m = p; tanMin = tan; } } p = p.next; } return m; } // interlink polygon nodes in z-order function indexCurve(start, minX, minY, size) { var p = start; do { if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); p.prevZ = p.prev; p.nextZ = p.next; p = p.next; } while (p !== start); p.prevZ.nextZ = null; p.prevZ = null; sortLinked(p); } // Simon Tatham's linked list merge sort algorithm // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html function sortLinked(list) { var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; do { p = list; list = null; tail = null; numMerges = 0; while (p) { numMerges++; q = p; pSize = 0; for (i = 0; i < inSize; i++) { pSize++; q = q.nextZ; if (!q) break; } qSize = inSize; while (pSize > 0 || (qSize > 0 && q)) { if (pSize === 0) { e = q; q = q.nextZ; qSize--; } else if (qSize === 0 || !q) { e = p; p = p.nextZ; pSize--; } else if (p.z <= q.z) { e = p; p = p.nextZ; pSize--; } else { e = q; q = q.nextZ; qSize--; } if (tail) tail.nextZ = e; else list = e; e.prevZ = tail; tail = e; } p = q; } tail.nextZ = null; inSize *= 2; } while (numMerges > 1); return list; } // z-order of a point given coords and size of the data bounding box function zOrder(x, y, minX, minY, size) { // coords are transformed into non-negative 15-bit integer range x = 32767 * (x - minX) / size; y = 32767 * (y - minY) / size; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; x = (x | (x << 2)) & 0x33333333; x = (x | (x << 1)) & 0x55555555; y = (y | (y << 8)) & 0x00FF00FF; y = (y | (y << 4)) & 0x0F0F0F0F; y = (y | (y << 2)) & 0x33333333; y = (y | (y << 1)) & 0x55555555; return x | (y << 1); } // find the leftmost node of a polygon ring function getLeftmost(start) { var p = start, leftmost = start; do { if (p.x < leftmost.x) leftmost = p; p = p.next; } while (p !== start); return leftmost; } // check if a point lies within a convex triangle function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; } // check if a diagonal between two polygon nodes is valid (lies in polygon interior) function isValidDiagonal(a, b) { return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); } // signed area of a triangle function area(p, q, r) { return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); } // check if two points are equal function equals(p1, p2) { return p1.x === p2.x && p1.y === p2.y; } // check if two segments intersect function intersects(p1, q1, p2, q2) { if ((equals(p1, q1) && equals(p2, q2)) || (equals(p1, q2) && equals(p2, q1))) return true; return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; } // check if a polygon diagonal intersects any polygon segments function intersectsPolygon(a, b) { var p = a; do { if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true; p = p.next; } while (p !== a); return false; } // check if a polygon diagonal is locally inside the polygon function locallyInside(a, b) { return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; } // check if the middle point of a polygon diagonal is inside the polygon function middleInside(a, b) { var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2; do { if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) inside = !inside; p = p.next; } while (p !== a); return inside; } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; // if one belongs to the outer ring and another to a hole, it merges it into a single ring function splitPolygon(a, b) { var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev; a.next = b; b.prev = a; a2.next = an; an.prev = a2; b2.next = a2; a2.prev = b2; bp.next = b2; b2.prev = bp; return b2; } // create a node and optionally link it with previous one (in a circular doubly linked list) function insertNode(i, x, y, last) { var p = new Node(i, x, y); if (!last) { p.prev = p; p.next = p; } else { p.next = last.next; p.prev = last; last.next.prev = p; last.next = p; } return p; } function removeNode(p) { p.next.prev = p.prev; p.prev.next = p.next; if (p.prevZ) p.prevZ.nextZ = p.nextZ; if (p.nextZ) p.nextZ.prevZ = p.prevZ; } /** * return a percentage difference between the polygon area and its triangulation area; * used to verify correctness of triangulation */ function deviation(data, holeIndices, dim, triangles) { var hasHoles = holeIndices && holeIndices.length; var outerLen = hasHoles ? holeIndices[0] * dim : data.length; var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); if (hasHoles) { for (var i = 0, len = holeIndices.length; i < len; i++) { var start = holeIndices[i] * dim; var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; polygonArea -= Math.abs(signedArea(data, start, end, dim)); } } var trianglesArea = 0; for (i = 0; i < triangles.length; i += 3) { var a = triangles[i] * dim; var b = triangles[i + 1] * dim; var c = triangles[i + 2] * dim; trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[c + 1] - data[a + 1])); } return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea); } Earcut.deviation = deviation; ; function signedArea(data, start, end, dim) { var sum = 0; for (var i = start, j = end - dim; i < end; i += dim) { sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); j = i; } return sum; } /** * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts */ function flatten(data) { var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0; for (var i = 0; i < data.length; i++) { for (var j = 0; j < data[i].length; j++) { for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); } if (i > 0) { holeIndex += data[i - 1].length; result.holes.push(holeIndex); } } return result; } Earcut.flatten = flatten; ; })(Earcut || (Earcut = {})); //# sourceMappingURL=babylon.earcut.js.map /// var BABYLON; (function (BABYLON) { var IndexedVector2 = /** @class */ (function (_super) { __extends(IndexedVector2, _super); function IndexedVector2(original, index) { var _this = _super.call(this, original.x, original.y) || this; _this.index = index; return _this; } return IndexedVector2; }(BABYLON.Vector2)); var PolygonPoints = /** @class */ (function () { function PolygonPoints() { this.elements = new Array(); } PolygonPoints.prototype.add = function (originalPoints) { var _this = this; var result = new Array(); originalPoints.forEach(function (point) { if (result.length === 0 || !point.equalsWithEpsilon(result[0])) { var newPoint = new IndexedVector2(point, _this.elements.length); result.push(newPoint); _this.elements.push(newPoint); } }); return result; }; PolygonPoints.prototype.computeBounds = function () { var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y); var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y); this.elements.forEach(function (point) { // x if (point.x < lmin.x) { lmin.x = point.x; } else if (point.x > lmax.x) { lmax.x = point.x; } // y if (point.y < lmin.y) { lmin.y = point.y; } else if (point.y > lmax.y) { lmax.y = point.y; } }); return { min: lmin, max: lmax, width: lmax.x - lmin.x, height: lmax.y - lmin.y }; }; return PolygonPoints; }()); var Polygon = /** @class */ (function () { function Polygon() { } Polygon.Rectangle = function (xmin, ymin, xmax, ymax) { return [ new BABYLON.Vector2(xmin, ymin), new BABYLON.Vector2(xmax, ymin), new BABYLON.Vector2(xmax, ymax), new BABYLON.Vector2(xmin, ymax) ]; }; Polygon.Circle = function (radius, cx, cy, numberOfSides) { if (cx === void 0) { cx = 0; } if (cy === void 0) { cy = 0; } if (numberOfSides === void 0) { numberOfSides = 32; } var result = new Array(); var angle = 0; var increment = (Math.PI * 2) / numberOfSides; for (var i = 0; i < numberOfSides; i++) { result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius)); angle -= increment; } return result; }; Polygon.Parse = function (input) { var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); }); var i, result = []; for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) { result.push(new BABYLON.Vector2(floats[i], floats[i + 1])); } return result; }; Polygon.StartingAt = function (x, y) { return BABYLON.Path2.StartingAt(x, y); }; return Polygon; }()); BABYLON.Polygon = Polygon; var PolygonMeshBuilder = /** @class */ (function () { function PolygonMeshBuilder(name, contours, scene) { this._points = new PolygonPoints(); this._outlinepoints = new PolygonPoints(); this._holes = new Array(); this._epoints = new Array(); this._eholes = new Array(); this._name = name; this._scene = scene; var points; if (contours instanceof BABYLON.Path2) { points = contours.getPoints(); } else { points = contours; } this._addToepoint(points); this._points.add(points); this._outlinepoints.add(points); } PolygonMeshBuilder.prototype._addToepoint = function (points) { for (var _i = 0, points_1 = points; _i < points_1.length; _i++) { var p = points_1[_i]; this._epoints.push(p.x, p.y); } }; PolygonMeshBuilder.prototype.addHole = function (hole) { this._points.add(hole); var holepoints = new PolygonPoints(); holepoints.add(hole); this._holes.push(holepoints); this._eholes.push(this._epoints.length / 2); this._addToepoint(hole); return this; }; PolygonMeshBuilder.prototype.build = function (updatable, depth) { var _this = this; if (updatable === void 0) { updatable = false; } if (depth === void 0) { depth = 0; } var result = new BABYLON.Mesh(this._name, this._scene); var normals = new Array(); var positions = new Array(); var uvs = new Array(); var bounds = this._points.computeBounds(); this._points.elements.forEach(function (p) { normals.push(0, 1.0, 0); positions.push(p.x, 0, p.y); uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height); }); var indices = new Array(); var res = Earcut.earcut(this._epoints, this._eholes, 2); for (var i = 0; i < res.length; i++) { indices.push(res[i]); } if (depth > 0) { var positionscount = (positions.length / 3); //get the current pointcount this._points.elements.forEach(function (p) { normals.push(0, -1.0, 0); positions.push(p.x, -depth, p.y); uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height); }); var totalCount = indices.length; for (var i = 0; i < totalCount; i += 3) { var i0 = indices[i + 0]; var i1 = indices[i + 1]; var i2 = indices[i + 2]; indices.push(i2 + positionscount); indices.push(i1 + positionscount); indices.push(i0 + positionscount); } //Add the sides this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false); this._holes.forEach(function (hole) { _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true); }); } result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable); result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable); result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable); result.setIndices(indices); return result; }; PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) { var StartIndex = positions.length / 3; var ulength = 0; for (var i = 0; i < points.elements.length; i++) { var p = points.elements[i]; var p1; if ((i + 1) > points.elements.length - 1) { p1 = points.elements[0]; } else { p1 = points.elements[i + 1]; } positions.push(p.x, 0, p.y); positions.push(p.x, -depth, p.y); positions.push(p1.x, 0, p1.y); positions.push(p1.x, -depth, p1.y); var v1 = new BABYLON.Vector3(p.x, 0, p.y); var v2 = new BABYLON.Vector3(p1.x, 0, p1.y); var v3 = v2.subtract(v1); var v4 = new BABYLON.Vector3(0, 1, 0); var vn = BABYLON.Vector3.Cross(v3, v4); vn = vn.normalize(); uvs.push(ulength / bounds.width, 0); uvs.push(ulength / bounds.width, 1); ulength += v3.length(); uvs.push((ulength / bounds.width), 0); uvs.push((ulength / bounds.width), 1); if (!flip) { normals.push(-vn.x, -vn.y, -vn.z); normals.push(-vn.x, -vn.y, -vn.z); normals.push(-vn.x, -vn.y, -vn.z); normals.push(-vn.x, -vn.y, -vn.z); indices.push(StartIndex); indices.push(StartIndex + 1); indices.push(StartIndex + 2); indices.push(StartIndex + 1); indices.push(StartIndex + 3); indices.push(StartIndex + 2); } else { normals.push(vn.x, vn.y, vn.z); normals.push(vn.x, vn.y, vn.z); normals.push(vn.x, vn.y, vn.z); normals.push(vn.x, vn.y, vn.z); indices.push(StartIndex); indices.push(StartIndex + 2); indices.push(StartIndex + 1); indices.push(StartIndex + 1); indices.push(StartIndex + 2); indices.push(StartIndex + 3); } StartIndex += 4; } ; }; return PolygonMeshBuilder; }()); BABYLON.PolygonMeshBuilder = PolygonMeshBuilder; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.polygonMesh.js.map var BABYLON; (function (BABYLON) { // Unique ID when we import meshes from Babylon to CSG var currentCSGMeshId = 0; // # class Vertex // Represents a vertex of a polygon. Use your own vertex class instead of this // one to provide additional features like texture coordinates and vertex // colors. Custom vertex classes need to provide a `pos` property and `clone()`, // `flip()`, and `interpolate()` methods that behave analogous to the ones // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal` // is not used anywhere else. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes var Vertex = /** @class */ (function () { function Vertex(pos, normal, uv) { this.pos = pos; this.normal = normal; this.uv = uv; } Vertex.prototype.clone = function () { return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone()); }; // Invert all orientation-specific data (e.g. vertex normal). Called when the // orientation of a polygon is flipped. Vertex.prototype.flip = function () { this.normal = this.normal.scale(-1); }; // Create a new vertex between this vertex and `other` by linearly // interpolating all properties using a parameter of `t`. Subclasses should // override this to interpolate additional properties. Vertex.prototype.interpolate = function (other, t) { return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t)); }; return Vertex; }()); // # class Plane // Represents a plane in 3D space. var Plane = /** @class */ (function () { function Plane(normal, w) { this.normal = normal; this.w = w; } Plane.FromPoints = function (a, b, c) { var v0 = c.subtract(a); var v1 = b.subtract(a); if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) { return null; } var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1)); return new Plane(n, BABYLON.Vector3.Dot(n, a)); }; Plane.prototype.clone = function () { return new Plane(this.normal.clone(), this.w); }; Plane.prototype.flip = function () { this.normal.scaleInPlace(-1); this.w = -this.w; }; // Split `polygon` by this plane if needed, then put the polygon or polygon // fragments in the appropriate lists. Coplanar polygons go into either // `coplanarFront` or `coplanarBack` depending on their orientation with // respect to this plane. Polygons in front or in back of this plane go into // either `front` or `back`. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) { var COPLANAR = 0; var FRONT = 1; var BACK = 2; var SPANNING = 3; // Classify each point as well as the entire polygon into one of the above // four classes. var polygonType = 0; var types = []; var i; var t; for (i = 0; i < polygon.vertices.length; i++) { t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w; var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR; polygonType |= type; types.push(type); } // Put the polygon in the correct list, splitting it when necessary. switch (polygonType) { case COPLANAR: (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon); break; case FRONT: front.push(polygon); break; case BACK: back.push(polygon); break; case SPANNING: var f = [], b = []; for (i = 0; i < polygon.vertices.length; i++) { var j = (i + 1) % polygon.vertices.length; var ti = types[i], tj = types[j]; var vi = polygon.vertices[i], vj = polygon.vertices[j]; if (ti !== BACK) f.push(vi); if (ti !== FRONT) b.push(ti !== BACK ? vi.clone() : vi); if ((ti | tj) === SPANNING) { t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos)); var v = vi.interpolate(vj, t); f.push(v); b.push(v.clone()); } } var poly; if (f.length >= 3) { poly = new Polygon(f, polygon.shared); if (poly.plane) front.push(poly); } if (b.length >= 3) { poly = new Polygon(b, polygon.shared); if (poly.plane) back.push(poly); } break; } }; // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a // point is on the plane. Plane.EPSILON = 1e-5; return Plane; }()); // # class Polygon // Represents a convex polygon. The vertices used to initialize a polygon must // be coplanar and form a convex loop. // // Each convex polygon has a `shared` property, which is shared between all // polygons that are clones of each other or were split from the same polygon. // This can be used to define per-polygon properties (such as surface color). var Polygon = /** @class */ (function () { function Polygon(vertices, shared) { this.vertices = vertices; this.shared = shared; this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos); } Polygon.prototype.clone = function () { var vertices = this.vertices.map(function (v) { return v.clone(); }); return new Polygon(vertices, this.shared); }; Polygon.prototype.flip = function () { this.vertices.reverse().map(function (v) { v.flip(); }); this.plane.flip(); }; return Polygon; }()); // # class Node // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons // by picking a polygon to split along. That polygon (and all other coplanar // polygons) are added directly to that node and the other polygons are added to // the front and/or back subtrees. This is not a leafy BSP tree since there is // no distinction between internal and leaf nodes. var Node = /** @class */ (function () { function Node(polygons) { this.plane = null; this.front = null; this.back = null; this.polygons = new Array(); if (polygons) { this.build(polygons); } } Node.prototype.clone = function () { var node = new Node(); node.plane = this.plane && this.plane.clone(); node.front = this.front && this.front.clone(); node.back = this.back && this.back.clone(); node.polygons = this.polygons.map(function (p) { return p.clone(); }); return node; }; // Convert solid space to empty space and empty space to solid space. Node.prototype.invert = function () { for (var i = 0; i < this.polygons.length; i++) { this.polygons[i].flip(); } if (this.plane) { this.plane.flip(); } if (this.front) { this.front.invert(); } if (this.back) { this.back.invert(); } var temp = this.front; this.front = this.back; this.back = temp; }; // Recursively remove all polygons in `polygons` that are inside this BSP // tree. Node.prototype.clipPolygons = function (polygons) { if (!this.plane) return polygons.slice(); var front = new Array(), back = new Array(); for (var i = 0; i < polygons.length; i++) { this.plane.splitPolygon(polygons[i], front, back, front, back); } if (this.front) { front = this.front.clipPolygons(front); } if (this.back) { back = this.back.clipPolygons(back); } else { back = []; } return front.concat(back); }; // Remove all polygons in this BSP tree that are inside the other BSP tree // `bsp`. Node.prototype.clipTo = function (bsp) { this.polygons = bsp.clipPolygons(this.polygons); if (this.front) this.front.clipTo(bsp); if (this.back) this.back.clipTo(bsp); }; // Return a list of all polygons in this BSP tree. Node.prototype.allPolygons = function () { var polygons = this.polygons.slice(); if (this.front) polygons = polygons.concat(this.front.allPolygons()); if (this.back) polygons = polygons.concat(this.back.allPolygons()); return polygons; }; // Build a BSP tree out of `polygons`. When called on an existing tree, the // new polygons are filtered down to the bottom of the tree and become new // nodes there. Each set of polygons is partitioned using the first polygon // (no heuristic is used to pick a good split). Node.prototype.build = function (polygons) { if (!polygons.length) return; if (!this.plane) this.plane = polygons[0].plane.clone(); var front = new Array(), back = new Array(); for (var i = 0; i < polygons.length; i++) { this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back); } if (front.length) { if (!this.front) this.front = new Node(); this.front.build(front); } if (back.length) { if (!this.back) this.back = new Node(); this.back.build(back); } }; return Node; }()); var CSG = /** @class */ (function () { function CSG() { this.polygons = new Array(); } // Convert BABYLON.Mesh to BABYLON.CSG CSG.FromMesh = function (mesh) { var vertex, normal, uv, position, polygon, polygons = new Array(), vertices; var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling; if (mesh instanceof BABYLON.Mesh) { mesh.computeWorldMatrix(true); matrix = mesh.getWorldMatrix(); meshPosition = mesh.position.clone(); meshRotation = mesh.rotation.clone(); if (mesh.rotationQuaternion) { meshRotationQuaternion = mesh.rotationQuaternion.clone(); } meshScaling = mesh.scaling.clone(); } else { throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh'; } var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind); var subMeshes = mesh.subMeshes; for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) { for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) { vertices = []; for (var j = 0; j < 3; j++) { var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]); uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]); var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]); position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix); normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix); vertex = new Vertex(position, normal, uv); vertices.push(vertex); } polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex }); // To handle the case of degenerated triangle // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated if (polygon.plane) polygons.push(polygon); } } var csg = CSG.FromPolygons(polygons); csg.matrix = matrix; csg.position = meshPosition; csg.rotation = meshRotation; csg.scaling = meshScaling; csg.rotationQuaternion = meshRotationQuaternion; currentCSGMeshId++; return csg; }; // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances. CSG.FromPolygons = function (polygons) { var csg = new CSG(); csg.polygons = polygons; return csg; }; CSG.prototype.clone = function () { var csg = new CSG(); csg.polygons = this.polygons.map(function (p) { return p.clone(); }); csg.copyTransformAttributes(this); return csg; }; CSG.prototype.union = function (csg) { var a = new Node(this.clone().polygons); var b = new Node(csg.clone().polygons); a.clipTo(b); b.clipTo(a); b.invert(); b.clipTo(a); b.invert(); a.build(b.allPolygons()); return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this); }; CSG.prototype.unionInPlace = function (csg) { var a = new Node(this.polygons); var b = new Node(csg.polygons); a.clipTo(b); b.clipTo(a); b.invert(); b.clipTo(a); b.invert(); a.build(b.allPolygons()); this.polygons = a.allPolygons(); }; CSG.prototype.subtract = function (csg) { var a = new Node(this.clone().polygons); var b = new Node(csg.clone().polygons); a.invert(); a.clipTo(b); b.clipTo(a); b.invert(); b.clipTo(a); b.invert(); a.build(b.allPolygons()); a.invert(); return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this); }; CSG.prototype.subtractInPlace = function (csg) { var a = new Node(this.polygons); var b = new Node(csg.polygons); a.invert(); a.clipTo(b); b.clipTo(a); b.invert(); b.clipTo(a); b.invert(); a.build(b.allPolygons()); a.invert(); this.polygons = a.allPolygons(); }; CSG.prototype.intersect = function (csg) { var a = new Node(this.clone().polygons); var b = new Node(csg.clone().polygons); a.invert(); b.clipTo(a); b.invert(); a.clipTo(b); b.clipTo(a); a.build(b.allPolygons()); a.invert(); return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this); }; CSG.prototype.intersectInPlace = function (csg) { var a = new Node(this.polygons); var b = new Node(csg.polygons); a.invert(); b.clipTo(a); b.invert(); a.clipTo(b); b.clipTo(a); a.build(b.allPolygons()); a.invert(); this.polygons = a.allPolygons(); }; // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is // not modified. CSG.prototype.inverse = function () { var csg = this.clone(); csg.inverseInPlace(); return csg; }; CSG.prototype.inverseInPlace = function () { this.polygons.map(function (p) { p.flip(); }); }; // This is used to keep meshes transformations so they can be restored // when we build back a Babylon Mesh // NB : All CSG operations are performed in world coordinates CSG.prototype.copyTransformAttributes = function (csg) { this.matrix = csg.matrix; this.position = csg.position; this.rotation = csg.rotation; this.scaling = csg.scaling; this.rotationQuaternion = csg.rotationQuaternion; return this; }; // Build Raw mesh from CSG // Coordinates here are in world space CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) { var matrix = this.matrix.clone(); matrix.invert(); var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj; if (keepSubMeshes) { // Sort Polygons, since subMeshes are indices range polygons.sort(function (a, b) { if (a.shared.meshId === b.shared.meshId) { return a.shared.subMeshId - b.shared.subMeshId; } else { return a.shared.meshId - b.shared.meshId; } }); } for (var i = 0, il = polygons.length; i < il; i++) { polygon = polygons[i]; // Building SubMeshes if (!subMesh_dict[polygon.shared.meshId]) { subMesh_dict[polygon.shared.meshId] = {}; } if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) { subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = { indexStart: +Infinity, indexEnd: -Infinity, materialIndex: polygon.shared.materialIndex }; } subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]; for (var j = 2, jl = polygon.vertices.length; j < jl; j++) { polygonIndices[0] = 0; polygonIndices[1] = j - 1; polygonIndices[2] = j; for (var k = 0; k < 3; k++) { vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos); normal.copyFrom(polygon.vertices[polygonIndices[k]].normal); uv.copyFrom(polygon.vertices[polygonIndices[k]].uv); var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix); var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix); vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z]; // Check if 2 points can be merged if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) { vertices.push(localVertex.x, localVertex.y, localVertex.z); uvs.push(uv.x, uv.y); normals.push(normal.x, normal.y, normal.z); vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1; } indices.push(vertex_idx); subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart); subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd); currentIndex++; } } } mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices); mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals); mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs); mesh.setIndices(indices, null); if (keepSubMeshes) { // We offset the materialIndex by the previous number of materials in the CSG mixed meshes var materialIndexOffset = 0, materialMaxIndex; mesh.subMeshes = new Array(); for (var m in subMesh_dict) { materialMaxIndex = -1; for (var sm in subMesh_dict[m]) { subMesh_obj = subMesh_dict[m][sm]; BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh); materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex); } materialIndexOffset += ++materialMaxIndex; } } return mesh; }; // Build Mesh from CSG taking material and transforms into account CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) { var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes); mesh.material = material; mesh.position.copyFrom(this.position); mesh.rotation.copyFrom(this.rotation); if (this.rotationQuaternion) { mesh.rotationQuaternion = this.rotationQuaternion.clone(); } mesh.scaling.copyFrom(this.scaling); mesh.computeWorldMatrix(true); return mesh; }; return CSG; }()); BABYLON.CSG = CSG; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.csg.js.map var BABYLON; (function (BABYLON) { var LensFlare = /** @class */ (function () { function LensFlare(size, position, color, imgUrl, system) { this.size = size; this.position = position; this.alphaMode = BABYLON.Engine.ALPHA_ONEONE; this.color = color || new BABYLON.Color3(1, 1, 1); this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null; this._system = system; system.lensFlares.push(this); } LensFlare.AddFlare = function (size, position, color, imgUrl, system) { return new LensFlare(size, position, color, imgUrl, system); }; LensFlare.prototype.dispose = function () { if (this.texture) { this.texture.dispose(); } // Remove from scene var index = this._system.lensFlares.indexOf(this); this._system.lensFlares.splice(index, 1); }; ; return LensFlare; }()); BABYLON.LensFlare = LensFlare; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.lensFlare.js.map var BABYLON; (function (BABYLON) { var LensFlareSystem = /** @class */ (function () { function LensFlareSystem(name, emitter, scene) { this.name = name; this.lensFlares = new Array(); this.borderLimit = 300; this.viewportBorder = 0; this.layerMask = 0x0FFFFFFF; this._vertexBuffers = {}; this._isEnabled = true; this._scene = scene || BABYLON.Engine.LastCreatedScene; this._emitter = emitter; this.id = name; scene.lensFlareSystems.push(this); this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); }; var engine = scene.getEngine(); // 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(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2); // Indices var indices = []; indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); this._indexBuffer = engine.createIndexBuffer(indices); // Effects this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], ""); } Object.defineProperty(LensFlareSystem.prototype, "isEnabled", { get: function () { return this._isEnabled; }, set: function (value) { this._isEnabled = value; }, enumerable: true, configurable: true }); LensFlareSystem.prototype.getScene = function () { return this._scene; }; LensFlareSystem.prototype.getEmitter = function () { return this._emitter; }; LensFlareSystem.prototype.setEmitter = function (newEmitter) { this._emitter = newEmitter; }; LensFlareSystem.prototype.getEmitterPosition = function () { return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position; }; LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) { var position = this.getEmitterPosition(); position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport); this._positionX = position.x; this._positionY = position.y; position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix()); if (this.viewportBorder > 0) { globalViewport.x -= this.viewportBorder; globalViewport.y -= this.viewportBorder; globalViewport.width += this.viewportBorder * 2; globalViewport.height += this.viewportBorder * 2; position.x += this.viewportBorder; position.y += this.viewportBorder; this._positionX += this.viewportBorder; this._positionY += this.viewportBorder; } if (position.z > 0) { if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) { if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) return true; } return true; } return false; }; LensFlareSystem.prototype._isVisible = function () { if (!this._isEnabled || !this._scene.activeCamera) { return false; } var emitterPosition = this.getEmitterPosition(); var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition); var distance = direction.length(); direction.normalize(); var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction); var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true); return !pickInfo || !pickInfo.hit || pickInfo.distance > distance; }; LensFlareSystem.prototype.render = function () { if (!this._effect.isReady() || !this._scene.activeCamera) return false; var engine = this._scene.getEngine(); var viewport = this._scene.activeCamera.viewport; var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true)); // Position if (!this.computeEffectivePosition(globalViewport)) { return false; } // Visibility if (!this._isVisible()) { return false; } // Intensity var awayX; var awayY; if (this._positionX < this.borderLimit + globalViewport.x) { awayX = this.borderLimit + globalViewport.x - this._positionX; } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) { awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit; } else { awayX = 0; } if (this._positionY < this.borderLimit + globalViewport.y) { awayY = this.borderLimit + globalViewport.y - this._positionY; } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) { awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit; } else { awayY = 0; } var away = (awayX > awayY) ? awayX : awayY; away -= this.viewportBorder; if (away > this.borderLimit) { away = this.borderLimit; } var intensity = 1.0 - (away / this.borderLimit); if (intensity < 0) { return false; } if (intensity > 1.0) { intensity = 1.0; } if (this.viewportBorder > 0) { globalViewport.x += this.viewportBorder; globalViewport.y += this.viewportBorder; globalViewport.width -= this.viewportBorder * 2; globalViewport.height -= this.viewportBorder * 2; this._positionX -= this.viewportBorder; this._positionY -= this.viewportBorder; } // Position var centerX = globalViewport.x + globalViewport.width / 2; var centerY = globalViewport.y + globalViewport.height / 2; var distX = centerX - this._positionX; var distY = centerY - this._positionY; // Effects engine.enableEffect(this._effect); engine.setState(false); engine.setDepthBuffer(false); // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect); // Flares for (var index = 0; index < this.lensFlares.length; index++) { var flare = this.lensFlares[index]; engine.setAlphaMode(flare.alphaMode); var x = centerX - (distX * flare.position); var y = centerY - (distY * flare.position); var cw = flare.size; var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true); var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0; var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2)); var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1); this._effect.setMatrix("viewportMatrix", viewportMatrix); // Texture this._effect.setTexture("textureSampler", flare.texture); // Color this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0); // Draw order engine.draw(true, 0, 6); } engine.setDepthBuffer(true); engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE); return true; }; LensFlareSystem.prototype.dispose = function () { var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]; if (vertexBuffer) { vertexBuffer.dispose(); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } while (this.lensFlares.length) { this.lensFlares[0].dispose(); } // Remove from scene var index = this._scene.lensFlareSystems.indexOf(this); this._scene.lensFlareSystems.splice(index, 1); }; LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) { var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId); var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId; var lensFlareSystem = new LensFlareSystem(name, emitter, scene); lensFlareSystem.id = parsedLensFlareSystem.id || name; lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit; for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) { var parsedFlare = parsedLensFlareSystem.flares[index]; BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem); } return lensFlareSystem; }; LensFlareSystem.prototype.serialize = function () { var serializationObject = {}; serializationObject.id = this.id; serializationObject.name = this.name; serializationObject.emitterId = this.getEmitter().id; serializationObject.borderLimit = this.borderLimit; serializationObject.flares = []; for (var index = 0; index < this.lensFlares.length; index++) { var flare = this.lensFlares[index]; serializationObject.flares.push({ size: flare.size, position: flare.position, color: flare.color.asArray(), textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "") }); } return serializationObject; }; return LensFlareSystem; }()); BABYLON.LensFlareSystem = LensFlareSystem; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.lensFlareSystem.js.map var BABYLON; (function (BABYLON) { /** * This is a holder class for the physics joint created by the physics plugin. * It holds a set of functions to control the underlying joint. */ var PhysicsJoint = /** @class */ (function () { function PhysicsJoint(type, jointData) { this.type = type; this.jointData = jointData; jointData.nativeParams = jointData.nativeParams || {}; } Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", { get: function () { return this._physicsJoint; }, set: function (newJoint) { if (this._physicsJoint) { //remove from the wolrd } this._physicsJoint = newJoint; }, enumerable: true, configurable: true }); Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", { set: function (physicsPlugin) { this._physicsPlugin = physicsPlugin; }, enumerable: true, configurable: true }); /** * Execute a function that is physics-plugin specific. * @param {Function} func the function that will be executed. * It accepts two parameters: the physics world and the physics joint. */ PhysicsJoint.prototype.executeNativeFunction = function (func) { func(this._physicsPlugin.world, this._physicsJoint); }; //TODO check if the native joints are the same //Joint Types PhysicsJoint.DistanceJoint = 0; PhysicsJoint.HingeJoint = 1; PhysicsJoint.BallAndSocketJoint = 2; PhysicsJoint.WheelJoint = 3; PhysicsJoint.SliderJoint = 4; //OIMO PhysicsJoint.PrismaticJoint = 5; //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions) PhysicsJoint.UniversalJoint = 6; PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint; //Cannon //Similar to a Ball-Joint. Different in params PhysicsJoint.PointToPointJoint = 8; //Cannon only at the moment PhysicsJoint.SpringJoint = 9; PhysicsJoint.LockJoint = 10; return PhysicsJoint; }()); BABYLON.PhysicsJoint = PhysicsJoint; /** * A class representing a physics distance joint. */ var DistanceJoint = /** @class */ (function (_super) { __extends(DistanceJoint, _super); function DistanceJoint(jointData) { return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this; } /** * Update the predefined distance. */ DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) { this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance); }; return DistanceJoint; }(PhysicsJoint)); BABYLON.DistanceJoint = DistanceJoint; var MotorEnabledJoint = /** @class */ (function (_super) { __extends(MotorEnabledJoint, _super); function MotorEnabledJoint(type, jointData) { return _super.call(this, type, jointData) || this; } /** * Set the motor values. * Attention, this function is plugin specific. Engines won't react 100% the same. * @param {number} force the force to apply * @param {number} maxForce max force for this motor. */ MotorEnabledJoint.prototype.setMotor = function (force, maxForce) { this._physicsPlugin.setMotor(this, force || 0, maxForce); }; /** * Set the motor's limits. * Attention, this function is plugin specific. Engines won't react 100% the same. */ MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) { this._physicsPlugin.setLimit(this, upperLimit, lowerLimit); }; return MotorEnabledJoint; }(PhysicsJoint)); BABYLON.MotorEnabledJoint = MotorEnabledJoint; /** * This class represents a single hinge physics joint */ var HingeJoint = /** @class */ (function (_super) { __extends(HingeJoint, _super); function HingeJoint(jointData) { return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this; } /** * Set the motor values. * Attention, this function is plugin specific. Engines won't react 100% the same. * @param {number} force the force to apply * @param {number} maxForce max force for this motor. */ HingeJoint.prototype.setMotor = function (force, maxForce) { this._physicsPlugin.setMotor(this, force || 0, maxForce); }; /** * Set the motor's limits. * Attention, this function is plugin specific. Engines won't react 100% the same. */ HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) { this._physicsPlugin.setLimit(this, upperLimit, lowerLimit); }; return HingeJoint; }(MotorEnabledJoint)); BABYLON.HingeJoint = HingeJoint; /** * This class represents a dual hinge physics joint (same as wheel joint) */ var Hinge2Joint = /** @class */ (function (_super) { __extends(Hinge2Joint, _super); function Hinge2Joint(jointData) { return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this; } /** * Set the motor values. * Attention, this function is plugin specific. Engines won't react 100% the same. * @param {number} force the force to apply * @param {number} maxForce max force for this motor. * @param {motorIndex} the motor's index, 0 or 1. */ Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) { if (motorIndex === void 0) { motorIndex = 0; } this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex); }; /** * Set the motor limits. * Attention, this function is plugin specific. Engines won't react 100% the same. * @param {number} upperLimit the upper limit * @param {number} lowerLimit lower limit * @param {motorIndex} the motor's index, 0 or 1. */ Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) { if (motorIndex === void 0) { motorIndex = 0; } this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex); }; return Hinge2Joint; }(MotorEnabledJoint)); BABYLON.Hinge2Joint = Hinge2Joint; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.physicsJoint.js.map var BABYLON; (function (BABYLON) { var PhysicsImpostor = /** @class */ (function () { function PhysicsImpostor(object, type, _options, _scene) { if (_options === void 0) { _options = { mass: 0 }; } var _this = this; this.object = object; this.type = type; this._options = _options; this._scene = _scene; this._bodyUpdateRequired = false; this._onBeforePhysicsStepCallbacks = new Array(); this._onAfterPhysicsStepCallbacks = new Array(); this._onPhysicsCollideCallbacks = []; this._deltaPosition = BABYLON.Vector3.Zero(); this._isDisposed = false; this._tmpPositionWithDelta = BABYLON.Vector3.Zero(); this._tmpRotationWithDelta = new BABYLON.Quaternion(); /** * this function is executed by the physics engine. */ this.beforeStep = function () { if (!_this._physicsEngine) { return; } if (_this._options.ignoreParent && _this.object.parent) { _this._tmpPositionWithDelta.copyFrom(_this.object.getAbsolutePosition()); //this.object.getAbsolutePosition().subtractToRef(this._deltaPosition, this._tmpPositionWithDelta); } else { _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta); } //conjugate deltaRotation if (_this.object.rotationQuaternion) { if (_this._deltaRotationConjugated) { _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta); } else { _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion); } } // Only if not disabled if (!_this._options.disableBidirectionalTransformation) { _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta); } _this._onBeforePhysicsStepCallbacks.forEach(function (func) { func(_this); }); }; /** * this function is executed by the physics engine. */ this.afterStep = function () { if (!_this._physicsEngine) { return; } _this._onAfterPhysicsStepCallbacks.forEach(function (func) { func(_this); }); _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this); if (_this._options.ignoreParent && _this.object.parent) { _this.object.position.subtractInPlace(_this.object.parent.getAbsolutePosition()); } else { _this.object.position.addInPlace(_this._deltaPosition); } if (_this._deltaRotation && _this.object.rotationQuaternion) { _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation); } }; /** * Legacy collision detection event support */ this.onCollideEvent = null; //event and body object due to cannon's event-based architecture. this.onCollide = function (e) { if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) { return; } if (!_this._physicsEngine) { return; } var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body); if (otherImpostor) { // Legacy collision detection event support if (_this.onCollideEvent) { _this.onCollideEvent(_this, otherImpostor); } _this._onPhysicsCollideCallbacks.filter(function (obj) { return obj.otherImpostors.indexOf(otherImpostor) !== -1; }).forEach(function (obj) { obj.callback(_this, otherImpostor); }); } }; //sanity check! if (!this.object) { BABYLON.Tools.Error("No object was provided. A physics object is obligatory"); return; } //legacy support for old syntax. if (!this._scene && object.getScene) { this._scene = object.getScene(); } if (!this._scene) { return; } this._physicsEngine = this._scene.getPhysicsEngine(); if (!this._physicsEngine) { BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."); } else { //set the object's quaternion, if not set if (!this.object.rotationQuaternion) { if (this.object.rotation) { this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z); } else { this.object.rotationQuaternion = new BABYLON.Quaternion(); } } //default options params this._options.mass = (_options.mass === void 0) ? 0 : _options.mass; this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction; this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution; this._joints = []; //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that. if (!this.object.parent || this._options.ignoreParent) { this._init(); } else if (this.object.parent.physicsImpostor) { BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent."); } } } Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", { get: function () { return this._isDisposed; }, enumerable: true, configurable: true }); Object.defineProperty(PhysicsImpostor.prototype, "mass", { get: function () { return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0; }, set: function (value) { this.setMass(value); }, enumerable: true, configurable: true }); Object.defineProperty(PhysicsImpostor.prototype, "friction", { get: function () { return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0; }, set: function (value) { if (!this._physicsEngine) { return; } this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value); }, enumerable: true, configurable: true }); Object.defineProperty(PhysicsImpostor.prototype, "restitution", { get: function () { return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0; }, set: function (value) { if (!this._physicsEngine) { return; } this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value); }, enumerable: true, configurable: true }); /** * This function will completly initialize this impostor. * It will create a new body - but only if this mesh has no parent. * If it has, this impostor will not be used other than to define the impostor * of the child mesh. */ PhysicsImpostor.prototype._init = function () { if (!this._physicsEngine) { return; } this._physicsEngine.removeImpostor(this); this.physicsBody = null; this._parent = this._parent || this._getPhysicsParent(); if (!this.parent || this._options.ignoreParent) { this._physicsEngine.addImpostor(this); } }; PhysicsImpostor.prototype._getPhysicsParent = function () { if (this.object.parent instanceof BABYLON.AbstractMesh) { var parentMesh = this.object.parent; return parentMesh.physicsImpostor; } return null; }; /** * Should a new body be generated. */ PhysicsImpostor.prototype.isBodyInitRequired = function () { return this._bodyUpdateRequired || (!this._physicsBody && !this._parent); }; PhysicsImpostor.prototype.setScalingUpdated = function (updated) { this.forceUpdate(); }; /** * Force a regeneration of this or the parent's impostor's body. * Use under cautious - This will remove all joints already implemented. */ PhysicsImpostor.prototype.forceUpdate = function () { this._init(); if (this.parent && !this._options.ignoreParent) { this.parent.forceUpdate(); } }; Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", { /*public get mesh(): AbstractMesh { return this._mesh; }*/ /** * Gets the body that holds this impostor. Either its own, or its parent. */ get: function () { return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody; }, /** * Set the physics body. Used mainly by the physics engine/plugin */ set: function (physicsBody) { if (this._physicsBody && this._physicsEngine) { this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this); } this._physicsBody = physicsBody; this.resetUpdateFlags(); }, enumerable: true, configurable: true }); Object.defineProperty(PhysicsImpostor.prototype, "parent", { get: function () { return !this._options.ignoreParent && this._parent ? this._parent : null; }, set: function (value) { this._parent = value; }, enumerable: true, configurable: true }); PhysicsImpostor.prototype.resetUpdateFlags = function () { this._bodyUpdateRequired = false; }; PhysicsImpostor.prototype.getObjectExtendSize = function () { if (this.object.getBoundingInfo) { var q = this.object.rotationQuaternion; //reset rotation this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION; //calculate the world matrix with no rotation this.object.computeWorldMatrix && this.object.computeWorldMatrix(true); var boundingInfo = this.object.getBoundingInfo(); var size = void 0; if (boundingInfo) { size = boundingInfo.boundingBox.extendSizeWorld.scale(2); } else { size = BABYLON.Vector3.Zero(); } //bring back the rotation this.object.rotationQuaternion = q; //calculate the world matrix with the new rotation this.object.computeWorldMatrix && this.object.computeWorldMatrix(true); return size; } else { return PhysicsImpostor.DEFAULT_OBJECT_SIZE; } }; PhysicsImpostor.prototype.getObjectCenter = function () { if (this.object.getBoundingInfo) { var boundingInfo = this.object.getBoundingInfo(); if (!boundingInfo) { return this.object.position; } return boundingInfo.boundingBox.centerWorld; } else { return this.object.position; } }; /** * Get a specific parametes from the options parameter. */ PhysicsImpostor.prototype.getParam = function (paramName) { return this._options[paramName]; }; /** * Sets a specific parameter in the options given to the physics plugin */ PhysicsImpostor.prototype.setParam = function (paramName, value) { this._options[paramName] = value; this._bodyUpdateRequired = true; }; /** * Specifically change the body's mass option. Won't recreate the physics body object */ PhysicsImpostor.prototype.setMass = function (mass) { if (this.getParam("mass") !== mass) { this.setParam("mass", mass); } if (this._physicsEngine) { this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass); } }; PhysicsImpostor.prototype.getLinearVelocity = function () { return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero(); }; PhysicsImpostor.prototype.setLinearVelocity = function (velocity) { if (this._physicsEngine) { this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity); } }; PhysicsImpostor.prototype.getAngularVelocity = function () { return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero(); }; PhysicsImpostor.prototype.setAngularVelocity = function (velocity) { if (this._physicsEngine) { this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity); } }; /** * Execute a function with the physics plugin native code. * Provide a function the will have two variables - the world object and the physics body object. */ PhysicsImpostor.prototype.executeNativeFunction = function (func) { if (this._physicsEngine) { func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody); } }; /** * Register a function that will be executed before the physics world is stepping forward. */ PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) { this._onBeforePhysicsStepCallbacks.push(func); }; PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) { var index = this._onBeforePhysicsStepCallbacks.indexOf(func); if (index > -1) { this._onBeforePhysicsStepCallbacks.splice(index, 1); } else { BABYLON.Tools.Warn("Function to remove was not found"); } }; /** * Register a function that will be executed after the physics step */ PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) { this._onAfterPhysicsStepCallbacks.push(func); }; PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) { var index = this._onAfterPhysicsStepCallbacks.indexOf(func); if (index > -1) { this._onAfterPhysicsStepCallbacks.splice(index, 1); } else { BABYLON.Tools.Warn("Function to remove was not found"); } }; /** * register a function that will be executed when this impostor collides against a different body. */ PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) { var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst]; this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList }); }; PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) { var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst]; var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList }); if (index > -1) { this._onPhysicsCollideCallbacks.splice(index, 1); } else { BABYLON.Tools.Warn("Function to remove was not found"); } }; /** * Apply a force */ PhysicsImpostor.prototype.applyForce = function (force, contactPoint) { if (this._physicsEngine) { this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint); } return this; }; /** * Apply an impulse */ PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) { if (this._physicsEngine) { this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint); } return this; }; /** * A help function to create a joint. */ PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) { var joint = new BABYLON.PhysicsJoint(jointType, jointData); this.addJoint(otherImpostor, joint); return this; }; /** * Add a joint to this impostor with a different impostor. */ PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) { this._joints.push({ otherImpostor: otherImpostor, joint: joint }); if (this._physicsEngine) { this._physicsEngine.addJoint(this, otherImpostor, joint); } return this; }; /** * Will keep this body still, in a sleep mode. */ PhysicsImpostor.prototype.sleep = function () { if (this._physicsEngine) { this._physicsEngine.getPhysicsPlugin().sleepBody(this); } return this; }; /** * Wake the body up. */ PhysicsImpostor.prototype.wakeUp = function () { if (this._physicsEngine) { this._physicsEngine.getPhysicsPlugin().wakeUpBody(this); } return this; }; PhysicsImpostor.prototype.clone = function (newObject) { if (!newObject) return null; return new PhysicsImpostor(newObject, this.type, this._options, this._scene); }; PhysicsImpostor.prototype.dispose = function () { var _this = this; //no dispose if no physics engine is available. if (!this._physicsEngine) { return; } this._joints.forEach(function (j) { if (_this._physicsEngine) { _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint); } }); //dispose the physics body this._physicsEngine.removeImpostor(this); if (this.parent) { this.parent.forceUpdate(); } else { /*this._object.getChildMeshes().forEach(function(mesh) { if (mesh.physicsImpostor) { if (disposeChildren) { mesh.physicsImpostor.dispose(); mesh.physicsImpostor = null; } } })*/ } this._isDisposed = true; }; PhysicsImpostor.prototype.setDeltaPosition = function (position) { this._deltaPosition.copyFrom(position); }; PhysicsImpostor.prototype.setDeltaRotation = function (rotation) { if (!this._deltaRotation) { this._deltaRotation = new BABYLON.Quaternion(); } this._deltaRotation.copyFrom(rotation); this._deltaRotationConjugated = this._deltaRotation.conjugate(); }; PhysicsImpostor.prototype.getBoxSizeToRef = function (result) { if (this._physicsEngine) { this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result); } return this; }; PhysicsImpostor.prototype.getRadius = function () { return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0; }; /** * Sync a bone with this impostor * @param bone The bone to sync to the impostor. * @param boneMesh The mesh that the bone is influencing. * @param jointPivot The pivot of the joint / bone in local space. * @param distToJoint Optional distance from the impostor to the joint. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. */ PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) { var tempVec = PhysicsImpostor._tmpVecs[0]; var mesh = this.object; if (mesh.rotationQuaternion) { if (adjustRotation) { var tempQuat = PhysicsImpostor._tmpQuat; mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat); bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh); } else { bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh); } } tempVec.x = 0; tempVec.y = 0; tempVec.z = 0; if (jointPivot) { tempVec.x = jointPivot.x; tempVec.y = jointPivot.y; tempVec.z = jointPivot.z; bone.getDirectionToRef(tempVec, boneMesh, tempVec); if (distToJoint === undefined || distToJoint === null) { distToJoint = jointPivot.length(); } tempVec.x *= distToJoint; tempVec.y *= distToJoint; tempVec.z *= distToJoint; } if (bone.getParent()) { tempVec.addInPlace(mesh.getAbsolutePosition()); bone.setAbsolutePosition(tempVec, boneMesh); } else { boneMesh.setAbsolutePosition(mesh.getAbsolutePosition()); boneMesh.position.x -= tempVec.x; boneMesh.position.y -= tempVec.y; boneMesh.position.z -= tempVec.z; } }; /** * Sync impostor to a bone * @param bone The bone that the impostor will be synced to. * @param boneMesh The mesh that the bone is influencing. * @param jointPivot The pivot of the joint / bone in local space. * @param distToJoint Optional distance from the impostor to the joint. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. * @param boneAxis Optional vector3 axis the bone is aligned with */ PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) { var mesh = this.object; if (mesh.rotationQuaternion) { if (adjustRotation) { var tempQuat = PhysicsImpostor._tmpQuat; bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat); tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion); } else { bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion); } } var pos = PhysicsImpostor._tmpVecs[0]; var boneDir = PhysicsImpostor._tmpVecs[1]; if (!boneAxis) { boneAxis = PhysicsImpostor._tmpVecs[2]; boneAxis.x = 0; boneAxis.y = 1; boneAxis.z = 0; } bone.getDirectionToRef(boneAxis, boneMesh, boneDir); bone.getAbsolutePositionToRef(boneMesh, pos); if ((distToJoint === undefined || distToJoint === null) && jointPivot) { distToJoint = jointPivot.length(); } if (distToJoint !== undefined && distToJoint !== null) { pos.x += boneDir.x * distToJoint; pos.y += boneDir.y * distToJoint; pos.z += boneDir.z * distToJoint; } mesh.setAbsolutePosition(pos); }; PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1); PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity(); PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()]; PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity(); //Impostor types PhysicsImpostor.NoImpostor = 0; PhysicsImpostor.SphereImpostor = 1; PhysicsImpostor.BoxImpostor = 2; PhysicsImpostor.PlaneImpostor = 3; PhysicsImpostor.MeshImpostor = 4; PhysicsImpostor.CylinderImpostor = 7; PhysicsImpostor.ParticleImpostor = 8; PhysicsImpostor.HeightmapImpostor = 9; return PhysicsImpostor; }()); BABYLON.PhysicsImpostor = PhysicsImpostor; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.physicsImpostor.js.map var BABYLON; (function (BABYLON) { var PhysicsEngine = /** @class */ (function () { function PhysicsEngine(gravity, _physicsPlugin) { if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); } this._physicsPlugin = _physicsPlugin; //new methods and parameters this._impostors = []; this._joints = []; if (!this._physicsPlugin.isSupported()) { throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. " + "Please make sure it is included."); } gravity = gravity || new BABYLON.Vector3(0, -9.807, 0); this.setGravity(gravity); this.setTimeStep(); } PhysicsEngine.prototype.setGravity = function (gravity) { this.gravity = gravity; this._physicsPlugin.setGravity(this.gravity); }; /** * Set the time step of the physics engine. * default is 1/60. * To slow it down, enter 1/600 for example. * To speed it up, 1/30 * @param {number} newTimeStep the new timestep to apply to this world. */ PhysicsEngine.prototype.setTimeStep = function (newTimeStep) { if (newTimeStep === void 0) { newTimeStep = 1 / 60; } this._physicsPlugin.setTimeStep(newTimeStep); }; /** * Get the time step of the physics engine. */ PhysicsEngine.prototype.getTimeStep = function () { return this._physicsPlugin.getTimeStep(); }; PhysicsEngine.prototype.dispose = function () { this._impostors.forEach(function (impostor) { impostor.dispose(); }); this._physicsPlugin.dispose(); }; PhysicsEngine.prototype.getPhysicsPluginName = function () { return this._physicsPlugin.name; }; /** * Adding a new impostor for the impostor tracking. * This will be done by the impostor itself. * @param {PhysicsImpostor} impostor the impostor to add */ PhysicsEngine.prototype.addImpostor = function (impostor) { impostor.uniqueId = this._impostors.push(impostor); //if no parent, generate the body if (!impostor.parent) { this._physicsPlugin.generatePhysicsBody(impostor); } }; /** * Remove an impostor from the engine. * This impostor and its mesh will not longer be updated by the physics engine. * @param {PhysicsImpostor} impostor the impostor to remove */ PhysicsEngine.prototype.removeImpostor = function (impostor) { var index = this._impostors.indexOf(impostor); if (index > -1) { var removed = this._impostors.splice(index, 1); //Is it needed? if (removed.length) { //this will also remove it from the world. removed[0].physicsBody = null; } } }; /** * Add a joint to the physics engine * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint * @param {PhysicsJoint} the joint that will connect both impostors. */ PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) { var impostorJoint = { mainImpostor: mainImpostor, connectedImpostor: connectedImpostor, joint: joint }; joint.physicsPlugin = this._physicsPlugin; this._joints.push(impostorJoint); this._physicsPlugin.generateJoint(impostorJoint); }; PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) { var matchingJoints = this._joints.filter(function (impostorJoint) { return (impostorJoint.connectedImpostor === connectedImpostor && impostorJoint.joint === joint && impostorJoint.mainImpostor === mainImpostor); }); if (matchingJoints.length) { this._physicsPlugin.removeJoint(matchingJoints[0]); //TODO remove it from the list as well } }; /** * Called by the scene. no need to call it. */ PhysicsEngine.prototype._step = function (delta) { var _this = this; //check if any mesh has no body / requires an update this._impostors.forEach(function (impostor) { if (impostor.isBodyInitRequired()) { _this._physicsPlugin.generatePhysicsBody(impostor); } }); if (delta > 0.1) { delta = 0.1; } else if (delta <= 0) { delta = 1.0 / 60.0; } this._physicsPlugin.executeStep(delta, this._impostors); }; PhysicsEngine.prototype.getPhysicsPlugin = function () { return this._physicsPlugin; }; PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) { for (var i = 0; i < this._impostors.length; ++i) { if (this._impostors[i].object === object) { return this._impostors[i]; } } return null; }; PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) { for (var i = 0; i < this._impostors.length; ++i) { if (this._impostors[i].physicsBody === body) { return this._impostors[i]; } } return null; }; // Statics PhysicsEngine.Epsilon = 0.001; return PhysicsEngine; }()); BABYLON.PhysicsEngine = PhysicsEngine; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.physicsEngine.js.map var BABYLON; (function (BABYLON) { var CannonJSPlugin = /** @class */ (function () { function CannonJSPlugin(_useDeltaForWorldStep, iterations) { if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; } if (iterations === void 0) { iterations = 10; } this._useDeltaForWorldStep = _useDeltaForWorldStep; this.name = "CannonJSPlugin"; this._physicsMaterials = new Array(); this._fixedTimeStep = 1 / 60; //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined); this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475); this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475); this._tmpPosition = BABYLON.Vector3.Zero(); this._tmpDeltaPosition = BABYLON.Vector3.Zero(); this._tmpUnityRotation = new BABYLON.Quaternion(); if (!this.isSupported()) { BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file."); return; } this.world = new this.BJSCANNON.World(); this.world.broadphase = new this.BJSCANNON.NaiveBroadphase(); this.world.solver.iterations = iterations; } CannonJSPlugin.prototype.setGravity = function (gravity) { this.world.gravity.copy(gravity); }; CannonJSPlugin.prototype.setTimeStep = function (timeStep) { this._fixedTimeStep = timeStep; }; CannonJSPlugin.prototype.getTimeStep = function () { return this._fixedTimeStep; }; CannonJSPlugin.prototype.executeStep = function (delta, impostors) { this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3); }; CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) { var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z); var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z); impostor.physicsBody.applyImpulse(impulse, worldPoint); }; CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) { var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z); var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z); impostor.physicsBody.applyForce(impulse, worldPoint); }; CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) { //parent-child relationship. Does this impostor has a parent impostor? if (impostor.parent) { if (impostor.physicsBody) { this.removePhysicsBody(impostor); //TODO is that needed? impostor.forceUpdate(); } return; } //should a new body be created for this impostor? if (impostor.isBodyInitRequired()) { var shape = this._createShape(impostor); //unregister events, if body is being changed var oldBody = impostor.physicsBody; if (oldBody) { this.removePhysicsBody(impostor); } //create the body and material var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution")); var bodyCreationObject = { mass: impostor.getParam("mass"), material: material }; // A simple extend, in case native options were used. var nativeOptions = impostor.getParam("nativeOptions"); for (var key in nativeOptions) { if (nativeOptions.hasOwnProperty(key)) { bodyCreationObject[key] = nativeOptions[key]; } } impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject); impostor.physicsBody.addEventListener("collide", impostor.onCollide); this.world.addEventListener("preStep", impostor.beforeStep); this.world.addEventListener("postStep", impostor.afterStep); impostor.physicsBody.addShape(shape); this.world.add(impostor.physicsBody); //try to keep the body moving in the right direction by taking old properties. //Should be tested! if (oldBody) { ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) { impostor.physicsBody[param].copy(oldBody[param]); }); } this._processChildMeshes(impostor); } //now update the body's transformation this._updatePhysicsBodyTransformation(impostor); }; CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) { var _this = this; var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : []; var currentRotation = mainImpostor.object.rotationQuaternion; if (meshChildren.length) { var processMesh = function (localPosition, mesh) { if (!currentRotation || !mesh.rotationQuaternion) { return; } var childImpostor = mesh.getPhysicsImpostor(); if (childImpostor) { var parent = childImpostor.parent; if (parent !== mainImpostor) { var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition()); var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation)); if (childImpostor.physicsBody) { _this.removePhysicsBody(childImpostor); childImpostor.physicsBody = null; } childImpostor.parent = mainImpostor; childImpostor.resetUpdateFlags(); mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w)); //Add the mass of the children. mainImpostor.physicsBody.mass += childImpostor.getParam("mass"); } } currentRotation.multiplyInPlace(mesh.rotationQuaternion); mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition())); }; meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition())); } }; CannonJSPlugin.prototype.removePhysicsBody = function (impostor) { impostor.physicsBody.removeEventListener("collide", impostor.onCollide); this.world.removeEventListener("preStep", impostor.beforeStep); this.world.removeEventListener("postStep", impostor.afterStep); this.world.remove(impostor.physicsBody); }; CannonJSPlugin.prototype.generateJoint = function (impostorJoint) { var mainBody = impostorJoint.mainImpostor.physicsBody; var connectedBody = impostorJoint.connectedImpostor.physicsBody; if (!mainBody || !connectedBody) { return; } var constraint; var jointData = impostorJoint.joint.jointData; //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html var constraintData = { pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null, pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null, axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null, axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null, maxForce: jointData.nativeParams.maxForce, collideConnected: !!jointData.collision }; switch (impostorJoint.joint.type) { case BABYLON.PhysicsJoint.HingeJoint: case BABYLON.PhysicsJoint.Hinge2Joint: constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData); break; case BABYLON.PhysicsJoint.DistanceJoint: constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2); break; case BABYLON.PhysicsJoint.SpringJoint: var springData = jointData; constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, { restLength: springData.length, stiffness: springData.stiffness, damping: springData.damping, localAnchorA: constraintData.pivotA, localAnchorB: constraintData.pivotB }); break; case BABYLON.PhysicsJoint.LockJoint: constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData); break; case BABYLON.PhysicsJoint.PointToPointJoint: case BABYLON.PhysicsJoint.BallAndSocketJoint: default: constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce); break; } //set the collideConnected flag after the creation, since DistanceJoint ignores it. constraint.collideConnected = !!jointData.collision; impostorJoint.joint.physicsJoint = constraint; //don't add spring as constraint, as it is not one. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) { this.world.addConstraint(constraint); } else { impostorJoint.mainImpostor.registerAfterPhysicsStep(function () { constraint.applyForce(); }); } }; CannonJSPlugin.prototype.removeJoint = function (impostorJoint) { this.world.removeConstraint(impostorJoint.joint.physicsJoint); }; CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) { var index; var mat; for (index = 0; index < this._physicsMaterials.length; index++) { mat = this._physicsMaterials[index]; if (mat.friction === friction && mat.restitution === restitution) { return mat; } } var currentMat = new this.BJSCANNON.Material(name); currentMat.friction = friction; currentMat.restitution = restitution; this._physicsMaterials.push(currentMat); return currentMat; }; CannonJSPlugin.prototype._checkWithEpsilon = function (value) { return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value; }; CannonJSPlugin.prototype._createShape = function (impostor) { var object = impostor.object; var returnValue; var extendSize = impostor.getObjectExtendSize(); switch (impostor.type) { case BABYLON.PhysicsImpostor.SphereImpostor: var radiusX = extendSize.x; var radiusY = extendSize.y; var radiusZ = extendSize.z; returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2); break; //TMP also for cylinder - TODO Cannon supports cylinder natively. case BABYLON.PhysicsImpostor.CylinderImpostor: returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16); break; case BABYLON.PhysicsImpostor.BoxImpostor: var box = extendSize.scale(0.5); returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z))); break; case BABYLON.PhysicsImpostor.PlaneImpostor: BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"); returnValue = new this.BJSCANNON.Plane(); break; case BABYLON.PhysicsImpostor.MeshImpostor: var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : []; var rawFaces = object.getIndices ? object.getIndices() : []; BABYLON.Tools.Warn("MeshImpostor only collides against spheres."); returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces); break; case BABYLON.PhysicsImpostor.HeightmapImpostor: returnValue = this._createHeightmap(object); break; case BABYLON.PhysicsImpostor.ParticleImpostor: returnValue = new this.BJSCANNON.Particle(); break; } return returnValue; }; CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) { var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind)); var matrix = new Array(); //For now pointDepth will not be used and will be automatically calculated. //Future reference - try and find the best place to add a reference to the pointDepth variable. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1); var boundingInfo = (object.getBoundingInfo()); var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.z); var minY = boundingInfo.boundingBox.extendSizeWorld.y; var elementSize = dim * 2 / arraySize; for (var i = 0; i < pos.length; i = i + 3) { var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2); var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1); var y = pos[i + 1] + minY; if (!matrix[x]) { matrix[x] = []; } if (!matrix[x][z]) { matrix[x][z] = y; } matrix[x][z] = Math.max(y, matrix[x][z]); } for (var x = 0; x <= arraySize; ++x) { if (!matrix[x]) { var loc = 1; while (!matrix[(x + loc) % arraySize]) { loc++; } matrix[x] = matrix[(x + loc) % arraySize].slice(); //console.log("missing x", x); } for (var z = 0; z <= arraySize; ++z) { if (!matrix[x][z]) { var loc = 1; var newValue; while (newValue === undefined) { newValue = matrix[x][(z + loc++) % arraySize]; } matrix[x][z] = newValue; } } } var shape = new this.BJSCANNON.Heightfield(matrix, { elementSize: elementSize }); //For future reference, needed for body transformation shape.minY = minY; return shape; }; CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) { var object = impostor.object; //make sure it is updated... object.computeWorldMatrix && object.computeWorldMatrix(true); // The delta between the mesh position and the mesh bounding box center var center = impostor.getObjectCenter(); this._tmpDeltaPosition.copyFrom(object.position.subtract(center)); this._tmpPosition.copyFrom(center); var quaternion = object.rotationQuaternion; if (!quaternion) { return; } //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) { //-90 DEG in X, precalculated quaternion = quaternion.multiply(this._minus90X); //Invert! (Precalculated, 90 deg in X) //No need to clone. this will never change. impostor.setDeltaRotation(this._plus90X); } //If it is a heightfield, if should be centered. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) { var mesh = object; var boundingInfo = mesh.getBoundingInfo(); //calculate the correct body position: var rotationQuaternion = mesh.rotationQuaternion; mesh.rotationQuaternion = this._tmpUnityRotation; mesh.computeWorldMatrix(true); //get original center with no rotation var c = center.clone(); var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0); //rotation is back mesh.rotationQuaternion = rotationQuaternion; //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps) var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z); mesh.setPivotMatrix(p); mesh.computeWorldMatrix(true); //calculate the translation var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate(); this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z); //add it inverted to the delta this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c)); this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y; mesh.setPivotMatrix(oldPivot); mesh.computeWorldMatrix(true); } else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) { this._tmpDeltaPosition.copyFromFloats(0, 0, 0); this._tmpPosition.copyFrom(object.position); } impostor.setDeltaPosition(this._tmpDeltaPosition); //Now update the impostor object impostor.physicsBody.position.copy(this._tmpPosition); impostor.physicsBody.quaternion.copy(quaternion); }; CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) { impostor.object.position.copyFrom(impostor.physicsBody.position); if (impostor.object.rotationQuaternion) { impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion); } }; CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) { impostor.physicsBody.position.copy(newPosition); impostor.physicsBody.quaternion.copy(newRotation); }; CannonJSPlugin.prototype.isSupported = function () { return this.BJSCANNON !== undefined; }; CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) { impostor.physicsBody.velocity.copy(velocity); }; CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) { impostor.physicsBody.angularVelocity.copy(velocity); }; CannonJSPlugin.prototype.getLinearVelocity = function (impostor) { var v = impostor.physicsBody.velocity; if (!v) { return null; } return new BABYLON.Vector3(v.x, v.y, v.z); }; CannonJSPlugin.prototype.getAngularVelocity = function (impostor) { var v = impostor.physicsBody.angularVelocity; if (!v) { return null; } return new BABYLON.Vector3(v.x, v.y, v.z); }; CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) { impostor.physicsBody.mass = mass; impostor.physicsBody.updateMassProperties(); }; CannonJSPlugin.prototype.getBodyMass = function (impostor) { return impostor.physicsBody.mass; }; CannonJSPlugin.prototype.getBodyFriction = function (impostor) { return impostor.physicsBody.material.friction; }; CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) { impostor.physicsBody.material.friction = friction; }; CannonJSPlugin.prototype.getBodyRestitution = function (impostor) { return impostor.physicsBody.material.restitution; }; CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) { impostor.physicsBody.material.restitution = restitution; }; CannonJSPlugin.prototype.sleepBody = function (impostor) { impostor.physicsBody.sleep(); }; CannonJSPlugin.prototype.wakeUpBody = function (impostor) { impostor.physicsBody.wakeUp(); }; CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) { joint.physicsJoint.distance = maxDistance; }; // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) { // if (!motorIndex) { // joint.physicsJoint.enableMotor(); // } // } // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) { // if (!motorIndex) { // joint.physicsJoint.disableMotor(); // } // } CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) { if (!motorIndex) { joint.physicsJoint.enableMotor(); joint.physicsJoint.setMotorSpeed(speed); if (maxForce) { this.setLimit(joint, maxForce); } } }; CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) { joint.physicsJoint.motorEquation.maxForce = upperLimit; joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit; }; CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) { var body = impostor.physicsBody; mesh.position.x = body.position.x; mesh.position.y = body.position.y; mesh.position.z = body.position.z; if (mesh.rotationQuaternion) { mesh.rotationQuaternion.x = body.quaternion.x; mesh.rotationQuaternion.y = body.quaternion.y; mesh.rotationQuaternion.z = body.quaternion.z; mesh.rotationQuaternion.w = body.quaternion.w; } }; CannonJSPlugin.prototype.getRadius = function (impostor) { var shape = impostor.physicsBody.shapes[0]; return shape.boundingSphereRadius; }; CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) { var shape = impostor.physicsBody.shapes[0]; result.x = shape.halfExtents.x * 2; result.y = shape.halfExtents.y * 2; result.z = shape.halfExtents.z * 2; }; CannonJSPlugin.prototype.dispose = function () { }; return CannonJSPlugin; }()); BABYLON.CannonJSPlugin = CannonJSPlugin; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.cannonJSPlugin.js.map var BABYLON; (function (BABYLON) { var OimoJSPlugin = /** @class */ (function () { function OimoJSPlugin(iterations) { this.name = "OimoJSPlugin"; this._tmpImpostorsArray = []; this._tmpPositionVector = BABYLON.Vector3.Zero(); this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined); this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true); this.world.worldscale(1); this.world.clear(); //making sure no stats are calculated this.world.isNoStat = true; } OimoJSPlugin.prototype.setGravity = function (gravity) { this.world.gravity.copy(gravity); }; OimoJSPlugin.prototype.setTimeStep = function (timeStep) { this.world.timeStep = timeStep; }; OimoJSPlugin.prototype.getTimeStep = function () { return this.world.timeStep; }; OimoJSPlugin.prototype.executeStep = function (delta, impostors) { var _this = this; impostors.forEach(function (impostor) { impostor.beforeStep(); }); this.world.step(); impostors.forEach(function (impostor) { impostor.afterStep(); //update the ordered impostors array _this._tmpImpostorsArray[impostor.uniqueId] = impostor; }); //check for collisions var contact = this.world.contacts; while (contact !== null) { if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) { contact = contact.next; continue; } //is this body colliding with any other? get the impostor var mainImpostor = this._tmpImpostorsArray[+contact.body1.name]; var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name]; if (!mainImpostor || !collidingImpostor) { contact = contact.next; continue; } mainImpostor.onCollide({ body: collidingImpostor.physicsBody }); collidingImpostor.onCollide({ body: mainImpostor.physicsBody }); contact = contact.next; } }; OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) { var mass = impostor.physicsBody.massInfo.mass; impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass)); }; OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) { BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead."); this.applyImpulse(impostor, force, contactPoint); }; OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) { var _this = this; //parent-child relationship. Does this impostor has a parent impostor? if (impostor.parent) { if (impostor.physicsBody) { this.removePhysicsBody(impostor); //TODO is that needed? impostor.forceUpdate(); } return; } if (impostor.isBodyInitRequired()) { var bodyConfig = { name: impostor.uniqueId, //Oimo must have mass, also for static objects. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")], size: [], type: [], pos: [], rot: [], move: impostor.getParam("mass") !== 0, //Supporting older versions of Oimo world: this.world }; var impostors = [impostor]; var addToArray = function (parent) { if (!parent.getChildMeshes) return; parent.getChildMeshes().forEach(function (m) { if (m.physicsImpostor) { impostors.push(m.physicsImpostor); //m.physicsImpostor._init(); } }); }; addToArray(impostor.object); var checkWithEpsilon_1 = function (value) { return Math.max(value, BABYLON.PhysicsEngine.Epsilon); }; impostors.forEach(function (i) { if (!impostor.object.rotationQuaternion) { return; } //get the correct bounding box var oldQuaternion = i.object.rotationQuaternion; var rot = new _this.BJSOIMO.Euler().setFromQuaternion({ x: impostor.object.rotationQuaternion.x, y: impostor.object.rotationQuaternion.y, z: impostor.object.rotationQuaternion.z, s: impostor.object.rotationQuaternion.w }); var extendSize = i.getObjectExtendSize(); if (i === impostor) { var center = impostor.getObjectCenter(); impostor.object.position.subtractToRef(center, _this._tmpPositionVector); //Can also use Array.prototype.push.apply bodyConfig.pos.push(center.x); bodyConfig.pos.push(center.y); bodyConfig.pos.push(center.z); //tmp solution bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD)); bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD)); bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD)); } else { var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition()); bodyConfig.pos.push(localPosition.x); bodyConfig.pos.push(localPosition.y); bodyConfig.pos.push(localPosition.z); //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged bodyConfig.rot.push(0); bodyConfig.rot.push(0); bodyConfig.rot.push(0); } // register mesh switch (i.type) { case BABYLON.PhysicsImpostor.ParticleImpostor: BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead"); case BABYLON.PhysicsImpostor.SphereImpostor: var radiusX = extendSize.x; var radiusY = extendSize.y; var radiusZ = extendSize.z; var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2; bodyConfig.type.push('sphere'); //due to the way oimo works with compounds, add 3 times bodyConfig.size.push(size); bodyConfig.size.push(size); bodyConfig.size.push(size); break; case BABYLON.PhysicsImpostor.CylinderImpostor: var sizeX = checkWithEpsilon_1(extendSize.x) / 2; var sizeY = checkWithEpsilon_1(extendSize.y); bodyConfig.type.push('cylinder'); bodyConfig.size.push(sizeX); bodyConfig.size.push(sizeY); //due to the way oimo works with compounds, add one more value. bodyConfig.size.push(sizeY); break; case BABYLON.PhysicsImpostor.PlaneImpostor: case BABYLON.PhysicsImpostor.BoxImpostor: default: var sizeX = checkWithEpsilon_1(extendSize.x); var sizeY = checkWithEpsilon_1(extendSize.y); var sizeZ = checkWithEpsilon_1(extendSize.z); bodyConfig.type.push('box'); bodyConfig.size.push(sizeX); bodyConfig.size.push(sizeY); bodyConfig.size.push(sizeZ); break; } //actually not needed, but hey... i.object.rotationQuaternion = oldQuaternion; }); impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig); } else { this._tmpPositionVector.copyFromFloats(0, 0, 0); } impostor.setDeltaPosition(this._tmpPositionVector); //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center); //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion); }; OimoJSPlugin.prototype.removePhysicsBody = function (impostor) { //impostor.physicsBody.dispose(); //Same as : (older oimo versions) this.world.removeRigidBody(impostor.physicsBody); }; OimoJSPlugin.prototype.generateJoint = function (impostorJoint) { var mainBody = impostorJoint.mainImpostor.physicsBody; var connectedBody = impostorJoint.connectedImpostor.physicsBody; if (!mainBody || !connectedBody) { return; } var jointData = impostorJoint.joint.jointData; var options = jointData.nativeParams || {}; var type; var nativeJointData = { body1: mainBody, body2: connectedBody, axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null), axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null), pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null), pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null), min: options.min, max: options.max, collision: options.collision || jointData.collision, spring: options.spring, //supporting older version of Oimo world: this.world }; switch (impostorJoint.joint.type) { case BABYLON.PhysicsJoint.BallAndSocketJoint: type = "jointBall"; break; case BABYLON.PhysicsJoint.SpringJoint: BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead"); var springData = jointData; nativeJointData.min = springData.length || nativeJointData.min; //Max should also be set, just make sure it is at least min nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max); case BABYLON.PhysicsJoint.DistanceJoint: type = "jointDistance"; nativeJointData.max = jointData.maxDistance; break; case BABYLON.PhysicsJoint.PrismaticJoint: type = "jointPrisme"; break; case BABYLON.PhysicsJoint.SliderJoint: type = "jointSlide"; break; case BABYLON.PhysicsJoint.WheelJoint: type = "jointWheel"; break; case BABYLON.PhysicsJoint.HingeJoint: default: type = "jointHinge"; break; } nativeJointData.type = type; impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData); }; OimoJSPlugin.prototype.removeJoint = function (impostorJoint) { //Bug in Oimo prevents us from disposing a joint in the playground //joint.joint.physicsJoint.dispose(); //So we will bruteforce it! try { this.world.removeJoint(impostorJoint.joint.physicsJoint); } catch (e) { BABYLON.Tools.Warn(e); } }; OimoJSPlugin.prototype.isSupported = function () { return this.BJSOIMO !== undefined; }; OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) { if (!impostor.physicsBody.sleeping) { //TODO check that if (impostor.physicsBody.shapes.next) { var parentShape = this._getLastShape(impostor.physicsBody); impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE; impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE; impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE; } else { impostor.object.position.copyFrom(impostor.physicsBody.getPosition()); } if (impostor.object.rotationQuaternion) { impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion()); impostor.object.rotationQuaternion.normalize(); } } }; OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) { var body = impostor.physicsBody; body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE); body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z); body.syncShapes(); body.awake(); }; OimoJSPlugin.prototype._getLastShape = function (body) { var lastShape = body.shapes; while (lastShape.next) { lastShape = lastShape.next; } return lastShape; }; OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) { impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z); }; OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) { impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z); }; OimoJSPlugin.prototype.getLinearVelocity = function (impostor) { var v = impostor.physicsBody.linearVelocity; if (!v) { return null; } return new BABYLON.Vector3(v.x, v.y, v.z); }; OimoJSPlugin.prototype.getAngularVelocity = function (impostor) { var v = impostor.physicsBody.angularVelocity; if (!v) { return null; } return new BABYLON.Vector3(v.x, v.y, v.z); }; OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) { var staticBody = mass === 0; //this will actually set the body's density and not its mass. //But this is how oimo treats the mass variable. impostor.physicsBody.shapes.density = staticBody ? 1 : mass; impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1); }; OimoJSPlugin.prototype.getBodyMass = function (impostor) { return impostor.physicsBody.shapes.density; }; OimoJSPlugin.prototype.getBodyFriction = function (impostor) { return impostor.physicsBody.shapes.friction; }; OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) { impostor.physicsBody.shapes.friction = friction; }; OimoJSPlugin.prototype.getBodyRestitution = function (impostor) { return impostor.physicsBody.shapes.restitution; }; OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) { impostor.physicsBody.shapes.restitution = restitution; }; OimoJSPlugin.prototype.sleepBody = function (impostor) { impostor.physicsBody.sleep(); }; OimoJSPlugin.prototype.wakeUpBody = function (impostor) { impostor.physicsBody.awake(); }; OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) { joint.physicsJoint.limitMotor.upperLimit = maxDistance; if (minDistance !== void 0) { joint.physicsJoint.limitMotor.lowerLimit = minDistance; } }; OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) { //TODO separate rotational and transational motors. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor; if (motor) { motor.setMotor(speed, maxForce); } }; OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) { //TODO separate rotational and transational motors. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor; if (motor) { motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit); } }; OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) { var body = impostor.physicsBody; mesh.position.x = body.position.x; mesh.position.y = body.position.y; mesh.position.z = body.position.z; if (mesh.rotationQuaternion) { mesh.rotationQuaternion.x = body.orientation.x; mesh.rotationQuaternion.y = body.orientation.y; mesh.rotationQuaternion.z = body.orientation.z; mesh.rotationQuaternion.w = body.orientation.s; } }; OimoJSPlugin.prototype.getRadius = function (impostor) { return impostor.physicsBody.shapes.radius; }; OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) { var shape = impostor.physicsBody.shapes; result.x = shape.halfWidth * 2; result.y = shape.halfHeight * 2; result.z = shape.halfDepth * 2; }; OimoJSPlugin.prototype.dispose = function () { this.world.clear(); }; return OimoJSPlugin; }()); BABYLON.OimoJSPlugin = OimoJSPlugin; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.oimoJSPlugin.js.map var BABYLON; (function (BABYLON) { var Internals; (function (Internals) { /* * Based on jsTGALoader - Javascript loader for TGA file * By Vincent Thibault * @blog http://blog.robrowser.com/javascript-tga-loader.html */ var TGATools = /** @class */ (function () { function TGATools() { } TGATools.GetTGAHeader = function (data) { var offset = 0; var header = { id_length: data[offset++], colormap_type: data[offset++], image_type: data[offset++], colormap_index: data[offset++] | data[offset++] << 8, colormap_length: data[offset++] | data[offset++] << 8, colormap_size: data[offset++], origin: [ data[offset++] | data[offset++] << 8, data[offset++] | data[offset++] << 8 ], width: data[offset++] | data[offset++] << 8, height: data[offset++] | data[offset++] << 8, pixel_size: data[offset++], flags: data[offset++] }; return header; }; TGATools.UploadContent = function (gl, data) { // Not enough data to contain header ? if (data.length < 19) { BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header"); return; } // Read Header var offset = 18; var header = TGATools.GetTGAHeader(data); // Assume it's a valid Targa file. if (header.id_length + offset > data.length) { BABYLON.Tools.Error("Unable to load TGA file - Not enough data"); return; } // Skip not needed data offset += header.id_length; var use_rle = false; var use_pal = false; var use_rgb = false; var use_grey = false; // Get some informations. switch (header.image_type) { case TGATools._TYPE_RLE_INDEXED: use_rle = true; case TGATools._TYPE_INDEXED: use_pal = true; break; case TGATools._TYPE_RLE_RGB: use_rle = true; case TGATools._TYPE_RGB: use_rgb = true; break; case TGATools._TYPE_RLE_GREY: use_rle = true; case TGATools._TYPE_GREY: use_grey = true; break; } var pixel_data; // var numAlphaBits = header.flags & 0xf; var pixel_size = header.pixel_size >> 3; var pixel_total = header.width * header.height * pixel_size; // Read palettes var palettes; if (use_pal) { palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3)); } // Read LRE if (use_rle) { pixel_data = new Uint8Array(pixel_total); var c, count, i; var localOffset = 0; var pixels = new Uint8Array(pixel_size); while (offset < pixel_total && localOffset < pixel_total) { c = data[offset++]; count = (c & 0x7f) + 1; // RLE pixels if (c & 0x80) { // Bind pixel tmp array for (i = 0; i < pixel_size; ++i) { pixels[i] = data[offset++]; } // Copy pixel array for (i = 0; i < count; ++i) { pixel_data.set(pixels, localOffset + i * pixel_size); } localOffset += pixel_size * count; } else { count *= pixel_size; for (i = 0; i < count; ++i) { pixel_data[localOffset + i] = data[offset++]; } localOffset += count; } } } else { pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total)); } // Load to texture var x_start, y_start, x_step, y_step, y_end, x_end; switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) { default: case TGATools._ORIGIN_UL: x_start = 0; x_step = 1; x_end = header.width; y_start = 0; y_step = 1; y_end = header.height; break; case TGATools._ORIGIN_BL: x_start = 0; x_step = 1; x_end = header.width; y_start = header.height - 1; y_step = -1; y_end = -1; break; case TGATools._ORIGIN_UR: x_start = header.width - 1; x_step = -1; x_end = -1; y_start = 0; y_step = 1; y_end = header.height; break; case TGATools._ORIGIN_BR: x_start = header.width - 1; x_step = -1; x_end = -1; y_start = header.height - 1; y_step = -1; y_end = -1; break; } // Load the specify method var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits'; var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData); }; TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { var image = pixel_data, colormap = palettes; var width = header.width, height = header.height; var color, i = 0, x, y; var imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i++) { color = image[i]; imageData[(x + width * y) * 4 + 3] = 255; imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0]; imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1]; imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2]; } } return imageData; }; TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { var image = pixel_data; var width = header.width, height = header.height; var color, i = 0, x, y; var imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i += 2) { color = image[i + 0] + (image[i + 1] << 8); // Inversed ? imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7; imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2; imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3; imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255; } } return imageData; }; TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { var image = pixel_data; var width = header.width, height = header.height; var i = 0, x, y; var imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i += 3) { imageData[(x + width * y) * 4 + 3] = 255; imageData[(x + width * y) * 4 + 2] = image[i + 0]; imageData[(x + width * y) * 4 + 1] = image[i + 1]; imageData[(x + width * y) * 4 + 0] = image[i + 2]; } } return imageData; }; TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { var image = pixel_data; var width = header.width, height = header.height; var i = 0, x, y; var imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i += 4) { imageData[(x + width * y) * 4 + 2] = image[i + 0]; imageData[(x + width * y) * 4 + 1] = image[i + 1]; imageData[(x + width * y) * 4 + 0] = image[i + 2]; imageData[(x + width * y) * 4 + 3] = image[i + 3]; } } return imageData; }; TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { var image = pixel_data; var width = header.width, height = header.height; var color, i = 0, x, y; var imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i++) { color = image[i]; imageData[(x + width * y) * 4 + 0] = color; imageData[(x + width * y) * 4 + 1] = color; imageData[(x + width * y) * 4 + 2] = color; imageData[(x + width * y) * 4 + 3] = 255; } } return imageData; }; TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { var image = pixel_data; var width = header.width, height = header.height; var i = 0, x, y; var imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i += 2) { imageData[(x + width * y) * 4 + 0] = image[i + 0]; imageData[(x + width * y) * 4 + 1] = image[i + 0]; imageData[(x + width * y) * 4 + 2] = image[i + 0]; imageData[(x + width * y) * 4 + 3] = image[i + 1]; } } return imageData; }; //private static _TYPE_NO_DATA = 0; TGATools._TYPE_INDEXED = 1; TGATools._TYPE_RGB = 2; TGATools._TYPE_GREY = 3; TGATools._TYPE_RLE_INDEXED = 9; TGATools._TYPE_RLE_RGB = 10; TGATools._TYPE_RLE_GREY = 11; TGATools._ORIGIN_MASK = 0x30; TGATools._ORIGIN_SHIFT = 0x04; TGATools._ORIGIN_BL = 0x00; TGATools._ORIGIN_BR = 0x01; TGATools._ORIGIN_UL = 0x02; TGATools._ORIGIN_UR = 0x03; return TGATools; }()); Internals.TGATools = TGATools; })(Internals = BABYLON.Internals || (BABYLON.Internals = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.tga.js.map var BABYLON; (function (BABYLON) { var Internals; (function (Internals) { // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html // All values and structures referenced from: // http://msdn.microsoft.com/en-us/library/bb943991.aspx/ var DDS_MAGIC = 0x20534444; var //DDSD_CAPS = 0x1, //DDSD_HEIGHT = 0x2, //DDSD_WIDTH = 0x4, //DDSD_PITCH = 0x8, //DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000; //DDSD_LINEARSIZE = 0x80000, //DDSD_DEPTH = 0x800000; // var DDSCAPS_COMPLEX = 0x8, // DDSCAPS_MIPMAP = 0x400000, // DDSCAPS_TEXTURE = 0x1000; var DDSCAPS2_CUBEMAP = 0x200; // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, // DDSCAPS2_VOLUME = 0x200000; var //DDPF_ALPHAPIXELS = 0x1, //DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, //DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000; function FourCCToInt32(value) { return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24); } function Int32ToFourCC(value) { return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff); } var FOURCC_DXT1 = FourCCToInt32("DXT1"); var FOURCC_DXT3 = FourCCToInt32("DXT3"); var FOURCC_DXT5 = FourCCToInt32("DXT5"); var FOURCC_DX10 = FourCCToInt32("DX10"); var FOURCC_D3DFMT_R16G16B16A16F = 113; var FOURCC_D3DFMT_R32G32B32A32F = 116; var DXGI_FORMAT_R16G16B16A16_FLOAT = 10; var DXGI_FORMAT_B8G8R8X8_UNORM = 88; var headerLengthInt = 31; // The header length in 32 bit ints // Offsets into the header array var off_magic = 0; var off_size = 1; var off_flags = 2; var off_height = 3; var off_width = 4; var off_mipmapCount = 7; var off_pfFlags = 20; var off_pfFourCC = 21; var off_RGBbpp = 22; // var off_RMask = 23; // var off_GMask = 24; // var off_BMask = 25; // var off_AMask = 26; // var off_caps1 = 27; var off_caps2 = 28; // var off_caps3 = 29; // var off_caps4 = 30; var off_dxgiFormat = 32; ; var DDSTools = /** @class */ (function () { function DDSTools() { } DDSTools.GetDDSInfo = function (arrayBuffer) { var header = new Int32Array(arrayBuffer, 0, headerLengthInt); var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4); var mipmapCount = 1; if (header[off_flags] & DDSD_MIPMAPCOUNT) { mipmapCount = Math.max(1, header[off_mipmapCount]); } var fourCC = header[off_pfFourCC]; var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0; var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; switch (fourCC) { case FOURCC_D3DFMT_R16G16B16A16F: textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT; break; case FOURCC_D3DFMT_R32G32B32A32F: textureType = BABYLON.Engine.TEXTURETYPE_FLOAT; break; case FOURCC_DX10: if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) { textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT; break; } } return { width: header[off_width], height: header[off_height], mipmapCount: mipmapCount, isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC, isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB, isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE, isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP, isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5), dxgiFormat: dxgiFormat, textureType: textureType }; }; DDSTools._ToHalfFloat = function (value) { if (!DDSTools._FloatView) { DDSTools._FloatView = new Float32Array(1); DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer); } DDSTools._FloatView[0] = value; var x = DDSTools._Int32View[0]; var bits = (x >> 16) & 0x8000; /* Get the sign */ var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */ var e = (x >> 23) & 0xff; /* Using int is faster here */ /* If zero, or denormal, or exponent underflows too much for a denormal * half, return signed zero. */ if (e < 103) { return bits; } /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */ if (e > 142) { bits |= 0x7c00; /* If exponent was 0xff and one mantissa bit was set, it means NaN, * not Inf, so make sure we set one mantissa bit too. */ bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff); return bits; } /* If exponent underflows but not too much, return a denormal */ if (e < 113) { m |= 0x0800; /* Extra rounding may overflow and set mantissa to 0 and exponent * to 1, which is OK. */ bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1); return bits; } bits |= ((e - 112) << 10) | (m >> 1); bits += m & 1; return bits; }; DDSTools._FromHalfFloat = function (value) { var s = (value & 0x8000) >> 15; var e = (value & 0x7C00) >> 10; var f = value & 0x03FF; if (e === 0) { return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10)); } else if (e == 0x1F) { return f ? NaN : ((s ? -1 : 1) * Infinity); } return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10))); }; DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) { var destArray = new Float32Array(dataLength); var srcData = new Uint16Array(arrayBuffer, dataOffset); var index = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var srcPos = (x + y * width) * 4; destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]); destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]); destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]); if (DDSTools.StoreLODInAlphaChannel) { destArray[index + 3] = lod; } else { destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]); } index += 4; } } return destArray; }; DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) { if (DDSTools.StoreLODInAlphaChannel) { var destArray = new Uint16Array(dataLength); var srcData = new Uint16Array(arrayBuffer, dataOffset); var index = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var srcPos = (x + y * width) * 4; destArray[index] = srcData[srcPos]; destArray[index + 1] = srcData[srcPos + 1]; destArray[index + 2] = srcData[srcPos + 2]; destArray[index + 3] = DDSTools._ToHalfFloat(lod); index += 4; } } return destArray; } return new Uint16Array(arrayBuffer, dataOffset, dataLength); }; DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) { if (DDSTools.StoreLODInAlphaChannel) { var destArray = new Float32Array(dataLength); var srcData = new Float32Array(arrayBuffer, dataOffset); var index = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var srcPos = (x + y * width) * 4; destArray[index] = srcData[srcPos]; destArray[index + 1] = srcData[srcPos + 1]; destArray[index + 2] = srcData[srcPos + 2]; destArray[index + 3] = lod; index += 4; } } return destArray; } return new Float32Array(arrayBuffer, dataOffset, dataLength); }; DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) { var destArray = new Uint8Array(dataLength); var srcData = new Float32Array(arrayBuffer, dataOffset); var index = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var srcPos = (x + y * width) * 4; destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255; destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255; destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255; if (DDSTools.StoreLODInAlphaChannel) { destArray[index + 3] = lod; } else { destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255; } index += 4; } } return destArray; }; DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) { var destArray = new Uint8Array(dataLength); var srcData = new Uint16Array(arrayBuffer, dataOffset); var index = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var srcPos = (x + y * width) * 4; destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255; destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255; destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255; if (DDSTools.StoreLODInAlphaChannel) { destArray[index + 3] = lod; } else { destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255; } index += 4; } } return destArray; }; DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) { var byteArray = new Uint8Array(dataLength); var srcData = new Uint8Array(arrayBuffer, dataOffset); var index = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var srcPos = (x + y * width) * 4; byteArray[index] = srcData[srcPos + 2]; byteArray[index + 1] = srcData[srcPos + 1]; byteArray[index + 2] = srcData[srcPos]; byteArray[index + 3] = srcData[srcPos + 3]; index += 4; } } return byteArray; }; DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) { var byteArray = new Uint8Array(dataLength); var srcData = new Uint8Array(arrayBuffer, dataOffset); var index = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var srcPos = (x + y * width) * 3; byteArray[index] = srcData[srcPos + 2]; byteArray[index + 1] = srcData[srcPos + 1]; byteArray[index + 2] = srcData[srcPos]; index += 3; } } return byteArray; }; DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) { var byteArray = new Uint8Array(dataLength); var srcData = new Uint8Array(arrayBuffer, dataOffset); var index = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var srcPos = (x + y * width); byteArray[index] = srcData[srcPos]; index++; } } return byteArray; }; DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) { if (lodIndex === void 0) { lodIndex = -1; } var ext = engine.getCaps().s3tc; var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip; var internalFormat = 0; var format = 0; var blockBytes = 1; if (header[off_magic] != DDS_MAGIC) { BABYLON.Tools.Error("Invalid magic number in DDS header"); return; } if (!info.isFourCC && !info.isRGB && !info.isLuminance) { BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code"); return; } if (info.isCompressed && !ext) { BABYLON.Tools.Error("Compressed textures are not supported on this platform."); return; } var bpp = header[off_RGBbpp]; dataOffset = header[off_size] + 4; var computeFormats = false; if (info.isFourCC && ext) { fourCC = header[off_pfFourCC]; switch (fourCC) { case FOURCC_DXT1: blockBytes = 8; internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT; break; case FOURCC_DXT3: blockBytes = 16; internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT; break; case FOURCC_DXT5: blockBytes = 16; internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT; break; case FOURCC_D3DFMT_R16G16B16A16F: computeFormats = true; break; case FOURCC_D3DFMT_R32G32B32A32F: computeFormats = true; break; case FOURCC_DX10: // There is an additionnal header so dataOffset need to be changed dataOffset += 5 * 4; // 5 uints var supported = false; switch (info.dxgiFormat) { case DXGI_FORMAT_R16G16B16A16_FLOAT: computeFormats = true; supported = true; break; case DXGI_FORMAT_B8G8R8X8_UNORM: info.isRGB = true; info.isFourCC = false; bpp = 32; supported = true; break; } if (supported) { break; } default: console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC)); return; } } if (computeFormats) { format = engine._getWebGLTextureType(info.textureType); internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType); } mipmapCount = 1; if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) { mipmapCount = Math.max(1, header[off_mipmapCount]); } for (var face = 0; face < faces; face++) { var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face); width = header[off_width]; height = header[off_height]; for (mip = 0; mip < mipmapCount; ++mip) { if (lodIndex === -1 || lodIndex === mip) { // In case of fixed LOD, if the lod has just been uploaded, early exit. var i = (lodIndex === -1) ? mip : 0; if (!info.isCompressed && info.isFourCC) { dataLength = width * height * 4; var FloatArray = null; if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { if (bpp === 128) { FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i); } else if (bpp === 64) { FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i); } info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; format = engine._getWebGLTextureType(info.textureType); internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType); } else { if (bpp === 128) { FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i); } else if (bpp === 64 && !engine.getCaps().textureHalfFloat) { FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i); info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT; format = engine._getWebGLTextureType(info.textureType); internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType); } else { FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i); } } if (FloatArray) { engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray); } } else if (info.isRGB) { if (bpp === 24) { dataLength = width * height * 3; byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray); } else { dataLength = width * height * 4; byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray); } } else if (info.isLuminance) { var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT); var unpaddedRowSize = width; var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment; dataLength = paddedRowSize * (height - 1) + unpaddedRowSize; byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray); } else { dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes; byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength); engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray); } } dataOffset += width * height * (bpp / 8); width *= 0.5; height *= 0.5; width = Math.max(1.0, width); height = Math.max(1.0, height); } } }; DDSTools.StoreLODInAlphaChannel = false; return DDSTools; }()); Internals.DDSTools = DDSTools; })(Internals = BABYLON.Internals || (BABYLON.Internals = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.dds.js.map var BABYLON; (function (BABYLON) { var Internals; (function (Internals) { /** * 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/ */ var KhronosTextureContainer = /** @class */ (function () { /** * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented */ function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) { this.arrayBuffer = arrayBuffer; // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is: // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n' // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A var identifier = new Uint8Array(this.arrayBuffer, 0, 12); if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 || identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) { BABYLON.Tools.Error("texture missing KTX identifier"); return; } // load the reset of the header in native 32 bit int var header = new Int32Array(this.arrayBuffer, 12, 13); // determine of the remaining header values are recorded in the opposite endianness & require conversion var oppositeEndianess = header[0] === 0x01020304; // read all the header elements in order they exist in the file, without modification (sans endainness) this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,) this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only) this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,) this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,) this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,) this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6 this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing. if (this.glType !== 0) { BABYLON.Tools.Error("only compressed formats currently supported"); return; } else { // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels); } if (this.pixelHeight === 0 || this.pixelDepth !== 0) { BABYLON.Tools.Error("only 2D textures currently supported"); return; } if (this.numberOfArrayElements !== 0) { BABYLON.Tools.Error("texture arrays not currently supported"); return; } if (this.numberOfFaces !== facesExpected) { BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces); return; } // we now have a completely validated file, so could use existence of loadType as success // would need to make this more elaborate & adjust checks above to support more than one load type this.loadType = KhronosTextureContainer.COMPRESSED_2D; } // not as fast hardware based, but will probably never need to use KhronosTextureContainer.prototype.switchEndainness = function (val) { return ((val & 0xFF) << 24) | ((val & 0xFF00) << 8) | ((val >> 8) & 0xFF00) | ((val >> 24) & 0xFF); }; /** * It is assumed that the texture has already been created & is currently bound */ KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) { switch (this.loadType) { case KhronosTextureContainer.COMPRESSED_2D: this._upload2DCompressedLevels(gl, loadMipmaps); break; case KhronosTextureContainer.TEX_2D: case KhronosTextureContainer.COMPRESSED_3D: case KhronosTextureContainer.TEX_3D: } }; KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) { // initialize width & height for level 1 var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData; var width = this.pixelWidth; var height = this.pixelHeight; var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1; for (var level = 0; level < mipmapCount; level++) { var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps for (var face = 0; face < this.numberOfFaces; face++) { var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face); var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize); gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray); dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image } width = Math.max(1.0, width * 0.5); height = Math.max(1.0, height * 0.5); } }; KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs) // load types KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D() KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D() KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D() KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D() return KhronosTextureContainer; }()); Internals.KhronosTextureContainer = KhronosTextureContainer; })(Internals = BABYLON.Internals || (BABYLON.Internals = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.khronosTextureContainer.js.map var BABYLON; (function (BABYLON) { var Debug; (function (Debug) { /** * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8 */ var SkeletonViewer = /** @class */ (function () { function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) { if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; } if (renderingGroupId === void 0) { renderingGroupId = 1; } this.skeleton = skeleton; this.mesh = mesh; this.autoUpdateBonesMatrices = autoUpdateBonesMatrices; this.renderingGroupId = renderingGroupId; this.color = BABYLON.Color3.White(); this._debugLines = new Array(); this._isEnabled = false; this._scene = scene; this.update(); this._renderFunction = this.update.bind(this); } Object.defineProperty(SkeletonViewer.prototype, "isEnabled", { get: function () { return this._isEnabled; }, set: function (value) { if (this._isEnabled === value) { return; } this._isEnabled = value; if (value) { this._scene.registerBeforeRender(this._renderFunction); } else { this._scene.unregisterBeforeRender(this._renderFunction); } }, enumerable: true, configurable: true }); SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) { if (x === void 0) { x = 0; } if (y === void 0) { y = 0; } if (z === void 0) { z = 0; } var tmat = BABYLON.Tmp.Matrix[0]; var parentBone = bone.getParent(); tmat.copyFrom(bone.getLocalMatrix()); if (x !== 0 || y !== 0 || z !== 0) { var tmat2 = BABYLON.Tmp.Matrix[1]; BABYLON.Matrix.IdentityToRef(tmat2); tmat2.m[12] = x; tmat2.m[13] = y; tmat2.m[14] = z; tmat2.multiplyToRef(tmat, tmat); } if (parentBone) { tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat); } tmat.multiplyToRef(meshMat, tmat); position.x = tmat.m[12]; position.y = tmat.m[13]; position.z = tmat.m[14]; }; SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) { var len = bones.length; var meshPos = this.mesh.position; for (var i = 0; i < len; i++) { var bone = bones[i]; var points = this._debugLines[i]; if (!points) { points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()]; this._debugLines[i] = points; } this._getBonePosition(points[0], bone, meshMat); this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0); points[0].subtractInPlace(meshPos); points[1].subtractInPlace(meshPos); } }; SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) { var len = bones.length; var boneNum = 0; var meshPos = this.mesh.position; for (var i = len - 1; i >= 0; i--) { var childBone = bones[i]; var parentBone = childBone.getParent(); if (!parentBone) { continue; } var points = this._debugLines[boneNum]; if (!points) { points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()]; this._debugLines[boneNum] = points; } childBone.getAbsolutePositionToRef(this.mesh, points[0]); parentBone.getAbsolutePositionToRef(this.mesh, points[1]); points[0].subtractInPlace(meshPos); points[1].subtractInPlace(meshPos); boneNum++; } }; SkeletonViewer.prototype.update = function () { if (this.autoUpdateBonesMatrices) { this.skeleton.computeAbsoluteTransforms(); } if (this.skeleton.bones[0].length === undefined) { this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix()); } else { this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix()); } if (!this._debugMesh) { this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene); this._debugMesh.renderingGroupId = this.renderingGroupId; } else { BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene); } this._debugMesh.position.copyFrom(this.mesh.position); this._debugMesh.color = this.color; }; SkeletonViewer.prototype.dispose = function () { if (this._debugMesh) { this.isEnabled = false; this._debugMesh.dispose(); this._debugMesh = null; } }; return SkeletonViewer; }()); Debug.SkeletonViewer = SkeletonViewer; })(Debug = BABYLON.Debug || (BABYLON.Debug = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.skeletonViewer.js.map var BABYLON; (function (BABYLON) { var Debug; (function (Debug) { var AxesViewer = /** @class */ (function () { function AxesViewer(scene, scaleLines) { if (scaleLines === void 0) { scaleLines = 1; } this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()]; this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()]; this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()]; this.scaleLines = 1; this.scaleLines = scaleLines; this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true); this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true); this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true); this._xmesh.renderingGroupId = 2; this._ymesh.renderingGroupId = 2; this._zmesh.renderingGroupId = 2; this._xmesh.material.checkReadyOnlyOnce = true; this._xmesh.color = new BABYLON.Color3(1, 0, 0); this._ymesh.material.checkReadyOnlyOnce = true; this._ymesh.color = new BABYLON.Color3(0, 1, 0); this._zmesh.material.checkReadyOnlyOnce = true; this._zmesh.color = new BABYLON.Color3(0, 0, 1); this.scene = scene; } AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) { var scaleLines = this.scaleLines; if (this._xmesh) { this._xmesh.position.copyFrom(position); } if (this._ymesh) { this._ymesh.position.copyFrom(position); } if (this._zmesh) { this._zmesh.position.copyFrom(position); } var point2 = this._xline[1]; point2.x = xaxis.x * scaleLines; point2.y = xaxis.y * scaleLines; point2.z = xaxis.z * scaleLines; BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh); point2 = this._yline[1]; point2.x = yaxis.x * scaleLines; point2.y = yaxis.y * scaleLines; point2.z = yaxis.z * scaleLines; BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh); point2 = this._zline[1]; point2.x = zaxis.x * scaleLines; point2.y = zaxis.y * scaleLines; point2.z = zaxis.z * scaleLines; BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh); }; AxesViewer.prototype.dispose = function () { if (this._xmesh) { this._xmesh.dispose(); } if (this._ymesh) { this._ymesh.dispose(); } if (this._zmesh) { this._zmesh.dispose(); } this._xmesh = null; this._ymesh = null; this._zmesh = null; this.scene = null; }; return AxesViewer; }()); Debug.AxesViewer = AxesViewer; })(Debug = BABYLON.Debug || (BABYLON.Debug = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.axesViewer.js.map var BABYLON; (function (BABYLON) { var Debug; (function (Debug) { var BoneAxesViewer = /** @class */ (function (_super) { __extends(BoneAxesViewer, _super); function BoneAxesViewer(scene, bone, mesh, scaleLines) { if (scaleLines === void 0) { scaleLines = 1; } var _this = _super.call(this, scene, scaleLines) || this; _this.pos = BABYLON.Vector3.Zero(); _this.xaxis = BABYLON.Vector3.Zero(); _this.yaxis = BABYLON.Vector3.Zero(); _this.zaxis = BABYLON.Vector3.Zero(); _this.mesh = mesh; _this.bone = bone; return _this; } BoneAxesViewer.prototype.update = function () { if (!this.mesh || !this.bone) { return; } var bone = this.bone; bone.getAbsolutePositionToRef(this.mesh, this.pos); bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis); bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis); bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis); _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis); }; BoneAxesViewer.prototype.dispose = function () { if (this.mesh) { this.mesh = null; this.bone = null; _super.prototype.dispose.call(this); } }; return BoneAxesViewer; }(Debug.AxesViewer)); Debug.BoneAxesViewer = BoneAxesViewer; })(Debug = BABYLON.Debug || (BABYLON.Debug = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.boneAxesViewer.js.map var BABYLON; (function (BABYLON) { var RayHelper = /** @class */ (function () { function RayHelper(ray) { this.ray = ray; } RayHelper.CreateAndShow = function (ray, scene, color) { var helper = new RayHelper(ray); helper.show(scene, color); return helper; }; RayHelper.prototype.show = function (scene, color) { if (!this._renderFunction && this.ray) { var ray = this.ray; this._renderFunction = this._render.bind(this); this._scene = scene; this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))]; this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true); if (this._renderFunction) { this._scene.registerBeforeRender(this._renderFunction); } } if (color && this._renderLine) { this._renderLine.color.copyFrom(color); } }; RayHelper.prototype.hide = function () { if (this._renderFunction && this._scene) { this._scene.unregisterBeforeRender(this._renderFunction); this._scene = null; this._renderFunction = null; if (this._renderLine) { this._renderLine.dispose(); this._renderLine = null; } this._renderPoints = []; } }; RayHelper.prototype._render = function () { var ray = this.ray; if (!ray) { return; } var point = this._renderPoints[1]; var len = Math.min(ray.length, 1000000); point.copyFrom(ray.direction); point.scaleInPlace(len); point.addInPlace(ray.origin); BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine); }; RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) { this._attachedToMesh = mesh; var ray = this.ray; if (!ray) { return; } if (!ray.direction) { ray.direction = BABYLON.Vector3.Zero(); } if (!ray.origin) { ray.origin = BABYLON.Vector3.Zero(); } if (length) { ray.length = length; } if (!meshSpaceOrigin) { meshSpaceOrigin = BABYLON.Vector3.Zero(); } if (!meshSpaceDirection) { // -1 so that this will work with Mesh.lookAt meshSpaceDirection = new BABYLON.Vector3(0, 0, -1); } if (!this._meshSpaceDirection) { this._meshSpaceDirection = meshSpaceDirection.clone(); this._meshSpaceOrigin = meshSpaceOrigin.clone(); } else { this._meshSpaceDirection.copyFrom(meshSpaceDirection); this._meshSpaceOrigin.copyFrom(meshSpaceOrigin); } if (!this._updateToMeshFunction) { this._updateToMeshFunction = this._updateToMesh.bind(this); this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction); } this._updateToMesh(); }; RayHelper.prototype.detachFromMesh = function () { if (this._attachedToMesh) { if (this._updateToMeshFunction) { this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction); } this._attachedToMesh = null; this._updateToMeshFunction = null; } }; RayHelper.prototype._updateToMesh = function () { var ray = this.ray; if (!this._attachedToMesh || !ray) { return; } if (this._attachedToMesh._isDisposed) { this.detachFromMesh(); return; } this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction); BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin); }; RayHelper.prototype.dispose = function () { this.hide(); this.detachFromMesh(); this.ray = null; }; return RayHelper; }()); BABYLON.RayHelper = RayHelper; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.rayHelper.js.map var BABYLON; (function (BABYLON) { var DebugLayer = /** @class */ (function () { function DebugLayer(scene) { this._scene = scene; } /** Creates the inspector window. */ DebugLayer.prototype._createInspector = function (config) { if (config === void 0) { config = {}; } var popup = config.popup || false; var initialTab = config.initialTab || 0; var parentElement = config.parentElement || null; if (!this._inspector) { this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors); } // else nothing to do,; instance is already existing }; DebugLayer.prototype.isVisible = function () { if (!this._inspector) { return false; } return true; }; DebugLayer.prototype.hide = function () { if (this._inspector) { try { this._inspector.dispose(); } catch (e) { // If the inspector has been removed directly from the inspector tool } this._inspector = null; } }; DebugLayer.prototype.show = function (config) { if (config === void 0) { config = {}; } if (typeof INSPECTOR == 'undefined') { // Load inspector and add it to the DOM BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config)); } else { // Otherwise creates the inspector this._createInspector(config); } }; DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js'; return DebugLayer; }()); BABYLON.DebugLayer = DebugLayer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.debugLayer.js.map var BABYLON; (function (BABYLON) { var Debug; (function (Debug) { var PhysicsViewer = /** @class */ (function () { function PhysicsViewer(scene) { this._impostors = []; this._meshes = []; this._numMeshes = 0; this._scene = scene || BABYLON.Engine.LastCreatedScene; var physicEngine = this._scene.getPhysicsEngine(); if (physicEngine) { this._physicsEnginePlugin = physicEngine.getPhysicsPlugin(); } } PhysicsViewer.prototype._updateDebugMeshes = function () { var plugin = this._physicsEnginePlugin; for (var i = 0; i < this._numMeshes; i++) { var impostor = this._impostors[i]; if (!impostor) { continue; } if (impostor.isDisposed) { this.hideImpostor(this._impostors[i--]); } else { var mesh = this._meshes[i]; if (mesh && plugin) { plugin.syncMeshWithImpostor(mesh, impostor); } } } }; PhysicsViewer.prototype.showImpostor = function (impostor) { if (!this._scene) { return; } for (var i = 0; i < this._numMeshes; i++) { if (this._impostors[i] == impostor) { return; } } var debugMesh = this._getDebugMesh(impostor, this._scene); if (debugMesh) { this._impostors[this._numMeshes] = impostor; this._meshes[this._numMeshes] = debugMesh; if (this._numMeshes === 0) { this._renderFunction = this._updateDebugMeshes.bind(this); this._scene.registerBeforeRender(this._renderFunction); } this._numMeshes++; } }; PhysicsViewer.prototype.hideImpostor = function (impostor) { if (!impostor || !this._scene) { return; } var removed = false; for (var i = 0; i < this._numMeshes; i++) { if (this._impostors[i] == impostor) { var mesh = this._meshes[i]; if (!mesh) { continue; } this._scene.removeMesh(mesh); mesh.dispose(); this._numMeshes--; if (this._numMeshes > 0) { this._meshes[i] = this._meshes[this._numMeshes]; this._impostors[i] = this._impostors[this._numMeshes]; this._meshes[this._numMeshes] = null; this._impostors[this._numMeshes] = null; } else { this._meshes[0] = null; this._impostors[0] = null; } removed = true; break; } } if (removed && this._numMeshes === 0) { this._scene.unregisterBeforeRender(this._renderFunction); } }; PhysicsViewer.prototype._getDebugMaterial = function (scene) { if (!this._debugMaterial) { this._debugMaterial = new BABYLON.StandardMaterial('', scene); this._debugMaterial.wireframe = true; } return this._debugMaterial; }; PhysicsViewer.prototype._getDebugBoxMesh = function (scene) { if (!this._debugBoxMesh) { this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene); this._debugBoxMesh.renderingGroupId = 1; this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity(); this._debugBoxMesh.material = this._getDebugMaterial(scene); scene.removeMesh(this._debugBoxMesh); } return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance'); }; PhysicsViewer.prototype._getDebugSphereMesh = function (scene) { if (!this._debugSphereMesh) { this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene); this._debugSphereMesh.renderingGroupId = 1; this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity(); this._debugSphereMesh.material = this._getDebugMaterial(scene); scene.removeMesh(this._debugSphereMesh); } return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance'); }; PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) { var mesh = null; if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) { mesh = this._getDebugBoxMesh(scene); impostor.getBoxSizeToRef(mesh.scaling); } else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) { mesh = this._getDebugSphereMesh(scene); var radius = impostor.getRadius(); mesh.scaling.x = radius * 2; mesh.scaling.y = radius * 2; mesh.scaling.z = radius * 2; } return mesh; }; PhysicsViewer.prototype.dispose = function () { for (var i = 0; i < this._numMeshes; i++) { this.hideImpostor(this._impostors[i]); } if (this._debugBoxMesh) { this._debugBoxMesh.dispose(); } if (this._debugSphereMesh) { this._debugSphereMesh.dispose(); } if (this._debugMaterial) { this._debugMaterial.dispose(); } this._impostors.length = 0; this._scene = null; this._physicsEnginePlugin = null; }; return PhysicsViewer; }()); Debug.PhysicsViewer = PhysicsViewer; })(Debug = BABYLON.Debug || (BABYLON.Debug = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.physicsViewer.js.map var BABYLON; (function (BABYLON) { var BoundingBoxRenderer = /** @class */ (function () { function BoundingBoxRenderer(scene) { this.frontColor = new BABYLON.Color3(1, 1, 1); this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1); this.showBackLines = true; this.renderList = new BABYLON.SmartArray(32); this._vertexBuffers = {}; this._scene = scene; } BoundingBoxRenderer.prototype._prepareRessources = function () { if (this._colorShader) { return; } this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", { attributes: [BABYLON.VertexBuffer.PositionKind], uniforms: ["world", "viewProjection", "color"] }); var engine = this._scene.getEngine(); var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 }); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false); this._createIndexBuffer(); }; BoundingBoxRenderer.prototype._createIndexBuffer = function () { var engine = this._scene.getEngine(); this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]); }; BoundingBoxRenderer.prototype._rebuild = function () { var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]; if (vb) { vb._rebuild(); } this._createIndexBuffer(); }; BoundingBoxRenderer.prototype.reset = function () { this.renderList.reset(); }; BoundingBoxRenderer.prototype.render = function () { if (this.renderList.length === 0) { return; } this._prepareRessources(); if (!this._colorShader.isReady()) { return; } var engine = this._scene.getEngine(); engine.setDepthWrite(false); this._colorShader._preBind(); for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) { var boundingBox = this.renderList.data[boundingBoxIndex]; var min = boundingBox.minimum; var max = boundingBox.maximum; var diff = max.subtract(min); var median = min.add(diff.scale(0.5)); var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z) .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)) .multiply(boundingBox.getWorldMatrix()); // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect()); if (this.showBackLines) { // Back engine.setDepthFunctionToGreaterOrEqual(); this._scene.resetCachedMaterial(); this._colorShader.setColor4("color", this.backColor.toColor4()); this._colorShader.bind(worldMatrix); // Draw order engine.draw(false, 0, 24); } // Front engine.setDepthFunctionToLess(); this._scene.resetCachedMaterial(); this._colorShader.setColor4("color", this.frontColor.toColor4()); this._colorShader.bind(worldMatrix); // Draw order engine.draw(false, 0, 24); } this._colorShader.unbind(); engine.setDepthFunctionToLessOrEqual(); engine.setDepthWrite(true); }; BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) { this._prepareRessources(); if (!this._colorShader.isReady() || !mesh._boundingInfo) { return; } var engine = this._scene.getEngine(); engine.setDepthWrite(false); engine.setColorWrite(false); this._colorShader._preBind(); var boundingBox = mesh._boundingInfo.boundingBox; var min = boundingBox.minimum; var max = boundingBox.maximum; var diff = max.subtract(min); var median = min.add(diff.scale(0.5)); var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z) .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)) .multiply(boundingBox.getWorldMatrix()); engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect()); engine.setDepthFunctionToLess(); this._scene.resetCachedMaterial(); this._colorShader.bind(worldMatrix); engine.draw(false, 0, 24); this._colorShader.unbind(); engine.setDepthFunctionToLessOrEqual(); engine.setDepthWrite(true); engine.setColorWrite(true); }; BoundingBoxRenderer.prototype.dispose = function () { if (!this._colorShader) { return; } this.renderList.dispose(); this._colorShader.dispose(); var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]; if (buffer) { buffer.dispose(); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null; } this._scene.getEngine()._releaseBuffer(this._indexBuffer); }; return BoundingBoxRenderer; }()); BABYLON.BoundingBoxRenderer = BoundingBoxRenderer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.boundingBoxRenderer.js.map var BABYLON; (function (BABYLON) { var MorphTarget = /** @class */ (function () { function MorphTarget(name, influence) { if (influence === void 0) { influence = 0; } this.name = name; this.animations = new Array(); this.onInfluenceChanged = new BABYLON.Observable(); this.influence = influence; } Object.defineProperty(MorphTarget.prototype, "influence", { get: function () { return this._influence; }, set: function (influence) { if (this._influence === influence) { return; } var previous = this._influence; this._influence = influence; if (this.onInfluenceChanged.hasObservers) { this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0); } }, enumerable: true, configurable: true }); Object.defineProperty(MorphTarget.prototype, "hasNormals", { get: function () { return this._normals !== undefined; }, enumerable: true, configurable: true }); Object.defineProperty(MorphTarget.prototype, "hasTangents", { get: function () { return this._tangents !== undefined; }, enumerable: true, configurable: true }); MorphTarget.prototype.setPositions = function (data) { this._positions = new Float32Array(data); }; MorphTarget.prototype.getPositions = function () { return this._positions; }; MorphTarget.prototype.setNormals = function (data) { this._normals = new Float32Array(data); }; MorphTarget.prototype.getNormals = function () { return this._normals; }; MorphTarget.prototype.setTangents = function (data) { this._tangents = new Float32Array(data); }; MorphTarget.prototype.getTangents = function () { return this._tangents; }; /** * Serializes the current target into a Serialization object. * Returns the serialized object. */ MorphTarget.prototype.serialize = function () { var serializationObject = {}; serializationObject.name = this.name; serializationObject.influence = this.influence; serializationObject.positions = Array.prototype.slice.call(this.getPositions()); if (this.hasNormals) { serializationObject.normals = Array.prototype.slice.call(this.getNormals()); } if (this.hasTangents) { serializationObject.tangents = Array.prototype.slice.call(this.getTangents()); } // Animations BABYLON.Animation.AppendSerializedAnimations(this, serializationObject); return serializationObject; }; // Statics MorphTarget.Parse = function (serializationObject) { var result = new MorphTarget(serializationObject.name, serializationObject.influence); result.setPositions(serializationObject.positions); if (serializationObject.normals) { result.setNormals(serializationObject.normals); } if (serializationObject.tangents) { result.setTangents(serializationObject.tangents); } // Animations if (serializationObject.animations) { for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) { var parsedAnimation = serializationObject.animations[animationIndex]; result.animations.push(BABYLON.Animation.Parse(parsedAnimation)); } } return result; }; MorphTarget.FromMesh = function (mesh, name, influence) { if (!name) { name = mesh.name; } var result = new MorphTarget(name, influence); result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind)); if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) { result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind)); } if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) { result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind)); } return result; }; return MorphTarget; }()); BABYLON.MorphTarget = MorphTarget; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.morphTarget.js.map var BABYLON; (function (BABYLON) { var MorphTargetManager = /** @class */ (function () { function MorphTargetManager(scene) { if (scene === void 0) { scene = null; } this._targets = new Array(); this._targetObservable = new Array(); this._activeTargets = new BABYLON.SmartArray(16); this._supportsNormals = false; this._supportsTangents = false; this._vertexCount = 0; this._uniqueId = 0; this._tempInfluences = new Array(); if (!scene) { scene = BABYLON.Engine.LastCreatedScene; } this._scene = scene; if (this._scene) { this._scene.morphTargetManagers.push(this); this._uniqueId = this._scene.getUniqueId(); } } Object.defineProperty(MorphTargetManager.prototype, "uniqueId", { get: function () { return this._uniqueId; }, enumerable: true, configurable: true }); Object.defineProperty(MorphTargetManager.prototype, "vertexCount", { get: function () { return this._vertexCount; }, enumerable: true, configurable: true }); Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", { get: function () { return this._supportsNormals; }, enumerable: true, configurable: true }); Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", { get: function () { return this._supportsTangents; }, enumerable: true, configurable: true }); Object.defineProperty(MorphTargetManager.prototype, "numTargets", { get: function () { return this._targets.length; }, enumerable: true, configurable: true }); Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", { get: function () { return this._activeTargets.length; }, enumerable: true, configurable: true }); Object.defineProperty(MorphTargetManager.prototype, "influences", { get: function () { return this._influences; }, enumerable: true, configurable: true }); MorphTargetManager.prototype.getActiveTarget = function (index) { return this._activeTargets.data[index]; }; MorphTargetManager.prototype.getTarget = function (index) { return this._targets[index]; }; MorphTargetManager.prototype.addTarget = function (target) { var _this = this; if (this._vertexCount) { if (this._vertexCount !== target.getPositions().length / 3) { BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count."); return; } } this._targets.push(target); this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) { _this._syncActiveTargets(needUpdate); })); this._syncActiveTargets(true); }; MorphTargetManager.prototype.removeTarget = function (target) { var index = this._targets.indexOf(target); if (index >= 0) { this._targets.splice(index, 1); target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]); this._vertexCount = 0; this._syncActiveTargets(true); } }; /** * Serializes the current manager into a Serialization object. * Returns the serialized object. */ MorphTargetManager.prototype.serialize = function () { var serializationObject = {}; serializationObject.id = this.uniqueId; serializationObject.targets = []; for (var _i = 0, _a = this._targets; _i < _a.length; _i++) { var target = _a[_i]; serializationObject.targets.push(target.serialize()); } return serializationObject; }; MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) { var influenceCount = 0; this._activeTargets.reset(); this._supportsNormals = true; this._supportsTangents = true; for (var _i = 0, _a = this._targets; _i < _a.length; _i++) { var target = _a[_i]; if (target.influence > 0) { this._activeTargets.push(target); this._tempInfluences[influenceCount++] = target.influence; this._supportsNormals = this._supportsNormals && target.hasNormals; this._supportsTangents = this._supportsTangents && target.hasTangents; if (this._vertexCount === 0) { this._vertexCount = target.getPositions().length / 3; } } } if (!this._influences || this._influences.length !== influenceCount) { this._influences = new Float32Array(influenceCount); } for (var index = 0; index < influenceCount; index++) { this._influences[index] = this._tempInfluences[index]; } if (needUpdate && this._scene) { // Flag meshes as dirty to resync with the active targets for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) { var mesh = _c[_b]; if (mesh.morphTargetManager === this) { mesh._syncGeometryWithMorphTargetManager(); } } } }; // Statics MorphTargetManager.Parse = function (serializationObject, scene) { var result = new MorphTargetManager(scene); result._uniqueId = serializationObject.id; for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) { var targetData = _a[_i]; result.addTarget(BABYLON.MorphTarget.Parse(targetData)); } return result; }; return MorphTargetManager; }()); BABYLON.MorphTargetManager = MorphTargetManager; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.morphTargetManager.js.map var BABYLON; (function (BABYLON) { var Octree = /** @class */ (function () { function Octree(creationFunc, maxBlockCapacity, maxDepth) { if (maxDepth === void 0) { maxDepth = 2; } this.maxDepth = maxDepth; this.dynamicContent = new Array(); this._maxBlockCapacity = maxBlockCapacity || 64; this._selectionContent = new BABYLON.SmartArray(1024); this._creationFunc = creationFunc; } // Methods Octree.prototype.update = function (worldMin, worldMax, entries) { Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc); }; Octree.prototype.addMesh = function (entry) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.addEntry(entry); } }; Octree.prototype.select = function (frustumPlanes, allowDuplicate) { this._selectionContent.reset(); for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.select(frustumPlanes, this._selectionContent, allowDuplicate); } if (allowDuplicate) { this._selectionContent.concat(this.dynamicContent); } else { this._selectionContent.concatWithNoDuplicate(this.dynamicContent); } return this._selectionContent; }; Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) { this._selectionContent.reset(); for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate); } if (allowDuplicate) { this._selectionContent.concat(this.dynamicContent); } else { this._selectionContent.concatWithNoDuplicate(this.dynamicContent); } return this._selectionContent; }; Octree.prototype.intersectsRay = function (ray) { this._selectionContent.reset(); for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.intersectsRay(ray, this._selectionContent); } this._selectionContent.concatWithNoDuplicate(this.dynamicContent); return this._selectionContent; }; Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) { target.blocks = new Array(); var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2); // Segmenting space for (var x = 0; x < 2; x++) { for (var y = 0; y < 2; y++) { for (var z = 0; z < 2; z++) { var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z)); var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1)); var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc); block.addEntries(entries); target.blocks.push(block); } } } }; Octree.CreationFuncForMeshes = function (entry, block) { var boundingInfo = entry.getBoundingInfo(); if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) { block.entries.push(entry); } }; Octree.CreationFuncForSubMeshes = function (entry, block) { var boundingInfo = entry.getBoundingInfo(); if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) { block.entries.push(entry); } }; return Octree; }()); BABYLON.Octree = Octree; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.octree.js.map var BABYLON; (function (BABYLON) { var OctreeBlock = /** @class */ (function () { function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) { this.entries = new Array(); this._boundingVectors = new Array(); this._capacity = capacity; this._depth = depth; this._maxDepth = maxDepth; this._creationFunc = creationFunc; this._minPoint = minPoint; this._maxPoint = maxPoint; this._boundingVectors.push(minPoint.clone()); this._boundingVectors.push(maxPoint.clone()); this._boundingVectors.push(minPoint.clone()); this._boundingVectors[2].x = maxPoint.x; this._boundingVectors.push(minPoint.clone()); this._boundingVectors[3].y = maxPoint.y; this._boundingVectors.push(minPoint.clone()); this._boundingVectors[4].z = maxPoint.z; this._boundingVectors.push(maxPoint.clone()); this._boundingVectors[5].z = minPoint.z; this._boundingVectors.push(maxPoint.clone()); this._boundingVectors[6].x = minPoint.x; this._boundingVectors.push(maxPoint.clone()); this._boundingVectors[7].y = minPoint.y; } Object.defineProperty(OctreeBlock.prototype, "capacity", { // Property get: function () { return this._capacity; }, enumerable: true, configurable: true }); Object.defineProperty(OctreeBlock.prototype, "minPoint", { get: function () { return this._minPoint; }, enumerable: true, configurable: true }); Object.defineProperty(OctreeBlock.prototype, "maxPoint", { get: function () { return this._maxPoint; }, enumerable: true, configurable: true }); // Methods OctreeBlock.prototype.addEntry = function (entry) { if (this.blocks) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.addEntry(entry); } return; } this._creationFunc(entry, this); if (this.entries.length > this.capacity && this._depth < this._maxDepth) { this.createInnerBlocks(); } }; OctreeBlock.prototype.addEntries = function (entries) { for (var index = 0; index < entries.length; index++) { var mesh = entries[index]; this.addEntry(mesh); } }; OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) { if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) { if (this.blocks) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.select(frustumPlanes, selection, allowDuplicate); } return; } if (allowDuplicate) { selection.concat(this.entries); } else { selection.concatWithNoDuplicate(this.entries); } } }; OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) { if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) { if (this.blocks) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate); } return; } if (allowDuplicate) { selection.concat(this.entries); } else { selection.concatWithNoDuplicate(this.entries); } } }; OctreeBlock.prototype.intersectsRay = function (ray, selection) { if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) { if (this.blocks) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.intersectsRay(ray, selection); } return; } selection.concatWithNoDuplicate(this.entries); } }; OctreeBlock.prototype.createInnerBlocks = function () { BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc); }; return OctreeBlock; }()); BABYLON.OctreeBlock = OctreeBlock; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.octreeBlock.js.map var BABYLON; (function (BABYLON) { var SIMDVector3 = /** @class */ (function () { function SIMDVector3() { } SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) { SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result); }; SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) { var m = transformation.m; var m0 = SIMD.Float32x4.load(m, 0); var m1 = SIMD.Float32x4.load(m, 4); var m2 = SIMD.Float32x4.load(m, 8); var m3 = SIMD.Float32x4.load(m, 12); var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3)); r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3)); result.x = SIMD.Float32x4.extractLane(r, 0); result.y = SIMD.Float32x4.extractLane(r, 1); result.z = SIMD.Float32x4.extractLane(r, 2); }; return SIMDVector3; }()); var SIMDMatrix = /** @class */ (function () { function SIMDMatrix() { } SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) { var tm = this.m; var om = other.m; var m0 = SIMD.Float32x4.load(om, 0); var m1 = SIMD.Float32x4.load(om, 4); var m2 = SIMD.Float32x4.load(om, 8); var m3 = SIMD.Float32x4.load(om, 12); for (var i = 0; i < 16; i += 4) { SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3))))); } return this; }; SIMDMatrix.prototype.invertToRefSIMD = function (other) { var src = this.m; var dest = other.m; // Load the 4 rows var src0 = SIMD.Float32x4.load(src, 0); var src1 = SIMD.Float32x4.load(src, 4); var src2 = SIMD.Float32x4.load(src, 8); var src3 = SIMD.Float32x4.load(src, 12); // Transpose the source matrix. Sort of. Not a true transpose operation var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5); var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5); var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6); row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7); tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7); var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7); var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6); row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7); // This is a true transposition, but it will lead to an incorrect result //tmp1 = shuffle(src0, src1, 0, 1, 4, 5); //tmp2 = shuffle(src2, src3, 0, 1, 4, 5); //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6); //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7); //tmp1 = shuffle(src0, src1, 2, 3, 6, 7); //tmp2 = shuffle(src2, src3, 2, 3, 6, 7); //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6); //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7); // ---- tmp1 = SIMD.Float32x4.mul(row2, row3); tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 var minor0 = SIMD.Float32x4.mul(row1, tmp1); var minor1 = SIMD.Float32x4.mul(row0, tmp1); tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0); minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1); minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110 // ---- tmp1 = SIMD.Float32x4.mul(row1, row2); tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0); var minor3 = SIMD.Float32x4.mul(row0, tmp1); tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1)); minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3); minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110 // ---- tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110 tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110 minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0); var minor2 = SIMD.Float32x4.mul(row0, tmp1); tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1)); minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2); minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110 // ---- tmp1 = SIMD.Float32x4.mul(row0, row1); tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2); minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3); tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2); minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1)); // ---- tmp1 = SIMD.Float32x4.mul(row0, row3); tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1)); minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2); tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1); minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1)); // ---- tmp1 = SIMD.Float32x4.mul(row0, row2); tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1); minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1)); tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1)); minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3); // Compute determinant var det = SIMD.Float32x4.mul(row0, minor0); det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110 det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001 tmp1 = SIMD.Float32x4.reciprocalApproximation(det); det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1))); det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0); // These shuffles aren't necessary if the faulty transposition is done // up at the top of this function. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3); //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3); //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3); //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3); // Compute final values by multiplying with 1/det SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0)); SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1)); SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2)); SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3)); return this; }; SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) { var out = result.m; var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0); var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0); var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0); // cc.kmVec3Subtract(f, pCenter, pEye); var f = SIMD.Float32x4.sub(center, eye); // cc.kmVec3Normalize(f, f); var tmp = SIMD.Float32x4.mul(f, f); tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3))); f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp)); // cc.kmVec3Assign(up, pUp); // cc.kmVec3Normalize(up, up); tmp = SIMD.Float32x4.mul(up, up); tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3))); up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp)); // cc.kmVec3Cross(s, f, up); var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3))); // cc.kmVec3Normalize(s, s); tmp = SIMD.Float32x4.mul(s, s); tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3))); s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp)); // cc.kmVec3Cross(u, s, f); var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3))); // cc.kmVec3Normalize(s, s); tmp = SIMD.Float32x4.mul(s, s); tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3))); s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp)); var zero = SIMD.Float32x4.splat(0.0); s = SIMD.Float32x4.neg(s); var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5); var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5); var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7); var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6); var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0); var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0); SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3))))); b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0); SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3))))); b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0); SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3))))); b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0); SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3))))); }; return SIMDMatrix; }()); var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray; var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef; var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef; var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef; var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef; var SIMDHelper = /** @class */ (function () { function SIMDHelper() { } Object.defineProperty(SIMDHelper, "IsEnabled", { get: function () { return SIMDHelper._isEnabled; }, enumerable: true, configurable: true }); SIMDHelper.DisableSIMD = function () { // Replace functions BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray; BABYLON.Matrix.prototype.invertToRef = previousInvertToRef; BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef; BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef; BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef; SIMDHelper._isEnabled = false; }; SIMDHelper.EnableSIMD = function () { if (self.SIMD === undefined) { return; } // check if polyfills needed if (!self.Math.fround) { self.Math.fround = (function (array) { return function (x) { return array[0] = x, array[0]; }; })(new Float32Array(1)); } if (!self.Math.imul) { self.Math.imul = function (a, b) { var ah = (a >>> 16) & 0xffff; var al = a & 0xffff; var bh = (b >>> 16) & 0xffff; var bl = b & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0); }; } // Replace functions BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD; BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD; BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD; BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD; BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD; SIMDHelper._isEnabled = true; }; SIMDHelper._isEnabled = false; return SIMDHelper; }()); BABYLON.SIMDHelper = SIMDHelper; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.math.SIMD.js.map var BABYLON; (function (BABYLON) { var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) { __extends(VRDistortionCorrectionPostProcess, _super); function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) { var _this = _super.call(this, name, "vrDistortionCorrection", [ 'LensCenter', 'Scale', 'ScaleIn', 'HmdWarpParam' ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this; _this._isRightEye = isRightEye; _this._distortionFactors = vrMetrics.distortionK; _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor; _this._lensCenterOffset = vrMetrics.lensCenterOffset; _this.adaptScaleToCurrentViewport = true; _this.onSizeChangedObservable.add(function () { _this.aspectRatio = _this.width * .5 / _this.height; _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio); _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio); _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5); }); _this.onApplyObservable.add(function (effect) { effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y); effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y); effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y); effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]); }); return _this; } return VRDistortionCorrectionPostProcess; }(BABYLON.PostProcess)); BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map var BABYLON; (function (BABYLON) { var AnaglyphPostProcess = /** @class */ (function (_super) { __extends(AnaglyphPostProcess, _super); function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) { var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this; _this._passedProcess = rigCameras[0]._rigPostProcess; _this.onApplyObservable.add(function (effect) { effect.setTextureFromPostProcess("leftSampler", _this._passedProcess); }); return _this; } return AnaglyphPostProcess; }(BABYLON.PostProcess)); BABYLON.AnaglyphPostProcess = AnaglyphPostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.anaglyphPostProcess.js.map var BABYLON; (function (BABYLON) { var StereoscopicInterlacePostProcess = /** @class */ (function (_super) { __extends(StereoscopicInterlacePostProcess, _super); function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) { var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this; _this._passedProcess = rigCameras[0]._rigPostProcess; _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height); _this.onSizeChangedObservable.add(function () { _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height); }); _this.onApplyObservable.add(function (effect) { effect.setTextureFromPostProcess("camASampler", _this._passedProcess); effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y); }); return _this; } return StereoscopicInterlacePostProcess; }(BABYLON.PostProcess)); BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map var BABYLON; (function (BABYLON) { var FreeCameraDeviceOrientationInput = /** @class */ (function () { function FreeCameraDeviceOrientationInput() { var _this = this; this._screenOrientationAngle = 0; this._screenQuaternion = new BABYLON.Quaternion(); this._alpha = 0; this._beta = 0; this._gamma = 0; this._orientationChanged = function () { _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0)); _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2); _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle)); }; this._deviceOrientation = function (evt) { _this._alpha = evt.alpha !== null ? evt.alpha : 0; _this._beta = evt.beta !== null ? evt.beta : 0; _this._gamma = evt.gamma !== null ? evt.gamma : 0; }; this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5)); this._orientationChanged(); } Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", { get: function () { return this._camera; }, set: function (camera) { this._camera = camera; if (this._camera != null && !this._camera.rotationQuaternion) { this._camera.rotationQuaternion = new BABYLON.Quaternion(); } }, enumerable: true, configurable: true }); FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) { window.addEventListener("orientationchange", this._orientationChanged); window.addEventListener("deviceorientation", this._deviceOrientation); //In certain cases, the attach control is called AFTER orientation was changed, //So this is needed. this._orientationChanged(); }; FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) { window.removeEventListener("orientationchange", this._orientationChanged); window.removeEventListener("deviceorientation", this._deviceOrientation); }; FreeCameraDeviceOrientationInput.prototype.checkInputs = function () { //if no device orientation provided, don't update the rotation. //Only testing against alpha under the assumption thatnorientation will never be so exact when set. if (!this._alpha) return; BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion); this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion); this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform); //Mirror on XY Plane this._camera.rotationQuaternion.z *= -1; this._camera.rotationQuaternion.w *= -1; }; FreeCameraDeviceOrientationInput.prototype.getClassName = function () { return "FreeCameraDeviceOrientationInput"; }; FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () { return "deviceOrientation"; }; return FreeCameraDeviceOrientationInput; }()); BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput; BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map var BABYLON; (function (BABYLON) { var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () { function ArcRotateCameraVRDeviceOrientationInput() { this.alphaCorrection = 1; this.betaCorrection = 1; this.gammaCorrection = 1; this._alpha = 0; this._beta = 0; this._gamma = 0; this._dirty = false; this._deviceOrientationHandler = this._onOrientationEvent.bind(this); } ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) { this.camera.attachControl(element, noPreventDefault); window.addEventListener("deviceorientation", this._deviceOrientationHandler); }; ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) { if (evt.alpha !== null) { this._alpha = +evt.alpha | 0; } if (evt.beta !== null) { this._beta = +evt.beta | 0; } if (evt.gamma !== null) { this._gamma = +evt.gamma | 0; } this._dirty = true; }; ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () { if (this._dirty) { this._dirty = false; if (this._gamma < 0) { this._gamma = 180 + this._gamma; } this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2; this.camera.beta = (this._gamma / 180.0 * Math.PI); } }; ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) { window.removeEventListener("deviceorientation", this._deviceOrientationHandler); }; ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () { return "ArcRotateCameraVRDeviceOrientationInput"; }; ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () { return "VRDeviceOrientation"; }; return ArcRotateCameraVRDeviceOrientationInput; }()); BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput; BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map var BABYLON; (function (BABYLON) { var VRCameraMetrics = /** @class */ (function () { function VRCameraMetrics() { this.compensateDistortion = true; } Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", { get: function () { return this.hResolution / (2 * this.vResolution); }, enumerable: true, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", { get: function () { return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance))); }, enumerable: true, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", { get: function () { var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2); var h = (4 * meters) / this.hScreenSize; return BABYLON.Matrix.Translation(h, 0, 0); }, enumerable: true, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", { get: function () { var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2); var h = (4 * meters) / this.hScreenSize; return BABYLON.Matrix.Translation(-h, 0, 0); }, enumerable: true, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", { get: function () { return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0); }, enumerable: true, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", { get: function () { return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0); }, enumerable: true, configurable: true }); VRCameraMetrics.GetDefault = function () { var result = new VRCameraMetrics(); result.hResolution = 1280; result.vResolution = 800; result.hScreenSize = 0.149759993; result.vScreenSize = 0.0935999975; result.vScreenCenter = 0.0467999987; result.eyeToScreenDistance = 0.0410000011; result.lensSeparationDistance = 0.0635000020; result.interpupillaryDistance = 0.0640000030; result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0]; result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0]; result.postProcessScaleFactor = 1.714605507808412; result.lensCenterOffset = 0.151976421; return result; }; return VRCameraMetrics; }()); BABYLON.VRCameraMetrics = VRCameraMetrics; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.vrCameraMetrics.js.map var BABYLON; (function (BABYLON) { var WebVRFreeCamera = /** @class */ (function (_super) { __extends(WebVRFreeCamera, _super); function WebVRFreeCamera(name, position, scene, webVROptions) { if (webVROptions === void 0) { webVROptions = {}; } var _this = _super.call(this, name, position, scene) || this; _this.webVROptions = webVROptions; _this._vrDevice = null; _this.rawPose = null; _this._specsVersion = "1.1"; _this._attached = false; _this._descendants = []; _this.devicePosition = BABYLON.Vector3.Zero(); _this.deviceScaleFactor = 1; _this.controllers = []; _this.onControllersAttachedObservable = new BABYLON.Observable(); _this.onControllerMeshLoadedObservable = new BABYLON.Observable(); _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera. _this.minZ = 0.1; //legacy support - the compensation boolean was removed. if (arguments.length === 5) { _this.webVROptions = arguments[4]; } // default webVR options if (_this.webVROptions.trackPosition == undefined) { _this.webVROptions.trackPosition = true; } if (_this.webVROptions.controllerMeshes == undefined) { _this.webVROptions.controllerMeshes = true; } if (_this.webVROptions.defaultLightingOnControllers == undefined) { _this.webVROptions.defaultLightingOnControllers = true; } _this.rotationQuaternion = new BABYLON.Quaternion(); _this.deviceRotationQuaternion = new BABYLON.Quaternion(); if (_this.webVROptions && _this.webVROptions.positionScale) { _this.deviceScaleFactor = _this.webVROptions.positionScale; } //enable VR var engine = _this.getEngine(); _this._onVREnabled = function (success) { if (success) { _this.initControllers(); } }; engine.onVRRequestPresentComplete.add(_this._onVREnabled); engine.initWebVR().add(function (event) { if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) { return; } _this._vrDevice = event.vrDisplay; //reset the rig parameters. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion }); if (_this._attached) { _this.getEngine().enableVR(); } }); if (typeof (VRFrameData) !== "undefined") _this._frameData = new VRFrameData(); /** * The idea behind the following lines: * objects that have the camera as parent should actually have the rig cameras as a parent. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera, * the second will not show it correctly. * * To solve this - each object that has the camera as parent will be added to a protected array. * When the rig camera renders, it will take this array and set all of those to be its children. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly. * Amazing! */ scene.onBeforeCameraRenderObservable.add(function (camera) { if (camera.parent === _this && _this.rigParenting) { _this._descendants = _this.getDescendants(true, function (n) { // don't take the cameras or the controllers! var isController = _this.controllers.some(function (controller) { return controller._mesh === n; }); var isRigCamera = _this._rigCameras.indexOf(n) !== -1; return !isController && !isRigCamera; }); _this._descendants.forEach(function (node) { node.parent = camera; }); } }); scene.onAfterCameraRenderObservable.add(function (camera) { if (camera.parent === _this && _this.rigParenting) { _this._descendants.forEach(function (node) { node.parent = _this; }); } }); return _this; } WebVRFreeCamera.prototype.dispose = function () { this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled); _super.prototype.dispose.call(this); }; WebVRFreeCamera.prototype.getControllerByName = function (name) { for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) { var gp = _a[_i]; if (gp.hand === name) { return gp; } } return null; }; Object.defineProperty(WebVRFreeCamera.prototype, "leftController", { get: function () { if (!this._leftController) { this._leftController = this.getControllerByName("left"); } return this._leftController; }, enumerable: true, configurable: true }); ; Object.defineProperty(WebVRFreeCamera.prototype, "rightController", { get: function () { if (!this._rightController) { this._rightController = this.getControllerByName("right"); } return this._rightController; }, enumerable: true, configurable: true }); ; WebVRFreeCamera.prototype.getForwardRay = function (length) { if (length === void 0) { length = 100; } if (this.leftCamera) { return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera } else { return _super.prototype.getForwardRay.call(this, length); } }; WebVRFreeCamera.prototype._checkInputs = function () { if (this._vrDevice && this._vrDevice.isPresenting) { this._vrDevice.getFrameData(this._frameData); this.updateFromDevice(this._frameData.pose); } _super.prototype._checkInputs.call(this); }; WebVRFreeCamera.prototype.updateFromDevice = function (poseData) { if (poseData && poseData.orientation) { this.rawPose = poseData; this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]); if (this.getScene().useRightHandedSystem) { this.deviceRotationQuaternion.z *= -1; this.deviceRotationQuaternion.w *= -1; } if (this.webVROptions.trackPosition && this.rawPose.position) { this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]); if (this.getScene().useRightHandedSystem) { this.devicePosition.z *= -1; } } } }; /** * WebVR's attach control will start broadcasting frames to the device. * Note that in certain browsers (chrome for example) this function must be called * within a user-interaction callback. Example: *
 scene.onPointerDown = function() { camera.attachControl(canvas); }
* * @param {HTMLElement} element * @param {boolean} [noPreventDefault] * * @memberOf WebVRFreeCamera */ WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) { _super.prototype.attachControl.call(this, element, noPreventDefault); this._attached = true; noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault; if (this._vrDevice) { this.getEngine().enableVR(); } }; WebVRFreeCamera.prototype.detachControl = function (element) { this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); _super.prototype.detachControl.call(this, element); this._attached = false; this.getEngine().disableVR(); }; WebVRFreeCamera.prototype.getClassName = function () { return "WebVRFreeCamera"; }; WebVRFreeCamera.prototype.resetToCurrentRotation = function () { //uses the vrDisplay's "resetPose()". //pitch and roll won't be affected. this._vrDevice.resetPose(); }; WebVRFreeCamera.prototype._updateRigCameras = function () { var camLeft = this._rigCameras[0]; var camRight = this._rigCameras[1]; camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion); camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion); camLeft.position.copyFrom(this.devicePosition); camRight.position.copyFrom(this.devicePosition); }; /** * This function is called by the two RIG cameras. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance) */ WebVRFreeCamera.prototype._getWebVRViewMatrix = function () { var _this = this; //WebVR 1.1 var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix; BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix); if (!this.getScene().useRightHandedSystem) { [2, 6, 8, 9, 14].forEach(function (num) { _this._webvrViewMatrix.m[num] *= -1; }); } // update the camera rotation matrix this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix); BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint); // Computing target and final matrix this.position.addToRef(this._transformedReferencePoint, this._currentTarget); var parentCamera = this._cameraRigParams["parentCamera"]; // should the view matrix be updated with scale and position offset? if (parentCamera.deviceScaleFactor !== 1) { this._webvrViewMatrix.invert(); // scale the position, if set if (parentCamera.deviceScaleFactor) { this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor; this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor; this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor; } this._webvrViewMatrix.invert(); } return this._webvrViewMatrix; }; WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () { var _this = this; var parentCamera = this.parent; parentCamera._vrDevice.depthNear = parentCamera.minZ; parentCamera._vrDevice.depthFar = parentCamera.maxZ; var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix; BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix); //babylon compatible matrix if (!this.getScene().useRightHandedSystem) { [8, 9, 10, 11].forEach(function (num) { _this._projectionMatrix.m[num] *= -1; }); } return this._projectionMatrix; }; WebVRFreeCamera.prototype.initControllers = function () { var _this = this; this.controllers = []; var manager = this.getScene().gamepadManager; this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) { if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) { var webVrController = gamepad; if (webVrController.defaultModel) { webVrController.defaultModel.setEnabled(false); } } }); this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) { if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) { var webVrController_1 = gamepad; if (_this.webVROptions.controllerMeshes) { if (webVrController_1.defaultModel) { webVrController_1.defaultModel.setEnabled(true); } else { // Load the meshes webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) { _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1); if (_this.webVROptions.defaultLightingOnControllers) { if (!_this._lightOnControllers) { _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene()); } var activateLightOnSubMeshes_1 = function (mesh, light) { var children = mesh.getChildren(); if (children.length !== 0) { children.forEach(function (mesh) { light.includedOnlyMeshes.push(mesh); activateLightOnSubMeshes_1(mesh, light); }); } }; _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh); activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers); } }); } } webVrController_1.attachToPoseControlledCamera(_this); // since this is async - sanity check. Is the controller already stored? if (_this.controllers.indexOf(webVrController_1) === -1) { //add to the controllers array _this.controllers.push(webVrController_1); //did we find enough controllers? Great! let the developer know. if (_this.controllers.length >= 2) { // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them... // So we're overriding setting left & right manually to be sure var firstViveWandDetected = false; for (var i = 0; i < _this.controllers.length; i++) { if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) { if (!firstViveWandDetected) { firstViveWandDetected = true; _this.controllers[i].hand = "left"; } else { _this.controllers[i].hand = "right"; } } } _this.onControllersAttachedObservable.notifyObservers(_this.controllers); } } } }); }; return WebVRFreeCamera; }(BABYLON.FreeCamera)); BABYLON.WebVRFreeCamera = WebVRFreeCamera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.webVRCamera.js.map /// var BABYLON; (function (BABYLON) { // We're mainly based on the logic defined into the FreeCamera code var DeviceOrientationCamera = /** @class */ (function (_super) { __extends(DeviceOrientationCamera, _super); function DeviceOrientationCamera(name, position, scene) { var _this = _super.call(this, name, position, scene) || this; _this._quaternionCache = new BABYLON.Quaternion(); _this.inputs.addDeviceOrientation(); return _this; } DeviceOrientationCamera.prototype.getClassName = function () { return "DeviceOrientationCamera"; }; DeviceOrientationCamera.prototype._checkInputs = function () { _super.prototype._checkInputs.call(this); this._quaternionCache.copyFrom(this.rotationQuaternion); if (this._initialQuaternion) { this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); } }; DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) { var _this = this; if (axis === void 0) { axis = BABYLON.Axis.Y; } //can only work if this camera has a rotation quaternion already. if (!this.rotationQuaternion) return; if (!this._initialQuaternion) { this._initialQuaternion = new BABYLON.Quaternion(); } this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion); ['x', 'y', 'z'].forEach(function (axisName) { if (!axis[axisName]) { _this._initialQuaternion[axisName] = 0; } else { _this._initialQuaternion[axisName] *= -1; } }); this._initialQuaternion.normalize(); //force rotation update this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); }; return DeviceOrientationCamera; }(BABYLON.FreeCamera)); BABYLON.DeviceOrientationCamera = DeviceOrientationCamera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.deviceOrientationCamera.js.map var BABYLON; (function (BABYLON) { var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) { __extends(VRDeviceOrientationFreeCamera, _super); function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) { if (compensateDistortion === void 0) { compensateDistortion = true; } if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); } var _this = _super.call(this, name, position, scene) || this; vrCameraMetrics.compensateDistortion = compensateDistortion; _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); return _this; } VRDeviceOrientationFreeCamera.prototype.getClassName = function () { return "VRDeviceOrientationFreeCamera"; }; return VRDeviceOrientationFreeCamera; }(BABYLON.DeviceOrientationCamera)); BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera; var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) { __extends(VRDeviceOrientationGamepadCamera, _super); function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) { if (compensateDistortion === void 0) { compensateDistortion = true; } if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); } var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this; _this.inputs.addGamepad(); return _this; } VRDeviceOrientationGamepadCamera.prototype.getClassName = function () { return "VRDeviceOrientationGamepadCamera"; }; return VRDeviceOrientationGamepadCamera; }(VRDeviceOrientationFreeCamera)); BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera; var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) { __extends(VRDeviceOrientationArcRotateCamera, _super); function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) { if (compensateDistortion === void 0) { compensateDistortion = true; } if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); } var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; vrCameraMetrics.compensateDistortion = compensateDistortion; _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); _this.inputs.addVRDeviceOrientation(); return _this; } VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () { return "VRDeviceOrientationArcRotateCamera"; }; return VRDeviceOrientationArcRotateCamera; }(BABYLON.ArcRotateCamera)); BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map /// /// /// /// var BABYLON; (function (BABYLON) { var AnaglyphFreeCamera = /** @class */ (function (_super) { __extends(AnaglyphFreeCamera, _super); function AnaglyphFreeCamera(name, position, interaxialDistance, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } AnaglyphFreeCamera.prototype.getClassName = function () { return "AnaglyphFreeCamera"; }; return AnaglyphFreeCamera; }(BABYLON.FreeCamera)); BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera; var AnaglyphArcRotateCamera = /** @class */ (function (_super) { __extends(AnaglyphArcRotateCamera, _super); function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) { var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } AnaglyphArcRotateCamera.prototype.getClassName = function () { return "AnaglyphArcRotateCamera"; }; return AnaglyphArcRotateCamera; }(BABYLON.ArcRotateCamera)); BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera; var AnaglyphGamepadCamera = /** @class */ (function (_super) { __extends(AnaglyphGamepadCamera, _super); function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } AnaglyphGamepadCamera.prototype.getClassName = function () { return "AnaglyphGamepadCamera"; }; return AnaglyphGamepadCamera; }(BABYLON.GamepadCamera)); BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera; var AnaglyphUniversalCamera = /** @class */ (function (_super) { __extends(AnaglyphUniversalCamera, _super); function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } AnaglyphUniversalCamera.prototype.getClassName = function () { return "AnaglyphUniversalCamera"; }; return AnaglyphUniversalCamera; }(BABYLON.UniversalCamera)); BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera; var StereoscopicFreeCamera = /** @class */ (function (_super) { __extends(StereoscopicFreeCamera, _super); function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } StereoscopicFreeCamera.prototype.getClassName = function () { return "StereoscopicFreeCamera"; }; return StereoscopicFreeCamera; }(BABYLON.FreeCamera)); BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera; var StereoscopicArcRotateCamera = /** @class */ (function (_super) { __extends(StereoscopicArcRotateCamera, _super); function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } StereoscopicArcRotateCamera.prototype.getClassName = function () { return "StereoscopicArcRotateCamera"; }; return StereoscopicArcRotateCamera; }(BABYLON.ArcRotateCamera)); BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera; var StereoscopicGamepadCamera = /** @class */ (function (_super) { __extends(StereoscopicGamepadCamera, _super); function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } StereoscopicGamepadCamera.prototype.getClassName = function () { return "StereoscopicGamepadCamera"; }; return StereoscopicGamepadCamera; }(BABYLON.GamepadCamera)); BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera; var StereoscopicUniversalCamera = /** @class */ (function (_super) { __extends(StereoscopicUniversalCamera, _super); function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } StereoscopicUniversalCamera.prototype.getClassName = function () { return "StereoscopicUniversalCamera"; }; return StereoscopicUniversalCamera; }(BABYLON.UniversalCamera)); BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.stereoscopicCameras.js.map var BABYLON; (function (BABYLON) { var VRExperienceHelper = /** @class */ (function () { function VRExperienceHelper(scene, webVROptions) { if (webVROptions === void 0) { webVROptions = {}; } var _this = this; this.webVROptions = webVROptions; // Can the system support WebVR, even if a headset isn't plugged in? this._webVRsupported = false; // If WebVR is supported, is a headset plugged in and are we ready to present? this._webVRready = false; // Are we waiting for the requestPresent callback to complete? this._webVRrequesting = false; // Are we presenting to the headset right now? this._webVRpresenting = false; // Are we presenting in the fullscreen fallback? this._fullscreenVRpresenting = false; this._scene = scene; if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) { this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene); } else { this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene); if (scene.activeCamera.rotation) { this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone(); } this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ; this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ; } this._scene.activeCamera = this._deviceOrientationCamera; this._position = this._scene.activeCamera.position; this._canvas = scene.getEngine().getRenderingCanvas(); if (this._canvas) { this._scene.activeCamera.attachControl(this._canvas); } this._btnVR = document.createElement("BUTTON"); this._btnVR.className = "babylonVRicon"; this._btnVR.id = "babylonVRiconbtn"; this._btnVR.title = "Click to switch to VR"; var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }"; css += ".babylonVRicon.vrdisplaypresenting { display: none; }"; // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR) // css += ".babylonVRicon.vrdisplaysupported { }"; // css += ".babylonVRicon.vrdisplayready { }"; // css += ".babylonVRicon.vrdisplayrequesting { }"; var style = document.createElement('style'); style.appendChild(document.createTextNode(css)); document.getElementsByTagName('head')[0].appendChild(style); if (this._canvas) { this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px"; this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px"; this._btnVR.addEventListener("click", function () { _this.enterVR(); }); window.addEventListener("resize", function () { if (_this._canvas) { _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px"; _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px"; } if (_this._fullscreenVRpresenting && _this._webVRready) { _this.exitVR(); } }); } document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false); document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false); document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false); document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false); document.body.appendChild(this._btnVR); // Exiting VR mode using 'ESC' key on desktop this._onKeyDown = function (event) { if (event.keyCode === 27 && _this.isInVRMode()) { _this.exitVR(); } }; document.addEventListener("keydown", this._onKeyDown); // Exiting VR mode double tapping the touch screen this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) { if (_this.isInVRMode()) { _this.exitVR(); if (_this._fullscreenVRpresenting) { _this._scene.getEngine().switchFullscreen(true); } } }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false); // Listen for WebVR display changes this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); }; this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); }; this._onVRRequestPresentStart = function () { _this._webVRrequesting = true; _this.updateButtonVisibility(); }; this._onVRRequestPresentComplete = function (success) { _this._webVRrequesting = false; _this.updateButtonVisibility(); }; scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged); scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart); scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete); window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); // Create the cameras this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene); this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions); this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); }); this.updateButtonVisibility(); } VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) { if (this.onControllerMeshLoaded) { this.onControllerMeshLoaded(webVRController); } }; VRExperienceHelper.prototype._onFullscreenChange = function () { if (document.fullscreen !== undefined) { this._fullscreenVRpresenting = document.fullscreen; } else if (document.mozFullScreen !== undefined) { this._fullscreenVRpresenting = document.mozFullScreen; } else if (document.webkitIsFullScreen !== undefined) { this._fullscreenVRpresenting = document.webkitIsFullScreen; } else if (document.msIsFullScreen !== undefined) { this._fullscreenVRpresenting = document.msIsFullScreen; } if (!this._fullscreenVRpresenting && this._canvas) { this.exitVR(); this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px"; this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px"; } }; VRExperienceHelper.prototype.isInVRMode = function () { return this._webVRpresenting || this._fullscreenVRpresenting; }; VRExperienceHelper.prototype.onVrDisplayPresentChange = function () { var vrDisplay = this._scene.getEngine().getVRDevice(); if (vrDisplay) { var wasPresenting = this._webVRpresenting; // A VR display is connected this._webVRpresenting = vrDisplay.isPresenting; if (wasPresenting && !this._webVRpresenting) this.exitVR(); } else { BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?'); } this.updateButtonVisibility(); }; VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) { this._webVRsupported = eventArgs.vrSupported; this._webVRready = !!eventArgs.vrDisplay; this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting; this.updateButtonVisibility(); }; VRExperienceHelper.prototype.updateButtonVisibility = function () { if (!this._btnVR) { return; } this._btnVR.className = "babylonVRicon"; if (this.isInVRMode()) { this._btnVR.className += " vrdisplaypresenting"; } else { if (this._webVRready) this._btnVR.className += " vrdisplayready"; if (this._webVRsupported) this._btnVR.className += " vrdisplaysupported"; if (this._webVRrequesting) this._btnVR.className += " vrdisplayrequesting"; } }; /** * Attempt to enter VR. If a headset is connected and ready, will request present on that. * Otherwise, will use the fullscreen API. */ VRExperienceHelper.prototype.enterVR = function () { if (this.onEnteringVR) { this.onEnteringVR(); } if (this._webVRrequesting) return; // If WebVR is supported and a headset is connected if (this._webVRready) { if (!this._webVRpresenting) { this._webVRCamera.position = this._position; this._scene.activeCamera = this._webVRCamera; } } else { this._vrDeviceOrientationCamera.position = this._position; this._scene.activeCamera = this._vrDeviceOrientationCamera; this._scene.getEngine().switchFullscreen(true); this.updateButtonVisibility(); } if (this._scene.activeCamera && this._canvas) { this._scene.activeCamera.attachControl(this._canvas); } }; /** * Attempt to exit VR, or fullscreen. */ VRExperienceHelper.prototype.exitVR = function () { if (this.onExitingVR) { this.onExitingVR(); } if (this._webVRpresenting) { this._scene.getEngine().disableVR(); } if (this._scene.activeCamera) { this._position = this._scene.activeCamera.position; } this._deviceOrientationCamera.position = this._position; this._scene.activeCamera = this._deviceOrientationCamera; if (this._canvas) { this._scene.activeCamera.attachControl(this._canvas); } this.updateButtonVisibility(); }; Object.defineProperty(VRExperienceHelper.prototype, "position", { get: function () { return this._position; }, set: function (value) { this._position = value; if (this._scene.activeCamera) { this._scene.activeCamera.position = value; } }, enumerable: true, configurable: true }); VRExperienceHelper.prototype.dispose = function () { if (this.isInVRMode()) { this.exitVR(); } this._deviceOrientationCamera.dispose(); if (this._webVRCamera) { this._webVRCamera.dispose(); } if (this._vrDeviceOrientationCamera) { this._vrDeviceOrientationCamera.dispose(); } document.body.removeChild(this._btnVR); document.removeEventListener("keydown", this._onKeyDown); window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); }; VRExperienceHelper.prototype.getClassName = function () { return "VRExperienceHelper"; }; return VRExperienceHelper; }()); BABYLON.VRExperienceHelper = VRExperienceHelper; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.vrExperienceHelper.js.map // Mainly based on these 2 articles : // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/ var BABYLON; (function (BABYLON) { var JoystickAxis; (function (JoystickAxis) { JoystickAxis[JoystickAxis["X"] = 0] = "X"; JoystickAxis[JoystickAxis["Y"] = 1] = "Y"; JoystickAxis[JoystickAxis["Z"] = 2] = "Z"; })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {})); var VirtualJoystick = /** @class */ (function () { function VirtualJoystick(leftJoystick) { var _this = this; if (leftJoystick) { this._leftJoystick = true; } else { this._leftJoystick = false; } this._joystickIndex = VirtualJoystick._globalJoystickIndex; VirtualJoystick._globalJoystickIndex++; // By default left & right arrow keys are moving the X // and up & down keys are moving the Y this._axisTargetedByLeftAndRight = JoystickAxis.X; this._axisTargetedByUpAndDown = JoystickAxis.Y; this.reverseLeftRight = false; this.reverseUpDown = false; // collections of pointers this._touches = new BABYLON.StringDictionary(); this.deltaPosition = BABYLON.Vector3.Zero(); this._joystickSensibility = 25; this._inversedSensibility = 1 / (this._joystickSensibility / 1000); this._rotationSpeed = 25; this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000); this._rotateOnAxisRelativeToMesh = false; this._onResize = function (evt) { VirtualJoystick.vjCanvasWidth = window.innerWidth; VirtualJoystick.vjCanvasHeight = window.innerHeight; if (VirtualJoystick.vjCanvas) { VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth; VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight; } VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2; VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2; }; // injecting a canvas element on top of the canvas 3D game if (!VirtualJoystick.vjCanvas) { window.addEventListener("resize", this._onResize, false); VirtualJoystick.vjCanvas = document.createElement("canvas"); VirtualJoystick.vjCanvasWidth = window.innerWidth; VirtualJoystick.vjCanvasHeight = window.innerHeight; VirtualJoystick.vjCanvas.width = window.innerWidth; VirtualJoystick.vjCanvas.height = window.innerHeight; VirtualJoystick.vjCanvas.style.width = "100%"; VirtualJoystick.vjCanvas.style.height = "100%"; VirtualJoystick.vjCanvas.style.position = "absolute"; VirtualJoystick.vjCanvas.style.backgroundColor = "transparent"; VirtualJoystick.vjCanvas.style.top = "0px"; VirtualJoystick.vjCanvas.style.left = "0px"; VirtualJoystick.vjCanvas.style.zIndex = "5"; VirtualJoystick.vjCanvas.style.msTouchAction = "none"; // Support for jQuery PEP polyfill VirtualJoystick.vjCanvas.setAttribute("touch-action", "none"); var context = VirtualJoystick.vjCanvas.getContext('2d'); if (!context) { throw new Error("Unable to create canvas for virtual joystick"); } VirtualJoystick.vjCanvasContext = context; VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff"; VirtualJoystick.vjCanvasContext.lineWidth = 2; document.body.appendChild(VirtualJoystick.vjCanvas); } VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2; VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2; this.pressed = false; // default joystick color this._joystickColor = "cyan"; this._joystickPointerID = -1; // current joystick position this._joystickPointerPos = new BABYLON.Vector2(0, 0); this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0); // origin joystick position this._joystickPointerStartPos = new BABYLON.Vector2(0, 0); this._deltaJoystickVector = new BABYLON.Vector2(0, 0); this._onPointerDownHandlerRef = function (evt) { _this._onPointerDown(evt); }; this._onPointerMoveHandlerRef = function (evt) { _this._onPointerMove(evt); }; this._onPointerOutHandlerRef = function (evt) { _this._onPointerUp(evt); }; this._onPointerUpHandlerRef = function (evt) { _this._onPointerUp(evt); }; VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false); VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false); VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false); VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false); VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) { evt.preventDefault(); // Disables system menu }, false); requestAnimationFrame(function () { _this._drawVirtualJoystick(); }); } VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) { this._joystickSensibility = newJoystickSensibility; this._inversedSensibility = 1 / (this._joystickSensibility / 1000); }; VirtualJoystick.prototype._onPointerDown = function (e) { var positionOnScreenCondition; e.preventDefault(); if (this._leftJoystick === true) { positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth); } else { positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth); } if (positionOnScreenCondition && this._joystickPointerID < 0) { // First contact will be dedicated to the virtual joystick this._joystickPointerID = e.pointerId; this._joystickPointerStartPos.x = e.clientX; this._joystickPointerStartPos.y = e.clientY; this._joystickPointerPos = this._joystickPointerStartPos.clone(); this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone(); this._deltaJoystickVector.x = 0; this._deltaJoystickVector.y = 0; this.pressed = true; this._touches.add(e.pointerId.toString(), e); } else { // You can only trigger the action buttons with a joystick declared if (VirtualJoystick._globalJoystickIndex < 2 && this._action) { this._action(); this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY }); } } }; VirtualJoystick.prototype._onPointerMove = function (e) { // If the current pointer is the one associated to the joystick (first touch contact) if (this._joystickPointerID == e.pointerId) { this._joystickPointerPos.x = e.clientX; this._joystickPointerPos.y = e.clientY; this._deltaJoystickVector = this._joystickPointerPos.clone(); this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos); var directionLeftRight = this.reverseLeftRight ? -1 : 1; var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility; switch (this._axisTargetedByLeftAndRight) { case JoystickAxis.X: this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX)); break; case JoystickAxis.Y: this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX)); break; case JoystickAxis.Z: this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX)); break; } var directionUpDown = this.reverseUpDown ? 1 : -1; var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility; switch (this._axisTargetedByUpAndDown) { case JoystickAxis.X: this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY)); break; case JoystickAxis.Y: this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY)); break; case JoystickAxis.Z: this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY)); break; } } else { var data = this._touches.get(e.pointerId.toString()); if (data) { data.x = e.clientX; data.y = e.clientY; } } }; VirtualJoystick.prototype._onPointerUp = function (e) { if (this._joystickPointerID == e.pointerId) { VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128); VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84); this._joystickPointerID = -1; this.pressed = false; } else { var touch = this._touches.get(e.pointerId.toString()); if (touch) { VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88); } } this._deltaJoystickVector.x = 0; this._deltaJoystickVector.y = 0; this._touches.remove(e.pointerId.toString()); }; /** * Change the color of the virtual joystick * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000") */ VirtualJoystick.prototype.setJoystickColor = function (newColor) { this._joystickColor = newColor; }; VirtualJoystick.prototype.setActionOnTouch = function (action) { this._action = action; }; // Define which axis you'd like to control for left & right VirtualJoystick.prototype.setAxisForLeftRight = function (axis) { switch (axis) { case JoystickAxis.X: case JoystickAxis.Y: case JoystickAxis.Z: this._axisTargetedByLeftAndRight = axis; break; default: this._axisTargetedByLeftAndRight = JoystickAxis.X; break; } }; // Define which axis you'd like to control for up & down VirtualJoystick.prototype.setAxisForUpDown = function (axis) { switch (axis) { case JoystickAxis.X: case JoystickAxis.Y: case JoystickAxis.Z: this._axisTargetedByUpAndDown = axis; break; default: this._axisTargetedByUpAndDown = JoystickAxis.Y; break; } }; VirtualJoystick.prototype._drawVirtualJoystick = function () { var _this = this; if (this.pressed) { this._touches.forEach(function (key, touch) { if (touch.pointerId === _this._joystickPointerID) { VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128); VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84); VirtualJoystick.vjCanvasContext.beginPath(); VirtualJoystick.vjCanvasContext.lineWidth = 6; VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor; VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true); VirtualJoystick.vjCanvasContext.stroke(); VirtualJoystick.vjCanvasContext.closePath(); VirtualJoystick.vjCanvasContext.beginPath(); VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor; VirtualJoystick.vjCanvasContext.lineWidth = 2; VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true); VirtualJoystick.vjCanvasContext.stroke(); VirtualJoystick.vjCanvasContext.closePath(); VirtualJoystick.vjCanvasContext.beginPath(); VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor; VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true); VirtualJoystick.vjCanvasContext.stroke(); VirtualJoystick.vjCanvasContext.closePath(); _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone(); } else { VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88); VirtualJoystick.vjCanvasContext.beginPath(); VirtualJoystick.vjCanvasContext.fillStyle = "white"; VirtualJoystick.vjCanvasContext.beginPath(); VirtualJoystick.vjCanvasContext.strokeStyle = "red"; VirtualJoystick.vjCanvasContext.lineWidth = 6; VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true); VirtualJoystick.vjCanvasContext.stroke(); VirtualJoystick.vjCanvasContext.closePath(); touch.prevX = touch.x; touch.prevY = touch.y; } ; }); } requestAnimationFrame(function () { _this._drawVirtualJoystick(); }); }; VirtualJoystick.prototype.releaseCanvas = function () { if (VirtualJoystick.vjCanvas) { VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef); VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef); VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef); VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef); window.removeEventListener("resize", this._onResize); document.body.removeChild(VirtualJoystick.vjCanvas); VirtualJoystick.vjCanvas = null; } }; // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas VirtualJoystick._globalJoystickIndex = 0; return VirtualJoystick; }()); BABYLON.VirtualJoystick = VirtualJoystick; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.virtualJoystick.js.map var BABYLON; (function (BABYLON) { // We're mainly based on the logic defined into the FreeCamera code var VirtualJoysticksCamera = /** @class */ (function (_super) { __extends(VirtualJoysticksCamera, _super); function VirtualJoysticksCamera(name, position, scene) { var _this = _super.call(this, name, position, scene) || this; _this.inputs.addVirtualJoystick(); return _this; } VirtualJoysticksCamera.prototype.getClassName = function () { return "VirtualJoysticksCamera"; }; return VirtualJoysticksCamera; }(BABYLON.FreeCamera)); BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map var BABYLON; (function (BABYLON) { var FreeCameraVirtualJoystickInput = /** @class */ (function () { function FreeCameraVirtualJoystickInput() { } FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () { return this._leftjoystick; }; FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () { return this._rightjoystick; }; FreeCameraVirtualJoystickInput.prototype.checkInputs = function () { if (this._leftjoystick) { var camera = this.camera; var speed = camera._computeLocalCameraSpeed() * 50; var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0); var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform); camera.cameraDirection = camera.cameraDirection.add(deltaTransform); camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition); if (!this._leftjoystick.pressed) { this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9); } if (!this._rightjoystick.pressed) { this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9); } } }; FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) { this._leftjoystick = new BABYLON.VirtualJoystick(true); this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z); this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X); this._leftjoystick.setJoystickSensibility(0.15); this._rightjoystick = new BABYLON.VirtualJoystick(false); this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X); this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y); this._rightjoystick.reverseUpDown = true; this._rightjoystick.setJoystickSensibility(0.05); this._rightjoystick.setJoystickColor("yellow"); }; FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) { this._leftjoystick.releaseCanvas(); this._rightjoystick.releaseCanvas(); }; FreeCameraVirtualJoystickInput.prototype.getClassName = function () { return "FreeCameraVirtualJoystickInput"; }; FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () { return "virtualJoystick"; }; return FreeCameraVirtualJoystickInput; }()); BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput; BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map var BABYLON; (function (BABYLON) { var SimplificationSettings = /** @class */ (function () { function SimplificationSettings(quality, distance, optimizeMesh) { this.quality = quality; this.distance = distance; this.optimizeMesh = optimizeMesh; } return SimplificationSettings; }()); BABYLON.SimplificationSettings = SimplificationSettings; var SimplificationQueue = /** @class */ (function () { function SimplificationQueue() { this.running = false; this._simplificationArray = []; } SimplificationQueue.prototype.addTask = function (task) { this._simplificationArray.push(task); }; SimplificationQueue.prototype.executeNext = function () { var task = this._simplificationArray.pop(); if (task) { this.running = true; this.runSimplification(task); } else { this.running = false; } }; SimplificationQueue.prototype.runSimplification = function (task) { var _this = this; if (task.parallelProcessing) { //parallel simplifier task.settings.forEach(function (setting) { var simplifier = _this.getSimplifier(task); simplifier.simplify(setting, function (newMesh) { task.mesh.addLODLevel(setting.distance, newMesh); newMesh.isVisible = true; //check if it is the last if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) { //all done, run the success callback. task.successCallback(); } _this.executeNext(); }); }); } else { //single simplifier. var simplifier = this.getSimplifier(task); var runDecimation = function (setting, callback) { simplifier.simplify(setting, function (newMesh) { task.mesh.addLODLevel(setting.distance, newMesh); newMesh.isVisible = true; //run the next quality level callback(); }); }; BABYLON.AsyncLoop.Run(task.settings.length, function (loop) { runDecimation(task.settings[loop.index], function () { loop.executeNext(); }); }, function () { //execution ended, run the success callback. if (task.successCallback) { task.successCallback(); } _this.executeNext(); }); } }; SimplificationQueue.prototype.getSimplifier = function (task) { switch (task.simplificationType) { case SimplificationType.QUADRATIC: default: return new QuadraticErrorSimplification(task.mesh); } }; return SimplificationQueue; }()); BABYLON.SimplificationQueue = SimplificationQueue; /** * The implemented types of simplification. * At the moment only Quadratic Error Decimation is implemented. */ var SimplificationType; (function (SimplificationType) { SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC"; })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {})); var DecimationTriangle = /** @class */ (function () { function DecimationTriangle(vertices) { this.vertices = vertices; this.error = new Array(4); this.deleted = false; this.isDirty = false; this.deletePending = false; this.borderFactor = 0; } return DecimationTriangle; }()); BABYLON.DecimationTriangle = DecimationTriangle; var DecimationVertex = /** @class */ (function () { function DecimationVertex(position, id) { this.position = position; this.id = id; this.isBorder = true; this.q = new QuadraticMatrix(); this.triangleCount = 0; this.triangleStart = 0; this.originalOffsets = []; } DecimationVertex.prototype.updatePosition = function (newPosition) { this.position.copyFrom(newPosition); }; return DecimationVertex; }()); BABYLON.DecimationVertex = DecimationVertex; var QuadraticMatrix = /** @class */ (function () { function QuadraticMatrix(data) { this.data = new Array(10); for (var i = 0; i < 10; ++i) { if (data && data[i]) { this.data[i] = data[i]; } else { this.data[i] = 0; } } } QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) { var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33]; return det; }; QuadraticMatrix.prototype.addInPlace = function (matrix) { for (var i = 0; i < 10; ++i) { this.data[i] += matrix.data[i]; } }; QuadraticMatrix.prototype.addArrayInPlace = function (data) { for (var i = 0; i < 10; ++i) { this.data[i] += data[i]; } }; QuadraticMatrix.prototype.add = function (matrix) { var m = new QuadraticMatrix(); for (var i = 0; i < 10; ++i) { m.data[i] = this.data[i] + matrix.data[i]; } return m; }; QuadraticMatrix.FromData = function (a, b, c, d) { return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d)); }; //returning an array to avoid garbage collection QuadraticMatrix.DataFromNumbers = function (a, b, c, d) { return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d]; }; return QuadraticMatrix; }()); BABYLON.QuadraticMatrix = QuadraticMatrix; var Reference = /** @class */ (function () { function Reference(vertexId, triangleId) { this.vertexId = vertexId; this.triangleId = triangleId; } return Reference; }()); BABYLON.Reference = Reference; /** * An implementation of the Quadratic Error simplification algorithm. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS * @author RaananW */ var QuadraticErrorSimplification = /** @class */ (function () { function QuadraticErrorSimplification(_mesh) { this._mesh = _mesh; this.initialized = false; this.syncIterations = 5000; this.aggressiveness = 7; this.decimationIterations = 100; this.boundingBoxEpsilon = BABYLON.Epsilon; } QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) { var _this = this; this.initDecimatedMesh(); //iterating through the submeshes array, one after the other. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) { _this.initWithMesh(loop.index, function () { _this.runDecimation(settings, loop.index, function () { loop.executeNext(); }); }, settings.optimizeMesh); }, function () { setTimeout(function () { successCallback(_this._reconstructedMesh); }, 0); }); }; QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) { var _this = this; var targetCount = ~~(this.triangles.length * settings.quality); var deletedTriangles = 0; var triangleCount = this.triangles.length; var iterationFunction = function (iteration, callback) { setTimeout(function () { if (iteration % 5 === 0) { _this.updateMesh(iteration === 0); } for (var i = 0; i < _this.triangles.length; ++i) { _this.triangles[i].isDirty = false; } var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness); var trianglesIterator = function (i) { var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length); var t = _this.triangles[tIdx]; if (!t) return; if (t.error[3] > threshold || t.deleted || t.isDirty) { return; } for (var j = 0; j < 3; ++j) { if (t.error[j] < threshold) { var deleted0 = []; var deleted1 = []; var v0 = t.vertices[j]; var v1 = t.vertices[(j + 1) % 3]; if (v0.isBorder || v1.isBorder) continue; var p = BABYLON.Vector3.Zero(); var n = BABYLON.Vector3.Zero(); var uv = BABYLON.Vector2.Zero(); var color = new BABYLON.Color4(0, 0, 0, 1); _this.calculateError(v0, v1, p, n, uv, color); var delTr = new Array(); if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) continue; if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) continue; if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) continue; var uniqueArray = new Array(); delTr.forEach(function (deletedT) { if (uniqueArray.indexOf(deletedT) === -1) { deletedT.deletePending = true; uniqueArray.push(deletedT); } }); if (uniqueArray.length % 2 !== 0) { continue; } v0.q = v1.q.add(v0.q); v0.updatePosition(p); var tStart = _this.references.length; deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles); deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles); var tCount = _this.references.length - tStart; if (tCount <= v0.triangleCount) { if (tCount) { for (var c = 0; c < tCount; c++) { _this.references[v0.triangleStart + c] = _this.references[tStart + c]; } } } else { v0.triangleStart = tStart; } v0.triangleCount = tCount; break; } } }; BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); }); }, 0); }; BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) { if (triangleCount - deletedTriangles <= targetCount) loop.breakLoop(); else { iterationFunction(loop.index, function () { loop.executeNext(); }); } }, function () { setTimeout(function () { //reconstruct this part of the mesh _this.reconstructMesh(submeshIndex); successCallback(); }, 0); }); }; QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) { var _this = this; this.vertices = []; this.triangles = []; var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind); var indices = this._mesh.getIndices(); var submesh = this._mesh.subMeshes[submeshIndex]; var findInVertices = function (positionToSearch) { if (optimizeMesh) { for (var ii = 0; ii < _this.vertices.length; ++ii) { if (_this.vertices[ii].position.equals(positionToSearch)) { return _this.vertices[ii]; } } } return null; }; var vertexReferences = []; var vertexInit = function (i) { if (!positionData) { return; } var offset = i + submesh.verticesStart; var position = BABYLON.Vector3.FromArray(positionData, offset * 3); var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length); vertex.originalOffsets.push(offset); if (vertex.id === _this.vertices.length) { _this.vertices.push(vertex); } vertexReferences.push(vertex.id); }; //var totalVertices = mesh.getTotalVertices(); var totalVertices = submesh.verticesCount; BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () { var indicesInit = function (i) { if (!indices) { return; } var offset = (submesh.indexStart / 3) + i; var pos = (offset * 3); var i0 = indices[pos + 0]; var i1 = indices[pos + 1]; var i2 = indices[pos + 2]; var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]]; var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]]; var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]]; var triangle = new DecimationTriangle([v0, v1, v2]); triangle.originalOffset = pos; _this.triangles.push(triangle); }; BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () { _this.init(callback); }); }); }; QuadraticErrorSimplification.prototype.init = function (callback) { var _this = this; var triangleInit1 = function (i) { var t = _this.triangles[i]; t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize(); for (var j = 0; j < 3; j++) { t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position)))); } }; BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () { var triangleInit2 = function (i) { var t = _this.triangles[i]; for (var j = 0; j < 3; ++j) { t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]); } t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]); }; BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () { _this.initialized = true; callback(); }); }); }; QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) { var newTriangles = []; var i; for (i = 0; i < this.vertices.length; ++i) { this.vertices[i].triangleCount = 0; } var t; var j; for (i = 0; i < this.triangles.length; ++i) { if (!this.triangles[i].deleted) { t = this.triangles[i]; for (j = 0; j < 3; ++j) { t.vertices[j].triangleCount = 1; } newTriangles.push(t); } } var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []); var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []); var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []); var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []); var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind); var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind); var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind); var vertexCount = 0; for (i = 0; i < this.vertices.length; ++i) { var vertex = this.vertices[i]; vertex.id = vertexCount; if (vertex.triangleCount) { vertex.originalOffsets.forEach(function (originalOffset) { if (!normalData) { return; } newPositionData.push(vertex.position.x); newPositionData.push(vertex.position.y); newPositionData.push(vertex.position.z); newNormalData.push(normalData[originalOffset * 3]); newNormalData.push(normalData[(originalOffset * 3) + 1]); newNormalData.push(normalData[(originalOffset * 3) + 2]); if (uvs && uvs.length) { newUVsData.push(uvs[(originalOffset * 2)]); newUVsData.push(uvs[(originalOffset * 2) + 1]); } else if (colorsData && colorsData.length) { newColorsData.push(colorsData[(originalOffset * 4)]); newColorsData.push(colorsData[(originalOffset * 4) + 1]); newColorsData.push(colorsData[(originalOffset * 4) + 2]); newColorsData.push(colorsData[(originalOffset * 4) + 3]); } ++vertexCount; }); } } var startingIndex = this._reconstructedMesh.getTotalIndices(); var startingVertex = this._reconstructedMesh.getTotalVertices(); var submeshesArray = this._reconstructedMesh.subMeshes; this._reconstructedMesh.subMeshes = []; var newIndicesArray = this._reconstructedMesh.getIndices(); //[]; var originalIndices = this._mesh.getIndices(); for (i = 0; i < newTriangles.length; ++i) { t = newTriangles[i]; //now get the new referencing point for each vertex [0, 1, 2].forEach(function (idx) { var id = originalIndices[t.originalOffset + idx]; var offset = t.vertices[idx].originalOffsets.indexOf(id); if (offset < 0) offset = 0; newIndicesArray.push(t.vertices[idx].id + offset + startingVertex); }); } //overwriting the old vertex buffers and indices. this._reconstructedMesh.setIndices(newIndicesArray); this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData); this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData); if (newUVsData.length > 0) this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData); if (newColorsData.length > 0) this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData); //create submesh var originalSubmesh = this._mesh.subMeshes[submeshIndex]; if (submeshIndex > 0) { this._reconstructedMesh.subMeshes = []; submeshesArray.forEach(function (submesh) { BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh()); }); BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh); } }; QuadraticErrorSimplification.prototype.initDecimatedMesh = function () { this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene()); this._reconstructedMesh.material = this._mesh.material; this._reconstructedMesh.parent = this._mesh.parent; this._reconstructedMesh.isVisible = false; this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId; }; QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) { for (var i = 0; i < vertex1.triangleCount; ++i) { var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId]; if (t.deleted) continue; var s = this.references[vertex1.triangleStart + i].vertexId; var v1 = t.vertices[(s + 1) % 3]; var v2 = t.vertices[(s + 2) % 3]; if ((v1 === vertex2 || v2 === vertex2)) { deletedArray[i] = true; delTr.push(t); continue; } var d1 = v1.position.subtract(point); d1 = d1.normalize(); var d2 = v2.position.subtract(point); d2 = d2.normalize(); if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) return true; var normal = BABYLON.Vector3.Cross(d1, d2).normalize(); deletedArray[i] = false; if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) return true; } return false; }; QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) { var newDeleted = deletedTriangles; for (var i = 0; i < vertex.triangleCount; ++i) { var ref = this.references[vertex.triangleStart + i]; var t = this.triangles[ref.triangleId]; if (t.deleted) continue; if (deletedArray[i] && t.deletePending) { t.deleted = true; newDeleted++; continue; } t.vertices[ref.vertexId] = origVertex; t.isDirty = true; t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2); t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2); t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2); t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]); this.references.push(ref); } return newDeleted; }; QuadraticErrorSimplification.prototype.identifyBorder = function () { for (var i = 0; i < this.vertices.length; ++i) { var vCount = []; var vId = []; var v = this.vertices[i]; var j; for (j = 0; j < v.triangleCount; ++j) { var triangle = this.triangles[this.references[v.triangleStart + j].triangleId]; for (var ii = 0; ii < 3; ii++) { var ofs = 0; var vv = triangle.vertices[ii]; while (ofs < vCount.length) { if (vId[ofs] === vv.id) break; ++ofs; } if (ofs === vCount.length) { vCount.push(1); vId.push(vv.id); } else { vCount[ofs]++; } } } for (j = 0; j < vCount.length; ++j) { if (vCount[j] === 1) { this.vertices[vId[j]].isBorder = true; } else { this.vertices[vId[j]].isBorder = false; } } } }; QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) { if (identifyBorders === void 0) { identifyBorders = false; } var i; if (!identifyBorders) { var newTrianglesVector = []; for (i = 0; i < this.triangles.length; ++i) { if (!this.triangles[i].deleted) { newTrianglesVector.push(this.triangles[i]); } } this.triangles = newTrianglesVector; } for (i = 0; i < this.vertices.length; ++i) { this.vertices[i].triangleCount = 0; this.vertices[i].triangleStart = 0; } var t; var j; var v; for (i = 0; i < this.triangles.length; ++i) { t = this.triangles[i]; for (j = 0; j < 3; ++j) { v = t.vertices[j]; v.triangleCount++; } } var tStart = 0; for (i = 0; i < this.vertices.length; ++i) { this.vertices[i].triangleStart = tStart; tStart += this.vertices[i].triangleCount; this.vertices[i].triangleCount = 0; } var newReferences = new Array(this.triangles.length * 3); for (i = 0; i < this.triangles.length; ++i) { t = this.triangles[i]; for (j = 0; j < 3; ++j) { v = t.vertices[j]; newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i); v.triangleCount++; } } this.references = newReferences; if (identifyBorders) { this.identifyBorder(); } }; QuadraticErrorSimplification.prototype.vertexError = function (q, point) { var x = point.x; var y = point.y; var z = point.z; return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9]; }; QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) { var q = vertex1.q.add(vertex2.q); var border = vertex1.isBorder && vertex2.isBorder; var error = 0; var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7); if (qDet !== 0 && !border) { if (!pointResult) { pointResult = BABYLON.Vector3.Zero(); } pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8)); pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8)); pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8)); error = this.vertexError(q, pointResult); } else { var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2)); //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize(); var error1 = this.vertexError(q, vertex1.position); var error2 = this.vertexError(q, vertex2.position); var error3 = this.vertexError(q, p3); error = Math.min(error1, error2, error3); if (error === error1) { if (pointResult) { pointResult.copyFrom(vertex1.position); } } else if (error === error2) { if (pointResult) { pointResult.copyFrom(vertex2.position); } } else { if (pointResult) { pointResult.copyFrom(p3); } } } return error; }; return QuadraticErrorSimplification; }()); BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.meshSimplification.js.map var BABYLON; (function (BABYLON) { var Internals; (function (Internals) { var MeshLODLevel = /** @class */ (function () { function MeshLODLevel(distance, mesh) { this.distance = distance; this.mesh = mesh; } return MeshLODLevel; }()); Internals.MeshLODLevel = MeshLODLevel; })(Internals = BABYLON.Internals || (BABYLON.Internals = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.meshLODLevel.js.map var BABYLON; (function (BABYLON) { // Standard optimizations var SceneOptimization = /** @class */ (function () { function SceneOptimization(priority) { if (priority === void 0) { priority = 0; } this.priority = priority; this.apply = function (scene) { return true; // Return true if everything that can be done was applied }; } return SceneOptimization; }()); BABYLON.SceneOptimization = SceneOptimization; var TextureOptimization = /** @class */ (function (_super) { __extends(TextureOptimization, _super); function TextureOptimization(priority, maximumSize) { if (priority === void 0) { priority = 0; } if (maximumSize === void 0) { maximumSize = 1024; } var _this = _super.call(this, priority) || this; _this.priority = priority; _this.maximumSize = maximumSize; _this.apply = function (scene) { var allDone = true; for (var index = 0; index < scene.textures.length; index++) { var texture = scene.textures[index]; if (!texture.canRescale || texture.getContext) { continue; } var currentSize = texture.getSize(); var maxDimension = Math.max(currentSize.width, currentSize.height); if (maxDimension > _this.maximumSize) { texture.scale(0.5); allDone = false; } } return allDone; }; return _this; } return TextureOptimization; }(SceneOptimization)); BABYLON.TextureOptimization = TextureOptimization; var HardwareScalingOptimization = /** @class */ (function (_super) { __extends(HardwareScalingOptimization, _super); function HardwareScalingOptimization(priority, maximumScale) { if (priority === void 0) { priority = 0; } if (maximumScale === void 0) { maximumScale = 2; } var _this = _super.call(this, priority) || this; _this.priority = priority; _this.maximumScale = maximumScale; _this._currentScale = 1; _this.apply = function (scene) { _this._currentScale++; scene.getEngine().setHardwareScalingLevel(_this._currentScale); return _this._currentScale >= _this.maximumScale; }; return _this; } return HardwareScalingOptimization; }(SceneOptimization)); BABYLON.HardwareScalingOptimization = HardwareScalingOptimization; var ShadowsOptimization = /** @class */ (function (_super) { __extends(ShadowsOptimization, _super); function ShadowsOptimization() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.apply = function (scene) { scene.shadowsEnabled = false; return true; }; return _this; } return ShadowsOptimization; }(SceneOptimization)); BABYLON.ShadowsOptimization = ShadowsOptimization; var PostProcessesOptimization = /** @class */ (function (_super) { __extends(PostProcessesOptimization, _super); function PostProcessesOptimization() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.apply = function (scene) { scene.postProcessesEnabled = false; return true; }; return _this; } return PostProcessesOptimization; }(SceneOptimization)); BABYLON.PostProcessesOptimization = PostProcessesOptimization; var LensFlaresOptimization = /** @class */ (function (_super) { __extends(LensFlaresOptimization, _super); function LensFlaresOptimization() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.apply = function (scene) { scene.lensFlaresEnabled = false; return true; }; return _this; } return LensFlaresOptimization; }(SceneOptimization)); BABYLON.LensFlaresOptimization = LensFlaresOptimization; var ParticlesOptimization = /** @class */ (function (_super) { __extends(ParticlesOptimization, _super); function ParticlesOptimization() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.apply = function (scene) { scene.particlesEnabled = false; return true; }; return _this; } return ParticlesOptimization; }(SceneOptimization)); BABYLON.ParticlesOptimization = ParticlesOptimization; var RenderTargetsOptimization = /** @class */ (function (_super) { __extends(RenderTargetsOptimization, _super); function RenderTargetsOptimization() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.apply = function (scene) { scene.renderTargetsEnabled = false; return true; }; return _this; } return RenderTargetsOptimization; }(SceneOptimization)); BABYLON.RenderTargetsOptimization = RenderTargetsOptimization; var MergeMeshesOptimization = /** @class */ (function (_super) { __extends(MergeMeshesOptimization, _super); function MergeMeshesOptimization() { var _this = _super !== null && _super.apply(this, arguments) || this; _this._canBeMerged = function (abstractMesh) { if (!(abstractMesh instanceof BABYLON.Mesh)) { return false; } var mesh = abstractMesh; if (!mesh.isVisible || !mesh.isEnabled()) { return false; } if (mesh.instances.length > 0) { return false; } if (mesh.skeleton || mesh.hasLODLevels) { return false; } if (mesh.parent) { return false; } return true; }; _this.apply = function (scene, updateSelectionTree) { var globalPool = scene.meshes.slice(0); var globalLength = globalPool.length; for (var index = 0; index < globalLength; index++) { var currentPool = new Array(); var current = globalPool[index]; // Checks if (!_this._canBeMerged(current)) { continue; } currentPool.push(current); // Find compatible meshes for (var subIndex = index + 1; subIndex < globalLength; subIndex++) { var otherMesh = globalPool[subIndex]; if (!_this._canBeMerged(otherMesh)) { continue; } if (otherMesh.material !== current.material) { continue; } if (otherMesh.checkCollisions !== current.checkCollisions) { continue; } currentPool.push(otherMesh); globalLength--; globalPool.splice(subIndex, 1); subIndex--; } if (currentPool.length < 2) { continue; } // Merge meshes BABYLON.Mesh.MergeMeshes(currentPool); } if (updateSelectionTree != undefined) { if (updateSelectionTree) { scene.createOrUpdateSelectionOctree(); } } else if (MergeMeshesOptimization.UpdateSelectionTree) { scene.createOrUpdateSelectionOctree(); } return true; }; return _this; } Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", { get: function () { return MergeMeshesOptimization._UpdateSelectionTree; }, set: function (value) { MergeMeshesOptimization._UpdateSelectionTree = value; }, enumerable: true, configurable: true }); MergeMeshesOptimization._UpdateSelectionTree = false; return MergeMeshesOptimization; }(SceneOptimization)); BABYLON.MergeMeshesOptimization = MergeMeshesOptimization; // Options var SceneOptimizerOptions = /** @class */ (function () { function SceneOptimizerOptions(targetFrameRate, trackerDuration) { if (targetFrameRate === void 0) { targetFrameRate = 60; } if (trackerDuration === void 0) { trackerDuration = 2000; } this.targetFrameRate = targetFrameRate; this.trackerDuration = trackerDuration; this.optimizations = new Array(); } SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) { var result = new SceneOptimizerOptions(targetFrameRate); var priority = 0; result.optimizations.push(new MergeMeshesOptimization(priority)); result.optimizations.push(new ShadowsOptimization(priority)); result.optimizations.push(new LensFlaresOptimization(priority)); // Next priority priority++; result.optimizations.push(new PostProcessesOptimization(priority)); result.optimizations.push(new ParticlesOptimization(priority)); // Next priority priority++; result.optimizations.push(new TextureOptimization(priority, 1024)); return result; }; SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) { var result = new SceneOptimizerOptions(targetFrameRate); var priority = 0; result.optimizations.push(new MergeMeshesOptimization(priority)); result.optimizations.push(new ShadowsOptimization(priority)); result.optimizations.push(new LensFlaresOptimization(priority)); // Next priority priority++; result.optimizations.push(new PostProcessesOptimization(priority)); result.optimizations.push(new ParticlesOptimization(priority)); // Next priority priority++; result.optimizations.push(new TextureOptimization(priority, 512)); // Next priority priority++; result.optimizations.push(new RenderTargetsOptimization(priority)); // Next priority priority++; result.optimizations.push(new HardwareScalingOptimization(priority, 2)); return result; }; SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) { var result = new SceneOptimizerOptions(targetFrameRate); var priority = 0; result.optimizations.push(new MergeMeshesOptimization(priority)); result.optimizations.push(new ShadowsOptimization(priority)); result.optimizations.push(new LensFlaresOptimization(priority)); // Next priority priority++; result.optimizations.push(new PostProcessesOptimization(priority)); result.optimizations.push(new ParticlesOptimization(priority)); // Next priority priority++; result.optimizations.push(new TextureOptimization(priority, 256)); // Next priority priority++; result.optimizations.push(new RenderTargetsOptimization(priority)); // Next priority priority++; result.optimizations.push(new HardwareScalingOptimization(priority, 4)); return result; }; return SceneOptimizerOptions; }()); BABYLON.SceneOptimizerOptions = SceneOptimizerOptions; // Scene optimizer tool var SceneOptimizer = /** @class */ (function () { function SceneOptimizer() { } SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) { // TODO: add an epsilon if (scene.getEngine().getFps() >= options.targetFrameRate) { if (onSuccess) { onSuccess(); } return; } // Apply current level of optimizations var allDone = true; var noOptimizationApplied = true; for (var index = 0; index < options.optimizations.length; index++) { var optimization = options.optimizations[index]; if (optimization.priority === currentPriorityLevel) { noOptimizationApplied = false; allDone = allDone && optimization.apply(scene); } } // If no optimization was applied, this is a failure :( if (noOptimizationApplied) { if (onFailure) { onFailure(); } return; } // If all optimizations were done, move to next level if (allDone) { currentPriorityLevel++; } // Let's the system running for a specific amount of time before checking FPS scene.executeWhenReady(function () { setTimeout(function () { SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure); }, options.trackerDuration); }); }; SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) { if (!options) { options = SceneOptimizerOptions.ModerateDegradationAllowed(); } // Let's the system running for a specific amount of time before checking FPS scene.executeWhenReady(function () { setTimeout(function () { SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure); }, options.trackerDuration); }); }; return SceneOptimizer; }()); BABYLON.SceneOptimizer = SceneOptimizer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.sceneOptimizer.js.map var BABYLON; (function (BABYLON) { var OutlineRenderer = /** @class */ (function () { function OutlineRenderer(scene) { this.zOffset = 1; this._scene = scene; } OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) { var _this = this; if (useOverlay === void 0) { useOverlay = false; } var scene = this._scene; var engine = this._scene.getEngine(); var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined); if (!this.isReady(subMesh, hardwareInstancedRendering)) { return; } var mesh = subMesh.getRenderingMesh(); var material = subMesh.getMaterial(); if (!material || !scene.activeCamera) { return; } engine.enableEffect(this._effect); // Logarithmic depth if (material.useLogarithmicDepth) { this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2)); } this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth); this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha); this._effect.setMatrix("viewProjection", scene.getTransformMatrix()); // Bones if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh)); } mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode); // Alpha test if (material && material.needAlphaTesting()) { var alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { this._effect.setTexture("diffuseSampler", alphaTexture); this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); } } engine.setZOffset(-this.zOffset); mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); }); engine.setZOffset(0); }; OutlineRenderer.prototype.isReady = function (subMesh, useInstances) { var defines = []; var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind]; var mesh = subMesh.getMesh(); var material = subMesh.getMaterial(); if (material) { // Alpha test if (material.needAlphaTesting()) { defines.push("#define ALPHATEST"); if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) { attribs.push(BABYLON.VertexBuffer.UVKind); defines.push("#define UV1"); } if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) { attribs.push(BABYLON.VertexBuffer.UV2Kind); defines.push("#define UV2"); } } //Logarithmic depth if (material.useLogarithmicDepth) { defines.push("#define LOGARITHMICDEPTH"); } } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0)); } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } // Instances if (useInstances) { defines.push("#define INSTANCES"); attribs.push("world0"); attribs.push("world1"); attribs.push("world2"); attribs.push("world3"); } // Get correct effect var join = defines.join("\n"); if (this._cachedDefines !== join) { this._cachedDefines = join; this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join); } return this._effect.isReady(); }; return OutlineRenderer; }()); BABYLON.OutlineRenderer = OutlineRenderer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.outlineRenderer.js.map var BABYLON; (function (BABYLON) { var FaceAdjacencies = /** @class */ (function () { function FaceAdjacencies() { this.edges = new Array(); this.edgesConnectedCount = 0; } return FaceAdjacencies; }()); var EdgesRenderer = /** @class */ (function () { // Beware when you use this class with complex objects as the adjacencies computation can be really long function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) { if (epsilon === void 0) { epsilon = 0.95; } if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; } this.edgesWidthScalerForOrthographic = 1000.0; this.edgesWidthScalerForPerspective = 50.0; this._linesPositions = new Array(); this._linesNormals = new Array(); this._linesIndices = new Array(); this._buffers = {}; this._checkVerticesInsteadOfIndices = false; this._source = source; this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices; this._epsilon = epsilon; this._prepareRessources(); this._generateEdgesLines(); } EdgesRenderer.prototype._prepareRessources = function () { if (this._lineShader) { return; } this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", { attributes: ["position", "normal"], uniforms: ["worldViewProjection", "color", "width", "aspectRatio"] }); this._lineShader.disableDepthWrite = true; this._lineShader.backFaceCulling = false; }; EdgesRenderer.prototype._rebuild = function () { var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind]; if (buffer) { buffer._rebuild(); } buffer = this._buffers[BABYLON.VertexBuffer.NormalKind]; if (buffer) { buffer._rebuild(); } var scene = this._source.getScene(); var engine = scene.getEngine(); this._ib = engine.createIndexBuffer(this._linesIndices); }; EdgesRenderer.prototype.dispose = function () { var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind]; if (buffer) { buffer.dispose(); this._buffers[BABYLON.VertexBuffer.PositionKind] = null; } buffer = this._buffers[BABYLON.VertexBuffer.NormalKind]; if (buffer) { buffer.dispose(); this._buffers[BABYLON.VertexBuffer.NormalKind] = null; } this._source.getScene().getEngine()._releaseBuffer(this._ib); this._lineShader.dispose(); }; EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) { if (pa === p0 && pb === p1 || pa === p1 && pb === p0) { return 0; } if (pa === p1 && pb === p2 || pa === p2 && pb === p1) { return 1; } if (pa === p2 && pb === p0 || pa === p0 && pb === p2) { return 2; } return -1; }; EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) { if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) { return 0; } if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) { return 1; } if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) { return 2; } return -1; }; EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) { var needToCreateLine; if (edge === undefined) { needToCreateLine = true; } else { var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]); needToCreateLine = dotProduct < this._epsilon; } if (needToCreateLine) { var offset = this._linesPositions.length / 3; var normal = p0.subtract(p1); normal.normalize(); // Positions this._linesPositions.push(p0.x); this._linesPositions.push(p0.y); this._linesPositions.push(p0.z); this._linesPositions.push(p0.x); this._linesPositions.push(p0.y); this._linesPositions.push(p0.z); this._linesPositions.push(p1.x); this._linesPositions.push(p1.y); this._linesPositions.push(p1.z); this._linesPositions.push(p1.x); this._linesPositions.push(p1.y); this._linesPositions.push(p1.z); // Normals this._linesNormals.push(p1.x); this._linesNormals.push(p1.y); this._linesNormals.push(p1.z); this._linesNormals.push(-1); this._linesNormals.push(p1.x); this._linesNormals.push(p1.y); this._linesNormals.push(p1.z); this._linesNormals.push(1); this._linesNormals.push(p0.x); this._linesNormals.push(p0.y); this._linesNormals.push(p0.z); this._linesNormals.push(-1); this._linesNormals.push(p0.x); this._linesNormals.push(p0.y); this._linesNormals.push(p0.z); this._linesNormals.push(1); // Indices this._linesIndices.push(offset); this._linesIndices.push(offset + 1); this._linesIndices.push(offset + 2); this._linesIndices.push(offset); this._linesIndices.push(offset + 2); this._linesIndices.push(offset + 3); } }; EdgesRenderer.prototype._generateEdgesLines = function () { var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind); var indices = this._source.getIndices(); if (!indices || !positions) { return; } // First let's find adjacencies var adjacencies = new Array(); var faceNormals = new Array(); var index; var faceAdjacencies; // Prepare faces for (index = 0; index < indices.length; index += 3) { faceAdjacencies = new FaceAdjacencies(); var p0Index = indices[index]; var p1Index = indices[index + 1]; var p2Index = indices[index + 2]; faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]); faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]); faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]); var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1)); faceNormal.normalize(); faceNormals.push(faceNormal); adjacencies.push(faceAdjacencies); } // Scan for (index = 0; index < adjacencies.length; index++) { faceAdjacencies = adjacencies[index]; for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) { var otherFaceAdjacencies = adjacencies[otherIndex]; if (faceAdjacencies.edgesConnectedCount === 3) { break; } if (otherFaceAdjacencies.edgesConnectedCount === 3) { continue; } var otherP0 = indices[otherIndex * 3]; var otherP1 = indices[otherIndex * 3 + 1]; var otherP2 = indices[otherIndex * 3 + 2]; for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) { var otherEdgeIndex = 0; if (faceAdjacencies.edges[edgeIndex] !== undefined) { continue; } switch (edgeIndex) { case 0: if (this._checkVerticesInsteadOfIndices) { otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2); } else { otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2); } break; case 1: if (this._checkVerticesInsteadOfIndices) { otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2); } else { otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2); } break; case 2: if (this._checkVerticesInsteadOfIndices) { otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2); } else { otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2); } break; } if (otherEdgeIndex === -1) { continue; } faceAdjacencies.edges[edgeIndex] = otherIndex; otherFaceAdjacencies.edges[otherEdgeIndex] = index; faceAdjacencies.edgesConnectedCount++; otherFaceAdjacencies.edgesConnectedCount++; if (faceAdjacencies.edgesConnectedCount === 3) { break; } } } } // Create lines for (index = 0; index < adjacencies.length; index++) { // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon var current = adjacencies[index]; this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1); this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2); this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0); } // Merge into a single mesh var engine = this._source.getScene().getEngine(); this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false); this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4); this._ib = engine.createIndexBuffer(this._linesIndices); this._indicesCount = this._linesIndices.length; }; EdgesRenderer.prototype.render = function () { var scene = this._source.getScene(); if (!this._lineShader.isReady() || !scene.activeCamera) { return; } var engine = scene.getEngine(); this._lineShader._preBind(); // VBOs engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect()); scene.resetCachedMaterial(); this._lineShader.setColor4("color", this._source.edgesColor); if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) { this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic); } else { this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective); } this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera)); this._lineShader.bind(this._source.getWorldMatrix()); // Draw order engine.draw(true, 0, this._indicesCount); this._lineShader.unbind(); engine.setDepthWrite(true); }; return EdgesRenderer; }()); BABYLON.EdgesRenderer = EdgesRenderer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.edgesRenderer.js.map /// /// var BABYLON; (function (BABYLON) { /** * Special Glow Blur post process only blurring the alpha channel * It enforces keeping the most luminous color in the color channel. */ var GlowBlurPostProcess = /** @class */ (function (_super) { __extends(GlowBlurPostProcess, _super); function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; } var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this; _this.direction = direction; _this.kernel = kernel; _this.onApplyObservable.add(function (effect) { effect.setFloat2("screenSize", _this.width, _this.height); effect.setVector2("direction", _this.direction); effect.setFloat("blurWidth", _this.kernel); }); return _this; } return GlowBlurPostProcess; }(BABYLON.PostProcess)); /** * The highlight layer Helps adding a glow effect around a mesh. * * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove * glowy meshes to your scene. * * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!! */ var HighlightLayer = /** @class */ (function () { /** * Instantiates a new highlight Layer and references it to the scene.. * @param name The name of the layer * @param scene The scene to use the layer in * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information) */ function HighlightLayer(name, scene, options) { this.name = name; this._vertexBuffers = {}; this._mainTextureDesiredSize = { width: 0, height: 0 }; this._meshes = {}; this._maxSize = 0; this._shouldRender = false; this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++; this._excludedMeshes = {}; /** * Specifies whether or not the inner glow is ACTIVE in the layer. */ this.innerGlow = true; /** * Specifies whether or not the outer glow is ACTIVE in the layer. */ this.outerGlow = true; /** * Specifies wether the highlight layer is enabled or not. */ this.isEnabled = true; /** * An event triggered when the highlight layer has been disposed. * @type {BABYLON.Observable} */ this.onDisposeObservable = new BABYLON.Observable(); /** * An event triggered when the highlight layer is about rendering the main texture with the glowy parts. * @type {BABYLON.Observable} */ this.onBeforeRenderMainTextureObservable = new BABYLON.Observable(); /** * An event triggered when the highlight layer is being blurred. * @type {BABYLON.Observable} */ this.onBeforeBlurObservable = new BABYLON.Observable(); /** * An event triggered when the highlight layer has been blurred. * @type {BABYLON.Observable} */ this.onAfterBlurObservable = new BABYLON.Observable(); /** * An event triggered when the glowing blurred texture is being merged in the scene. * @type {BABYLON.Observable} */ this.onBeforeComposeObservable = new BABYLON.Observable(); /** * An event triggered when the glowing blurred texture has been merged in the scene. * @type {BABYLON.Observable} */ this.onAfterComposeObservable = new BABYLON.Observable(); /** * An event triggered when the highlight layer changes its size. * @type {BABYLON.Observable} */ this.onSizeChangedObservable = new BABYLON.Observable(); this._scene = scene || BABYLON.Engine.LastCreatedScene; var engine = scene.getEngine(); this._engine = engine; this._maxSize = this._engine.getCaps().maxTextureSize; this._scene.highlightLayers.push(this); // Warn on stencil. if (!this._engine.isStencilEnable) { BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }"); } // Adapt options this._options = options || { mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }; this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5; this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0; this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1; this._options.blurVerticalSize = this._options.blurVerticalSize || 1; this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE; // VBO var vertices = []; vertices.push(1, 1); vertices.push(-1, 1); vertices.push(-1, -1); vertices.push(1, -1); var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer; this._createIndexBuffer(); // Effect this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], ""); // Render target this.setMainTextureSize(); // Create Textures and post processes this.createTextureAndPostProcesses(); } Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", { /** * Gets the horizontal size of the blur. */ get: function () { return this._horizontalBlurPostprocess.kernel; }, /** * Specifies the horizontal size of the blur. */ set: function (value) { this._horizontalBlurPostprocess.kernel = value; }, enumerable: true, configurable: true }); Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", { /** * Gets the vertical size of the blur. */ get: function () { return this._verticalBlurPostprocess.kernel; }, /** * Specifies the vertical size of the blur. */ set: function (value) { this._verticalBlurPostprocess.kernel = value; }, enumerable: true, configurable: true }); Object.defineProperty(HighlightLayer.prototype, "camera", { /** * Gets the camera attached to the layer. */ get: function () { return this._options.camera; }, enumerable: true, configurable: true }); HighlightLayer.prototype._createIndexBuffer = function () { var engine = this._scene.getEngine(); // Indices var indices = []; indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); this._indexBuffer = engine.createIndexBuffer(indices); }; HighlightLayer.prototype._rebuild = function () { var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]; if (vb) { vb._rebuild(); } this._createIndexBuffer(); }; /** * Creates the render target textures and post processes used in the highlight layer. */ HighlightLayer.prototype.createTextureAndPostProcesses = function () { var _this = this; var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio; var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio; blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth; blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight; this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", { width: this._mainTextureDesiredSize.width, height: this._mainTextureDesiredSize.height }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this._mainTexture.activeCamera = this._options.camera; this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; this._mainTexture.anisotropicFilteringLevel = 1; this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE); this._mainTexture.renderParticles = false; this._mainTexture.renderList = null; this._mainTexture.ignoreCameraViewport = true; this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", { width: blurTextureWidth, height: blurTextureHeight }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; this._blurTexture.anisotropicFilteringLevel = 16; this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE); this._blurTexture.renderParticles = false; this._blurTexture.ignoreCameraViewport = true; this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine()); this._downSamplePostprocess.onApplyObservable.add(function (effect) { effect.setTexture("textureSampler", _this._mainTexture); }); if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) { this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine()); this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) { effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); }); this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine()); this._verticalBlurPostprocess.onApplyObservable.add(function (effect) { effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); }); } else { this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine()); this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) { effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); }); this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine()); this._verticalBlurPostprocess.onApplyObservable.add(function (effect) { effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); }); } this._mainTexture.onAfterUnbindObservable.add(function () { _this.onBeforeBlurObservable.notifyObservers(_this); var internalTexture = _this._blurTexture.getInternalTexture(); if (internalTexture) { _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true); } _this.onAfterBlurObservable.notifyObservers(_this); }); // Custom render function var renderSubMesh = function (subMesh) { if (!_this._meshes) { return; } var material = subMesh.getMaterial(); var mesh = subMesh.getRenderingMesh(); var scene = _this._scene; var engine = scene.getEngine(); if (!material) { return; } // Culling engine.setState(material.backFaceCulling); // Managing instances var batch = mesh._getInstancesRenderList(subMesh._id); if (batch.mustReturn) { return; } // Excluded Mesh if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) { return; } ; var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined); var highlightLayerMesh = _this._meshes[mesh.uniqueId]; var emissiveTexture = null; if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) { emissiveTexture = material.emissiveTexture; } if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) { engine.enableEffect(_this._glowMapGenerationEffect); mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode); _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix()); if (highlightLayerMesh) { _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0); } else { _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a); } // Alpha test if (material && material.needAlphaTesting()) { var alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture); var textureMatrix = alphaTexture.getTextureMatrix(); if (textureMatrix) { _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix); } } } // Glow emissive only if (emissiveTexture) { _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture); _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix()); } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh)); } // Draw mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); }); } else { // Need to reset refresh rate of the shadowMap _this._mainTexture.resetRefreshCounter(); } }; this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { _this.onBeforeRenderMainTextureObservable.notifyObservers(_this); var index; var engine = _this._scene.getEngine(); if (depthOnlySubMeshes.length) { engine.setColorWrite(false); for (index = 0; index < depthOnlySubMeshes.length; index++) { renderSubMesh(depthOnlySubMeshes.data[index]); } engine.setColorWrite(true); } for (index = 0; index < opaqueSubMeshes.length; index++) { renderSubMesh(opaqueSubMeshes.data[index]); } for (index = 0; index < alphaTestSubMeshes.length; index++) { renderSubMesh(alphaTestSubMeshes.data[index]); } for (index = 0; index < transparentSubMeshes.length; index++) { renderSubMesh(transparentSubMeshes.data[index]); } }; this._mainTexture.onClearObservable.add(function (engine) { engine.clear(HighlightLayer.neutralColor, true, true, true); }); }; /** * Checks for the readiness of the element composing the layer. * @param subMesh the mesh to check for * @param useInstances specify wether or not to use instances to render the mesh * @param emissiveTexture the associated emissive texture used to generate the glow * @return true if ready otherwise, false */ HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) { var material = subMesh.getMaterial(); if (!material) { return false; } if (!material.isReady(subMesh.getMesh(), useInstances)) { return false; } var defines = []; var attribs = [BABYLON.VertexBuffer.PositionKind]; var mesh = subMesh.getMesh(); var uv1 = false; var uv2 = false; // Alpha test if (material && material.needAlphaTesting()) { var alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { defines.push("#define ALPHATEST"); if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) && alphaTexture.coordinatesIndex === 1) { defines.push("#define DIFFUSEUV2"); uv2 = true; } else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) { defines.push("#define DIFFUSEUV1"); uv1 = true; } } } // Emissive if (emissiveTexture) { defines.push("#define EMISSIVE"); if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) && emissiveTexture.coordinatesIndex === 1) { defines.push("#define EMISSIVEUV2"); uv2 = true; } else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) { defines.push("#define EMISSIVEUV1"); uv1 = true; } } if (uv1) { attribs.push(BABYLON.VertexBuffer.UVKind); defines.push("#define UV1"); } if (uv2) { attribs.push(BABYLON.VertexBuffer.UV2Kind); defines.push("#define UV2"); } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0)); } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } // Instances if (useInstances) { defines.push("#define INSTANCES"); attribs.push("world0"); attribs.push("world1"); attribs.push("world2"); attribs.push("world3"); } // Get correct effect var join = defines.join("\n"); if (this._cachedDefines !== join) { this._cachedDefines = join; this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join); } return this._glowMapGenerationEffect.isReady(); }; /** * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene. */ HighlightLayer.prototype.render = function () { var currentEffect = this._glowMapMergeEffect; // Check if (!currentEffect.isReady() || !this._blurTexture.isReady()) return; var engine = this._scene.getEngine(); this.onBeforeComposeObservable.notifyObservers(this); // Render engine.enableEffect(currentEffect); engine.setState(false); // Cache var previousStencilBuffer = engine.getStencilBuffer(); var previousStencilFunction = engine.getStencilFunction(); var previousStencilMask = engine.getStencilMask(); var previousStencilOperationPass = engine.getStencilOperationPass(); var previousStencilOperationFail = engine.getStencilOperationFail(); var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail(); var previousAlphaMode = engine.getAlphaMode(); // Texture currentEffect.setTexture("textureSampler", this._blurTexture); // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect); // Stencil operations engine.setStencilOperationPass(BABYLON.Engine.REPLACE); engine.setStencilOperationFail(BABYLON.Engine.KEEP); engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP); // Draw order engine.setAlphaMode(this._options.alphaBlendingMode); engine.setStencilMask(0x00); engine.setStencilBuffer(true); engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference); if (this.outerGlow) { currentEffect.setFloat("offset", 0); engine.setStencilFunction(BABYLON.Engine.NOTEQUAL); engine.draw(true, 0, 6); } if (this.innerGlow) { currentEffect.setFloat("offset", 1); engine.setStencilFunction(BABYLON.Engine.EQUAL); engine.draw(true, 0, 6); } // Restore Cache engine.setStencilFunction(previousStencilFunction); engine.setStencilMask(previousStencilMask); engine.setAlphaMode(previousAlphaMode); engine.setStencilBuffer(previousStencilBuffer); engine.setStencilOperationPass(previousStencilOperationPass); engine.setStencilOperationFail(previousStencilOperationFail); engine.setStencilOperationDepthFail(previousStencilOperationDepthFail); engine._stencilState.reset(); this.onAfterComposeObservable.notifyObservers(this); // Handle size changes. var size = this._mainTexture.getSize(); this.setMainTextureSize(); if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) { // Recreate RTT and post processes on size change. this.onSizeChangedObservable.notifyObservers(this); this.disposeTextureAndPostProcesses(); this.createTextureAndPostProcesses(); } }; /** * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer. * @param mesh The mesh to exclude from the highlight layer */ HighlightLayer.prototype.addExcludedMesh = function (mesh) { if (!this._excludedMeshes) { return; } var meshExcluded = this._excludedMeshes[mesh.uniqueId]; if (!meshExcluded) { this._excludedMeshes[mesh.uniqueId] = { mesh: mesh, beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) { mesh.getEngine().setStencilBuffer(false); }), afterRender: mesh.onAfterRenderObservable.add(function (mesh) { mesh.getEngine().setStencilBuffer(true); }), }; } }; /** * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer. * @param mesh The mesh to highlight */ HighlightLayer.prototype.removeExcludedMesh = function (mesh) { if (!this._excludedMeshes) { return; } var meshExcluded = this._excludedMeshes[mesh.uniqueId]; if (meshExcluded) { if (meshExcluded.beforeRender) { mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender); } if (meshExcluded.afterRender) { mesh.onAfterRenderObservable.remove(meshExcluded.afterRender); } } this._excludedMeshes[mesh.uniqueId] = null; }; /** * Add a mesh in the highlight layer in order to make it glow with the chosen color. * @param mesh The mesh to highlight * @param color The color of the highlight * @param glowEmissiveOnly Extract the glow from the emissive texture */ HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) { var _this = this; if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; } if (!this._meshes) { return; } var meshHighlight = this._meshes[mesh.uniqueId]; if (meshHighlight) { meshHighlight.color = color; } else { this._meshes[mesh.uniqueId] = { mesh: mesh, color: color, // Lambda required for capture due to Observable this context observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) { if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) { _this.defaultStencilReference(mesh); } else { mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference); } }), observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference), glowEmissiveOnly: glowEmissiveOnly }; } this._shouldRender = true; }; /** * Remove a mesh from the highlight layer in order to make it stop glowing. * @param mesh The mesh to highlight */ HighlightLayer.prototype.removeMesh = function (mesh) { if (!this._meshes) { return; } var meshHighlight = this._meshes[mesh.uniqueId]; if (meshHighlight) { if (meshHighlight.observerHighlight) { mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight); } if (meshHighlight.observerDefault) { mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault); } } this._meshes[mesh.uniqueId] = null; this._shouldRender = false; for (var meshHighlightToCheck in this._meshes) { if (meshHighlightToCheck) { this._shouldRender = true; break; } } }; /** * Returns true if the layer contains information to display, otherwise false. */ HighlightLayer.prototype.shouldRender = function () { return this.isEnabled && this._shouldRender; }; /** * Sets the main texture desired size which is the closest power of two * of the engine canvas size. */ HighlightLayer.prototype.setMainTextureSize = function () { if (this._options.mainTextureFixedSize) { this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize; this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize; } else { this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio; this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio; this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width; this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height; } }; /** * Force the stencil to the normal expected value for none glowing parts */ HighlightLayer.prototype.defaultStencilReference = function (mesh) { mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference); }; /** * Dispose only the render target textures and post process. */ HighlightLayer.prototype.disposeTextureAndPostProcesses = function () { this._blurTexture.dispose(); this._mainTexture.dispose(); this._downSamplePostprocess.dispose(); this._horizontalBlurPostprocess.dispose(); this._verticalBlurPostprocess.dispose(); }; /** * Dispose the highlight layer and free resources. */ HighlightLayer.prototype.dispose = function () { var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]; if (vertexBuffer) { vertexBuffer.dispose(); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } // Clean textures and post processes this.disposeTextureAndPostProcesses(); if (this._meshes) { // Clean mesh references for (var id in this._meshes) { var meshHighlight = this._meshes[id]; if (meshHighlight && meshHighlight.mesh) { if (meshHighlight.observerHighlight) { meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight); } if (meshHighlight.observerDefault) { meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault); } } } this._meshes = null; } if (this._excludedMeshes) { for (var id in this._excludedMeshes) { var meshHighlight = this._excludedMeshes[id]; if (meshHighlight) { if (meshHighlight.beforeRender) { meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender); } if (meshHighlight.afterRender) { meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender); } } } this._excludedMeshes = null; } // Remove from scene var index = this._scene.highlightLayers.indexOf(this, 0); if (index > -1) { this._scene.highlightLayers.splice(index, 1); } // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.onBeforeRenderMainTextureObservable.clear(); this.onBeforeBlurObservable.clear(); this.onBeforeComposeObservable.clear(); this.onAfterComposeObservable.clear(); this.onSizeChangedObservable.clear(); }; /** * The neutral color used during the preparation of the glow effect. * This is black by default as the blend operation is a blend operation. */ HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0); /** * Stencil value used for glowing meshes. */ HighlightLayer.glowingMeshStencilReference = 0x02; /** * Stencil value used for the other meshes in the scene. */ HighlightLayer.normalMeshStencilReference = 0x01; return HighlightLayer; }()); BABYLON.HighlightLayer = HighlightLayer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.highlightlayer.js.map var BABYLON; (function (BABYLON) { var AssetTaskState; (function (AssetTaskState) { AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT"; AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING"; AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE"; AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR"; })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {})); var AbstractAssetTask = /** @class */ (function () { function AbstractAssetTask(name) { this.name = name; this.isCompleted = false; this.taskState = AssetTaskState.INIT; } AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) { var _this = this; this.taskState = AssetTaskState.RUNNING; this.runTask(scene, function () { _this.onDoneCallback(onSuccess, onError); }, function (msg, exception) { _this.onErrorCallback(onError, msg, exception); }); }; AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) { throw new Error("runTask is not implemented"); }; AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) { this.taskState = AssetTaskState.ERROR; this.errorObject = { message: message, exception: exception }; if (this.onError) { this.onError(this, message, exception); } onError(); }; AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) { try { this.taskState = AssetTaskState.DONE; this.isCompleted = true; if (this.onSuccess) { this.onSuccess(this); } onSuccess(); } catch (e) { this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e); } }; return AbstractAssetTask; }()); BABYLON.AbstractAssetTask = AbstractAssetTask; var MeshAssetTask = /** @class */ (function (_super) { __extends(MeshAssetTask, _super); function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) { var _this = _super.call(this, name) || this; _this.name = name; _this.meshesNames = meshesNames; _this.rootUrl = rootUrl; _this.sceneFilename = sceneFilename; return _this; } MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) { var _this = this; BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) { _this.loadedMeshes = meshes; _this.loadedParticleSystems = particleSystems; _this.loadedSkeletons = skeletons; onSuccess(); }, null, function (scene, message, exception) { onError(message, exception); }); }; return MeshAssetTask; }(AbstractAssetTask)); BABYLON.MeshAssetTask = MeshAssetTask; var TextFileAssetTask = /** @class */ (function (_super) { __extends(TextFileAssetTask, _super); function TextFileAssetTask(name, url) { var _this = _super.call(this, name) || this; _this.name = name; _this.url = url; return _this; } TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) { var _this = this; BABYLON.Tools.LoadFile(this.url, function (data) { _this.text = data; onSuccess(); }, undefined, scene.database, false, function (request, exception) { if (request) { onError(request.status + " " + request.statusText, exception); } }); }; return TextFileAssetTask; }(AbstractAssetTask)); BABYLON.TextFileAssetTask = TextFileAssetTask; var BinaryFileAssetTask = /** @class */ (function (_super) { __extends(BinaryFileAssetTask, _super); function BinaryFileAssetTask(name, url) { var _this = _super.call(this, name) || this; _this.name = name; _this.url = url; return _this; } BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) { var _this = this; BABYLON.Tools.LoadFile(this.url, function (data) { _this.data = data; onSuccess(); }, undefined, scene.database, true, function (request, exception) { if (request) { onError(request.status + " " + request.statusText, exception); } }); }; return BinaryFileAssetTask; }(AbstractAssetTask)); BABYLON.BinaryFileAssetTask = BinaryFileAssetTask; var ImageAssetTask = /** @class */ (function (_super) { __extends(ImageAssetTask, _super); function ImageAssetTask(name, url) { var _this = _super.call(this, name) || this; _this.name = name; _this.url = url; return _this; } ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) { var _this = this; var img = new Image(); BABYLON.Tools.SetCorsBehavior(this.url, img); img.onload = function () { _this.image = img; onSuccess(); }; img.onerror = function (err) { onError("Error loading image", err); }; img.src = this.url; }; return ImageAssetTask; }(AbstractAssetTask)); BABYLON.ImageAssetTask = ImageAssetTask; var TextureAssetTask = /** @class */ (function (_super) { __extends(TextureAssetTask, _super); function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } var _this = _super.call(this, name) || this; _this.name = name; _this.url = url; _this.noMipmap = noMipmap; _this.invertY = invertY; _this.samplingMode = samplingMode; return _this; } TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) { var onload = function () { onSuccess(); }; var onerror = function (msg, exception) { onError(msg, exception); }; this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror); }; return TextureAssetTask; }(AbstractAssetTask)); BABYLON.TextureAssetTask = TextureAssetTask; var CubeTextureAssetTask = /** @class */ (function (_super) { __extends(CubeTextureAssetTask, _super); function CubeTextureAssetTask(name, url, extensions, noMipmap, files) { var _this = _super.call(this, name) || this; _this.name = name; _this.url = url; _this.extensions = extensions; _this.noMipmap = noMipmap; _this.files = files; return _this; } CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) { var onload = function () { onSuccess(); }; var onerror = function (msg, exception) { onError(msg, exception); }; this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror); }; return CubeTextureAssetTask; }(AbstractAssetTask)); BABYLON.CubeTextureAssetTask = CubeTextureAssetTask; var HDRCubeTextureAssetTask = /** @class */ (function (_super) { __extends(HDRCubeTextureAssetTask, _super); function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) { if (noMipmap === void 0) { noMipmap = false; } if (generateHarmonics === void 0) { generateHarmonics = true; } if (useInGammaSpace === void 0) { useInGammaSpace = false; } if (usePMREMGenerator === void 0) { usePMREMGenerator = false; } var _this = _super.call(this, name) || this; _this.name = name; _this.url = url; _this.size = size; _this.noMipmap = noMipmap; _this.generateHarmonics = generateHarmonics; _this.useInGammaSpace = useInGammaSpace; _this.usePMREMGenerator = usePMREMGenerator; return _this; } HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) { var onload = function () { onSuccess(); }; var onerror = function (message, exception) { onError(message, exception); }; this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror); }; return HDRCubeTextureAssetTask; }(AbstractAssetTask)); BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask; var AssetsManager = /** @class */ (function () { function AssetsManager(scene) { this.tasks = new Array(); this.waitingTasksCount = 0; //Observables this.onTaskSuccessObservable = new BABYLON.Observable(); this.onTaskErrorObservable = new BABYLON.Observable(); this.onTasksDoneObservable = new BABYLON.Observable(); this.useDefaultLoadingScreen = true; this._scene = scene; } AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) { var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename); this.tasks.push(task); return task; }; AssetsManager.prototype.addTextFileTask = function (taskName, url) { var task = new TextFileAssetTask(taskName, url); this.tasks.push(task); return task; }; AssetsManager.prototype.addBinaryFileTask = function (taskName, url) { var task = new BinaryFileAssetTask(taskName, url); this.tasks.push(task); return task; }; AssetsManager.prototype.addImageTask = function (taskName, url) { var task = new ImageAssetTask(taskName, url); this.tasks.push(task); return task; }; AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) { if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode); this.tasks.push(task); return task; }; AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) { var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files); this.tasks.push(task); return task; }; AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) { if (noMipmap === void 0) { noMipmap = false; } if (generateHarmonics === void 0) { generateHarmonics = true; } if (useInGammaSpace === void 0) { useInGammaSpace = false; } if (usePMREMGenerator === void 0) { usePMREMGenerator = false; } var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator); this.tasks.push(task); return task; }; AssetsManager.prototype._decreaseWaitingTasksCount = function () { this.waitingTasksCount--; if (this.waitingTasksCount === 0) { try { if (this.onFinish) { this.onFinish(this.tasks); } this.onTasksDoneObservable.notifyObservers(this.tasks); } catch (e) { BABYLON.Tools.Error("Error running tasks-done callbacks."); console.log(e); } this._scene.getEngine().hideLoadingUI(); } }; AssetsManager.prototype._runTask = function (task) { var _this = this; var done = function () { try { if (_this.onTaskSuccess) { _this.onTaskSuccess(task); } _this.onTaskSuccessObservable.notifyObservers(task); _this._decreaseWaitingTasksCount(); } catch (e) { error("Error executing task success callbacks", e); } }; var error = function (message, exception) { task.errorObject = task.errorObject || { message: message, exception: exception }; if (_this.onTaskError) { _this.onTaskError(task); } _this.onTaskErrorObservable.notifyObservers(task); _this._decreaseWaitingTasksCount(); }; task.run(this._scene, done, error); }; AssetsManager.prototype.reset = function () { this.tasks = new Array(); return this; }; AssetsManager.prototype.load = function () { this.waitingTasksCount = this.tasks.length; if (this.waitingTasksCount === 0) { if (this.onFinish) { this.onFinish(this.tasks); } this.onTasksDoneObservable.notifyObservers(this.tasks); return this; } if (this.useDefaultLoadingScreen) { this._scene.getEngine().displayLoadingUI(); } for (var index = 0; index < this.tasks.length; index++) { var task = this.tasks[index]; this._runTask(task); } return this; }; return AssetsManager; }()); BABYLON.AssetsManager = AssetsManager; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.assetsManager.js.map var BABYLON; (function (BABYLON) { var serializedGeometries = []; var serializeGeometry = function (geometry, serializationGeometries) { if (serializedGeometries[geometry.id]) { return; } if (geometry.doNotSerialize) { return; } if (geometry instanceof BABYLON.Geometry.Primitives.Box) { serializationGeometries.boxes.push(geometry.serialize()); } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) { serializationGeometries.spheres.push(geometry.serialize()); } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) { serializationGeometries.cylinders.push(geometry.serialize()); } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) { serializationGeometries.toruses.push(geometry.serialize()); } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) { serializationGeometries.grounds.push(geometry.serialize()); } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) { serializationGeometries.planes.push(geometry.serialize()); } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) { serializationGeometries.torusKnots.push(geometry.serialize()); } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) { throw new Error("Unknown primitive type"); } else { serializationGeometries.vertexData.push(geometry.serializeVerticeData()); } serializedGeometries[geometry.id] = true; }; var serializeMesh = function (mesh, serializationScene) { var serializationObject = {}; // Geometry var geometry = mesh._geometry; if (geometry) { if (!mesh.getScene().getGeometryByID(geometry.id)) { // Geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry serializeGeometry(geometry, serializationScene.geometries); } } // Custom if (mesh.serialize) { mesh.serialize(serializationObject); } return serializationObject; }; var finalizeSingleMesh = function (mesh, serializationObject) { //only works if the mesh is already loaded if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) { //serialize material if (mesh.material) { if (mesh.material instanceof BABYLON.StandardMaterial) { serializationObject.materials = serializationObject.materials || []; if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) { serializationObject.materials.push(mesh.material.serialize()); } } else if (mesh.material instanceof BABYLON.MultiMaterial) { serializationObject.multiMaterials = serializationObject.multiMaterials || []; if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) { serializationObject.multiMaterials.push(mesh.material.serialize()); } } } //serialize geometry var geometry = mesh._geometry; if (geometry) { if (!serializationObject.geometries) { serializationObject.geometries = {}; serializationObject.geometries.boxes = []; serializationObject.geometries.spheres = []; serializationObject.geometries.cylinders = []; serializationObject.geometries.toruses = []; serializationObject.geometries.grounds = []; serializationObject.geometries.planes = []; serializationObject.geometries.torusKnots = []; serializationObject.geometries.vertexData = []; } serializeGeometry(geometry, serializationObject.geometries); } // Skeletons if (mesh.skeleton) { serializationObject.skeletons = serializationObject.skeletons || []; serializationObject.skeletons.push(mesh.skeleton.serialize()); } //serialize the actual mesh serializationObject.meshes = serializationObject.meshes || []; serializationObject.meshes.push(serializeMesh(mesh, serializationObject)); } }; var SceneSerializer = /** @class */ (function () { function SceneSerializer() { } SceneSerializer.ClearCache = function () { serializedGeometries = []; }; SceneSerializer.Serialize = function (scene) { var serializationObject = {}; SceneSerializer.ClearCache(); // Scene serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading; serializationObject.autoClear = scene.autoClear; serializationObject.clearColor = scene.clearColor.asArray(); serializationObject.ambientColor = scene.ambientColor.asArray(); serializationObject.gravity = scene.gravity.asArray(); serializationObject.collisionsEnabled = scene.collisionsEnabled; serializationObject.workerCollisions = scene.workerCollisions; // Fog if (scene.fogMode && scene.fogMode !== 0) { serializationObject.fogMode = scene.fogMode; serializationObject.fogColor = scene.fogColor.asArray(); serializationObject.fogStart = scene.fogStart; serializationObject.fogEnd = scene.fogEnd; serializationObject.fogDensity = scene.fogDensity; } //Physics if (scene.isPhysicsEnabled()) { var physicEngine = scene.getPhysicsEngine(); if (physicEngine) { serializationObject.physicsEnabled = true; serializationObject.physicsGravity = physicEngine.gravity.asArray(); serializationObject.physicsEngine = physicEngine.getPhysicsPluginName(); } } // Metadata if (scene.metadata) { serializationObject.metadata = scene.metadata; } // Morph targets serializationObject.morphTargetManagers = []; for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) { var abstractMesh = _a[_i]; var manager = abstractMesh.morphTargetManager; if (manager) { serializationObject.morphTargetManagers.push(manager.serialize()); } } // Lights serializationObject.lights = []; var index; var light; for (index = 0; index < scene.lights.length; index++) { light = scene.lights[index]; if (!light.doNotSerialize) { serializationObject.lights.push(light.serialize()); } } // Cameras serializationObject.cameras = []; for (index = 0; index < scene.cameras.length; index++) { var camera = scene.cameras[index]; if (!camera.doNotSerialize) { serializationObject.cameras.push(camera.serialize()); } } if (scene.activeCamera) { serializationObject.activeCameraID = scene.activeCamera.id; } // Animations BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject); // Materials serializationObject.materials = []; serializationObject.multiMaterials = []; var material; for (index = 0; index < scene.materials.length; index++) { material = scene.materials[index]; if (!material.doNotSerialize) { serializationObject.materials.push(material.serialize()); } } // MultiMaterials serializationObject.multiMaterials = []; for (index = 0; index < scene.multiMaterials.length; index++) { var multiMaterial = scene.multiMaterials[index]; serializationObject.multiMaterials.push(multiMaterial.serialize()); } // Skeletons serializationObject.skeletons = []; for (index = 0; index < scene.skeletons.length; index++) { serializationObject.skeletons.push(scene.skeletons[index].serialize()); } // Geometries serializationObject.geometries = {}; serializationObject.geometries.boxes = []; serializationObject.geometries.spheres = []; serializationObject.geometries.cylinders = []; serializationObject.geometries.toruses = []; serializationObject.geometries.grounds = []; serializationObject.geometries.planes = []; serializationObject.geometries.torusKnots = []; serializationObject.geometries.vertexData = []; serializedGeometries = []; var geometries = scene.getGeometries(); for (index = 0; index < geometries.length; index++) { var geometry = geometries[index]; if (geometry.isReady()) { serializeGeometry(geometry, serializationObject.geometries); } } // Meshes serializationObject.meshes = []; for (index = 0; index < scene.meshes.length; index++) { var abstractMesh = scene.meshes[index]; if (abstractMesh instanceof BABYLON.Mesh) { var mesh = abstractMesh; if (!mesh.doNotSerialize) { if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) { serializationObject.meshes.push(serializeMesh(mesh, serializationObject)); } } } } // Particles Systems serializationObject.particleSystems = []; for (index = 0; index < scene.particleSystems.length; index++) { serializationObject.particleSystems.push(scene.particleSystems[index].serialize()); } // Lens flares serializationObject.lensFlareSystems = []; for (index = 0; index < scene.lensFlareSystems.length; index++) { serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize()); } // Shadows serializationObject.shadowGenerators = []; for (index = 0; index < scene.lights.length; index++) { light = scene.lights[index]; var shadowGenerator = light.getShadowGenerator(); if (shadowGenerator) { serializationObject.shadowGenerators.push(shadowGenerator.serialize()); } } // Action Manager if (scene.actionManager) { serializationObject.actions = scene.actionManager.serialize("scene"); } // Audio serializationObject.sounds = []; for (index = 0; index < scene.soundTracks.length; index++) { var soundtrack = scene.soundTracks[index]; for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) { serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize()); } } return serializationObject; }; SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) { if (withParents === void 0) { withParents = false; } if (withChildren === void 0) { withChildren = false; } var serializationObject = {}; SceneSerializer.ClearCache(); toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize]; if (withParents || withChildren) { //deliberate for loop! not for each, appended should be processed as well. for (var i = 0; i < toSerialize.length; ++i) { if (withChildren) { toSerialize[i].getDescendants().forEach(function (node) { if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) { toSerialize.push(node); } }); } //make sure the array doesn't contain the object already if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) { toSerialize.push(toSerialize[i].parent); } } } toSerialize.forEach(function (mesh) { finalizeSingleMesh(mesh, serializationObject); }); return serializationObject; }; return SceneSerializer; }()); BABYLON.SceneSerializer = SceneSerializer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.sceneSerializer.js.map var BABYLON; (function (BABYLON) { var ReflectionProbe = /** @class */ (function () { function ReflectionProbe(name, size, scene, generateMipMaps) { if (generateMipMaps === void 0) { generateMipMaps = true; } var _this = this; this.name = name; this._viewMatrix = BABYLON.Matrix.Identity(); this._target = BABYLON.Vector3.Zero(); this._add = BABYLON.Vector3.Zero(); this.invertYAxis = false; this.position = BABYLON.Vector3.Zero(); this._scene = scene; this._scene.reflectionProbes.push(this); this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true); this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) { switch (faceIndex) { case 0: _this._add.copyFromFloats(1, 0, 0); break; case 1: _this._add.copyFromFloats(-1, 0, 0); break; case 2: _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0); break; case 3: _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0); break; case 4: _this._add.copyFromFloats(0, 0, 1); break; case 5: _this._add.copyFromFloats(0, 0, -1); break; } if (_this._attachedMesh) { _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition()); } _this.position.addToRef(_this._add, _this._target); BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix); scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix); }); this._renderTargetTexture.onAfterUnbindObservable.add(function () { scene.updateTransformMatrix(true); }); if (scene.activeCamera) { this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ); } } Object.defineProperty(ReflectionProbe.prototype, "samples", { get: function () { return this._renderTargetTexture.samples; }, set: function (value) { this._renderTargetTexture.samples = value; }, enumerable: true, configurable: true }); Object.defineProperty(ReflectionProbe.prototype, "refreshRate", { get: function () { return this._renderTargetTexture.refreshRate; }, set: function (value) { this._renderTargetTexture.refreshRate = value; }, enumerable: true, configurable: true }); ReflectionProbe.prototype.getScene = function () { return this._scene; }; Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", { get: function () { return this._renderTargetTexture; }, enumerable: true, configurable: true }); Object.defineProperty(ReflectionProbe.prototype, "renderList", { get: function () { return this._renderTargetTexture.renderList; }, enumerable: true, configurable: true }); ReflectionProbe.prototype.attachToMesh = function (mesh) { this._attachedMesh = mesh; }; /** * 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. */ ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) { this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil); }; ReflectionProbe.prototype.dispose = function () { var index = this._scene.reflectionProbes.indexOf(this); if (index !== -1) { // Remove from the scene if found this._scene.reflectionProbes.splice(index, 1); } if (this._renderTargetTexture) { this._renderTargetTexture.dispose(); this._renderTargetTexture = null; } }; return ReflectionProbe; }()); BABYLON.ReflectionProbe = ReflectionProbe; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.reflectionProbe.js.map var BABYLON; (function (BABYLON) { var Layer = /** @class */ (function () { function Layer(name, imgUrl, scene, isBackground, color) { this.name = name; this.scale = new BABYLON.Vector2(1, 1); this.offset = new BABYLON.Vector2(0, 0); this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE; this.layerMask = 0x0FFFFFFF; this._vertexBuffers = {}; // Events /** * An event triggered when the layer is disposed. * @type {BABYLON.Observable} */ this.onDisposeObservable = new BABYLON.Observable(); /** * An event triggered before rendering the scene * @type {BABYLON.Observable} */ this.onBeforeRenderObservable = new BABYLON.Observable(); /** * An event triggered after rendering the scene * @type {BABYLON.Observable} */ this.onAfterRenderObservable = new BABYLON.Observable(); this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null; this.isBackground = isBackground === undefined ? true : isBackground; this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color; this._scene = (scene || BABYLON.Engine.LastCreatedScene); this._scene.layers.push(this); var engine = this._scene.getEngine(); // VBO var vertices = []; vertices.push(1, 1); vertices.push(-1, 1); vertices.push(-1, -1); vertices.push(1, -1); var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer; this._createIndexBuffer(); // Effects this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], ""); this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST"); } Object.defineProperty(Layer.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(Layer.prototype, "onBeforeRender", { set: function (callback) { if (this._onBeforeRenderObserver) { this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); } this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(Layer.prototype, "onAfterRender", { set: function (callback) { if (this._onAfterRenderObserver) { this.onAfterRenderObservable.remove(this._onAfterRenderObserver); } this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); }, enumerable: true, configurable: true }); Layer.prototype._createIndexBuffer = function () { var engine = this._scene.getEngine(); // Indices var indices = []; indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); this._indexBuffer = engine.createIndexBuffer(indices); }; Layer.prototype._rebuild = function () { var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]; if (vb) { vb._rebuild(); } this._createIndexBuffer(); }; Layer.prototype.render = function () { var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect; // Check if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) return; var engine = this._scene.getEngine(); this.onBeforeRenderObservable.notifyObservers(this); // Render engine.enableEffect(currentEffect); engine.setState(false); // Texture currentEffect.setTexture("textureSampler", this.texture); currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix()); // Color currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a); // Scale / offset currentEffect.setVector2("offset", this.offset); currentEffect.setVector2("scale", this.scale); // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect); // Draw order if (!this.alphaTest) { engine.setAlphaMode(this.alphaBlendingMode); engine.draw(true, 0, 6); engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE); } else { engine.draw(true, 0, 6); } this.onAfterRenderObservable.notifyObservers(this); }; Layer.prototype.dispose = function () { var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]; if (vertexBuffer) { vertexBuffer.dispose(); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } if (this.texture) { this.texture.dispose(); this.texture = null; } // Remove from scene var index = this._scene.layers.indexOf(this); this._scene.layers.splice(index, 1); // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.onAfterRenderObservable.clear(); this.onBeforeRenderObservable.clear(); }; return Layer; }()); BABYLON.Layer = Layer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.layer.js.map var BABYLON; (function (BABYLON) { var TextureTools = /** @class */ (function () { function TextureTools() { } /** * Uses the GPU to create a copy texture rescaled at a given size * @param texture Texture to copy from * @param width Desired width * @param height Desired height * @return Generated texture */ TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) { if (useBilinearMode === void 0) { useBilinearMode = true; } var scene = texture.getScene(); var engine = scene.getEngine(); var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false); rtt.wrapU = texture.wrapU; rtt.wrapV = texture.wrapV; rtt.uOffset = texture.uOffset; rtt.vOffset = texture.vOffset; rtt.uScale = texture.uScale; rtt.vScale = texture.vScale; rtt.uAng = texture.uAng; rtt.vAng = texture.vAng; rtt.wAng = texture.wAng; rtt.coordinatesIndex = texture.coordinatesIndex; rtt.level = texture.level; rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel; rtt._texture.isReady = false; texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT); passPostProcess.getEffect().executeWhenCompiled(function () { passPostProcess.onApply = function (effect) { effect.setTexture("textureSampler", texture); }; var internalTexture = rtt.getInternalTexture(); if (internalTexture) { scene.postProcessManager.directRender([passPostProcess], internalTexture); engine.unBindFramebuffer(internalTexture); rtt.disposeFramebufferObjects(); passPostProcess.dispose(); internalTexture.isReady = true; } }); return rtt; }; TextureTools.GetEnvironmentBRDFTexture = function (scene) { if (!scene._environmentBRDFTexture) { var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE); texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; scene._environmentBRDFTexture = texture; } return scene._environmentBRDFTexture; }; TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII="; return TextureTools; }()); BABYLON.TextureTools = TextureTools; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.textureTools.js.map var BABYLON; (function (BABYLON) { var FramingBehavior = /** @class */ (function () { function FramingBehavior() { this._mode = FramingBehavior.FitFrustumSidesMode; this._radiusScale = 1.0; this._positionScale = 0.5; this._defaultElevation = 0.3; this._elevationReturnTime = 1500; this._elevationReturnWaitTime = 1000; this._zoomStopsAnimation = false; this._framingTime = 1500; this._isPointerDown = false; this._lastInteractionTime = -Infinity; // Framing control this._animatables = new Array(); this._betaIsAnimating = false; } Object.defineProperty(FramingBehavior.prototype, "name", { get: function () { return "Framing"; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "mode", { /** * Gets current mode used by the behavior. */ get: function () { return this._mode; }, /** * Sets the current mode used by the behavior */ set: function (mode) { this._mode = mode; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "radiusScale", { /** * Gets the scale applied to the radius */ get: function () { return this._radiusScale; }, /** * Sets the scale applied to the radius (1 by default) */ set: function (radius) { this._radiusScale = radius; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "positionScale", { /** * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. */ get: function () { return this._positionScale; }, /** * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. */ set: function (scale) { this._positionScale = scale; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "defaultElevation", { /** * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle * behaviour is triggered, in radians. */ get: function () { return this._defaultElevation; }, /** * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle * behaviour is triggered, in radians. */ set: function (elevation) { this._defaultElevation = elevation; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", { /** * Gets the time (in milliseconds) taken to return to the default beta position. * Negative value indicates camera should not return to default. */ get: function () { return this._elevationReturnTime; }, /** * Sets the time (in milliseconds) taken to return to the default beta position. * Negative value indicates camera should not return to default. */ set: function (speed) { this._elevationReturnTime = speed; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", { /** * Gets the delay (in milliseconds) taken before the camera returns to the default beta position. */ get: function () { return this._elevationReturnWaitTime; }, /** * Sets the delay (in milliseconds) taken before the camera returns to the default beta position. */ set: function (time) { this._elevationReturnWaitTime = time; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", { /** * Gets the flag that indicates if user zooming should stop animation. */ get: function () { return this._zoomStopsAnimation; }, /** * Sets the flag that indicates if user zooming should stop animation. */ set: function (flag) { this._zoomStopsAnimation = flag; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "framingTime", { /** * Gets the transition time when framing the mesh, in milliseconds */ get: function () { return this._framingTime; }, /** * Sets the transition time when framing the mesh, in milliseconds */ set: function (time) { this._framingTime = time; }, enumerable: true, configurable: true }); FramingBehavior.prototype.attach = function (camera) { var _this = this; this._attachedCamera = camera; var scene = this._attachedCamera.getScene(); FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode); this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) { if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) { _this._isPointerDown = true; return; } if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) { _this._isPointerDown = false; } }); this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) { if (mesh) { _this.zoomOnMesh(mesh); } }); this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { // Stop the animation if there is user interaction and the animation should stop for this interaction _this._applyUserInteraction(); // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it // back to the default position after a given timeout _this._maintainCameraAboveGround(); }); }; FramingBehavior.prototype.detach = function () { if (!this._attachedCamera) { return; } var scene = this._attachedCamera.getScene(); if (this._onPrePointerObservableObserver) { scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); } if (this._onAfterCheckInputsObserver) { this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); } if (this._onMeshTargetChangedObserver) { this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); } this._attachedCamera = null; }; /** * Targets the given mesh and updates zoom level accordingly. * @param mesh The mesh to target. * @param radius Optional. If a cached radius position already exists, overrides default. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh * @param onAnimationEnd Callback triggered at the end of the framing animation */ FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) { if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } if (onAnimationEnd === void 0) { onAnimationEnd = null; } mesh.computeWorldMatrix(true); var boundingBox = mesh.getBoundingInfo().boundingBox; this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd); }; /** * Targets the given mesh and updates zoom level accordingly. * @param mesh The mesh to target. * @param radius Optional. If a cached radius position already exists, overrides default. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh * @param onAnimationEnd Callback triggered at the end of the framing animation */ FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) { var _this = this; if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } if (onAnimationEnd === void 0) { onAnimationEnd = null; } var zoomTarget; if (!this._attachedCamera) { return; } // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY var bottom = minimumWorld.y; var top = maximumWorld.y; var zoomTargetY = bottom + (top - bottom) * this._positionScale; var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5); if (focusOnOriginXZ) { zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0); } else { var centerWorld = minimumWorld.add(radiusWorld); zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z); } if (!this._vectorTransition) { this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction); } this._betaIsAnimating = true; var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime); if (animatable) { this._animatables.push(animatable); } // sets the radius and lower radius bounds // Small delta ensures camera is not always at lower zoom limit. var radius = 0; if (this._mode === FramingBehavior.FitFrustumSidesMode) { var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ; radius = position; } else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) { radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); if (this._attachedCamera.lowerRadiusLimit === null) { this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ; } } // Set sensibilities var extend = maximumWorld.subtract(minimumWorld).length(); this._attachedCamera.panningSensibility = 5000 / extend; this._attachedCamera.wheelPrecision = 100 / radius; // transition to new radius if (!this._radiusTransition) { this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); } animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () { if (onAnimationEnd) { onAnimationEnd(); } if (_this._attachedCamera) { _this._attachedCamera.storeState(); } }); if (animatable) { this._animatables.push(animatable); } }; /** * Calculates the lowest radius for the camera based on the bounding box of the mesh. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary * frustum width. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order * to fully enclose the mesh in the viewing frustum. */ FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) { var size = maximumWorld.subtract(minimumWorld); var boxVectorGlobalDiagonal = size.length(); var frustumSlope = this._getFrustumSlope(); // Formula for setting distance // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene) var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5; // Horizon distance var radius = radiusWithoutFraming * this._radiusScale; var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x)); var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y)); var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum); var camera = this._attachedCamera; if (!camera) { return 0; } if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) { // Don't exceed the requested limit distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance; } // Don't exceed the upper radius limit if (camera.upperRadiusLimit) { distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance; } return distance; }; /** * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera * is automatically returned to its default position (expected to be above ground plane). */ FramingBehavior.prototype._maintainCameraAboveGround = function () { var _this = this; if (this._elevationReturnTime < 0) { return; } var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime; var defaultBeta = Math.PI * 0.5 - this._defaultElevation; var limitBeta = Math.PI * 0.5; // Bring the camera back up if below the ground plane if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) { this._betaIsAnimating = true; //Transition to new position this.stopAllAnimations(); if (!this._betaTransition) { this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); } var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () { _this._clearAnimationLocks(); _this.stopAllAnimations(); }); if (animatabe) { this._animatables.push(animatabe); } } }; /** * Returns the frustum slope based on the canvas ratio and camera FOV * @returns The frustum slope represented as a Vector2 with X and Y slopes */ FramingBehavior.prototype._getFrustumSlope = function () { // Calculate the viewport ratio // Aspect Ratio is Height/Width. var camera = this._attachedCamera; if (!camera) { return BABYLON.Vector2.Zero(); } var engine = camera.getScene().getEngine(); var aspectRatio = engine.getAspectRatio(camera); // Camera FOV is the vertical field of view (top-bottom) in radians. // Slope of the frustum top/bottom planes in view space, relative to the forward vector. var frustumSlopeY = Math.tan(camera.fov / 2); // Slope of the frustum left/right planes in view space, relative to the forward vector. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit // along the forward vector. var frustumSlopeX = frustumSlopeY * aspectRatio; return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY); }; /** * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties. */ FramingBehavior.prototype._clearAnimationLocks = function () { this._betaIsAnimating = false; }; /** * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. */ FramingBehavior.prototype._applyUserInteraction = function () { if (this.isUserIsMoving) { this._lastInteractionTime = BABYLON.Tools.Now; this.stopAllAnimations(); this._clearAnimationLocks(); } }; /** * Stops and removes all animations that have been applied to the camera */ FramingBehavior.prototype.stopAllAnimations = function () { if (this._attachedCamera) { this._attachedCamera.animations = []; } while (this._animatables.length) { if (this._animatables[0]) { this._animatables[0].onAnimationEnd = null; this._animatables[0].stop(); } this._animatables.shift(); } }; Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", { /** * Gets a value indicating if the user is moving the camera */ get: function () { if (!this._attachedCamera) { return false; } return this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown; }, enumerable: true, configurable: true }); /** * The easing function used by animations */ FramingBehavior.EasingFunction = new BABYLON.ExponentialEase(); /** * The easing mode used by animations */ FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; // Statics /** * The camera can move all the way towards the mesh. */ FramingBehavior.IgnoreBoundsSizeMode = 0; /** * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides */ FramingBehavior.FitFrustumSidesMode = 1; return FramingBehavior; }()); BABYLON.FramingBehavior = FramingBehavior; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.framingBehavior.js.map var BABYLON; (function (BABYLON) { /** * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius */ var BouncingBehavior = /** @class */ (function () { function BouncingBehavior() { /** * The duration of the animation, in milliseconds */ this.transitionDuration = 450; /** * Length of the distance animated by the transition when lower radius is reached */ this.lowerRadiusTransitionRange = 2; /** * Length of the distance animated by the transition when upper radius is reached */ this.upperRadiusTransitionRange = -2; this._autoTransitionRange = false; // Animations this._radiusIsAnimating = false; this._radiusBounceTransition = null; this._animatables = new Array(); } Object.defineProperty(BouncingBehavior.prototype, "name", { get: function () { return "Bouncing"; }, enumerable: true, configurable: true }); Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", { /** * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically */ get: function () { return this._autoTransitionRange; }, /** * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically * Transition ranges will be set to 5% of the bounding box diagonal in world space */ set: function (value) { var _this = this; if (this._autoTransitionRange === value) { return; } this._autoTransitionRange = value; var camera = this._attachedCamera; if (!camera) { return; } if (value) { this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) { if (!mesh) { return; } mesh.computeWorldMatrix(true); var diagonal = mesh.getBoundingInfo().diagonalLength; _this.lowerRadiusTransitionRange = diagonal * 0.05; _this.upperRadiusTransitionRange = diagonal * 0.05; }); } else if (this._onMeshTargetChangedObserver) { camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); } }, enumerable: true, configurable: true }); BouncingBehavior.prototype.attach = function (camera) { var _this = this; this._attachedCamera = camera; this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { if (!_this._attachedCamera) { return; } // Add the bounce animation to the lower radius limit if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) { _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange); } // Add the bounce animation to the upper radius limit if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) { _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange); } }); }; BouncingBehavior.prototype.detach = function () { if (!this._attachedCamera) { return; } if (this._onAfterCheckInputsObserver) { this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); } if (this._onMeshTargetChangedObserver) { this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); } this._attachedCamera = null; }; /** * Checks if the camera radius is at the specified limit. Takes into account animation locks. * @param radiusLimit The limit to check against. * @return Bool to indicate if at limit. */ BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) { if (!this._attachedCamera) { return false; } if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) { return true; } return false; }; /** * Applies an animation to the radius of the camera, extending by the radiusDelta. * @param radiusDelta The delta by which to animate to. Can be negative. */ BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) { var _this = this; if (!this._attachedCamera) { return; } if (!this._radiusBounceTransition) { BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode); this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction); } // Prevent zoom until bounce has completed this._cachedWheelPrecision = this._attachedCamera.wheelPrecision; this._attachedCamera.wheelPrecision = Infinity; this._attachedCamera.inertialRadiusOffset = 0; // Animate to the radius limit this.stopAllAnimations(); this._radiusIsAnimating = true; var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }); if (animatable) { this._animatables.push(animatable); } }; /** * Removes all animation locks. Allows new animations to be added to any of the camera properties. */ BouncingBehavior.prototype._clearAnimationLocks = function () { this._radiusIsAnimating = false; if (this._attachedCamera) { this._attachedCamera.wheelPrecision = this._cachedWheelPrecision; } }; /** * Stops and removes all animations that have been applied to the camera */ BouncingBehavior.prototype.stopAllAnimations = function () { if (this._attachedCamera) { this._attachedCamera.animations = []; } while (this._animatables.length) { this._animatables[0].onAnimationEnd = null; this._animatables[0].stop(); this._animatables.shift(); } }; /** * The easing function used by animations */ BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3); /** * The easing mode used by animations */ BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT; return BouncingBehavior; }()); BABYLON.BouncingBehavior = BouncingBehavior; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.bouncingBehavior.js.map var BABYLON; (function (BABYLON) { var AutoRotationBehavior = /** @class */ (function () { function AutoRotationBehavior() { this._zoomStopsAnimation = false; this._idleRotationSpeed = 0.05; this._idleRotationWaitTime = 2000; this._idleRotationSpinupTime = 2000; this._isPointerDown = false; this._lastFrameTime = null; this._lastInteractionTime = -Infinity; this._cameraRotationSpeed = 0; this._lastFrameRadius = 0; } Object.defineProperty(AutoRotationBehavior.prototype, "name", { get: function () { return "AutoRotation"; }, enumerable: true, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", { /** * Gets the flag that indicates if user zooming should stop animation. */ get: function () { return this._zoomStopsAnimation; }, /** * Sets the flag that indicates if user zooming should stop animation. */ set: function (flag) { this._zoomStopsAnimation = flag; }, enumerable: true, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", { /** * Gets the default speed at which the camera rotates around the model. */ get: function () { return this._idleRotationSpeed; }, /** * Sets the default speed at which the camera rotates around the model. */ set: function (speed) { this._idleRotationSpeed = speed; }, enumerable: true, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", { /** * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating. */ get: function () { return this._idleRotationWaitTime; }, /** * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating. */ set: function (time) { this._idleRotationWaitTime = time; }, enumerable: true, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", { /** * Gets the time (milliseconds) to take to spin up to the full idle rotation speed. */ get: function () { return this._idleRotationSpinupTime; }, /** * Sets the time (milliseconds) to take to spin up to the full idle rotation speed. */ set: function (time) { this._idleRotationSpinupTime = time; }, enumerable: true, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", { /** * Gets a value indicating if the camera is currently rotating because of this behavior */ get: function () { return Math.abs(this._cameraRotationSpeed) > 0; }, enumerable: true, configurable: true }); AutoRotationBehavior.prototype.attach = function (camera) { var _this = this; this._attachedCamera = camera; var scene = this._attachedCamera.getScene(); this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) { if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) { _this._isPointerDown = true; return; } if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) { _this._isPointerDown = false; } }); this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { var now = BABYLON.Tools.Now; var dt = 0; if (_this._lastFrameTime != null) { dt = now - _this._lastFrameTime; } _this._lastFrameTime = now; // Stop the animation if there is user interaction and the animation should stop for this interaction _this._applyUserInteraction(); var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime; var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0); _this._cameraRotationSpeed = _this._idleRotationSpeed * scale; // Step camera rotation by rotation speed if (_this._attachedCamera) { _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000); } }); }; AutoRotationBehavior.prototype.detach = function () { if (!this._attachedCamera) { return; } var scene = this._attachedCamera.getScene(); if (this._onPrePointerObservableObserver) { scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); } this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); this._attachedCamera = null; }; /** * Returns true if user is scrolling. * @return true if user is scrolling. */ AutoRotationBehavior.prototype._userIsZooming = function () { if (!this._attachedCamera) { return false; } return this._attachedCamera.inertialRadiusOffset !== 0; }; AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () { if (!this._attachedCamera) { return false; } var zoomHasHitLimit = false; if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) { zoomHasHitLimit = true; } // Update the record of previous radius - works as an approx. indicator of hitting radius limits this._lastFrameRadius = this._attachedCamera.radius; return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming(); }; /** * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. */ AutoRotationBehavior.prototype._applyUserInteraction = function () { if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) { this._lastInteractionTime = BABYLON.Tools.Now; } }; // Tools AutoRotationBehavior.prototype._userIsMoving = function () { if (!this._attachedCamera) { return false; } return this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown; }; return AutoRotationBehavior; }()); BABYLON.AutoRotationBehavior = AutoRotationBehavior; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.autoRotationBehavior.js.map BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include\n#include\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\nvoid main(void) {\n#include\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include\n#include\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#include\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include\n\n#include\n\n#include\n\n#include[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include\n#include\n#include\n\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n\n#include\nvoid main(void) {\n#include\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && !defined(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include\n#include(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include\n\n#include\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include\n\n#include\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; imaxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN\n#include\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include\n#include\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include[3]\n#else\n#include[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i\n#include\n#include\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include\n\n#include\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include\n#include\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include\n\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"}; BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; icurrRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"}; /// var BABYLON; (function (BABYLON) { var GridMaterialDefines = /** @class */ (function (_super) { __extends(GridMaterialDefines, _super); function GridMaterialDefines() { var _this = _super.call(this) || this; _this.TRANSPARENT = false; _this.FOG = false; _this.PREMULTIPLYALPHA = false; _this.rebuild(); return _this; } return GridMaterialDefines; }(BABYLON.MaterialDefines)); /** * The grid materials allows you to wrap any shape with a grid. * Colors are customizable. */ var GridMaterial = /** @class */ (function (_super) { __extends(GridMaterial, _super); /** * constructor * @param name The name given to the material in order to identify it afterwards. * @param scene The scene the material is used in. */ function GridMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; /** * Main color of the grid (e.g. between lines) */ _this.mainColor = BABYLON.Color3.Black(); /** * Color of the grid lines. */ _this.lineColor = BABYLON.Color3.Teal(); /** * The scale of the grid compared to unit. */ _this.gridRatio = 1.0; /** * Allows setting an offset for the grid lines. */ _this.gridOffset = BABYLON.Vector3.Zero(); /** * The frequency of thicker lines. */ _this.majorUnitFrequency = 10; /** * The visibility of minor units in the grid. */ _this.minorUnitVisibility = 0.33; /** * The grid opacity outside of the lines. */ _this.opacity = 1.0; /** * Determine RBG output is premultiplied by alpha value. */ _this.preMultiplyAlpha = false; _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity); return _this; } /** * Returns wehter or not the grid requires alpha blending. */ GridMaterial.prototype.needAlphaBlending = function () { return this.opacity < 1.0; }; GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { if (this.isFrozen) { if (this._wasPreviouslyReady && subMesh.effect) { return true; } } if (!subMesh._materialDefines) { subMesh._materialDefines = new GridMaterialDefines(); } var defines = subMesh._materialDefines; var scene = this.getScene(); if (!this.checkReadyOnEveryCall && subMesh.effect) { if (this._renderId === scene.getRenderId()) { return true; } } if (defines.TRANSPARENT !== (this.opacity < 1.0)) { defines.TRANSPARENT = !defines.TRANSPARENT; defines.markAsUnprocessed(); } if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) { defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA; defines.markAsUnprocessed(); } BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines); // Get correct effect if (defines.isDirty) { defines.markAsProcessed(); scene.resetCachedMaterial(); // Attributes var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind]; // Defines var join = defines.toString(); subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines); } if (!subMesh.effect || !subMesh.effect.isReady()) { return false; } this._renderId = scene.getRenderId(); this._wasPreviouslyReady = true; return true; }; GridMaterial.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); this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix())); this._activeEffect.setMatrix("view", scene.getViewMatrix()); this._activeEffect.setMatrix("projection", scene.getProjectionMatrix()); // Uniforms if (this._mustRebind(scene, effect)) { this._activeEffect.setColor3("mainColor", this.mainColor); this._activeEffect.setColor3("lineColor", this.lineColor); this._activeEffect.setVector3("gridOffset", this.gridOffset); this._gridControl.x = this.gridRatio; this._gridControl.y = Math.round(this.majorUnitFrequency); this._gridControl.z = this.minorUnitVisibility; this._gridControl.w = this.opacity; this._activeEffect.setVector4("gridControl", this._gridControl); } // Fog BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect); this._afterBind(mesh, this._activeEffect); }; GridMaterial.prototype.dispose = function (forceDisposeEffect) { _super.prototype.dispose.call(this, forceDisposeEffect); }; GridMaterial.prototype.clone = function (name) { var _this = this; return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this); }; GridMaterial.prototype.serialize = function () { var serializationObject = BABYLON.SerializationHelper.Serialize(this); serializationObject.customType = "BABYLON.GridMaterial"; return serializationObject; }; GridMaterial.prototype.getClassName = function () { return "GridMaterial"; }; GridMaterial.Parse = function (source, scene, rootUrl) { return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl); }; __decorate([ BABYLON.serializeAsColor3() ], GridMaterial.prototype, "mainColor", void 0); __decorate([ BABYLON.serializeAsColor3() ], GridMaterial.prototype, "lineColor", void 0); __decorate([ BABYLON.serialize() ], GridMaterial.prototype, "gridRatio", void 0); __decorate([ BABYLON.serializeAsColor3() ], GridMaterial.prototype, "gridOffset", void 0); __decorate([ BABYLON.serialize() ], GridMaterial.prototype, "majorUnitFrequency", void 0); __decorate([ BABYLON.serialize() ], GridMaterial.prototype, "minorUnitVisibility", void 0); __decorate([ BABYLON.serialize() ], GridMaterial.prototype, "opacity", void 0); __decorate([ BABYLON.serialize() ], GridMaterial.prototype, "preMultiplyAlpha", void 0); return GridMaterial; }(BABYLON.PushMaterial)); BABYLON.GridMaterial = GridMaterial; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.gridmaterial.js.map BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}"; BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}"; /// var BABYLON; (function (BABYLON) { /** * Background material defines definition. */ var BackgroundMaterialDefines = /** @class */ (function (_super) { __extends(BackgroundMaterialDefines, _super); /** * Constructor of the defines. */ function BackgroundMaterialDefines() { var _this = _super.call(this) || this; /** * True if the opacity texture is in use. */ _this.OPACITY = false; /** * The direct UV channel to use. */ _this.OPACITYDIRECTUV = 0; /** * True if the opacity texture is used in gray scale. */ _this.OPACITYRGB = false; /** * True if the environment texture is in use. */ _this.ENVIRONMENT = false; /** * True if the environment is defined in gamma space. */ _this.GAMMAENVIRONMENT = false; /** * True if the environment texture does not contain background dedicated data. * The material will fallback to use the luminance of the background. */ _this.RGBENVIRONMENT = false; /** * True if an extra blur needs to be added in the environment. */ _this.ENVIRONMENTBLUR = false; /** * False if the current Webgl implementation does not support the texture lod extension. */ _this.TEXTURELODSUPPORT = false; /** * True if you want the material to fade to the environment color at grazing angle. */ _this.OPACITYFRESNEL = false; /** * True if you want the shadow being generated from the diffuse color of the light. * It is actually using 1 - diffuse to adpat the color to the color not reflected * by the target. */ _this.SHADOWFROMLIGHTCOLOR = false; // Image Processing Configuration. _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; // Default BJS. _this.MAINUV1 = false; _this.MAINUV2 = false; _this.UV1 = false; _this.UV2 = false; _this.CLIPPLANE = false; _this.POINTSIZE = false; _this.FOG = false; _this.NORMAL = false; _this.NUM_BONE_INFLUENCERS = 0; _this.BonesPerMesh = 0; _this.INSTANCES = false; _this.SHADOWFLOAT = false; _this.rebuild(); return _this; } return BackgroundMaterialDefines; }(BABYLON.MaterialDefines)); /** * Background material */ var BackgroundMaterial = /** @class */ (function (_super) { __extends(BackgroundMaterial, _super); /** * constructor * @param name The name of the material * @param scene The scene to add the material to */ function BackgroundMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; _this.primaryColor = BABYLON.Color3.White(); _this.primaryLevel = 1; _this.secondaryColor = BABYLON.Color3.Gray(); _this.secondaryLevel = 1; _this.thirdColor = BABYLON.Color3.Black(); _this.thirdLevel = 1; _this.environmentTexture = null; _this.opacityTexture = null; _this.environmentBlur = 0; _this.lightChannelsInTexture = false; /** * Specify the list of lights casting shadow on the material. * All scene shadow lights will be included if null. */ _this._shadowLights = null; _this.shadowLights = null; _this.shadowBlurScale = 1; _this.shadowLevel = 0; _this.opacityFresnel = true; /** * Keep track of the image processing observer to allow dispose and replace. */ _this._imageProcessingObserver = null; /** * Number of Simultaneous lights allowed on the material. */ _this._maxSimultaneousLights = 4; // Temp values kept as cache in the material. _this._renderTargets = new BABYLON.SmartArray(16); // Setup the default processing configuration to the scene. _this._attachImageProcessingConfiguration(null); _this.getRenderTargetTextures = function () { _this._renderTargets.reset(); if (_this._opacityTexture && _this._opacityTexture.isRenderTarget) { _this._renderTargets.push(_this._opacityTexture); } if (_this._environmentTexture && _this._environmentTexture.isRenderTarget) { _this._renderTargets.push(_this._environmentTexture); } return _this._renderTargets; }; return _this; } /** * Attaches a new image processing configuration to the PBR Material. * @param configuration (if null the scene configuration will be use) */ BackgroundMaterial.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(BackgroundMaterial.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(BackgroundMaterial.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(BackgroundMaterial.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(BackgroundMaterial.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(BackgroundMaterial.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(BackgroundMaterial.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(BackgroundMaterial.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(BackgroundMaterial.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 }); /** * The entire material has been created in order to prevent overdraw. * @returns false */ BackgroundMaterial.prototype.needAlphaTesting = function () { return false; }; /** * The entire material has been created in order to prevent overdraw. * @returns false */ BackgroundMaterial.prototype.needAlphaBlending = function () { return false; }; /** * Gets the environment texture to use in the material. * @returns the texture */ BackgroundMaterial.prototype._getEnvironmentTexture = function () { if (this._environmentTexture) { return this._environmentTexture; } return this.getScene().environmentTexture; }; /** * Checks wether the material is ready to be rendered for a given mesh. * @param mesh The mesh to render * @param subMesh The submesh to check against * @param useInstances Specify wether or not the material is used with instances */ BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { var _this = this; if (useInstances === void 0) { useInstances = false; } if (subMesh.effect && this.isFrozen) { if (this._wasPreviouslyReady) { return true; } } if (!subMesh._materialDefines) { subMesh._materialDefines = new BackgroundMaterialDefines(); } 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, false, this._maxSimultaneousLights); defines._needNormals = true; // Textures if (defines._areTexturesDirty) { defines._needUVs = false; if (scene.texturesEnabled) { if (scene.getEngine().getCaps().textureLOD) { defines.TEXTURELODSUPPORT = true; } if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) { if (!this._opacityTexture.isReadyOrNotBlocking()) { return false; } BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY"); defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB; defines.OPACITYFRESNEL = this._opacityFresnel; } else { defines.OPACITY = false; defines.OPACITYRGB = false; defines.OPACITYFRESNEL = false; } var environmentTexture = this._getEnvironmentTexture(); if (environmentTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) { if (!environmentTexture.isReadyOrNotBlocking()) { return false; } BABYLON.MaterialHelper.PrepareDefinesForMergedUV(environmentTexture, defines, "ENVIRONMENT"); defines.GAMMAENVIRONMENT = environmentTexture.gammaSpace; defines.ENVIRONMENTBLUR = this._environmentBlur > 0; defines.RGBENVIRONMENT = !this.lightChannelsInTexture; } else { defines.ENVIRONMENT = false; defines.GAMMAENVIRONMENT = false; defines.RGBENVIRONMENT = false; } } } if (defines._areImageProcessingDirty) { if (!this._imageProcessingConfiguration.isReady()) { return false; } this._imageProcessingConfiguration.prepareDefines(defines); } // Misc. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines); // Values that need to be evaluated on every frame BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false); // Attribs if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) { if (mesh) { if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) { mesh.createNormals(true); BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name); } } } // Get correct effect if (defines.isDirty) { defines.markAsProcessed(); scene.resetCachedMaterial(); // Fallbacks var fallbacks = new BABYLON.EffectFallbacks(); if (defines.FOG) { fallbacks.addFallback(0, "FOG"); } if (defines.POINTSIZE) { fallbacks.addFallback(1, "POINTSIZE"); } BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights); if (defines.NUM_BONE_INFLUENCERS > 0) { fallbacks.addCPUSkinningFallback(0, mesh); } //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); } BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks); BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines); var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vFogInfos", "vFogColor", "pointSize", "vClipPlane", "mBones", "vPrimaryColor", "vSecondaryColor", "vThirdColor", "vEnvironmentInfo", "environmentMatrix", "vEnvironmentMicrosurfaceInfos", "shadowLevel", "vOpacityInfo", "opacityMatrix", ]; var samplers = ["opacitySampler", "environmentSampler", "environmentSamplerLow", "environmentSamplerHigh"]; 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("background", { attributes: attribs, uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers: samplers, defines: join, fallbacks: fallbacks, onCompiled: onCompiled, onError: this.onError, indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights } }, engine), defines); this.buildUniformLayout(); } if (!subMesh.effect || !subMesh.effect.isReady()) { return false; } defines._renderId = scene.getRenderId(); this._wasPreviouslyReady = true; return true; }; /** * Build the uniform buffer used in the material. */ BackgroundMaterial.prototype.buildUniformLayout = function () { // Order is important ! this._uniformBuffer.addUniform("vPrimaryColor", 4); this._uniformBuffer.addUniform("vSecondaryColor", 4); this._uniformBuffer.addUniform("vThirdColor", 4); this._uniformBuffer.addUniform("vOpacityInfo", 2); this._uniformBuffer.addUniform("vEnvironmentInfo", 2); this._uniformBuffer.addUniform("opacityMatrix", 16); this._uniformBuffer.addUniform("environmentMatrix", 16); this._uniformBuffer.addUniform("vEnvironmentMicrosurfaceInfos", 3); this._uniformBuffer.addUniform("pointSize", 1); this._uniformBuffer.addUniform("shadowLevel", 1); this._uniformBuffer.create(); }; /** * Unbind the material. */ BackgroundMaterial.prototype.unbind = function () { if (this._opacityTexture && this._opacityTexture.isRenderTarget) { this._uniformBuffer.setTexture("opacitySampler", null); } if (this._environmentTexture && this._environmentTexture.isRenderTarget) { this._uniformBuffer.setTexture("environmentSampler", null); } _super.prototype.unbind.call(this); }; /** * Bind only the world matrix to the material. * @param world The world matrix to bind. */ BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) { this._activeEffect.setMatrix("world", world); }; /** * Bind the material for a dedicated submeh (every used meshes will be considered opaque). * @param world The world matrix to bind. * @param subMesh The submesh to bind for. */ BackgroundMaterial.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); // Bones BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect); var mustRebind = this._mustRebind(scene, effect, mesh.visibility); if (mustRebind) { this._uniformBuffer.bindToEffect(effect, "Material"); this.bindViewProjection(effect); var environmentTexture = this._getEnvironmentTexture(); if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) { // Texture uniforms if (scene.texturesEnabled) { if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) { this._uniformBuffer.updateFloat2("vOpacityInfo", this._opacityTexture.coordinatesIndex, this._opacityTexture.level); BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity"); } if (environmentTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) { this._uniformBuffer.updateMatrix("environmentMatrix", environmentTexture.getReflectionTextureMatrix()); this._uniformBuffer.updateFloat2("vEnvironmentInfo", environmentTexture.level, this._environmentBlur); this._uniformBuffer.updateFloat3("vEnvironmentMicrosurfaceInfos", environmentTexture.getSize().width, environmentTexture.lodGenerationScale, environmentTexture.lodGenerationOffset); } } if (this.shadowLevel > 0) { this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel); } // Point size if (this.pointsCloud) { this._uniformBuffer.updateFloat("pointSize", this.pointSize); } this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel); this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel); this._uniformBuffer.updateColor4("vThirdColor", this._thirdColor, this._thirdLevel); } // Textures if (scene.texturesEnabled) { if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) { this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture); } if (environmentTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) { if (defines.ENVIRONMENTBLUR && defines.TEXTURELODSUPPORT) { this._uniformBuffer.setTexture("environmentSampler", environmentTexture); } else if (!defines.ENVIRONMENTBLUR) { this._uniformBuffer.setTexture("environmentSampler", environmentTexture); } else { this._uniformBuffer.setTexture("environmentSampler", environmentTexture._lodTextureMid || environmentTexture); this._uniformBuffer.setTexture("environmentSamplerLow", environmentTexture._lodTextureLow || environmentTexture); this._uniformBuffer.setTexture("environmentSamplerHigh", environmentTexture._lodTextureHigh || environmentTexture); } } } // Clip plane BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene); var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition; // var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null)); effect.setFloat3("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z); } if (mustRebind || !this.isFrozen) { if (scene.lightsEnabled) { BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false); } // View this.bindView(effect); // Fog BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect); // image processing this._imageProcessingConfiguration.bind(this._activeEffect); } this._uniformBuffer.update(); this._afterBind(mesh); }; /** * Dispose the material. * @forceDisposeEffect Force disposal of the associated effect. * @forceDisposeTextures Force disposal of the associated textures. */ BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) { if (forceDisposeEffect === void 0) { forceDisposeEffect = false; } if (forceDisposeTextures === void 0) { forceDisposeTextures = false; } if (forceDisposeTextures) { if (this.opacityTexture) { this.opacityTexture.dispose(); } if (this.environmentTexture) { this.environmentTexture.dispose(); } } this._renderTargets.dispose(); if (this._imageProcessingConfiguration && this._imageProcessingObserver) { this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); } _super.prototype.dispose.call(this, forceDisposeEffect); }; /** * Clones the material. * @name The cloned name. * @returns The cloned material. */ BackgroundMaterial.prototype.clone = function (name) { var _this = this; return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this); }; /** * Serializes the current material to its JSON representation. * @returns The JSON representation. */ BackgroundMaterial.prototype.serialize = function () { var serializationObject = BABYLON.SerializationHelper.Serialize(this); serializationObject.customType = "BABYLON.BackgroundMaterial"; return serializationObject; }; /** * Gets the class name of the material * @returns "BackgroundMaterial" */ BackgroundMaterial.prototype.getClassName = function () { return "BackgroundMaterial"; }; /** * Parse a JSON input to create back a background material. * @param source * @param scene * @param rootUrl * @returns the instantiated BackgroundMaterial. */ BackgroundMaterial.Parse = function (source, scene, rootUrl) { return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl); }; __decorate([ BABYLON.serializeAsColor3() ], BackgroundMaterial.prototype, "_primaryColor", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty") ], BackgroundMaterial.prototype, "primaryColor", void 0); __decorate([ BABYLON.serialize() ], BackgroundMaterial.prototype, "_primaryLevel", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty") ], BackgroundMaterial.prototype, "primaryLevel", void 0); __decorate([ BABYLON.serializeAsColor3() ], BackgroundMaterial.prototype, "_secondaryColor", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty") ], BackgroundMaterial.prototype, "secondaryColor", void 0); __decorate([ BABYLON.serialize() ], BackgroundMaterial.prototype, "_secondaryLevel", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty") ], BackgroundMaterial.prototype, "secondaryLevel", void 0); __decorate([ BABYLON.serializeAsColor3() ], BackgroundMaterial.prototype, "_thirdColor", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty") ], BackgroundMaterial.prototype, "thirdColor", void 0); __decorate([ BABYLON.serialize() ], BackgroundMaterial.prototype, "_thirdLevel", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty") ], BackgroundMaterial.prototype, "thirdLevel", void 0); __decorate([ BABYLON.serializeAsTexture() ], BackgroundMaterial.prototype, "_environmentTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "environmentTexture", void 0); __decorate([ BABYLON.serializeAsTexture() ], BackgroundMaterial.prototype, "_opacityTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "opacityTexture", void 0); __decorate([ BABYLON.serialize() ], BackgroundMaterial.prototype, "_environmentBlur", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "environmentBlur", void 0); __decorate([ BABYLON.serialize() ], BackgroundMaterial.prototype, "_lightChannelsInTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "lightChannelsInTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "shadowLights", void 0); __decorate([ BABYLON.serialize() ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "shadowBlurScale", void 0); __decorate([ BABYLON.serialize() ], BackgroundMaterial.prototype, "_shadowLevel", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "shadowLevel", void 0); __decorate([ BABYLON.serialize() ], BackgroundMaterial.prototype, "_opacityFresnel", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "opacityFresnel", void 0); __decorate([ BABYLON.serializeAsImageProcessingConfiguration() ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0); return BackgroundMaterial; }(BABYLON.PushMaterial)); BABYLON.BackgroundMaterial = BackgroundMaterial; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.backgroundMaterial.js.map BABYLON.Effect.ShadersStore['backgroundVertexShader'] = "precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n\n#include\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfo.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include\n\n#include\n\n#include[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n"; BABYLON.Effect.ShadersStore['backgroundPixelShader'] = "#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n\n#ifdef ENVIRONMENT\n#define sampleEnvironment(s,c) textureCube(s,c)\nuniform samplerCube environmentSampler;\n#ifdef ENVIRONMENTBLUR\n#ifdef TEXTURELODSUPPORT\n#define sampleEnvironmentLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube environmentSamplerLow;\nuniform samplerCube environmentSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n\n#include\nvoid main(void) {\n#include\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\n#include[0..maxSimultaneousLights]\n\n#ifdef ENVIRONMENT\nvec3 environmentColor=vec3(0.,0.,0.);\n\nvec3 environmentCoords=(vPositionW.xyz-vEyePosition.xyz);\n#ifdef INVERTCUBICMAP\nenvironmentCoords.y=1.0-environmentCoords.y;\n#endif\n\nenvironmentCoords=vec3(environmentMatrix*vec4(environmentCoords,0));\n#ifdef ENVIRONMENTBLUR\nfloat environmentLOD=vEnvironmentInfo.y;\n#ifdef TEXTURELODSUPPORT\n\nenvironmentLOD=environmentLOD*log2(vEnvironmentMicrosurfaceInfos.x)*vEnvironmentMicrosurfaceInfos.y+vEnvironmentMicrosurfaceInfos.z;\nenvironmentColor=sampleEnvironmentLod(environmentSampler,environmentCoords,environmentLOD).rgb;\n#else\nfloat lodEnvironmentNormalized=clamp(environmentLOD,0.,1.);\nfloat lodEnvironmentNormalizedDoubled=lodEnvironmentNormalized*2.0;\nvec3 environmentSpecularMid=sampleEnvironment(environmentSampler,environmentCoords).rgb;\nif(lodEnvironmentNormalizedDoubled<1.0){\nenvironmentColor=mix(\nsampleEnvironment(environmentSamplerHigh,environmentCoords).rgb,\nenvironmentSpecularMid,\nlodEnvironmentNormalizedDoubled\n);\n} else {\nenvironmentColor=mix(\nenvironmentSpecularMid,\nsampleEnvironment(environmentSamplerLow,environmentCoords).rgb,\nlodEnvironmentNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nenvironmentColor=sampleEnvironment(environmentSampler,environmentCoords).rgb;\n#endif\n#ifdef GAMMAENVIRONMENT\nenvironmentColor=toLinearSpace(environmentColor.rgb);\n#endif\n\nenvironmentColor*=vEnvironmentInfo.x;\n\n#ifdef OPACITY\nvec3 reflectEnvironmentColor=vec3(0.,0.,0.);\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nfloat environmentMix=getLuminance(opacityMap.rgb);\n#else\nfloat environmentMix=opacityMap.a;\n#endif\nenvironmentMix*=vOpacityInfo.y;\n#ifdef OPACITYFRESNEL\n\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nenvironmentMix*=fadeFactor*fadeFactor;\nshadow=mix(1.,shadow,environmentMix);\n#endif\n\nvec3 viewDir=vPositionW.xyz-vEyePosition.xyz;\nvec3 reflectEnvironmentCoords=reflect(viewDir,normalW);\n#ifdef INVERTCUBICMAP\nreflectEnvironmentCoords.y=1.0-reflectEnvironmentCoords.y;\n#endif\n\nreflectEnvironmentCoords=vec3(environmentMatrix*vec4(reflectEnvironmentCoords,0));\n#ifdef ENVIRONMENTBLUR\n#ifdef TEXTURELODSUPPORT\n\nreflectEnvironmentColor=sampleEnvironmentLod(environmentSampler,reflectEnvironmentCoords,environmentLOD).rgb;\n#else\nvec3 reflectEnvironmentSpecularMid=sampleEnvironment(environmentSampler,reflectEnvironmentCoords).rgb;\nif(lodEnvironmentNormalizedDoubled<1.0){\nreflectEnvironmentColor=mix(\nsampleEnvironment(environmentSamplerHigh,reflectEnvironmentCoords).rgb,\nenvironmentSpecularMid,\nlodEnvironmentNormalizedDoubled\n);\n} else {\nreflectEnvironmentColor=mix(\nenvironmentSpecularMid,\nsampleEnvironment(environmentSamplerLow,reflectEnvironmentCoords).rgb,\nlodEnvironmentNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nreflectEnvironmentColor=sampleEnvironment(environmentSampler,reflectEnvironmentCoords).rgb;\n#endif\n#ifdef GAMMAENVIRONMENT\nreflectEnvironmentColor=toLinearSpace(reflectEnvironmentColor.rgb);\n#endif\n\nreflectEnvironmentColor*=vEnvironmentInfo.x;\n\nenvironmentColor=mix(environmentColor,reflectEnvironmentColor,environmentMix);\n#endif\n#else\nvec3 environmentColor=vec3(1.,1.,1.);\n#endif\n\n#ifdef RGBENVIRONMENT\nenvironmentColor=vec3(1.,1.,1.)*getLuminance(environmentColor);\n#endif\n\nvec3 colorBase=environmentColor.r*vPrimaryColor.rgb*vPrimaryColor.a;\ncolorBase+=environmentColor.g*vSecondaryColor.rgb*vSecondaryColor.a;\ncolorBase+=environmentColor.b*vThirdColor.rgb*vThirdColor.a;\ncolorBase=mix(colorBase*shadowLevel,colorBase,shadow);\nvec4 color=vec4(colorBase,1.0);\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\ngl_FragColor=color;\n}"; BABYLON.Effect.IncludesShadersStore['backgroundFragmentDeclaration'] = " uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vThirdColor;\nuniform float shadowLevel;\n#ifdef OPACITY\nuniform vec2 vOpacityInfo;\n#endif\n#ifdef ENVIRONMENT\nuniform vec2 vEnvironmentInfo;\nuniform mat4 environmentMatrix;\nuniform vec3 vEnvironmentMicrosurfaceInfos;\n#endif"; BABYLON.Effect.IncludesShadersStore['backgroundUboDeclaration'] = "layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vThirdColor;\nuniform vec2 vOpacityInfo;\nuniform vec2 vEnvironmentInfo;\nuniform mat4 opacityMatrix;\nuniform mat4 environmentMatrix;\nuniform vec3 vEnvironmentMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"; BABYLON.Effect.IncludesShadersStore['backgroundVertexDeclaration'] = "uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfo;\n#endif\n#ifdef ENVIRONMENT\nuniform vec2 vEnvironmentInfo;\nuniform mat4 environmentMatrix;\nuniform vec3 vEnvionmentMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif"; /// var BABYLON; (function (BABYLON) { var GLTFLoaderCoordinateSystemMode; (function (GLTFLoaderCoordinateSystemMode) { // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem). // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO"; // The glTF right-handed data is not transformed in any form and is loaded directly. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH"; // Sets the useRightHandedSystem flag on the scene. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED"; })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {})); var GLTFFileLoader = /** @class */ (function () { function GLTFFileLoader() { // V2 options this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO; this.name = "gltf"; this.extensions = { ".gltf": { isBinary: false }, ".glb": { isBinary: true } }; } GLTFFileLoader.prototype.dispose = function () { if (this._loader) { this._loader.dispose(); this._loader = null; } }; GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) { var loaderData = GLTFFileLoader._parse(data, onError); if (!loaderData) { return; } if (this.onParsed) { this.onParsed(loaderData); } this._loader = this._getLoader(loaderData, onError); if (!this._loader) { return; } this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError); }; GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) { var loaderData = GLTFFileLoader._parse(data, onError); if (!loaderData) { return; } if (this.onParsed) { this.onParsed(loaderData); } this._loader = this._getLoader(loaderData, onError); if (!this._loader) { return; } return this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError); }; GLTFFileLoader.prototype.canDirectLoad = function (data) { return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1)); }; GLTFFileLoader._parse = function (data, onError) { try { if (data instanceof ArrayBuffer) { return GLTFFileLoader._parseBinary(data, onError); } return { json: JSON.parse(data), bin: null }; } catch (e) { onError(e.message); return null; } }; GLTFFileLoader.prototype._getLoader = function (loaderData, onError) { var loaderVersion = { major: 2, minor: 0 }; var asset = loaderData.json.asset || {}; var version = GLTFFileLoader._parseVersion(asset.version); if (!version) { onError("Invalid version: " + asset.version); return null; } if (asset.minVersion !== undefined) { var minVersion = GLTFFileLoader._parseVersion(asset.minVersion); if (!minVersion) { onError("Invalid minimum version: " + asset.minVersion); return null; } if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) { onError("Incompatible minimum version: " + asset.minVersion); return null; } } var createLoaders = { 1: GLTFFileLoader.CreateGLTFLoaderV1, 2: GLTFFileLoader.CreateGLTFLoaderV2 }; var createLoader = createLoaders[version.major]; if (!createLoader) { onError("Unsupported version: " + asset.version); return null; } return createLoader(this); }; GLTFFileLoader._parseBinary = function (data, onError) { var Binary = { Magic: 0x46546C67 }; var binaryReader = new BinaryReader(data); var magic = binaryReader.readUint32(); if (magic !== Binary.Magic) { onError("Unexpected magic: " + magic); return null; } var version = binaryReader.readUint32(); switch (version) { case 1: return GLTFFileLoader._parseV1(binaryReader, onError); case 2: return GLTFFileLoader._parseV2(binaryReader, onError); } onError("Unsupported version: " + version); return null; }; GLTFFileLoader._parseV1 = function (binaryReader, onError) { var ContentFormat = { JSON: 0 }; var length = binaryReader.readUint32(); if (length != binaryReader.getLength()) { onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength()); return null; } var contentLength = binaryReader.readUint32(); var contentFormat = binaryReader.readUint32(); var content; switch (contentFormat) { case ContentFormat.JSON: content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength))); break; default: onError("Unexpected content format: " + contentFormat); return null; } var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition(); var body = binaryReader.readUint8Array(bytesRemaining); return { json: content, bin: body }; }; GLTFFileLoader._parseV2 = function (binaryReader, onError) { var ChunkFormat = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; var length = binaryReader.readUint32(); if (length !== binaryReader.getLength()) { onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength()); return null; } // JSON chunk var chunkLength = binaryReader.readUint32(); var chunkFormat = binaryReader.readUint32(); if (chunkFormat !== ChunkFormat.JSON) { onError("First chunk format is not JSON"); return null; } var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength))); // Look for BIN chunk var bin = null; while (binaryReader.getPosition() < binaryReader.getLength()) { var chunkLength_1 = binaryReader.readUint32(); var chunkFormat_1 = binaryReader.readUint32(); switch (chunkFormat_1) { case ChunkFormat.JSON: onError("Unexpected JSON chunk"); return null; case ChunkFormat.BIN: bin = binaryReader.readUint8Array(chunkLength_1); break; default: // ignore unrecognized chunkFormat binaryReader.skipBytes(chunkLength_1); break; } } return { json: json, bin: bin }; }; GLTFFileLoader._parseVersion = function (version) { var match = (version + "").match(/^(\d+)\.(\d+)$/); if (!match) { return null; } return { major: parseInt(match[1]), minor: parseInt(match[2]) }; }; GLTFFileLoader._compareVersion = function (a, b) { if (a.major > b.major) return 1; if (a.major < b.major) return -1; if (a.minor > b.minor) return 1; if (a.minor < b.minor) return -1; return 0; }; GLTFFileLoader._decodeBufferToText = function (buffer) { var result = ""; var length = buffer.byteLength; for (var i = 0; i < length; i++) { result += String.fromCharCode(buffer[i]); } return result; }; // V1 options GLTFFileLoader.HomogeneousCoordinates = false; GLTFFileLoader.IncrementalLoading = true; return GLTFFileLoader; }()); BABYLON.GLTFFileLoader = GLTFFileLoader; var BinaryReader = /** @class */ (function () { function BinaryReader(arrayBuffer) { this._arrayBuffer = arrayBuffer; this._dataView = new DataView(arrayBuffer); this._byteOffset = 0; } BinaryReader.prototype.getPosition = function () { return this._byteOffset; }; BinaryReader.prototype.getLength = function () { return this._arrayBuffer.byteLength; }; BinaryReader.prototype.readUint32 = function () { var value = this._dataView.getUint32(this._byteOffset, true); this._byteOffset += 4; return value; }; BinaryReader.prototype.readUint8Array = function (length) { var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length); this._byteOffset += length; return value; }; BinaryReader.prototype.skipBytes = function (length) { this._byteOffset += length; }; return BinaryReader; }()); if (BABYLON.SceneLoader) { BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader()); } })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFFileLoader.js.map /// var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { /** * Enums */ var EComponentType; (function (EComponentType) { EComponentType[EComponentType["BYTE"] = 5120] = "BYTE"; EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; EComponentType[EComponentType["SHORT"] = 5122] = "SHORT"; EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT"; })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {})); var EShaderType; (function (EShaderType) { EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT"; EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX"; })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {})); var EParameterType; (function (EParameterType) { EParameterType[EParameterType["BYTE"] = 5120] = "BYTE"; EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; EParameterType[EParameterType["SHORT"] = 5122] = "SHORT"; EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; EParameterType[EParameterType["INT"] = 5124] = "INT"; EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT"; EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2"; EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3"; EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4"; EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2"; EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3"; EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4"; EParameterType[EParameterType["BOOL"] = 35670] = "BOOL"; EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2"; EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3"; EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4"; EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2"; EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3"; EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4"; EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D"; })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {})); var ETextureWrapMode; (function (ETextureWrapMode) { ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE"; ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT"; })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {})); var ETextureFilterType; (function (ETextureFilterType) { ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST"; ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR"; ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST"; ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST"; ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR"; ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR"; })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {})); var ETextureFormat; (function (ETextureFormat) { ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA"; ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB"; ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA"; ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE"; ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {})); var ECullingType; (function (ECullingType) { ECullingType[ECullingType["FRONT"] = 1028] = "FRONT"; ECullingType[ECullingType["BACK"] = 1029] = "BACK"; ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK"; })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {})); var EBlendingFunction; (function (EBlendingFunction) { EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO"; EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE"; EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR"; EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR"; EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR"; EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR"; EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA"; EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA"; EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA"; EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA"; EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR"; EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR"; EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA"; EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA"; EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE"; })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {})); })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map /// var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { /** * Tokenizer. Used for shaders compatibility * Automatically map world, view, projection, worldViewProjection, attributes and so on */ var ETokenType; (function (ETokenType) { ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER"; ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN"; ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT"; })(ETokenType || (ETokenType = {})); var Tokenizer = /** @class */ (function () { function Tokenizer(toParse) { this._pos = 0; this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/; this._toParse = toParse; this._maxPos = toParse.length; } Tokenizer.prototype.getNextToken = function () { if (this.isEnd()) return ETokenType.END_OF_INPUT; this.currentString = this.read(); this.currentToken = ETokenType.UNKNOWN; if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) { this.currentToken = ETokenType.IDENTIFIER; this.currentIdentifier = this.currentString; while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) { this.currentIdentifier += this.currentString; this.forward(); } } return this.currentToken; }; Tokenizer.prototype.peek = function () { return this._toParse[this._pos]; }; Tokenizer.prototype.read = function () { return this._toParse[this._pos++]; }; Tokenizer.prototype.forward = function () { this._pos++; }; Tokenizer.prototype.isEnd = function () { return this._pos >= this._maxPos; }; return Tokenizer; }()); /** * Values */ var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"]; var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"]; var glTFAnimationPaths = ["translation", "rotation", "scale"]; var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"]; /** * Parse */ var parseBuffers = function (parsedBuffers, gltfRuntime) { for (var buf in parsedBuffers) { var parsedBuffer = parsedBuffers[buf]; gltfRuntime.buffers[buf] = parsedBuffer; gltfRuntime.buffersCount++; } }; var parseShaders = function (parsedShaders, gltfRuntime) { for (var sha in parsedShaders) { var parsedShader = parsedShaders[sha]; gltfRuntime.shaders[sha] = parsedShader; gltfRuntime.shaderscount++; } }; var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) { for (var object in parsedObjects) { var parsedObject = parsedObjects[object]; gltfRuntime[runtimeProperty][object] = parsedObject; } }; /** * Utils */ var normalizeUVs = function (buffer) { if (!buffer) { return; } for (var i = 0; i < buffer.length / 2; i++) { buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1]; } }; var getAttribute = function (attributeParameter) { if (attributeParameter.semantic === "NORMAL") { return "normal"; } else if (attributeParameter.semantic === "POSITION") { return "position"; } else if (attributeParameter.semantic === "JOINT") { return "matricesIndices"; } else if (attributeParameter.semantic === "WEIGHT") { return "matricesWeights"; } else if (attributeParameter.semantic === "COLOR") { return "color"; } else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) { var channel = Number(attributeParameter.semantic.split("_")[1]); return "uv" + (channel === 0 ? "" : channel + 1); } return null; }; /** * Loads and creates animations */ var loadAnimations = function (gltfRuntime) { for (var anim in gltfRuntime.animations) { var animation = gltfRuntime.animations[anim]; if (!animation.channels || !animation.samplers) { continue; } var lastAnimation = null; for (var i = 0; i < animation.channels.length; i++) { // Get parameters and load buffers var channel = animation.channels[i]; var sampler = animation.samplers[channel.sampler]; if (!sampler) { continue; } var inputData = null; var outputData = null; if (animation.parameters) { inputData = animation.parameters[sampler.input]; outputData = animation.parameters[sampler.output]; } else { inputData = sampler.input; outputData = sampler.output; } var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]); var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]); var targetID = channel.target.id; var targetNode = gltfRuntime.scene.getNodeByID(targetID); if (targetNode === null) { targetNode = gltfRuntime.scene.getNodeByName(targetID); } if (targetNode === null) { BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to"); continue; } var isBone = targetNode instanceof BABYLON.Bone; // Get target path (position, rotation or scaling) var targetPath = channel.target.path; var targetPathIndex = glTFAnimationPaths.indexOf(targetPath); if (targetPathIndex !== -1) { targetPath = babylonAnimationPaths[targetPathIndex]; } // Determine animation type var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX; if (!isBone) { if (targetPath === "rotationQuaternion") { animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION; targetNode.rotationQuaternion = new BABYLON.Quaternion(); } else { animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3; } } // Create animation and key frames var babylonAnimation = null; var keys = []; var arrayOffset = 0; var modifyKey = false; if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) { babylonAnimation = lastAnimation; modifyKey = true; } if (!modifyKey) { babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE); } // For each frame for (var j = 0; j < bufferInput.length; j++) { var value = null; if (targetPath === "rotationQuaternion") { value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]); arrayOffset += 4; } else { value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]); arrayOffset += 3; } if (isBone) { var bone = targetNode; var translation = BABYLON.Vector3.Zero(); var rotationQuaternion = new BABYLON.Quaternion(); var scaling = BABYLON.Vector3.Zero(); // Warning on decompose var mat = bone.getBaseMatrix(); if (modifyKey && lastAnimation) { mat = lastAnimation.getKeys()[j].value; } mat.decompose(scaling, rotationQuaternion, translation); if (targetPath === "position") { translation = value; } else if (targetPath === "rotationQuaternion") { rotationQuaternion = value; } else { scaling = value; } value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation); } if (!modifyKey) { keys.push({ frame: bufferInput[j], value: value }); } else if (lastAnimation) { lastAnimation.getKeys()[j].value = value; } } // Finish if (!modifyKey && babylonAnimation) { babylonAnimation.setKeys(keys); targetNode.animations.push(babylonAnimation); } lastAnimation = babylonAnimation; gltfRuntime.scene.stopAnimation(targetNode); gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0); } } }; /** * Returns the bones transformation matrix */ var configureBoneTransformation = function (node) { var mat = null; if (node.translation || node.rotation || node.scale) { var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]); var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]); var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]); mat = BABYLON.Matrix.Compose(scale, rotation, position); } else { mat = BABYLON.Matrix.FromArray(node.matrix); } return mat; }; /** * Returns the parent bone */ var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) { // Try to find for (var i = 0; i < newSkeleton.bones.length; i++) { if (newSkeleton.bones[i].name === jointName) { return newSkeleton.bones[i]; } } // Not found, search in gltf nodes var nodes = gltfRuntime.nodes; for (var nde in nodes) { var node = nodes[nde]; if (!node.jointName) { continue; } var children = node.children; for (var i = 0; i < children.length; i++) { var child = gltfRuntime.nodes[children[i]]; if (!child.jointName) { continue; } if (child.jointName === jointName) { var mat = configureBoneTransformation(node); var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat); bone.id = nde; return bone; } } } return null; }; /** * Returns the appropriate root node */ var getNodeToRoot = function (nodesToRoot, id) { for (var i = 0; i < nodesToRoot.length; i++) { var nodeToRoot = nodesToRoot[i]; for (var j = 0; j < nodeToRoot.node.children.length; j++) { var child = nodeToRoot.node.children[j]; if (child === id) { return nodeToRoot.bone; } } } return null; }; /** * Returns the node with the joint name */ var getJointNode = function (gltfRuntime, jointName) { var nodes = gltfRuntime.nodes; var node = nodes[jointName]; if (node) { return { node: node, id: jointName }; } for (var nde in nodes) { node = nodes[nde]; if (node.jointName === jointName) { return { node: node, id: nde }; } } return null; }; /** * Checks if a nodes is in joints */ var nodeIsInJoints = function (skins, id) { for (var i = 0; i < skins.jointNames.length; i++) { if (skins.jointNames[i] === id) { return true; } } return false; }; /** * Fills the nodes to root for bones and builds hierarchy */ var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) { // Creates nodes for root for (var nde in gltfRuntime.nodes) { var node = gltfRuntime.nodes[nde]; var id = nde; if (!node.jointName || nodeIsInJoints(skins, node.jointName)) { continue; } // Create node to root bone var mat = configureBoneTransformation(node); var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat); bone.id = id; nodesToRoot.push({ bone: bone, node: node, id: id }); } // Parenting for (var i = 0; i < nodesToRoot.length; i++) { var nodeToRoot = nodesToRoot[i]; var children = nodeToRoot.node.children; for (var j = 0; j < children.length; j++) { var child = null; for (var k = 0; k < nodesToRoot.length; k++) { if (nodesToRoot[k].id === children[j]) { child = nodesToRoot[k]; break; } } if (child) { child.bone._parent = nodeToRoot.bone; nodeToRoot.bone.children.push(child.bone); } } } }; /** * Imports a skeleton */ var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) { if (!newSkeleton) { newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene); } if (!skins.babylonSkeleton) { return newSkeleton; } // Find the root bones var nodesToRoot = []; var nodesToRootToAdd = []; getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot); newSkeleton.bones = []; // Joints for (var i = 0; i < skins.jointNames.length; i++) { var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]); if (!jointNode) { continue; } var node = jointNode.node; if (!node) { BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist"); continue; } var id = jointNode.id; // Optimize, if the bone already exists... var existingBone = gltfRuntime.scene.getBoneByID(id); if (existingBone) { newSkeleton.bones.push(existingBone); continue; } // Search for parent bone var foundBone = false; var parentBone = null; for (var j = 0; j < i; j++) { var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]); if (!jointNode_1) { continue; } var joint = jointNode_1.node; if (!joint) { BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent"); continue; } var children = joint.children; if (!children) { continue; } foundBone = false; for (var k = 0; k < children.length; k++) { if (children[k] === id) { parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton); foundBone = true; break; } } if (foundBone) { break; } } // Create bone var mat = configureBoneTransformation(node); if (!parentBone && nodesToRoot.length > 0) { parentBone = getNodeToRoot(nodesToRoot, id); if (parentBone) { if (nodesToRootToAdd.indexOf(parentBone) === -1) { nodesToRootToAdd.push(parentBone); } } } var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat); bone.id = id; } // Polish var bones = newSkeleton.bones; newSkeleton.bones = []; for (var i = 0; i < skins.jointNames.length; i++) { var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]); if (!jointNode) { continue; } for (var j = 0; j < bones.length; j++) { if (bones[j].id === jointNode.id) { newSkeleton.bones.push(bones[j]); break; } } } newSkeleton.prepare(); // Finish for (var i = 0; i < nodesToRootToAdd.length; i++) { newSkeleton.bones.push(nodesToRootToAdd[i]); } return newSkeleton; }; /** * Imports a mesh and its geometries */ var importMesh = function (gltfRuntime, node, meshes, id, newMesh) { if (!newMesh) { newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene); newMesh.id = id; } if (!node.babylonNode) { return newMesh; } var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene); if (!newMesh.material) { newMesh.material = multiMat; } var vertexData = new BABYLON.VertexData(); var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh); var verticesStarts = new Array(); var verticesCounts = new Array(); var indexStarts = new Array(); var indexCounts = new Array(); for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) { var meshID = meshes[meshIndex]; var mesh = gltfRuntime.meshes[meshID]; if (!mesh) { continue; } // Positions, normals and UVs for (var i = 0; i < mesh.primitives.length; i++) { // Temporary vertex data var tempVertexData = new BABYLON.VertexData(); var primitive = mesh.primitives[i]; if (primitive.mode !== 4) { // continue; } var attributes = primitive.attributes; var accessor = null; var buffer = null; // Set positions, normal and uvs for (var semantic in attributes) { // Link accessor and buffer view accessor = gltfRuntime.accessors[attributes[semantic]]; buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor); if (semantic === "NORMAL") { tempVertexData.normals = new Float32Array(buffer.length); tempVertexData.normals.set(buffer); } else if (semantic === "POSITION") { if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) { tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4); for (var j = 0; j < buffer.length; j += 4) { tempVertexData.positions[j] = buffer[j]; tempVertexData.positions[j + 1] = buffer[j + 1]; tempVertexData.positions[j + 2] = buffer[j + 2]; } } else { tempVertexData.positions = new Float32Array(buffer.length); tempVertexData.positions.set(buffer); } verticesCounts.push(tempVertexData.positions.length); } else if (semantic.indexOf("TEXCOORD_") !== -1) { var channel = Number(semantic.split("_")[1]); var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1)); var uvs = new Float32Array(buffer.length); uvs.set(buffer); normalizeUVs(uvs); tempVertexData.set(uvs, uvKind); } else if (semantic === "JOINT") { tempVertexData.matricesIndices = new Float32Array(buffer.length); tempVertexData.matricesIndices.set(buffer); } else if (semantic === "WEIGHT") { tempVertexData.matricesWeights = new Float32Array(buffer.length); tempVertexData.matricesWeights.set(buffer); } else if (semantic === "COLOR") { tempVertexData.colors = new Float32Array(buffer.length); tempVertexData.colors.set(buffer); } } // Indices accessor = gltfRuntime.accessors[primitive.indices]; if (accessor) { buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor); tempVertexData.indices = new Int32Array(buffer.length); tempVertexData.indices.set(buffer); indexCounts.push(tempVertexData.indices.length); } else { // Set indices on the fly var indices = []; for (var j = 0; j < tempVertexData.positions.length / 3; j++) { indices.push(j); } tempVertexData.indices = new Int32Array(indices); indexCounts.push(tempVertexData.indices.length); } vertexData.merge(tempVertexData); // Sub material var material = gltfRuntime.scene.getMaterialByID(primitive.material); multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material); // Update vertices start and index start verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]); indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]); } } // Apply geometry geometry.setAllVerticesData(vertexData, false); newMesh.computeWorldMatrix(true); // Apply submeshes newMesh.subMeshes = []; var index = 0; for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) { var meshID = meshes[meshIndex]; var mesh = gltfRuntime.meshes[meshID]; if (!mesh) { continue; } for (var i = 0; i < mesh.primitives.length; i++) { if (mesh.primitives[i].mode !== 4) { //continue; } BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true); index++; } } // Finish return newMesh; }; /** * Configure node transformation from position, rotation and scaling */ var configureNode = function (newNode, position, rotation, scaling) { if (newNode.position) { newNode.position = position; } if (newNode.rotationQuaternion || newNode.rotation) { newNode.rotationQuaternion = rotation; } if (newNode.scaling) { newNode.scaling = scaling; } }; /** * Configures node from transformation matrix */ var configureNodeFromMatrix = function (newNode, node, parent) { if (node.matrix) { var position = new BABYLON.Vector3(0, 0, 0); var rotation = new BABYLON.Quaternion(); var scaling = new BABYLON.Vector3(0, 0, 0); var mat = BABYLON.Matrix.FromArray(node.matrix); mat.decompose(scaling, rotation, position); configureNode(newNode, position, rotation, scaling); } else if (node.translation && node.rotation && node.scale) { configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale)); } newNode.computeWorldMatrix(true); }; /** * Imports a node */ var importNode = function (gltfRuntime, node, id, parent) { var lastNode = null; if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) { if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) { return null; } } // Meshes if (node.skin) { if (node.meshes) { var skin = gltfRuntime.skins[node.skin]; var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode); newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin); if (newMesh.skeleton === null && skin.babylonSkeleton) { newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin); if (!skin.babylonSkeleton) { skin.babylonSkeleton = newMesh.skeleton; } } lastNode = newMesh; } } else if (node.meshes) { /** * Improve meshes property */ var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode); lastNode = newMesh; } else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) { var light = gltfRuntime.lights[node.light]; if (light) { if (light.type === "ambient") { var ambienLight = light[light.type]; var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene); hemiLight.name = node.name || ""; if (ambienLight.color) { hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color); } lastNode = hemiLight; } else if (light.type === "directional") { var directionalLight = light[light.type]; var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene); dirLight.name = node.name || ""; if (directionalLight.color) { dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color); } lastNode = dirLight; } else if (light.type === "point") { var pointLight = light[light.type]; var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene); ptLight.name = node.name || ""; if (pointLight.color) { ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color); } lastNode = ptLight; } else if (light.type === "spot") { var spotLight = light[light.type]; var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene); spLight.name = node.name || ""; if (spotLight.color) { spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color); } if (spotLight.fallOfAngle) { spLight.angle = spotLight.fallOfAngle; } if (spotLight.fallOffExponent) { spLight.exponent = spotLight.fallOffExponent; } lastNode = spLight; } } } else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) { var camera = gltfRuntime.cameras[node.camera]; if (camera) { if (camera.type === "orthographic") { var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene); orthoCamera.name = node.name || ""; orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA; orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas()); lastNode = orthoCamera; } else if (camera.type === "perspective") { var perspectiveCamera = camera[camera.type]; var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene); persCamera.name = node.name || ""; persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas()); if (!perspectiveCamera.aspectRatio) { perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight(); } if (perspectiveCamera.znear && perspectiveCamera.zfar) { persCamera.maxZ = perspectiveCamera.zfar; persCamera.minZ = perspectiveCamera.znear; } lastNode = persCamera; } } } // Empty node if (!node.jointName) { if (node.babylonNode) { return node.babylonNode; } else if (lastNode === null) { var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene); node.babylonNode = dummy; lastNode = dummy; } } if (lastNode !== null) { if (node.matrix && lastNode instanceof BABYLON.Mesh) { configureNodeFromMatrix(lastNode, node, parent); } else { var translation = node.translation || [0, 0, 0]; var rotation = node.rotation || [0, 0, 0, 1]; var scale = node.scale || [1, 1, 1]; configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale)); } lastNode.updateCache(true); node.babylonNode = lastNode; } return lastNode; }; /** * Traverses nodes and creates them */ var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) { if (meshIncluded === void 0) { meshIncluded = false; } var node = gltfRuntime.nodes[id]; var newNode = null; if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) { if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) { meshIncluded = true; } else { meshIncluded = false; } } else { meshIncluded = true; } if (!node.jointName && meshIncluded) { newNode = importNode(gltfRuntime, node, id, parent); if (newNode !== null) { newNode.id = id; newNode.parent = parent; } } if (node.children) { for (var i = 0; i < node.children.length; i++) { traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded); } } }; /** * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.) */ var postLoad = function (gltfRuntime) { // Nodes var currentScene = gltfRuntime.currentScene; if (currentScene) { for (var i = 0; i < currentScene.nodes.length; i++) { traverseNodes(gltfRuntime, currentScene.nodes[i], null); } } else { for (var thing in gltfRuntime.scenes) { currentScene = gltfRuntime.scenes[thing]; for (var i = 0; i < currentScene.nodes.length; i++) { traverseNodes(gltfRuntime, currentScene.nodes[i], null); } } } // Set animations loadAnimations(gltfRuntime); for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) { var skeleton = gltfRuntime.scene.skeletons[i]; gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0); } }; /** * onBind shaderrs callback to set uniforms and matrices */ var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) { var materialValues = material.values || technique.parameters; for (var unif in unTreatedUniforms) { var uniform = unTreatedUniforms[unif]; var type = uniform.type; if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) { if (uniform.semantic && !uniform.source && !uniform.node) { GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect()); } else if (uniform.semantic && (uniform.source || uniform.node)) { var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || ""); if (source === null) { source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || ""); } if (source === null) { continue; } GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect()); } } else { var value = materialValues[technique.uniforms[unif]]; if (!value) { continue; } if (type === GLTF1.EParameterType.SAMPLER_2D) { var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture; if (texture === null || texture === undefined) { continue; } shaderMaterial.getEffect().setTexture(unif, texture); } else { GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type); } } } onSuccess(shaderMaterial); }; /** * Prepare uniforms to send the only one time * Loads the appropriate textures */ var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) { var materialValues = material.values || technique.parameters; var techniqueUniforms = technique.uniforms; /** * Prepare values here (not matrices) */ for (var unif in unTreatedUniforms) { var uniform = unTreatedUniforms[unif]; var type = uniform.type; var value = materialValues[techniqueUniforms[unif]]; if (value === undefined) { // In case the value is the same for all materials value = uniform.value; } if (!value) { continue; } var onLoadTexture = function (uniformName) { return function (texture) { if (uniform.value && uniformName) { // Static uniform shaderMaterial.setTexture(uniformName, texture); delete unTreatedUniforms[uniformName]; } }; }; // Texture (sampler2D) if (type === GLTF1.EParameterType.SAMPLER_2D) { GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); }); } else { if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) { // Static uniform delete unTreatedUniforms[unif]; } } } }; /** * Shader compilation failed */ var onShaderCompileError = function (program, shaderMaterial, onError) { return function (effect, error) { shaderMaterial.dispose(true); onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied"); }; }; /** * Shader compilation success */ var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) { return function (_) { prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms); shaderMaterial.onBind = function (mesh) { onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess); }; }; }; /** * Returns the appropriate uniform if already handled by babylon */ var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) { for (var unif in technique.uniforms) { var uniform = technique.uniforms[unif]; var uniformParameter = technique.parameters[uniform]; if (tokenizer.currentIdentifier === unif) { if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) { var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic); if (transformIndex !== -1) { delete unTreatedUniforms[unif]; return babylonTransforms[transformIndex]; } } } } return tokenizer.currentIdentifier; }; /** * All shaders loaded. Create materials one by one */ var importMaterials = function (gltfRuntime) { // Create materials for (var mat in gltfRuntime.materials) { GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { }); } }; /** * Implementation of the base glTF spec */ var GLTFLoaderBase = /** @class */ (function () { function GLTFLoaderBase() { } GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) { var gltfRuntime = { extensions: {}, accessors: {}, buffers: {}, bufferViews: {}, meshes: {}, lights: {}, cameras: {}, nodes: {}, images: {}, textures: {}, shaders: {}, programs: {}, samplers: {}, techniques: {}, materials: {}, animations: {}, skins: {}, extensionsUsed: [], scenes: {}, buffersCount: 0, shaderscount: 0, scene: scene, rootUrl: rootUrl, loadedBufferCount: 0, loadedBufferViews: {}, loadedShaderCount: 0, importOnlyMeshes: false, dummyNodes: [] }; // Parse if (parsedData.extensions) { parseObject(parsedData.extensions, "extensions", gltfRuntime); } if (parsedData.extensionsUsed) { parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime); } if (parsedData.buffers) { parseBuffers(parsedData.buffers, gltfRuntime); } if (parsedData.bufferViews) { parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime); } if (parsedData.accessors) { parseObject(parsedData.accessors, "accessors", gltfRuntime); } if (parsedData.meshes) { parseObject(parsedData.meshes, "meshes", gltfRuntime); } if (parsedData.lights) { parseObject(parsedData.lights, "lights", gltfRuntime); } if (parsedData.cameras) { parseObject(parsedData.cameras, "cameras", gltfRuntime); } if (parsedData.nodes) { parseObject(parsedData.nodes, "nodes", gltfRuntime); } if (parsedData.images) { parseObject(parsedData.images, "images", gltfRuntime); } if (parsedData.textures) { parseObject(parsedData.textures, "textures", gltfRuntime); } if (parsedData.shaders) { parseShaders(parsedData.shaders, gltfRuntime); } if (parsedData.programs) { parseObject(parsedData.programs, "programs", gltfRuntime); } if (parsedData.samplers) { parseObject(parsedData.samplers, "samplers", gltfRuntime); } if (parsedData.techniques) { parseObject(parsedData.techniques, "techniques", gltfRuntime); } if (parsedData.materials) { parseObject(parsedData.materials, "materials", gltfRuntime); } if (parsedData.animations) { parseObject(parsedData.animations, "animations", gltfRuntime); } if (parsedData.skins) { parseObject(parsedData.skins, "skins", gltfRuntime); } if (parsedData.scenes) { gltfRuntime.scenes = parsedData.scenes; } if (parsedData.scene && parsedData.scenes) { gltfRuntime.currentScene = parsedData.scenes[parsedData.scene]; } return gltfRuntime; }; GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) { var buffer = gltfRuntime.buffers[id]; if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) { setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); }); } else { BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) { if (request) { onError(request.status + " " + request.statusText); } }); } }; GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) { var texture = gltfRuntime.textures[id]; if (!texture || !texture.source) { onError(""); return; } if (texture.babylonTexture) { onSuccess(null); return; } var source = gltfRuntime.images[texture.source]; if (GLTF1.GLTFUtils.IsBase64(source.uri)) { setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); }); } else { BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) { if (request) { onError(request.status + " " + request.statusText); } }); } }; GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) { var texture = gltfRuntime.textures[id]; if (texture.babylonTexture) { onSuccess(texture.babylonTexture); return; } var sampler = gltfRuntime.samplers[texture.sampler]; var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) || (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) || (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) || (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR); var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; var blob = new Blob([buffer]); var blobURL = URL.createObjectURL(blob); var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); }; var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL); if (sampler.wrapS !== undefined) { newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS); } if (sampler.wrapT !== undefined) { newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT); } newTexture.name = id; texture.babylonTexture = newTexture; onSuccess(newTexture); }; GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) { var shader = gltfRuntime.shaders[id]; if (GLTF1.GLTFUtils.IsBase64(shader.uri)) { var shaderString = atob(shader.uri.split(",")[1]); onSuccess(shaderString); } else { BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) { if (request) { onError(request.status + " " + request.statusText); } }); } }; GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) { var material = gltfRuntime.materials[id]; if (!material.technique) { if (onError) { onError("No technique found."); } return; } var technique = gltfRuntime.techniques[material.technique]; if (!technique) { var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene); defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5); defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation; onSuccess(defaultMaterial); return; } var program = gltfRuntime.programs[technique.program]; var states = technique.states; var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"]; var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"]; var newVertexShader = ""; var newPixelShader = ""; var vertexTokenizer = new Tokenizer(vertexShader); var pixelTokenizer = new Tokenizer(pixelShader); var unTreatedUniforms = {}; var uniforms = []; var attributes = []; var samplers = []; // Fill uniform, sampler2D and attributes for (var unif in technique.uniforms) { var uniform = technique.uniforms[unif]; var uniformParameter = technique.parameters[uniform]; unTreatedUniforms[unif] = uniformParameter; if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) { var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic); if (transformIndex !== -1) { uniforms.push(babylonTransforms[transformIndex]); delete unTreatedUniforms[unif]; } else { uniforms.push(unif); } } else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) { samplers.push(unif); } else { uniforms.push(unif); } } for (var attr in technique.attributes) { var attribute = technique.attributes[attr]; var attributeParameter = technique.parameters[attribute]; if (attributeParameter.semantic) { attributes.push(getAttribute(attributeParameter)); } } // Configure vertex shader while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) { var tokenType = vertexTokenizer.currentToken; if (tokenType !== ETokenType.IDENTIFIER) { newVertexShader += vertexTokenizer.currentString; continue; } var foundAttribute = false; for (var attr in technique.attributes) { var attribute = technique.attributes[attr]; var attributeParameter = technique.parameters[attribute]; if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) { newVertexShader += getAttribute(attributeParameter); foundAttribute = true; break; } } if (foundAttribute) { continue; } newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms); } // Configure pixel shader while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) { var tokenType = pixelTokenizer.currentToken; if (tokenType !== ETokenType.IDENTIFIER) { newPixelShader += pixelTokenizer.currentString; continue; } newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms); } // Create shader material var shaderPath = { vertex: program.vertexShader + id, fragment: program.fragmentShader + id }; var options = { attributes: attributes, uniforms: uniforms, samplers: samplers, needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1 }; BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader; BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader; var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options); shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError); shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess); shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation; if (states && states.functions) { var functions = states.functions; if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) { shaderMaterial.backFaceCulling = false; } var blendFunc = functions.blendFuncSeparate; if (blendFunc) { if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE; } else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE; } else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD; } else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT; } else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY; } else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED; } } } }; return GLTFLoaderBase; }()); GLTF1.GLTFLoaderBase = GLTFLoaderBase; /** * glTF V1 Loader */ var GLTFLoader = /** @class */ (function () { function GLTFLoader() { } GLTFLoader.RegisterExtension = function (extension) { if (GLTFLoader.Extensions[extension.name]) { BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists"); return; } GLTFLoader.Extensions[extension.name] = extension; }; GLTFLoader.prototype.dispose = function () { // do nothing }; GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) { var _this = this; scene.useRightHandedSystem = true; GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) { gltfRuntime.importOnlyMeshes = true; if (meshesNames === "") { gltfRuntime.importMeshesNames = []; } else if (typeof meshesNames === "string") { gltfRuntime.importMeshesNames = [meshesNames]; } else if (meshesNames && !(meshesNames instanceof Array)) { gltfRuntime.importMeshesNames = [meshesNames]; } else { gltfRuntime.importMeshesNames = []; BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]"); } // Create nodes _this._createNodes(gltfRuntime); var meshes = new Array(); var skeletons = new Array(); // Fill arrays of meshes and skeletons for (var nde in gltfRuntime.nodes) { var node = gltfRuntime.nodes[nde]; if (node.babylonNode instanceof BABYLON.AbstractMesh) { meshes.push(node.babylonNode); } } for (var skl in gltfRuntime.skins) { var skin = gltfRuntime.skins[skl]; if (skin.babylonSkeleton instanceof BABYLON.Skeleton) { skeletons.push(skin.babylonSkeleton); } } // Load buffers, shaders, materials, etc. _this._loadBuffersAsync(gltfRuntime, function () { _this._loadShadersAsync(gltfRuntime, function () { importMaterials(gltfRuntime); postLoad(gltfRuntime); if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) { onSuccess(meshes, null, skeletons); } }); }, onProgress); if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) { onSuccess(meshes, null, skeletons); } }, onError); return true; }; GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) { var _this = this; scene.useRightHandedSystem = true; GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) { // Load runtime extensios GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () { // Create nodes _this._createNodes(gltfRuntime); // Load buffers, shaders, materials, etc. _this._loadBuffersAsync(gltfRuntime, function () { _this._loadShadersAsync(gltfRuntime, function () { importMaterials(gltfRuntime); postLoad(gltfRuntime); if (!BABYLON.GLTFFileLoader.IncrementalLoading) { onSuccess(); } }); }); if (BABYLON.GLTFFileLoader.IncrementalLoading) { onSuccess(); } }, onError); }, onError); }; GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) { var hasShaders = false; var processShader = function (sha, shader) { GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) { gltfRuntime.loadedShaderCount++; if (shaderString) { BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString; } if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) { onload(); } }, function () { BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri); }); }; for (var sha in gltfRuntime.shaders) { hasShaders = true; var shader = gltfRuntime.shaders[sha]; if (shader) { processShader.bind(this, sha, shader)(); } else { BABYLON.Tools.Error("No shader named: " + sha); } } if (!hasShaders) { onload(); } }; ; GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) { var hasBuffers = false; var processBuffer = function (buf, buffer) { GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) { gltfRuntime.loadedBufferCount++; if (bufferView) { if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) { BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message } gltfRuntime.loadedBufferViews[buf] = bufferView; } if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) { onLoad(); } }, function () { BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri); }); }; for (var buf in gltfRuntime.buffers) { hasBuffers = true; var buffer = gltfRuntime.buffers[buf]; if (buffer) { processBuffer.bind(this, buf, buffer)(); } else { BABYLON.Tools.Error("No buffer named: " + buf); } } if (!hasBuffers) { onLoad(); } }; GLTFLoader.prototype._createNodes = function (gltfRuntime) { var currentScene = gltfRuntime.currentScene; if (currentScene) { // Only one scene even if multiple scenes are defined for (var i = 0; i < currentScene.nodes.length; i++) { traverseNodes(gltfRuntime, currentScene.nodes[i], null); } } else { // Load all scenes for (var thing in gltfRuntime.scenes) { currentScene = gltfRuntime.scenes[thing]; for (var i = 0; i < currentScene.nodes.length; i++) { traverseNodes(gltfRuntime, currentScene.nodes[i], null); } } } }; GLTFLoader.Extensions = {}; return GLTFLoader; }()); GLTF1.GLTFLoader = GLTFLoader; ; BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); }; })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoader.js.map /// var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { /** * Utils functions for GLTF */ var GLTFUtils = /** @class */ (function () { function GLTFUtils() { } /** * Sets the given "parameter" matrix * @param scene: the {BABYLON.Scene} object * @param source: the source node where to pick the matrix * @param parameter: the GLTF technique parameter * @param uniformName: the name of the shader's uniform * @param shaderMaterial: the shader material */ GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) { var mat = null; if (parameter.semantic === "MODEL") { mat = source.getWorldMatrix(); } else if (parameter.semantic === "PROJECTION") { mat = scene.getProjectionMatrix(); } else if (parameter.semantic === "VIEW") { mat = scene.getViewMatrix(); } else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") { mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert()); } else if (parameter.semantic === "MODELVIEW") { mat = source.getWorldMatrix().multiply(scene.getViewMatrix()); } else if (parameter.semantic === "MODELVIEWPROJECTION") { mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()); } else if (parameter.semantic === "MODELINVERSE") { mat = source.getWorldMatrix().invert(); } else if (parameter.semantic === "VIEWINVERSE") { mat = scene.getViewMatrix().invert(); } else if (parameter.semantic === "PROJECTIONINVERSE") { mat = scene.getProjectionMatrix().invert(); } else if (parameter.semantic === "MODELVIEWINVERSE") { mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert(); } else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") { mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert(); } else if (parameter.semantic === "MODELINVERSETRANSPOSE") { mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert()); } else { debugger; } if (mat) { switch (parameter.type) { case GLTF1.EParameterType.FLOAT_MAT2: shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat)); break; case GLTF1.EParameterType.FLOAT_MAT3: shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat)); break; case GLTF1.EParameterType.FLOAT_MAT4: shaderMaterial.setMatrix(uniformName, mat); break; default: break; } } }; /** * Sets the given "parameter" matrix * @param shaderMaterial: the shader material * @param uniform: the name of the shader's uniform * @param value: the value of the uniform * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4) */ GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) { switch (type) { case GLTF1.EParameterType.FLOAT: shaderMaterial.setFloat(uniform, value); return true; case GLTF1.EParameterType.FLOAT_VEC2: shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value)); return true; case GLTF1.EParameterType.FLOAT_VEC3: shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value)); return true; case GLTF1.EParameterType.FLOAT_VEC4: shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value)); return true; default: return false; } }; /** * If the uri is a base64 string * @param uri: the uri to test */ GLTFUtils.IsBase64 = function (uri) { return uri.length < 5 ? false : uri.substr(0, 5) === "data:"; }; /** * Decode the base64 uri * @param uri: the uri to decode */ GLTFUtils.DecodeBase64 = function (uri) { var decodedString = atob(uri.split(",")[1]); var bufferLength = decodedString.length; var bufferView = new Uint8Array(new ArrayBuffer(bufferLength)); for (var i = 0; i < bufferLength; i++) { bufferView[i] = decodedString.charCodeAt(i); } return bufferView.buffer; }; /** * Returns the wrap mode of the texture * @param mode: the mode value */ GLTFUtils.GetWrapMode = function (mode) { switch (mode) { case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE; case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE; case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE; default: return BABYLON.Texture.WRAP_ADDRESSMODE; } }; /** * Returns the byte stride giving an accessor * @param accessor: the GLTF accessor objet */ GLTFUtils.GetByteStrideFromType = function (accessor) { // Needs this function since "byteStride" isn't requiered in glTF format var type = accessor.type; switch (type) { case "VEC2": return 2; case "VEC3": return 3; case "VEC4": return 4; case "MAT2": return 4; case "MAT3": return 9; case "MAT4": return 16; default: return 1; } }; /** * Returns the texture filter mode giving a mode value * @param mode: the filter mode value */ GLTFUtils.GetTextureFilterMode = function (mode) { switch (mode) { case GLTF1.ETextureFilterType.LINEAR: case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST: case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE; case GLTF1.ETextureFilterType.NEAREST: case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE; default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE; } }; GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) { var byteOffset = bufferView.byteOffset + byteOffset; var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer]; if (byteOffset + byteLength > loadedBufferView.byteLength) { throw new Error("Buffer access is out of range"); } var buffer = loadedBufferView.buffer; byteOffset += loadedBufferView.byteOffset; switch (componentType) { case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength); case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength); case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength); case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength); default: return new Float32Array(buffer, byteOffset, byteLength); } }; /** * Returns a buffer from its accessor * @param gltfRuntime: the GLTF runtime * @param accessor: the GLTF accessor */ GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) { var bufferView = gltfRuntime.bufferViews[accessor.bufferView]; var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor); return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType); }; /** * Decodes a buffer view into a string * @param view: the buffer view */ GLTFUtils.DecodeBufferToText = function (view) { var result = ""; var length = view.byteLength; for (var i = 0; i < length; ++i) { result += String.fromCharCode(view[i]); } return result; }; /** * Returns the default material of gltf. Related to * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material * @param scene: the Babylon.js scene */ GLTFUtils.GetDefaultMaterial = function (scene) { if (!GLTFUtils._DefaultMaterial) { BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [ "precision highp float;", "", "uniform mat4 worldView;", "uniform mat4 projection;", "", "attribute vec3 position;", "", "void main(void)", "{", " gl_Position = projection * worldView * vec4(position, 1.0);", "}" ].join("\n"); BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [ "precision highp float;", "", "uniform vec4 u_emission;", "", "void main(void)", "{", " gl_FragColor = u_emission;", "}" ].join("\n"); var shaderPath = { vertex: "GLTFDefaultMaterial", fragment: "GLTFDefaultMaterial" }; var options = { attributes: ["position"], uniforms: ["worldView", "projection", "u_emission"], samplers: new Array(), needAlphaBlending: false }; GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options); GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0)); } return GLTFUtils._DefaultMaterial; }; // The GLTF default material GLTFUtils._DefaultMaterial = null; return GLTFUtils; }()); GLTF1.GLTFUtils = GLTFUtils; })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoaderUtils.js.map /// var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { var GLTFLoaderExtension = /** @class */ (function () { function GLTFLoaderExtension(name) { this._name = name; } Object.defineProperty(GLTFLoaderExtension.prototype, "name", { get: function () { return this._name; }, enumerable: true, configurable: true }); /** * Defines an override for loading the runtime * Return true to stop further extensions from loading the runtime */ GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) { return false; }; /** * Defines an onverride for creating gltf runtime * Return true to stop further extensions from creating the runtime */ GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) { return false; }; /** * Defines an override for loading buffers * Return true to stop further extensions from loading this buffer */ GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) { return false; }; /** * Defines an override for loading texture buffers * Return true to stop further extensions from loading this texture data */ GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) { return false; }; /** * Defines an override for creating textures * Return true to stop further extensions from loading this texture */ GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) { return false; }; /** * Defines an override for loading shader strings * Return true to stop further extensions from loading this shader data */ GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) { return false; }; /** * Defines an override for loading materials * Return true to stop further extensions from loading this material */ GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) { return false; }; // --------- // Utilities // --------- GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError); }, function () { setTimeout(function () { onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl)); }); }); }; GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError); }, function () { setTimeout(function () { onSuccess(); }); }); }; GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress); }, function () { GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress); }); }; GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) { GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError); }; GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError); }, function () { GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError); }); }; GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError); }, function () { GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError); }); }; GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError); }, function () { GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError); }); }; GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, function () { GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }); }; GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) { for (var extensionName in GLTF1.GLTFLoader.Extensions) { var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName]; if (func(loaderExtension)) { return; } } defaultFunc(); }; return GLTFLoaderExtension; }()); GLTF1.GLTFLoaderExtension = GLTFLoaderExtension; })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoaderExtension.js.map /// var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { var BinaryExtensionBufferName = "binary_glTF"; ; ; var GLTFBinaryExtension = /** @class */ (function (_super) { __extends(GLTFBinaryExtension, _super); function GLTFBinaryExtension() { return _super.call(this, "KHR_binary_glTF") || this; } GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) { var extensionsUsed = data.json.extensionsUsed; if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) { return false; } this._bin = data.bin; onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl)); return true; }; GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) { if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) { return false; } if (id !== BinaryExtensionBufferName) { return false; } onSuccess(this._bin); return true; }; GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) { var texture = gltfRuntime.textures[id]; var source = gltfRuntime.images[texture.source]; if (!source.extensions || !(this.name in source.extensions)) { return false; } var sourceExt = source.extensions[this.name]; var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView]; var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE); onSuccess(buffer); return true; }; GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) { var shader = gltfRuntime.shaders[id]; if (!shader.extensions || !(this.name in shader.extensions)) { return false; } var binaryExtensionShader = shader.extensions[this.name]; var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView]; var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE); setTimeout(function () { var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes); onSuccess(shaderString); }); return true; }; return GLTFBinaryExtension; }(GLTF1.GLTFLoaderExtension)); GLTF1.GLTFBinaryExtension = GLTFBinaryExtension; GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension()); })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFBinaryExtension.js.map /// var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { ; ; ; var GLTFMaterialsCommonExtension = /** @class */ (function (_super) { __extends(GLTFMaterialsCommonExtension, _super); function GLTFMaterialsCommonExtension() { return _super.call(this, "KHR_materials_common") || this; } GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) { if (!gltfRuntime.extensions) return false; var extension = gltfRuntime.extensions[this.name]; if (!extension) return false; // Create lights var lights = extension.lights; if (lights) { for (var thing in lights) { var light = lights[thing]; switch (light.type) { case "ambient": var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene); var ambient = light.ambient; if (ambient) { ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]); } break; case "point": var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene); var point = light.point; if (point) { pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]); } break; case "directional": var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene); var directional = light.directional; if (directional) { dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]); } break; case "spot": var spot = light.spot; if (spot) { var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene); spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]); } break; default: BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported"); break; } } } return false; }; GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) { var material = gltfRuntime.materials[id]; if (!material || !material.extensions) return false; var extension = material.extensions[this.name]; if (!extension) return false; var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene); standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation; if (extension.technique === "CONSTANT") { standardMaterial.disableLighting = true; } standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided; standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency; standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess; // Ambient if (typeof extension.values.ambient === "string") { this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError); } else { standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]); } // Diffuse if (typeof extension.values.diffuse === "string") { this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError); } else { standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]); } // Emission if (typeof extension.values.emission === "string") { this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError); } else { standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]); } // Specular if (typeof extension.values.specular === "string") { this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError); } else { standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]); } return true; }; GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) { // Create buffer from texture url GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { // Create texture from buffer GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError); }, onError); }; return GLTFMaterialsCommonExtension; }(GLTF1.GLTFLoaderExtension)); GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension; GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension()); })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map /// var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { /** * Enums */ var EComponentType; (function (EComponentType) { EComponentType[EComponentType["BYTE"] = 5120] = "BYTE"; EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; EComponentType[EComponentType["SHORT"] = 5122] = "SHORT"; EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT"; })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {})); var EMeshPrimitiveMode; (function (EMeshPrimitiveMode) { EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS"; EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES"; EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP"; EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP"; EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES"; EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {})); var ETextureMagFilter; (function (ETextureMagFilter) { ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST"; ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR"; })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {})); var ETextureMinFilter; (function (ETextureMinFilter) { ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST"; ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR"; ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST"; ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST"; ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR"; ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR"; })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {})); var ETextureWrapMode; (function (ETextureWrapMode) { ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE"; ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT"; })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {})); })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map /// var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var GLTFLoaderTracker = /** @class */ (function () { function GLTFLoaderTracker(onComplete) { this._pendingCount = 0; this._callback = onComplete; } GLTFLoaderTracker.prototype._addPendingData = function (data) { this._pendingCount++; }; GLTFLoaderTracker.prototype._removePendingData = function (data) { if (--this._pendingCount === 0) { this._callback(); } }; return GLTFLoaderTracker; }()); var GLTFLoader = /** @class */ (function () { function GLTFLoader(parent) { this._disposed = false; this._renderReady = false; this._requests = new Array(); this._renderReadyObservable = new BABYLON.Observable(); // Count of pending work that needs to complete before the asset is rendered. this._renderPendingCount = 0; // Count of pending work that needs to complete before the loader is disposed. this._loaderPendingCount = 0; this._loaderTrackers = new Array(); this._parent = parent; } GLTFLoader.RegisterExtension = function (extension) { if (GLTFLoader.Extensions[extension.name]) { BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists"); return; } GLTFLoader.Extensions[extension.name] = extension; // Keep the order of registration so that extensions registered first are called first. GLTF2.GLTFLoaderExtension._Extensions.push(extension); }; GLTFLoader.prototype.dispose = function () { if (this._disposed) { return; } this._disposed = true; // Abort requests that are not complete for (var _i = 0, _a = this._requests; _i < _a.length; _i++) { var request = _a[_i]; if (request.readyState !== (XMLHttpRequest.DONE || 4)) { request.abort(); } } // Revoke object urls created during load if (this._gltf.textures) { for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) { var texture = _c[_b]; if (texture.url) { URL.revokeObjectURL(texture.url); } } } this._gltf = undefined; this._babylonScene = undefined; this._parent = undefined; this._rootUrl = undefined; this._defaultMaterial = undefined; this._rootNode = undefined; this._successCallback = undefined; this._progressCallback = undefined; this._errorCallback = undefined; this._renderReady = false; this._requests = undefined; this._renderReadyObservable = undefined; this._renderPendingCount = 0; this._loaderPendingCount = 0; this._loaderTrackers = undefined; }; GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) { var _this = this; this._loadAsync(meshesNames, scene, data, rootUrl, function () { onSuccess(_this._getMeshes(), null, _this._getSkeletons()); }, onProgress, onError); }; GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) { this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError); }; GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) { var _this = this; this._tryCatchOnError(function () { _this._loadData(data); _this._babylonScene = scene; _this._rootUrl = rootUrl; _this._successCallback = onSuccess; _this._progressCallback = onProgress; _this._errorCallback = onError; GLTF2.GLTFUtils.AssignIndices(_this._gltf.accessors); GLTF2.GLTFUtils.AssignIndices(_this._gltf.animations); GLTF2.GLTFUtils.AssignIndices(_this._gltf.buffers); GLTF2.GLTFUtils.AssignIndices(_this._gltf.bufferViews); GLTF2.GLTFUtils.AssignIndices(_this._gltf.images); GLTF2.GLTFUtils.AssignIndices(_this._gltf.materials); GLTF2.GLTFUtils.AssignIndices(_this._gltf.meshes); GLTF2.GLTFUtils.AssignIndices(_this._gltf.nodes); GLTF2.GLTFUtils.AssignIndices(_this._gltf.scenes); GLTF2.GLTFUtils.AssignIndices(_this._gltf.skins); GLTF2.GLTFUtils.AssignIndices(_this._gltf.textures); _this._addPendingData(_this); _this._loadDefaultScene(nodeNames); _this._loadAnimations(); _this._removePendingData(_this); }); }; GLTFLoader.prototype._onError = function (message) { if (this._disposed) { return; } BABYLON.Tools.Error("glTF Loader: " + message); if (this._errorCallback) { this._errorCallback(message); } this.dispose(); }; GLTFLoader.prototype._onProgress = function (event) { if (this._disposed) { return; } if (this._progressCallback) { this._progressCallback(event); } }; GLTFLoader.prototype._executeWhenRenderReady = function (func) { if (this._renderReady) { func(); } else { this._renderReadyObservable.add(func); } }; GLTFLoader.prototype._onRenderReady = function () { if (this._rootNode.babylonMesh) { this._rootNode.babylonMesh.setEnabled(true); } this._startAnimations(); this._successCallback(); this._renderReadyObservable.notifyObservers(this); }; GLTFLoader.prototype._onComplete = function () { if (this._parent.onComplete) { this._parent.onComplete(); } this.dispose(); }; GLTFLoader.prototype._loadData = function (data) { this._gltf = data.json; if (data.bin) { var buffers = this._gltf.buffers; if (buffers && buffers[0] && !buffers[0].uri) { var binaryBuffer = buffers[0]; if (binaryBuffer.byteLength != data.bin.byteLength) { BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")"); } binaryBuffer.loadedData = data.bin; } else { BABYLON.Tools.Warn("Unexpected BIN chunk"); } } }; GLTFLoader.prototype._getMeshes = function () { var meshes = [this._rootNode.babylonMesh || null]; var nodes = this._gltf.nodes; if (nodes) { for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { var node = nodes_1[_i]; if (node.babylonMesh) { meshes.push(node.babylonMesh); } } } return meshes; }; GLTFLoader.prototype._getSkeletons = function () { var skeletons = new Array(); var skins = this._gltf.skins; if (skins) { for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) { var skin = skins_1[_i]; if (skin.babylonSkeleton instanceof BABYLON.Skeleton) { skeletons.push(skin.babylonSkeleton); } } } return skeletons; }; GLTFLoader.prototype._getAnimationTargets = function () { var targets = new Array(); var animations = this._gltf.animations; if (animations) { for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) { var animation = animations_1[_i]; targets.push.apply(targets, animation.targets); } } return targets; }; GLTFLoader.prototype._startAnimations = function () { for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) { var target = _a[_i]; this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); } }; GLTFLoader.prototype._loadDefaultScene = function (nodeNames) { var scene = GLTF2.GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0); if (!scene) { throw new Error("Failed to find scene " + (this._gltf.scene || 0)); } this._loadScene("#/scenes/" + scene.index, scene, nodeNames); }; GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) { this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) }; switch (this._parent.coordinateSystemMode) { case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: if (!this._babylonScene.useRightHandedSystem && this._rootNode.babylonMesh) { this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0); this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1); } break; case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: // do nothing break; case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: this._babylonScene.useRightHandedSystem = true; break; default: BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")"); return; } var nodeIndices = scene.nodes; this._traverseNodes(context, nodeIndices, function (node, parentNode) { node.parent = parentNode; return true; }, this._rootNode); if (nodeNames) { if (!(nodeNames instanceof Array)) { nodeNames = [nodeNames]; } var filteredNodeIndices_1 = new Array(); this._traverseNodes(context, nodeIndices, function (node) { if (nodeNames.indexOf(node.name) !== -1) { filteredNodeIndices_1.push(node.index); return false; } return true; }, this._rootNode); nodeIndices = filteredNodeIndices_1; } for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) { var index = nodeIndices_1[_i]; var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index); if (!node) { throw new Error(context + ": Failed to find node " + index); } this._loadNode("#/nodes/" + index, node); } // Disable the root mesh until the asset is ready to render. if (this._rootNode.babylonMesh) { this._rootNode.babylonMesh.setEnabled(false); } }; GLTFLoader.prototype._loadNode = function (context, node) { if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) { return; } node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene); this._loadTransform(node); if (node.mesh != null) { var mesh = GLTF2.GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh); if (!mesh) { throw new Error(context + ": Failed to find mesh " + node.mesh); } this._loadMesh("#/meshes/" + node.mesh, node, mesh); } node.babylonMesh.parent = (node.parent ? node.parent.babylonMesh : null); node.babylonAnimationTargets = node.babylonAnimationTargets || []; node.babylonAnimationTargets.push(node.babylonMesh); if (node.skin != null) { var skin = GLTF2.GLTFUtils.GetArrayItem(this._gltf.skins, node.skin); if (!skin) { throw new Error(context + ": Failed to find skin " + node.skin); } node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin); } if (node.camera != null) { // TODO: handle cameras } if (node.children) { for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var index = _a[_i]; var childNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index); if (!childNode) { throw new Error(context + ": Failed to find child node " + index); } this._loadNode("#/nodes/" + index, childNode); } } }; GLTFLoader.prototype._loadMesh = function (context, node, mesh) { var _this = this; if (!node.babylonMesh) { return; } node.babylonMesh.name = node.babylonMesh.name || mesh.name || ""; var primitives = mesh.primitives; if (!primitives || primitives.length === 0) { throw new Error(context + ": Primitives are missing"); } this._createMorphTargets(context, node, mesh); this._loadAllVertexDataAsync(context, mesh, function () { if (!node.babylonMesh) { return; } _this._loadMorphTargets(context, node, mesh); var vertexData = new BABYLON.VertexData(); for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) { var primitive = primitives_1[_i]; vertexData.merge(primitive.vertexData); } new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh); // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh. node.babylonMesh.subMeshes = []; var verticesStart = 0; var indicesStart = 0; for (var index = 0; index < primitives.length; index++) { var vertexData_1 = primitives[index].vertexData; var verticesCount = vertexData_1.positions.length; var indicesCount = vertexData_1.indices.length; BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh); verticesStart += verticesCount; indicesStart += indicesCount; } ; }); var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene); node.babylonMesh.material = multiMaterial; var subMaterials = multiMaterial.subMaterials; var _loop_1 = function (index) { var primitive = primitives[index]; if (primitive.material == null) { subMaterials[index] = this_1._getDefaultMaterial(); } else { var material_1 = GLTF2.GLTFUtils.GetArrayItem(this_1._gltf.materials, primitive.material); if (!material_1) { throw new Error(context + ": Failed to find material " + primitive.material); } this_1._loadMaterial("#/materials/" + material_1.index, material_1, function (babylonMaterial, isNew) { if (isNew && _this._parent.onMaterialLoaded) { _this._parent.onMaterialLoaded(babylonMaterial); } if (_this._parent.onBeforeMaterialReadyAsync) { _this._addLoaderPendingData(material_1); _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () { _this._tryCatchOnError(function () { subMaterials[index] = babylonMaterial; _this._removeLoaderPendingData(material_1); }); }); } else { subMaterials[index] = babylonMaterial; } }); } }; var this_1 = this; for (var index = 0; index < primitives.length; index++) { _loop_1(index); } ; }; GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) { var primitives = mesh.primitives; var numRemainingPrimitives = primitives.length; var _loop_2 = function (index) { var primitive = primitives[index]; this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) { primitive.vertexData = vertexData; if (--numRemainingPrimitives === 0) { onSuccess(); } }); }; var this_2 = this; for (var index = 0; index < primitives.length; index++) { _loop_2(index); } }; GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) { var _this = this; var attributes = primitive.attributes; if (!attributes) { throw new Error(context + ": Attributes are missing"); } if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) { // TODO: handle other primitive modes throw new Error(context + ": Mode " + primitive.mode + " is not currently supported"); } var vertexData = new BABYLON.VertexData(); var numRemainingAttributes = Object.keys(attributes).length; var _loop_3 = function (attribute) { var accessor = GLTF2.GLTFUtils.GetArrayItem(this_3._gltf.accessors, attributes[attribute]); if (!accessor) { throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]); } this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) { switch (attribute) { case "NORMAL": vertexData.normals = data; break; case "POSITION": vertexData.positions = data; break; case "TANGENT": vertexData.tangents = data; break; case "TEXCOORD_0": vertexData.uvs = data; break; case "TEXCOORD_1": vertexData.uvs2 = data; break; case "JOINTS_0": vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data)); break; case "WEIGHTS_0": vertexData.matricesWeights = data; break; case "COLOR_0": vertexData.colors = data; break; default: BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'"); break; } if (--numRemainingAttributes === 0) { if (primitive.indices == null) { vertexData.indices = new Uint32Array(vertexData.positions.length / 3); for (var i = 0; i < vertexData.indices.length; i++) { vertexData.indices[i] = i; } onSuccess(vertexData); } else { var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices); if (!indicesAccessor) { throw new Error(context + ": Failed to find indices accessor " + primitive.indices); } _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) { vertexData.indices = data; onSuccess(vertexData); }); } } }); }; var this_3 = this; for (var attribute in attributes) { _loop_3(attribute); } }; GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) { var primitives = mesh.primitives; var targets = primitives[0].targets; if (!targets || !node.babylonMesh) { return; } for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) { var primitive = primitives_2[_i]; if (!primitive.targets || primitive.targets.length != targets.length) { throw new Error(context + ": All primitives are required to list the same number of targets"); } } var morphTargetManager = new BABYLON.MorphTargetManager(); node.babylonMesh.morphTargetManager = morphTargetManager; for (var index = 0; index < targets.length; index++) { var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0; morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight)); } }; GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) { if (!node.babylonMesh) { return; } var morphTargetManager = node.babylonMesh.morphTargetManager; if (!morphTargetManager) { return; } this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () { var numTargets = morphTargetManager.numTargets; for (var index = 0; index < numTargets; index++) { var vertexData = new BABYLON.VertexData(); for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) { var primitive = _a[_i]; vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 }); } var target = morphTargetManager.getTarget(index); target.setNormals(vertexData.normals); target.setPositions(vertexData.positions); target.setTangents(vertexData.tangents); } }); }; GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) { if (!node.babylonMesh || !node.babylonMesh.morphTargetManager) { return; } var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets; var _loop_4 = function (primitive) { var targets = primitive.targets; if (!targets) { return "continue"; } primitive.targetsVertexData = new Array(targets.length); var _loop_5 = function (index) { this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) { primitive.targetsVertexData[index] = vertexData; if (--numRemainingTargets === 0) { onSuccess(); } }); }; for (var index = 0; index < targets.length; index++) { _loop_5(index); } }; var this_4 = this; for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) { var primitive = _a[_i]; _loop_4(primitive); } }; GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) { var targetVertexData = new BABYLON.VertexData(); var numRemainingAttributes = Object.keys(attributes).length; var _loop_6 = function (attribute) { var accessor = GLTF2.GLTFUtils.GetArrayItem(this_5._gltf.accessors, attributes[attribute]); if (!accessor) { throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]); } this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) { // glTF stores morph target information as deltas while babylon.js expects the final data. // As a result we have to add the original data to the delta to calculate the final data. var values = data; switch (attribute) { case "NORMAL": for (var i = 0; i < values.length; i++) { values[i] += vertexData.normals[i]; } targetVertexData.normals = values; break; case "POSITION": for (var i = 0; i < values.length; i++) { values[i] += vertexData.positions[i]; } targetVertexData.positions = values; break; case "TANGENT": // Tangent data for morph targets is stored as xyz delta. // The vertexData.tangent is stored as xyzw. // So we need to skip every fourth vertexData.tangent. for (var i = 0, j = 0; i < values.length; i++, j++) { values[i] += vertexData.tangents[j]; if ((i + 1) % 3 == 0) { j++; } } targetVertexData.tangents = values; break; default: BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'"); break; } if (--numRemainingAttributes === 0) { onSuccess(targetVertexData); } }); }; var this_5 = this; for (var attribute in attributes) { _loop_6(attribute); } }; GLTFLoader.prototype._loadTransform = function (node) { if (!node.babylonMesh) { return; } var position = BABYLON.Vector3.Zero(); var rotation = BABYLON.Quaternion.Identity(); var scaling = BABYLON.Vector3.One(); if (node.matrix) { var matrix = BABYLON.Matrix.FromArray(node.matrix); matrix.decompose(scaling, rotation, position); } else { if (node.translation) position = BABYLON.Vector3.FromArray(node.translation); if (node.rotation) rotation = BABYLON.Quaternion.FromArray(node.rotation); if (node.scale) scaling = BABYLON.Vector3.FromArray(node.scale); } node.babylonMesh.position = position; node.babylonMesh.rotationQuaternion = rotation; node.babylonMesh.scaling = scaling; }; GLTFLoader.prototype._loadSkin = function (context, skin) { var _this = this; var skeletonId = "skeleton" + skin.index; skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene); if (skin.inverseBindMatrices == null) { this._loadBones(context, skin, null); } else { var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices); if (!accessor) { throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices); } this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) { _this._loadBones(context, skin, data); }); } return skin.babylonSkeleton; }; GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) { var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index); node.babylonBones = node.babylonBones || {}; node.babylonBones[skin.index] = babylonBone; node.babylonAnimationTargets = node.babylonAnimationTargets || []; node.babylonAnimationTargets.push(babylonBone); return babylonBone; }; GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) { var babylonBones = {}; for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) { var index = _a[_i]; var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index); if (!node) { throw new Error(context + ": Failed to find joint " + index); } this._loadBone(node, skin, inverseBindMatrixData, babylonBones); } }; GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) { var babylonBone = babylonBones[node.index]; if (babylonBone) { return babylonBone; } var boneIndex = skin.joints.indexOf(node.index); var baseMatrix = BABYLON.Matrix.Identity(); if (inverseBindMatrixData && boneIndex !== -1) { baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16); baseMatrix.invertToRef(baseMatrix); } var babylonParentBone = null; if (node.index !== skin.skeleton && node.parent !== this._rootNode) { babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones); baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix); } babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex); babylonBones[node.index] = babylonBone; return babylonBone; }; GLTFLoader.prototype._getNodeMatrix = function (node) { return node.matrix ? BABYLON.Matrix.FromArray(node.matrix) : BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero()); }; GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) { if (parentNode === void 0) { parentNode = null; } for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) { var index = indices_1[_i]; var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index); if (!node) { throw new Error(context + ": Failed to find node " + index); } this._traverseNode(context, node, action, parentNode); } }; GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) { if (parentNode === void 0) { parentNode = null; } if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) { return; } if (!action(node, parentNode)) { return; } if (node.children) { this._traverseNodes(context, node.children, action, node); } }; GLTFLoader.prototype._loadAnimations = function () { var animations = this._gltf.animations; if (!animations) { return; } for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) { var animation = animations[animationIndex]; var context = "#/animations/" + animationIndex; for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) { var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex); if (!channel) { throw new Error(context + ": Failed to find channel " + channelIndex); } var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler); if (!sampler) { throw new Error(context + ": Failed to find sampler " + channel.sampler); } this._loadAnimationChannel(animation, context + "/channels/" + channelIndex, channel, context + "/samplers/" + channel.sampler, sampler); } } }; GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) { var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node); if (!targetNode) { throw new Error(channelContext + ": Failed to find target node " + channel.target.node); } var targetPath; var animationType; switch (channel.target.path) { case "translation": targetPath = "position"; animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3; break; case "rotation": targetPath = "rotationQuaternion"; animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION; break; case "scale": targetPath = "scaling"; animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3; break; case "weights": targetPath = "influence"; animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT; break; default: throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'"); } var inputData; var outputData; var checkSuccess = function () { if (!inputData || !outputData) { return; } var outputBufferOffset = 0; var getNextOutputValue; switch (targetPath) { case "position": getNextOutputValue = function () { var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset); outputBufferOffset += 3; return value; }; break; case "rotationQuaternion": getNextOutputValue = function () { var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset); outputBufferOffset += 4; return value; }; break; case "scaling": getNextOutputValue = function () { var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset); outputBufferOffset += 3; return value; }; break; case "influence": getNextOutputValue = function () { if (!targetNode.babylonMesh || !targetNode.babylonMesh.morphTargetManager) { return; } var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets; var value = new Array(numTargets); for (var i = 0; i < numTargets; i++) { value[i] = outputData[outputBufferOffset++]; } return value; }; break; } var getNextKey; switch (sampler.interpolation) { case "LINEAR": getNextKey = function (frameIndex) { return ({ frame: inputData[frameIndex], value: getNextOutputValue() }); }; break; case "CUBICSPLINE": getNextKey = function (frameIndex) { return ({ frame: inputData[frameIndex], inTangent: getNextOutputValue(), value: getNextOutputValue(), outTangent: getNextOutputValue() }); }; break; default: throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'"); } ; var keys = new Array(inputData.length); for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) { keys[frameIndex] = getNextKey(frameIndex); } animation.targets = animation.targets || []; if (targetPath === "influence" && targetNode.babylonMesh && targetNode.babylonMesh.morphTargetManager) { var morphTargetManager = targetNode.babylonMesh.morphTargetManager; var _loop_7 = function (targetIndex) { var morphTarget = morphTargetManager.getTarget(targetIndex); var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex; var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType); babylonAnimation.setKeys(keys.map(function (key) { return ({ frame: key.frame, inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined, value: key.value[targetIndex], outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined }); })); morphTarget.animations.push(babylonAnimation); animation.targets.push(morphTarget); }; for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) { _loop_7(targetIndex); } } else if (targetNode.babylonAnimationTargets) { var animationName = animation.name || "anim" + animation.index; var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType); babylonAnimation.setKeys(keys); for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) { var target = _a[_i]; target.animations.push(babylonAnimation.clone()); animation.targets.push(target); } } }; var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input); if (!inputAccessor) { throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input); } this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) { inputData = data; checkSuccess(); }); var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output); if (!outputAccessor) { throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output); } this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) { outputData = data; checkSuccess(); }); }; GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) { var _this = this; this._addPendingData(buffer); if (buffer.loadedData) { onSuccess(buffer.loadedData); this._removePendingData(buffer); } else if (buffer.loadedObservable) { buffer.loadedObservable.add(function (buffer) { onSuccess(buffer.loadedData); _this._removePendingData(buffer); }); } else { if (!buffer.uri) { throw new Error(context + ": Uri is missing"); } if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) { var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri); buffer.loadedData = new Uint8Array(data); onSuccess(buffer.loadedData); this._removePendingData(buffer); } else { buffer.loadedObservable = new BABYLON.Observable(); buffer.loadedObservable.add(function (buffer) { onSuccess(buffer.loadedData); _this._removePendingData(buffer); }); this._loadUri(context, buffer.uri, function (data) { buffer.loadedData = data; if (buffer.loadedObservable) { buffer.loadedObservable.notifyObservers(buffer); buffer.loadedObservable = undefined; } }); } } }; GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) { var _this = this; var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer); if (!buffer) { throw new Error(context + ": Failed to find buffer " + bufferView.buffer); } this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) { if (_this._disposed || !bufferData) { return; } var data; try { data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength); } catch (e) { throw new Error(context + ": " + e.message); } onSuccess(data); }); }; GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) { var _this = this; if (accessor.sparse) { throw new Error(context + ": Sparse accessors are not currently supported"); } if (accessor.normalized) { throw new Error(context + ": Normalized accessors are not currently supported"); } var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView); if (!bufferView) { throw new Error(context + ": Failed to find buffer view " + accessor.bufferView); } this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) { var numComponents = _this._getNumComponentsOfType(accessor.type); if (numComponents === 0) { throw new Error(context + ": Invalid type (" + accessor.type + ")"); } var data; var byteOffset = accessor.byteOffset; var byteStride = bufferView.byteStride; try { switch (accessor.componentType) { case GLTF2.EComponentType.BYTE: data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride); break; case GLTF2.EComponentType.UNSIGNED_BYTE: data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride); break; case GLTF2.EComponentType.SHORT: data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride); break; case GLTF2.EComponentType.UNSIGNED_SHORT: data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride); break; case GLTF2.EComponentType.UNSIGNED_INT: data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride); break; case GLTF2.EComponentType.FLOAT: data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride); break; default: throw new Error(context + ": Invalid component type (" + accessor.componentType + ")"); } } catch (e) { throw new Error(context + ": " + e); } onSuccess(data); }); }; GLTFLoader.prototype._getNumComponentsOfType = function (type) { switch (type) { case "SCALAR": return 1; case "VEC2": return 2; case "VEC3": return 3; case "VEC4": return 4; case "MAT2": return 4; case "MAT3": return 9; case "MAT4": return 16; } return 0; }; GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) { byteOffset = data.byteOffset + (byteOffset || 0); var targetLength = count * numComponents; if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) { return new typedArray(data.buffer, byteOffset, targetLength); } var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT; var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count); var targetBuffer = new typedArray(targetLength); var sourceIndex = 0; var targetIndex = 0; while (targetIndex < targetLength) { for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) { targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex]; targetIndex++; } sourceIndex += elementStride; } return targetBuffer; }; GLTFLoader.prototype._addPendingData = function (data) { if (!this._renderReady) { this._renderPendingCount++; } this._addLoaderPendingData(data); }; GLTFLoader.prototype._removePendingData = function (data) { if (!this._renderReady) { if (--this._renderPendingCount === 0) { this._renderReady = true; this._onRenderReady(); } } this._removeLoaderPendingData(data); }; GLTFLoader.prototype._addLoaderPendingData = function (data) { this._loaderPendingCount++; for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) { var tracker = _a[_i]; tracker._addPendingData(data); } }; GLTFLoader.prototype._removeLoaderPendingData = function (data) { for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) { var tracker = _a[_i]; tracker._removePendingData(data); } if (--this._loaderPendingCount === 0) { this._onComplete(); } }; GLTFLoader.prototype._whenAction = function (action, onComplete) { var _this = this; var tracker = new GLTFLoaderTracker(function () { _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1); onComplete(); }); this._loaderTrackers.push(tracker); this._addLoaderPendingData(tracker); action(); this._removeLoaderPendingData(tracker); }; GLTFLoader.prototype._getDefaultMaterial = function () { if (!this._defaultMaterial) { var id = "__gltf_default"; var material = this._babylonScene.getMaterialByName(id); if (!material) { material = new BABYLON.PBRMaterial(id, this._babylonScene); material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation; material.metallic = 1; material.roughness = 1; } this._defaultMaterial = material; } return this._defaultMaterial; }; GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) { var babylonMaterial = material.babylonMaterial; // Ensure metallic workflow babylonMaterial.metallic = 1; babylonMaterial.roughness = 1; var properties = material.pbrMetallicRoughness; if (!properties) { return; } babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1); babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor; babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor; if (properties.baseColorTexture && properties.baseColorTexture.texCoord) { var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index); if (!texture) { throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index); } babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord); } if (properties.metallicRoughnessTexture && properties.metallicRoughnessTexture.texCoord) { var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index); if (!texture) { throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index); } babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord); babylonMaterial.useMetallnessFromMetallicTextureBlue = true; babylonMaterial.useRoughnessFromMetallicTextureGreen = true; babylonMaterial.useRoughnessFromMetallicTextureAlpha = false; } this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor); }; GLTFLoader.prototype._loadMaterial = function (context, material, assign) { if (material.babylonMaterial) { assign(material.babylonMaterial, false); return; } if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) { return; } this._createPbrMaterial(material); this._loadMaterialBaseProperties(context, material); this._loadMaterialMetallicRoughnessProperties(context, material); if (material.babylonMaterial) { assign(material.babylonMaterial, true); } }; GLTFLoader.prototype._createPbrMaterial = function (material) { var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene); babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation; material.babylonMaterial = babylonMaterial; }; GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) { var babylonMaterial = material.babylonMaterial; babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0); if (material.doubleSided) { babylonMaterial.backFaceCulling = false; babylonMaterial.twoSidedLighting = true; } if (material.normalTexture && material.normalTexture.texCoord) { var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index); if (!texture) { throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index); } babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord); babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem; babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem; if (material.normalTexture.scale != null) { babylonMaterial.bumpTexture.level = material.normalTexture.scale; } } if (material.occlusionTexture && material.occlusionTexture.texCoord) { var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index); if (!texture) { throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index); } babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord); babylonMaterial.useAmbientInGrayScale = true; if (material.occlusionTexture.strength != null) { babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength; } } if (material.emissiveTexture && material.emissiveTexture.texCoord) { var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index); if (!texture) { throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index); } babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord); } }; GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) { var babylonMaterial = material.babylonMaterial; var alphaMode = material.alphaMode || "OPAQUE"; switch (alphaMode) { case "OPAQUE": // default is opaque break; case "MASK": babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff); if (colorFactor) { if (colorFactor[3] == 0) { babylonMaterial.alphaCutOff = 1; } else { babylonMaterial.alphaCutOff /= colorFactor[3]; } } if (babylonMaterial.albedoTexture) { babylonMaterial.albedoTexture.hasAlpha = true; } break; case "BLEND": if (colorFactor) { babylonMaterial.alpha = colorFactor[3]; } if (babylonMaterial.albedoTexture) { babylonMaterial.albedoTexture.hasAlpha = true; babylonMaterial.useAlphaFromAlbedoTexture = true; } break; default: throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'"); } }; GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) { var _this = this; var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler)); if (!sampler) { throw new Error(context + ": Failed to find sampler " + texture.sampler); } var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR); var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter); this._addPendingData(texture); var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () { _this._tryCatchOnError(function () { _this._removePendingData(texture); }); }, function (message) { _this._tryCatchOnError(function () { throw new Error(context + ": " + message); }); }); if (texture.url) { babylonTexture.updateURL(texture.url); } else if (texture.dataReadyObservable) { texture.dataReadyObservable.add(function (texture) { babylonTexture.updateURL(texture.url); }); } else { texture.dataReadyObservable = new BABYLON.Observable(); texture.dataReadyObservable.add(function (texture) { babylonTexture.updateURL(texture.url); }); var image_1 = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source); if (!image_1) { throw new Error(context + ": Failed to find source " + texture.source); } this._loadImage("#/images/" + image_1.index, image_1, function (data) { texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType })); if (texture.dataReadyObservable) { texture.dataReadyObservable.notifyObservers(texture); } }); } babylonTexture.coordinatesIndex = coordinatesIndex || 0; if (sampler.wrapS !== undefined) { babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS); } if (sampler.wrapT !== undefined) { babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT); } babylonTexture.name = texture.name || "texture" + texture.index; if (this._parent.onTextureLoaded) { this._parent.onTextureLoaded(babylonTexture); } return babylonTexture; }; GLTFLoader.prototype._loadImage = function (context, image, onSuccess) { if (image.uri) { if (GLTF2.GLTFUtils.IsBase64(image.uri)) { onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri))); } else { this._loadUri(context, image.uri, onSuccess); } } else { var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView); if (!bufferView) { throw new Error(context + ": Failed to find buffer view " + image.bufferView); } this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess); } }; GLTFLoader.prototype._loadUri = function (context, uri, onSuccess) { var _this = this; if (!GLTF2.GLTFUtils.ValidateUri(uri)) { throw new Error(context + ": Uri '" + uri + "' is invalid"); } var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) { _this._tryCatchOnError(function () { onSuccess(new Uint8Array(data)); }); }, function (event) { _this._tryCatchOnError(function () { _this._onProgress(event); }); }, this._babylonScene.database, true, function (request) { _this._tryCatchOnError(function () { throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : "")); }); }); if (request) { this._requests.push(request); } }; GLTFLoader.prototype._tryCatchOnError = function (handler) { try { handler(); } catch (e) { this._onError(e.message); } }; GLTFLoader.Extensions = {}; return GLTFLoader; }()); GLTF2.GLTFLoader = GLTFLoader; BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); }; })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoader.js.map /// var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { /** * Utils functions for GLTF */ var GLTFUtils = /** @class */ (function () { function GLTFUtils() { } /** * If the uri is a base64 string * @param uri: the uri to test */ GLTFUtils.IsBase64 = function (uri) { return uri.length < 5 ? false : uri.substr(0, 5) === "data:"; }; /** * Decode the base64 uri * @param uri: the uri to decode */ GLTFUtils.DecodeBase64 = function (uri) { var decodedString = atob(uri.split(",")[1]); var bufferLength = decodedString.length; var bufferView = new Uint8Array(new ArrayBuffer(bufferLength)); for (var i = 0; i < bufferLength; i++) { bufferView[i] = decodedString.charCodeAt(i); } return bufferView.buffer; }; GLTFUtils.ValidateUri = function (uri) { return (uri.indexOf("..") === -1); }; GLTFUtils.AssignIndices = function (array) { if (array) { for (var index = 0; index < array.length; index++) { array[index].index = index; } } }; GLTFUtils.GetArrayItem = function (array, index) { if (!array || !array[index]) { return null; } return array[index]; }; GLTFUtils.GetTextureWrapMode = function (mode) { // Set defaults if undefined mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode; switch (mode) { case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE; case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE; case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE; default: BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")"); return BABYLON.Texture.WRAP_ADDRESSMODE; } }; GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) { // Set defaults if undefined magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter; minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter; if (magFilter === GLTF2.ETextureMagFilter.LINEAR) { switch (minFilter) { case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST; case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR; case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST; case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST; case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR; case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR; default: BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")"); return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR; } } else { if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) { BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")"); } switch (minFilter) { case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST; case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR; case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST; case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST; case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR; case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR; default: BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")"); return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST; } } }; return GLTFUtils; }()); GLTF2.GLTFUtils = GLTFUtils; })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoaderUtils.js.map /// var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var GLTFLoaderExtension = /** @class */ (function () { function GLTFLoaderExtension() { this.enabled = true; } GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; }; GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; }; GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; }; GLTFLoaderExtension.prototype._loadExtension = function (property, action) { var _this = this; if (!property.extensions) { return false; } var extension = property.extensions[this.name]; if (!extension) { return false; } // Clear out the extension before executing the action to avoid recursing into the same property. property.extensions[this.name] = undefined; action(extension, function () { // Restore the extension after completing the action. if (property.extensions) { property.extensions[_this.name] = extension; } }); return true; }; GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) { return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); }); }; GLTFLoaderExtension.LoadNode = function (loader, context, node) { return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); }); }; GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) { return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); }); }; GLTFLoaderExtension._ApplyExtensions = function (action) { var extensions = GLTFLoaderExtension._Extensions; if (!extensions) { return false; } for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { var extension = extensions_1[_i]; if (extension.enabled && action(extension)) { return true; } } return false; }; // // Utilities // GLTFLoaderExtension._Extensions = []; return GLTFLoaderExtension; }()); GLTF2.GLTFLoaderExtension = GLTFLoaderExtension; })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoaderExtension.js.map /// var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var Extensions; (function (Extensions) { // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension. var MSFTLOD = /** @class */ (function (_super) { __extends(MSFTLOD, _super); function MSFTLOD() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(MSFTLOD.prototype, "name", { get: function () { return "MSFT_lod"; }, enumerable: true, configurable: true }); MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) { return this._loadExtension(node, function (extension, onComplete) { if (!loader._gltf.nodes) { return; } for (var i = extension.ids.length - 1; i >= 0; i--) { var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]); if (!lodNode) { throw new Error(context + ": Failed to find node " + extension.ids[i]); } loader._traverseNode(context, lodNode, action, parentNode); } loader._traverseNode(context, node, action, parentNode); onComplete(); }); }; MSFTLOD.prototype._loadNode = function (loader, context, node) { var _this = this; return this._loadExtension(node, function (extension, onComplete) { var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; }); loader._addLoaderPendingData(node); _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () { loader._removeLoaderPendingData(node); onComplete(); }); }); }; MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) { var _this = this; loader._whenAction(function () { loader._loadNode(context, nodes[index]); }, function () { if (index !== nodes.length - 1) { var previousNode = nodes[index + 1]; if (previousNode.babylonMesh) { previousNode.babylonMesh.setEnabled(false); } } if (index === 0) { onComplete(); return; } setTimeout(function () { loader._tryCatchOnError(function () { _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete); }); }, MSFTLOD.MinimalLODDelay); }); }; MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) { var _this = this; return this._loadExtension(material, function (extension, onComplete) { var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; }); loader._addLoaderPendingData(material); _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () { if (material.extensions) { material.extensions[_this.name] = extension; } loader._removeLoaderPendingData(material); onComplete(); }); }); }; MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) { var _this = this; loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) { assign(babylonMaterial, isNew); if (index === 0) { onComplete(); return; } // Load the next LOD when the loader is ready to render and // all active material textures of the current LOD are loaded. loader._executeWhenRenderReady(function () { BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () { setTimeout(function () { loader._tryCatchOnError(function () { _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete); }); }, MSFTLOD.MinimalLODDelay); }); }); }); }; /** * Specify the minimal delay between LODs in ms (default = 250) */ MSFTLOD.MinimalLODDelay = 250; return MSFTLOD; }(GLTF2.GLTFLoaderExtension)); Extensions.MSFTLOD = MSFTLOD; GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD()); })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {})); })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=MSFT_lod.js.map /// var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var Extensions; (function (Extensions) { var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) { __extends(KHRMaterialsPbrSpecularGlossiness, _super); function KHRMaterialsPbrSpecularGlossiness() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", { get: function () { return "KHR_materials_pbrSpecularGlossiness"; }, enumerable: true, configurable: true }); KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) { var _this = this; return this._loadExtension(material, function (extension, onComplete) { loader._createPbrMaterial(material); loader._loadMaterialBaseProperties(context, material); _this._loadSpecularGlossinessProperties(loader, context, material, extension); if (material.babylonMaterial) { assign(material.babylonMaterial, true); } }); }; KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) { var babylonMaterial = material.babylonMaterial; babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1); babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1); babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor; if (loader._gltf.textures) { if (properties.diffuseTexture) { var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index); if (!texture) { throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index); } if (properties.diffuseTexture.texCoord) { babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord); } } if (properties.specularGlossinessTexture) { var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index); if (!texture) { throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index); } if (properties.specularGlossinessTexture.texCoord) { babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord); } babylonMaterial.reflectivityTexture.hasAlpha = true; babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true; } } loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor); }; return KHRMaterialsPbrSpecularGlossiness; }(GLTF2.GLTFLoaderExtension)); Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness; GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness()); })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {})); })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map (function universalModuleDefinition(root, factory) { if (root && root["BABYLON"]) { return; } if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["BABYLON"] = factory(); else { root["BABYLON"] = factory(); } })(this, function() { return BABYLON; });