babylon.tools.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. var BABYLON;
  2. (function (BABYLON) {
  3. // Screenshots
  4. var screenshotCanvas;
  5. var cloneValue = function (source, destinationObject) {
  6. if (!source)
  7. return null;
  8. if (source instanceof BABYLON.Mesh) {
  9. return null;
  10. }
  11. if (source instanceof BABYLON.SubMesh) {
  12. return source.clone(destinationObject);
  13. }
  14. else if (source.clone) {
  15. return source.clone();
  16. }
  17. return null;
  18. };
  19. var Tools = (function () {
  20. function Tools() {
  21. }
  22. Tools.Instantiate = function (className) {
  23. var arr = className.split(".");
  24. var fn = (window || this);
  25. for (var i = 0, len = arr.length; i < len; i++) {
  26. fn = fn[arr[i]];
  27. }
  28. if (typeof fn !== "function") {
  29. return null;
  30. }
  31. return fn;
  32. };
  33. Tools.SetImmediate = function (action) {
  34. if (window.setImmediate) {
  35. window.setImmediate(action);
  36. }
  37. else {
  38. setTimeout(action, 1);
  39. }
  40. };
  41. Tools.IsExponentOfTwo = function (value) {
  42. var count = 1;
  43. do {
  44. count *= 2;
  45. } while (count < value);
  46. return count === value;
  47. };
  48. Tools.GetExponentOfTwo = function (value, max) {
  49. var count = 1;
  50. do {
  51. count *= 2;
  52. } while (count < value);
  53. if (count > max)
  54. count = max;
  55. return count;
  56. };
  57. Tools.GetFilename = function (path) {
  58. var index = path.lastIndexOf("/");
  59. if (index < 0)
  60. return path;
  61. return path.substring(index + 1);
  62. };
  63. Tools.GetDOMTextContent = function (element) {
  64. var result = "";
  65. var child = element.firstChild;
  66. while (child) {
  67. if (child.nodeType === 3) {
  68. result += child.textContent;
  69. }
  70. child = child.nextSibling;
  71. }
  72. return result;
  73. };
  74. Tools.ToDegrees = function (angle) {
  75. return angle * 180 / Math.PI;
  76. };
  77. Tools.ToRadians = function (angle) {
  78. return angle * Math.PI / 180;
  79. };
  80. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  81. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  82. var output = "";
  83. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  84. var i = 0;
  85. var bytes = new Uint8Array(buffer);
  86. while (i < bytes.length) {
  87. chr1 = bytes[i++];
  88. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  89. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  90. enc1 = chr1 >> 2;
  91. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  92. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  93. enc4 = chr3 & 63;
  94. if (isNaN(chr2)) {
  95. enc3 = enc4 = 64;
  96. }
  97. else if (isNaN(chr3)) {
  98. enc4 = 64;
  99. }
  100. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  101. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  102. }
  103. return "data:image/png;base64," + output;
  104. };
  105. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  106. if (bias === void 0) { bias = null; }
  107. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  108. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  109. for (var index = indexStart; index < indexStart + indexCount; index++) {
  110. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  111. minimum = BABYLON.Vector3.Minimize(current, minimum);
  112. maximum = BABYLON.Vector3.Maximize(current, maximum);
  113. }
  114. if (bias) {
  115. minimum.x -= minimum.x * bias.x + bias.y;
  116. minimum.y -= minimum.y * bias.x + bias.y;
  117. minimum.z -= minimum.z * bias.x + bias.y;
  118. maximum.x += maximum.x * bias.x + bias.y;
  119. maximum.y += maximum.y * bias.x + bias.y;
  120. maximum.z += maximum.z * bias.x + bias.y;
  121. }
  122. return {
  123. minimum: minimum,
  124. maximum: maximum
  125. };
  126. };
  127. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  128. if (bias === void 0) { bias = null; }
  129. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  130. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  131. for (var index = start; index < start + count; index++) {
  132. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  133. minimum = BABYLON.Vector3.Minimize(current, minimum);
  134. maximum = BABYLON.Vector3.Maximize(current, maximum);
  135. }
  136. if (bias) {
  137. minimum.x -= minimum.x * bias.x + bias.y;
  138. minimum.y -= minimum.y * bias.x + bias.y;
  139. minimum.z -= minimum.z * bias.x + bias.y;
  140. maximum.x += maximum.x * bias.x + bias.y;
  141. maximum.y += maximum.y * bias.x + bias.y;
  142. maximum.z += maximum.z * bias.x + bias.y;
  143. }
  144. return {
  145. minimum: minimum,
  146. maximum: maximum
  147. };
  148. };
  149. Tools.Vector2ArrayFeeder = function (array) {
  150. return function (index) {
  151. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  152. var length = isFloatArray ? array.length / 2 : array.length;
  153. if (index >= length) {
  154. return null;
  155. }
  156. if (isFloatArray) {
  157. var fa = array;
  158. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  159. }
  160. var a = array;
  161. return a[index];
  162. };
  163. };
  164. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  165. if (bias === void 0) { bias = null; }
  166. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  167. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  168. var i = 0;
  169. var cur = feeder(i++);
  170. while (cur) {
  171. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  172. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  173. cur = feeder(i++);
  174. }
  175. if (bias) {
  176. minimum.x -= minimum.x * bias.x + bias.y;
  177. minimum.y -= minimum.y * bias.x + bias.y;
  178. maximum.x += maximum.x * bias.x + bias.y;
  179. maximum.y += maximum.y * bias.x + bias.y;
  180. }
  181. return {
  182. minimum: minimum,
  183. maximum: maximum
  184. };
  185. };
  186. Tools.MakeArray = function (obj, allowsNullUndefined) {
  187. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  188. return undefined;
  189. return Array.isArray(obj) ? obj : [obj];
  190. };
  191. // Misc.
  192. Tools.GetPointerPrefix = function () {
  193. var eventPrefix = "pointer";
  194. // Check if pointer events are supported
  195. if (!window.PointerEvent && !navigator.pointerEnabled) {
  196. eventPrefix = "mouse";
  197. }
  198. return eventPrefix;
  199. };
  200. Tools.QueueNewFrame = function (func) {
  201. if (window.requestAnimationFrame)
  202. window.requestAnimationFrame(func);
  203. else if (window.msRequestAnimationFrame)
  204. window.msRequestAnimationFrame(func);
  205. else if (window.webkitRequestAnimationFrame)
  206. window.webkitRequestAnimationFrame(func);
  207. else if (window.mozRequestAnimationFrame)
  208. window.mozRequestAnimationFrame(func);
  209. else if (window.oRequestAnimationFrame)
  210. window.oRequestAnimationFrame(func);
  211. else {
  212. window.setTimeout(func, 16);
  213. }
  214. };
  215. Tools.RequestFullscreen = function (element, options) {
  216. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  217. if (!requestFunction)
  218. return;
  219. requestFunction.call(element, options);
  220. };
  221. Tools.ExitFullscreen = function () {
  222. if (document.exitFullscreen) {
  223. document.exitFullscreen();
  224. }
  225. else if (document.mozCancelFullScreen) {
  226. document.mozCancelFullScreen();
  227. }
  228. else if (document.webkitCancelFullScreen) {
  229. document.webkitCancelFullScreen();
  230. }
  231. else if (document.msCancelFullScreen) {
  232. document.msCancelFullScreen();
  233. }
  234. };
  235. // External files
  236. Tools.CleanUrl = function (url) {
  237. url = url.replace(/#/mg, "%23");
  238. return url;
  239. };
  240. Tools.LoadImage = function (url, onload, onerror, database) {
  241. if (url instanceof ArrayBuffer) {
  242. url = Tools.EncodeArrayBufferTobase64(url);
  243. }
  244. url = Tools.CleanUrl(url);
  245. var img = new Image();
  246. if (url.substr(0, 5) !== "data:") {
  247. if (Tools.CorsBehavior) {
  248. switch (typeof (Tools.CorsBehavior)) {
  249. case "function":
  250. var result = Tools.CorsBehavior(url);
  251. if (result) {
  252. img.crossOrigin = result;
  253. }
  254. break;
  255. case "string":
  256. default:
  257. img.crossOrigin = Tools.CorsBehavior;
  258. break;
  259. }
  260. }
  261. }
  262. img.onload = function () {
  263. onload(img);
  264. };
  265. img.onerror = function (err) {
  266. Tools.Error("Error while trying to load texture: " + url);
  267. if (Tools.UseFallbackTexture) {
  268. img.src = "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";
  269. onload(img);
  270. }
  271. else {
  272. onerror();
  273. }
  274. };
  275. var noIndexedDB = function () {
  276. img.src = url;
  277. };
  278. var loadFromIndexedDB = function () {
  279. database.loadImageFromDB(url, img);
  280. };
  281. //ANY database to do!
  282. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  283. database.openAsync(loadFromIndexedDB, noIndexedDB);
  284. }
  285. else {
  286. if (url.indexOf("file:") === -1) {
  287. noIndexedDB();
  288. }
  289. else {
  290. try {
  291. var textureName = url.substring(5).toLowerCase();
  292. var blobURL;
  293. try {
  294. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  295. }
  296. catch (ex) {
  297. // Chrome doesn't support oneTimeOnly parameter
  298. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  299. }
  300. img.src = blobURL;
  301. }
  302. catch (e) {
  303. img.src = null;
  304. }
  305. }
  306. }
  307. return img;
  308. };
  309. //ANY
  310. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  311. url = Tools.CleanUrl(url);
  312. var noIndexedDB = function () {
  313. var request = new XMLHttpRequest();
  314. var loadUrl = Tools.BaseUrl + url;
  315. request.open('GET', loadUrl, true);
  316. if (useArrayBuffer) {
  317. request.responseType = "arraybuffer";
  318. }
  319. request.onprogress = progressCallBack;
  320. request.onreadystatechange = function () {
  321. if (request.readyState === 4) {
  322. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  323. callback(!useArrayBuffer ? request.responseText : request.response);
  324. }
  325. else {
  326. if (onError) {
  327. onError();
  328. }
  329. else {
  330. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  331. }
  332. }
  333. }
  334. };
  335. request.send(null);
  336. };
  337. var loadFromIndexedDB = function () {
  338. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  339. };
  340. if (url.indexOf("file:") !== -1) {
  341. var fileName = url.substring(5).toLowerCase();
  342. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  343. }
  344. else {
  345. // Caching all files
  346. if (database && database.enableSceneOffline) {
  347. database.openAsync(loadFromIndexedDB, noIndexedDB);
  348. }
  349. else {
  350. noIndexedDB();
  351. }
  352. }
  353. };
  354. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  355. var reader = new FileReader();
  356. reader.onload = function (e) {
  357. //target doesn't have result from ts 1.3
  358. callback(e.target['result']);
  359. };
  360. reader.onprogress = progressCallback;
  361. reader.readAsDataURL(fileToLoad);
  362. };
  363. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  364. var reader = new FileReader();
  365. reader.onerror = function (e) {
  366. Tools.Log("Error while reading file: " + fileToLoad.name);
  367. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  368. };
  369. reader.onload = function (e) {
  370. //target doesn't have result from ts 1.3
  371. callback(e.target['result']);
  372. };
  373. reader.onprogress = progressCallBack;
  374. if (!useArrayBuffer) {
  375. // Asynchronous read
  376. reader.readAsText(fileToLoad);
  377. }
  378. else {
  379. reader.readAsArrayBuffer(fileToLoad);
  380. }
  381. };
  382. //returns a downloadable url to a file content.
  383. Tools.FileAsURL = function (content) {
  384. var fileBlob = new Blob([content]);
  385. var url = window.URL || window.webkitURL;
  386. var link = url.createObjectURL(fileBlob);
  387. return link;
  388. };
  389. // Misc.
  390. Tools.Format = function (value, decimals) {
  391. if (decimals === void 0) { decimals = 2; }
  392. return value.toFixed(decimals);
  393. };
  394. Tools.CheckExtends = function (v, min, max) {
  395. if (v.x < min.x)
  396. min.x = v.x;
  397. if (v.y < min.y)
  398. min.y = v.y;
  399. if (v.z < min.z)
  400. min.z = v.z;
  401. if (v.x > max.x)
  402. max.x = v.x;
  403. if (v.y > max.y)
  404. max.y = v.y;
  405. if (v.z > max.z)
  406. max.z = v.z;
  407. };
  408. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  409. for (var prop in source) {
  410. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  411. continue;
  412. }
  413. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  414. continue;
  415. }
  416. var sourceValue = source[prop];
  417. var typeOfSourceValue = typeof sourceValue;
  418. if (typeOfSourceValue === "function") {
  419. continue;
  420. }
  421. if (typeOfSourceValue === "object") {
  422. if (sourceValue instanceof Array) {
  423. destination[prop] = [];
  424. if (sourceValue.length > 0) {
  425. if (typeof sourceValue[0] == "object") {
  426. for (var index = 0; index < sourceValue.length; index++) {
  427. var clonedValue = cloneValue(sourceValue[index], destination);
  428. if (destination[prop].indexOf(clonedValue) === -1) {
  429. destination[prop].push(clonedValue);
  430. }
  431. }
  432. }
  433. else {
  434. destination[prop] = sourceValue.slice(0);
  435. }
  436. }
  437. }
  438. else {
  439. destination[prop] = cloneValue(sourceValue, destination);
  440. }
  441. }
  442. else {
  443. destination[prop] = sourceValue;
  444. }
  445. }
  446. };
  447. Tools.IsEmpty = function (obj) {
  448. for (var i in obj) {
  449. return false;
  450. }
  451. return true;
  452. };
  453. Tools.RegisterTopRootEvents = function (events) {
  454. for (var index = 0; index < events.length; index++) {
  455. var event = events[index];
  456. window.addEventListener(event.name, event.handler, false);
  457. try {
  458. if (window.parent) {
  459. window.parent.addEventListener(event.name, event.handler, false);
  460. }
  461. }
  462. catch (e) {
  463. }
  464. }
  465. };
  466. Tools.UnregisterTopRootEvents = function (events) {
  467. for (var index = 0; index < events.length; index++) {
  468. var event = events[index];
  469. window.removeEventListener(event.name, event.handler);
  470. try {
  471. if (window.parent) {
  472. window.parent.removeEventListener(event.name, event.handler);
  473. }
  474. }
  475. catch (e) {
  476. }
  477. }
  478. };
  479. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  480. // Read the contents of the framebuffer
  481. var numberOfChannelsByLine = width * 4;
  482. var halfHeight = height / 2;
  483. //Reading datas from WebGL
  484. var data = engine.readPixels(0, 0, width, height);
  485. //To flip image on Y axis.
  486. for (var i = 0; i < halfHeight; i++) {
  487. for (var j = 0; j < numberOfChannelsByLine; j++) {
  488. var currentCell = j + i * numberOfChannelsByLine;
  489. var targetLine = height - i - 1;
  490. var targetCell = j + targetLine * numberOfChannelsByLine;
  491. var temp = data[currentCell];
  492. data[currentCell] = data[targetCell];
  493. data[targetCell] = temp;
  494. }
  495. }
  496. // Create a 2D canvas to store the result
  497. if (!screenshotCanvas) {
  498. screenshotCanvas = document.createElement('canvas');
  499. }
  500. screenshotCanvas.width = width;
  501. screenshotCanvas.height = height;
  502. var context = screenshotCanvas.getContext('2d');
  503. // Copy the pixels to a 2D canvas
  504. var imageData = context.createImageData(width, height);
  505. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  506. var castData = imageData.data;
  507. castData.set(data);
  508. context.putImageData(imageData, 0, 0);
  509. var base64Image = screenshotCanvas.toDataURL();
  510. if (successCallback) {
  511. successCallback(base64Image);
  512. }
  513. else {
  514. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  515. if (("download" in document.createElement("a"))) {
  516. var a = window.document.createElement("a");
  517. a.href = base64Image;
  518. var date = new Date();
  519. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  520. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  521. window.document.body.appendChild(a);
  522. a.addEventListener("click", function () {
  523. a.parentElement.removeChild(a);
  524. });
  525. a.click();
  526. }
  527. else {
  528. var newWindow = window.open("");
  529. var img = newWindow.document.createElement("img");
  530. img.src = base64Image;
  531. newWindow.document.body.appendChild(img);
  532. }
  533. }
  534. };
  535. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  536. var width;
  537. var height;
  538. //If a precision value is specified
  539. if (size.precision) {
  540. width = Math.round(engine.getRenderWidth() * size.precision);
  541. height = Math.round(width / engine.getAspectRatio(camera));
  542. size = { width: width, height: height };
  543. }
  544. else if (size.width && size.height) {
  545. width = size.width;
  546. height = size.height;
  547. }
  548. else if (size.width && !size.height) {
  549. width = size.width;
  550. height = Math.round(width / engine.getAspectRatio(camera));
  551. size = { width: width, height: height };
  552. }
  553. else if (size.height && !size.width) {
  554. height = size.height;
  555. width = Math.round(height * engine.getAspectRatio(camera));
  556. size = { width: width, height: height };
  557. }
  558. else if (!isNaN(size)) {
  559. height = size;
  560. width = size;
  561. }
  562. else {
  563. Tools.Error("Invalid 'size' parameter !");
  564. return;
  565. }
  566. var scene = camera.getScene();
  567. var previousCamera = null;
  568. if (scene.activeCamera !== camera) {
  569. previousCamera = scene.activeCamera;
  570. scene.activeCamera = camera;
  571. }
  572. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  573. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  574. texture.renderList = scene.meshes;
  575. texture.onAfterRenderObservable.add(function () {
  576. Tools.DumpFramebuffer(width, height, engine, successCallback);
  577. });
  578. scene.incrementRenderId();
  579. texture.render(true);
  580. texture.dispose();
  581. if (previousCamera) {
  582. scene.activeCamera = previousCamera;
  583. }
  584. camera.getProjectionMatrix(true); // Force cache refresh;
  585. };
  586. // XHR response validator for local file scenario
  587. Tools.ValidateXHRData = function (xhr, dataType) {
  588. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  589. if (dataType === void 0) { dataType = 7; }
  590. try {
  591. if (dataType & 1) {
  592. if (xhr.responseText && xhr.responseText.length > 0) {
  593. return true;
  594. }
  595. else if (dataType === 1) {
  596. return false;
  597. }
  598. }
  599. if (dataType & 2) {
  600. // Check header width and height since there is no "TGA" magic number
  601. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  602. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  603. return true;
  604. }
  605. else if (dataType === 2) {
  606. return false;
  607. }
  608. }
  609. if (dataType & 4) {
  610. // Check for the "DDS" magic number
  611. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  612. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  613. return true;
  614. }
  615. else {
  616. return false;
  617. }
  618. }
  619. }
  620. catch (e) {
  621. }
  622. return false;
  623. };
  624. Object.defineProperty(Tools, "NoneLogLevel", {
  625. get: function () {
  626. return Tools._NoneLogLevel;
  627. },
  628. enumerable: true,
  629. configurable: true
  630. });
  631. Object.defineProperty(Tools, "MessageLogLevel", {
  632. get: function () {
  633. return Tools._MessageLogLevel;
  634. },
  635. enumerable: true,
  636. configurable: true
  637. });
  638. Object.defineProperty(Tools, "WarningLogLevel", {
  639. get: function () {
  640. return Tools._WarningLogLevel;
  641. },
  642. enumerable: true,
  643. configurable: true
  644. });
  645. Object.defineProperty(Tools, "ErrorLogLevel", {
  646. get: function () {
  647. return Tools._ErrorLogLevel;
  648. },
  649. enumerable: true,
  650. configurable: true
  651. });
  652. Object.defineProperty(Tools, "AllLogLevel", {
  653. get: function () {
  654. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  655. },
  656. enumerable: true,
  657. configurable: true
  658. });
  659. Tools._AddLogEntry = function (entry) {
  660. Tools._LogCache = entry + Tools._LogCache;
  661. if (Tools.OnNewCacheEntry) {
  662. Tools.OnNewCacheEntry(entry);
  663. }
  664. };
  665. Tools._FormatMessage = function (message) {
  666. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  667. var date = new Date();
  668. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  669. };
  670. Tools._LogDisabled = function (message) {
  671. // nothing to do
  672. };
  673. Tools._LogEnabled = function (message) {
  674. var formattedMessage = Tools._FormatMessage(message);
  675. console.log("BJS - " + formattedMessage);
  676. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  677. Tools._AddLogEntry(entry);
  678. };
  679. Tools._WarnDisabled = function (message) {
  680. // nothing to do
  681. };
  682. Tools._WarnEnabled = function (message) {
  683. var formattedMessage = Tools._FormatMessage(message);
  684. console.warn("BJS - " + formattedMessage);
  685. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  686. Tools._AddLogEntry(entry);
  687. };
  688. Tools._ErrorDisabled = function (message) {
  689. // nothing to do
  690. };
  691. Tools._ErrorEnabled = function (message) {
  692. Tools.errorsCount++;
  693. var formattedMessage = Tools._FormatMessage(message);
  694. console.error("BJS - " + formattedMessage);
  695. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  696. Tools._AddLogEntry(entry);
  697. };
  698. Object.defineProperty(Tools, "LogCache", {
  699. get: function () {
  700. return Tools._LogCache;
  701. },
  702. enumerable: true,
  703. configurable: true
  704. });
  705. Tools.ClearLogCache = function () {
  706. Tools._LogCache = "";
  707. Tools.errorsCount = 0;
  708. };
  709. Object.defineProperty(Tools, "LogLevels", {
  710. set: function (level) {
  711. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  712. Tools.Log = Tools._LogEnabled;
  713. }
  714. else {
  715. Tools.Log = Tools._LogDisabled;
  716. }
  717. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  718. Tools.Warn = Tools._WarnEnabled;
  719. }
  720. else {
  721. Tools.Warn = Tools._WarnDisabled;
  722. }
  723. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  724. Tools.Error = Tools._ErrorEnabled;
  725. }
  726. else {
  727. Tools.Error = Tools._ErrorDisabled;
  728. }
  729. },
  730. enumerable: true,
  731. configurable: true
  732. });
  733. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  734. get: function () {
  735. return Tools._PerformanceNoneLogLevel;
  736. },
  737. enumerable: true,
  738. configurable: true
  739. });
  740. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  741. get: function () {
  742. return Tools._PerformanceUserMarkLogLevel;
  743. },
  744. enumerable: true,
  745. configurable: true
  746. });
  747. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  748. get: function () {
  749. return Tools._PerformanceConsoleLogLevel;
  750. },
  751. enumerable: true,
  752. configurable: true
  753. });
  754. Object.defineProperty(Tools, "PerformanceLogLevel", {
  755. set: function (level) {
  756. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  757. Tools.StartPerformanceCounter = Tools._StartUserMark;
  758. Tools.EndPerformanceCounter = Tools._EndUserMark;
  759. return;
  760. }
  761. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  762. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  763. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  764. return;
  765. }
  766. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  767. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  768. },
  769. enumerable: true,
  770. configurable: true
  771. });
  772. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  773. };
  774. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  775. };
  776. Tools._StartUserMark = function (counterName, condition) {
  777. if (condition === void 0) { condition = true; }
  778. if (!condition || !Tools._performance.mark) {
  779. return;
  780. }
  781. Tools._performance.mark(counterName + "-Begin");
  782. };
  783. Tools._EndUserMark = function (counterName, condition) {
  784. if (condition === void 0) { condition = true; }
  785. if (!condition || !Tools._performance.mark) {
  786. return;
  787. }
  788. Tools._performance.mark(counterName + "-End");
  789. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  790. };
  791. Tools._StartPerformanceConsole = function (counterName, condition) {
  792. if (condition === void 0) { condition = true; }
  793. if (!condition) {
  794. return;
  795. }
  796. Tools._StartUserMark(counterName, condition);
  797. if (console.time) {
  798. console.time(counterName);
  799. }
  800. };
  801. Tools._EndPerformanceConsole = function (counterName, condition) {
  802. if (condition === void 0) { condition = true; }
  803. if (!condition) {
  804. return;
  805. }
  806. Tools._EndUserMark(counterName, condition);
  807. if (console.time) {
  808. console.timeEnd(counterName);
  809. }
  810. };
  811. Object.defineProperty(Tools, "Now", {
  812. get: function () {
  813. if (window.performance && window.performance.now) {
  814. return window.performance.now();
  815. }
  816. return new Date().getTime();
  817. },
  818. enumerable: true,
  819. configurable: true
  820. });
  821. /**
  822. * This method will return the name of the class used to create the instance of the given object.
  823. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  824. * @param object the object to get the class name from
  825. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  826. */
  827. Tools.getClassName = function (object, isType) {
  828. if (isType === void 0) { isType = false; }
  829. var name = null;
  830. if (!isType && object.getClassName) {
  831. name = object.getClassName();
  832. }
  833. else {
  834. if (object instanceof Object) {
  835. var classObj = isType ? object : Object.getPrototypeOf(object);
  836. name = classObj.constructor["__bjsclassName__"];
  837. }
  838. if (!name) {
  839. name = typeof object;
  840. }
  841. }
  842. return name;
  843. };
  844. Tools.first = function (array, predicate) {
  845. for (var _i = 0; _i < array.length; _i++) {
  846. var el = array[_i];
  847. if (predicate(el)) {
  848. return el;
  849. }
  850. }
  851. };
  852. /**
  853. * 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.
  854. * @param array
  855. */
  856. Tools.arrayOrStringFeeder = function (array) {
  857. return function (index) {
  858. if (index >= array.length) {
  859. return null;
  860. }
  861. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  862. if (val && val.getHashCode) {
  863. val = val.getHashCode();
  864. }
  865. if (typeof val === "string") {
  866. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  867. }
  868. return val;
  869. };
  870. };
  871. /**
  872. * Compute the hashCode of a stream of number
  873. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  874. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  875. * @return the hash code computed
  876. */
  877. Tools.hashCodeFromStream = function (feeder) {
  878. // Based from here: http://stackoverflow.com/a/7616484/802124
  879. var hash = 0;
  880. var index = 0;
  881. var chr = feeder(index++);
  882. while (chr != null) {
  883. hash = ((hash << 5) - hash) + chr;
  884. hash |= 0; // Convert to 32bit integer
  885. chr = feeder(index++);
  886. }
  887. return hash;
  888. };
  889. Tools.BaseUrl = "";
  890. Tools.CorsBehavior = "anonymous";
  891. Tools.UseFallbackTexture = true;
  892. // Logs
  893. Tools._NoneLogLevel = 0;
  894. Tools._MessageLogLevel = 1;
  895. Tools._WarningLogLevel = 2;
  896. Tools._ErrorLogLevel = 4;
  897. Tools._LogCache = "";
  898. Tools.errorsCount = 0;
  899. Tools.Log = Tools._LogEnabled;
  900. Tools.Warn = Tools._WarnEnabled;
  901. Tools.Error = Tools._ErrorEnabled;
  902. // Performances
  903. Tools._PerformanceNoneLogLevel = 0;
  904. Tools._PerformanceUserMarkLogLevel = 1;
  905. Tools._PerformanceConsoleLogLevel = 2;
  906. Tools._performance = window.performance;
  907. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  908. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  909. return Tools;
  910. })();
  911. BABYLON.Tools = Tools;
  912. /**
  913. * Use this className as a decorator on a given class definition to add it a name.
  914. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  915. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  916. * @param name
  917. */
  918. function className(name) {
  919. return function (target) {
  920. target["__bjsclassName__"] = name;
  921. };
  922. }
  923. BABYLON.className = className;
  924. /**
  925. * An implementation of a loop for asynchronous functions.
  926. */
  927. var AsyncLoop = (function () {
  928. /**
  929. * Constroctor.
  930. * @param iterations the number of iterations.
  931. * @param _fn the function to run each iteration
  932. * @param _successCallback the callback that will be called upon succesful execution
  933. * @param offset starting offset.
  934. */
  935. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  936. if (offset === void 0) { offset = 0; }
  937. this.iterations = iterations;
  938. this._fn = _fn;
  939. this._successCallback = _successCallback;
  940. this.index = offset - 1;
  941. this._done = false;
  942. }
  943. /**
  944. * Execute the next iteration. Must be called after the last iteration was finished.
  945. */
  946. AsyncLoop.prototype.executeNext = function () {
  947. if (!this._done) {
  948. if (this.index + 1 < this.iterations) {
  949. ++this.index;
  950. this._fn(this);
  951. }
  952. else {
  953. this.breakLoop();
  954. }
  955. }
  956. };
  957. /**
  958. * Break the loop and run the success callback.
  959. */
  960. AsyncLoop.prototype.breakLoop = function () {
  961. this._done = true;
  962. this._successCallback();
  963. };
  964. /**
  965. * Helper function
  966. */
  967. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  968. if (offset === void 0) { offset = 0; }
  969. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  970. loop.executeNext();
  971. return loop;
  972. };
  973. /**
  974. * A for-loop that will run a given number of iterations synchronous and the rest async.
  975. * @param iterations total number of iterations
  976. * @param syncedIterations number of synchronous iterations in each async iteration.
  977. * @param fn the function to call each iteration.
  978. * @param callback a success call back that will be called when iterating stops.
  979. * @param breakFunction a break condition (optional)
  980. * @param timeout timeout settings for the setTimeout function. default - 0.
  981. * @constructor
  982. */
  983. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  984. if (timeout === void 0) { timeout = 0; }
  985. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  986. if (breakFunction && breakFunction())
  987. loop.breakLoop();
  988. else {
  989. setTimeout(function () {
  990. for (var i = 0; i < syncedIterations; ++i) {
  991. var iteration = (loop.index * syncedIterations) + i;
  992. if (iteration >= iterations)
  993. break;
  994. fn(iteration);
  995. if (breakFunction && breakFunction()) {
  996. loop.breakLoop();
  997. break;
  998. }
  999. }
  1000. loop.executeNext();
  1001. }, timeout);
  1002. }
  1003. }, callback);
  1004. };
  1005. return AsyncLoop;
  1006. })();
  1007. BABYLON.AsyncLoop = AsyncLoop;
  1008. })(BABYLON || (BABYLON = {}));