babylon.tools.js 42 KB

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