babylon.tools.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. module BABYLON {
  2. export interface IAnimatable {
  3. animations: Array<Animation>;
  4. }
  5. export interface ISize {
  6. width: number;
  7. height: number;
  8. }
  9. // Screenshots
  10. var screenshotCanvas: HTMLCanvasElement;
  11. var cloneValue = (source, destinationObject) => {
  12. if (!source)
  13. return null;
  14. if (source instanceof Mesh) {
  15. return null;
  16. }
  17. if (source instanceof SubMesh) {
  18. return source.clone(destinationObject);
  19. } else if (source.clone) {
  20. return source.clone();
  21. }
  22. return null;
  23. };
  24. export class Tools {
  25. public static BaseUrl = "";
  26. public static ToHex(i: number): string {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. }
  33. public static SetImmediate(action: () => void) {
  34. if (window.setImmediate) {
  35. window.setImmediate(action);
  36. } else {
  37. setTimeout(action, 1);
  38. }
  39. }
  40. public static IsExponantOfTwo(value: number): boolean {
  41. var count = 1;
  42. do {
  43. count *= 2;
  44. } while (count < value);
  45. return count === value;
  46. }
  47. public static GetExponantOfTwo(value: number, max: number): number {
  48. var count = 1;
  49. do {
  50. count *= 2;
  51. } while (count < value);
  52. if (count > max)
  53. count = max;
  54. return count;
  55. }
  56. public static GetFilename(path: string): string {
  57. var index = path.lastIndexOf("/");
  58. if (index < 0)
  59. return path;
  60. return path.substring(index + 1);
  61. }
  62. public static GetDOMTextContent(element: HTMLElement): string {
  63. var result = "";
  64. var child = element.firstChild;
  65. while (child) {
  66. if (child.nodeType === 3) {
  67. result += child.textContent;
  68. }
  69. child = child.nextSibling;
  70. }
  71. return result;
  72. }
  73. public static ToDegrees(angle: number): number {
  74. return angle * 180 / Math.PI;
  75. }
  76. public static ToRadians(angle: number): number {
  77. return angle * Math.PI / 180;
  78. }
  79. public static ExtractMinAndMaxIndexed(positions: number[], indices: number[], indexStart: number, indexCount: number): { minimum: Vector3; maximum: Vector3 } {
  80. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  81. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  82. for (var index = indexStart; index < indexStart + indexCount; index++) {
  83. var current = new Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  84. minimum = Vector3.Minimize(current, minimum);
  85. maximum = Vector3.Maximize(current, maximum);
  86. }
  87. return {
  88. minimum: minimum,
  89. maximum: maximum
  90. };
  91. }
  92. public static ExtractMinAndMax(positions: number[], start: number, count: number): { minimum: Vector3; maximum: Vector3 } {
  93. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  95. for (var index = start; index < start + count; index++) {
  96. var current = new Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  97. minimum = Vector3.Minimize(current, minimum);
  98. maximum = Vector3.Maximize(current, maximum);
  99. }
  100. return {
  101. minimum: minimum,
  102. maximum: maximum
  103. };
  104. }
  105. public static MakeArray(obj, allowsNullUndefined?: boolean): Array<any> {
  106. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  107. return undefined;
  108. return Array.isArray(obj) ? obj : [obj];
  109. }
  110. // Misc.
  111. public static GetPointerPrefix(): string {
  112. var eventPrefix = "pointer";
  113. // Check if hand.js is referenced or if the browser natively supports pointer events
  114. if (!navigator.pointerEnabled) {
  115. eventPrefix = "mouse";
  116. }
  117. return eventPrefix;
  118. }
  119. public static QueueNewFrame(func): void {
  120. if (window.requestAnimationFrame)
  121. window.requestAnimationFrame(func);
  122. else if (window.msRequestAnimationFrame)
  123. window.msRequestAnimationFrame(func);
  124. else if (window.webkitRequestAnimationFrame)
  125. window.webkitRequestAnimationFrame(func);
  126. else if (window.mozRequestAnimationFrame)
  127. window.mozRequestAnimationFrame(func);
  128. else if (window.oRequestAnimationFrame)
  129. window.oRequestAnimationFrame(func);
  130. else {
  131. window.setTimeout(func, 16);
  132. }
  133. }
  134. public static RequestFullscreen(element): void {
  135. if (element.requestFullscreen)
  136. element.requestFullscreen();
  137. else if (element.msRequestFullscreen)
  138. element.msRequestFullscreen();
  139. else if (element.webkitRequestFullscreen)
  140. element.webkitRequestFullscreen();
  141. else if (element.mozRequestFullScreen)
  142. element.mozRequestFullScreen();
  143. }
  144. public static ExitFullscreen(): void {
  145. if (document.exitFullscreen) {
  146. document.exitFullscreen();
  147. }
  148. else if (document.mozCancelFullScreen) {
  149. document.mozCancelFullScreen();
  150. }
  151. else if (document.webkitCancelFullScreen) {
  152. document.webkitCancelFullScreen();
  153. }
  154. else if (document.msCancelFullScreen) {
  155. document.msCancelFullScreen();
  156. }
  157. }
  158. // External files
  159. public static CleanUrl(url: string): string {
  160. url = url.replace(/#/mg, "%23");
  161. return url;
  162. }
  163. public static LoadImage(url: string, onload, onerror, database): HTMLImageElement {
  164. url = Tools.CleanUrl(url);
  165. var img = new Image();
  166. if (url.substr(0, 5) !== "data:")
  167. img.crossOrigin = 'anonymous';
  168. img.onload = () => {
  169. onload(img);
  170. };
  171. img.onerror = err => {
  172. Tools.Error("Error while trying to load texture: " + url);
  173. 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";
  174. onload(img);
  175. };
  176. var noIndexedDB = () => {
  177. img.src = url;
  178. };
  179. var loadFromIndexedDB = () => {
  180. database.loadImageFromDB(url, img);
  181. };
  182. //ANY database to do!
  183. if (database && database.enableTexturesOffline && Database.IsUASupportingBlobStorage) {
  184. database.openAsync(loadFromIndexedDB, noIndexedDB);
  185. }
  186. else {
  187. if (url.indexOf("file:") === -1) {
  188. noIndexedDB();
  189. }
  190. else {
  191. try {
  192. var textureName = url.substring(5);
  193. var blobURL;
  194. try {
  195. blobURL = URL.createObjectURL(FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  196. }
  197. catch (ex) {
  198. // Chrome doesn't support oneTimeOnly parameter
  199. blobURL = URL.createObjectURL(FilesInput.FilesTextures[textureName]);
  200. }
  201. img.src = blobURL;
  202. }
  203. catch (e) {
  204. img.src = null;
  205. }
  206. }
  207. }
  208. return img;
  209. }
  210. //ANY
  211. public static LoadFile(url: string, callback: (data: any) => void, progressCallBack?: () => void, database?, useArrayBuffer?: boolean, onError?: () => void): void {
  212. url = Tools.CleanUrl(url);
  213. var noIndexedDB = () => {
  214. var request = new XMLHttpRequest();
  215. var loadUrl = Tools.BaseUrl + url;
  216. request.open('GET', loadUrl, true);
  217. if (useArrayBuffer) {
  218. request.responseType = "arraybuffer";
  219. }
  220. request.onprogress = progressCallBack;
  221. request.onreadystatechange = () => {
  222. if (request.readyState === 4) {
  223. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  224. callback(!useArrayBuffer ? request.responseText : request.response);
  225. } else { // Failed
  226. if (onError) {
  227. onError();
  228. } else {
  229. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  230. }
  231. }
  232. }
  233. };
  234. request.send(null);
  235. };
  236. var loadFromIndexedDB = () => {
  237. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  238. };
  239. if (url.indexOf("file:") !== -1) {
  240. var fileName = url.substring(5);
  241. Tools.ReadFile(FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  242. }
  243. else {
  244. // Caching all files
  245. if (database && database.enableSceneOffline) {
  246. database.openAsync(loadFromIndexedDB, noIndexedDB);
  247. }
  248. else {
  249. noIndexedDB();
  250. }
  251. }
  252. }
  253. public static ReadFileAsDataURL(fileToLoad, callback, progressCallback): void {
  254. var reader = new FileReader();
  255. reader.onload = e => {
  256. //target doesn't have result from ts 1.3
  257. callback(e.target['result']);
  258. };
  259. reader.onprogress = progressCallback;
  260. reader.readAsDataURL(fileToLoad);
  261. }
  262. public static ReadFile(fileToLoad, callback, progressCallBack, useArrayBuffer?: boolean): void {
  263. var reader = new FileReader();
  264. reader.onerror = e => {
  265. Tools.Log("Error while reading file: " + fileToLoad.name);
  266. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  267. };
  268. reader.onload = e => {
  269. //target doesn't have result from ts 1.3
  270. callback(e.target['result']);
  271. };
  272. reader.onprogress = progressCallBack;
  273. if (!useArrayBuffer) {
  274. // Asynchronous read
  275. reader.readAsText(fileToLoad);
  276. }
  277. else {
  278. reader.readAsArrayBuffer(fileToLoad);
  279. }
  280. }
  281. //returns a downloadable url to a file content.
  282. public static FileAsURL(content:string): string {
  283. var fileBlob = new Blob([content]);
  284. var url = window.URL || window.webkitURL;
  285. var link:string = url.createObjectURL(fileBlob);
  286. return link;
  287. }
  288. // Misc.
  289. public static Clamp(value: number, min = 0, max = 1): number {
  290. return Math.min(max, Math.max(min, value));
  291. }
  292. // Returns -1 when value is a negative number and
  293. // +1 when value is a positive number.
  294. public static Sign(value: number): number {
  295. value = +value; // convert to a number
  296. if (value === 0 || isNaN(value))
  297. return value;
  298. return value > 0 ? 1 : -1;
  299. }
  300. public static Format(value: number, decimals: number = 2): string {
  301. return value.toFixed(decimals);
  302. }
  303. public static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void {
  304. if (v.x < min.x)
  305. min.x = v.x;
  306. if (v.y < min.y)
  307. min.y = v.y;
  308. if (v.z < min.z)
  309. min.z = v.z;
  310. if (v.x > max.x)
  311. max.x = v.x;
  312. if (v.y > max.y)
  313. max.y = v.y;
  314. if (v.z > max.z)
  315. max.z = v.z;
  316. }
  317. public static WithinEpsilon(a: number, b: number, epsilon: number = 1.401298E-45): boolean {
  318. var num = a - b;
  319. return -epsilon <= num && num <= epsilon;
  320. }
  321. public static DeepCopy(source, destination, doNotCopyList?: string[], mustCopyList?: string[]): void {
  322. for (var prop in source) {
  323. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  324. continue;
  325. }
  326. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  327. continue;
  328. }
  329. var sourceValue = source[prop];
  330. var typeOfSourceValue = typeof sourceValue;
  331. if (typeOfSourceValue === "function") {
  332. continue;
  333. }
  334. if (typeOfSourceValue === "object") {
  335. if (sourceValue instanceof Array) {
  336. destination[prop] = [];
  337. if (sourceValue.length > 0) {
  338. if (typeof sourceValue[0] == "object") {
  339. for (var index = 0; index < sourceValue.length; index++) {
  340. var clonedValue = cloneValue(sourceValue[index], destination);
  341. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  342. destination[prop].push(clonedValue);
  343. }
  344. }
  345. } else {
  346. destination[prop] = sourceValue.slice(0);
  347. }
  348. }
  349. } else {
  350. destination[prop] = cloneValue(sourceValue, destination);
  351. }
  352. } else {
  353. destination[prop] = sourceValue;
  354. }
  355. }
  356. }
  357. public static IsEmpty(obj): boolean {
  358. for (var i in obj) {
  359. return false;
  360. }
  361. return true;
  362. }
  363. public static RegisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  364. for (var index = 0; index < events.length; index++) {
  365. var event = events[index];
  366. window.addEventListener(event.name, event.handler, false);
  367. try {
  368. if (window.parent) {
  369. window.parent.addEventListener(event.name, event.handler, false);
  370. }
  371. } catch (e) {
  372. // Silently fails...
  373. }
  374. }
  375. }
  376. public static UnregisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  377. for (var index = 0; index < events.length; index++) {
  378. var event = events[index];
  379. window.removeEventListener(event.name, event.handler);
  380. try {
  381. if (window.parent) {
  382. window.parent.removeEventListener(event.name, event.handler);
  383. }
  384. } catch (e) {
  385. // Silently fails...
  386. }
  387. }
  388. }
  389. public static DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: String) => void): void {
  390. // Read the contents of the framebuffer
  391. var numberOfChannelsByLine = width * 4;
  392. var halfHeight = height / 2;
  393. //Reading datas from WebGL
  394. var data = engine.readPixels(0, 0, width, height);
  395. //To flip image on Y axis.
  396. for (var i = 0; i < halfHeight; i++) {
  397. for (var j = 0; j < numberOfChannelsByLine; j++) {
  398. var currentCell = j + i * numberOfChannelsByLine;
  399. var targetLine = height - i - 1;
  400. var targetCell = j + targetLine * numberOfChannelsByLine;
  401. var temp = data[currentCell];
  402. data[currentCell] = data[targetCell];
  403. data[targetCell] = temp;
  404. }
  405. }
  406. // Create a 2D canvas to store the result
  407. if (!screenshotCanvas) {
  408. screenshotCanvas = document.createElement('canvas');
  409. }
  410. screenshotCanvas.width = width;
  411. screenshotCanvas.height = height;
  412. var context = screenshotCanvas.getContext('2d');
  413. // Copy the pixels to a 2D canvas
  414. var imageData = context.createImageData(width, height);
  415. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  416. var castData = <Uint8Array>(<any>imageData.data);
  417. castData.set(data);
  418. context.putImageData(imageData, 0, 0);
  419. var base64Image = screenshotCanvas.toDataURL();
  420. if (successCallback) {
  421. successCallback(base64Image);
  422. } else {
  423. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  424. if (("download" in document.createElement("a"))) {
  425. var a = window.document.createElement("a");
  426. a.href = base64Image;
  427. var date = new Date();
  428. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  429. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  430. window.document.body.appendChild(a);
  431. a.addEventListener("click", () => {
  432. a.parentElement.removeChild(a);
  433. });
  434. a.click();
  435. //Or opening a new tab with the image if it is not possible to automatically start download.
  436. } else {
  437. var newWindow = window.open("");
  438. var img = newWindow.document.createElement("img");
  439. img.src = base64Image;
  440. newWindow.document.body.appendChild(img);
  441. }
  442. }
  443. }
  444. public static CreateScreenshot(engine: Engine, camera: Camera, size: any, successCallback?: (data: String) => void): void {
  445. var width: number;
  446. var height: number;
  447. //If a precision value is specified
  448. if (size.precision) {
  449. width = Math.round(engine.getRenderWidth() * size.precision);
  450. height = Math.round(width / engine.getAspectRatio(camera));
  451. size = { width: width, height: height };
  452. }
  453. else if (size.width && size.height) {
  454. width = size.width;
  455. height = size.height;
  456. }
  457. //If passing only width, computing height to keep display canvas ratio.
  458. else if (size.width && !size.height) {
  459. width = size.width;
  460. height = Math.round(width / engine.getAspectRatio(camera));
  461. size = { width: width, height: height };
  462. }
  463. //If passing only height, computing width to keep display canvas ratio.
  464. else if (size.height && !size.width) {
  465. height = size.height;
  466. width = Math.round(height * engine.getAspectRatio(camera));
  467. size = { width: width, height: height };
  468. }
  469. //Assuming here that "size" parameter is a number
  470. else if (!isNaN(size)) {
  471. height = size;
  472. width = size;
  473. }
  474. else {
  475. Tools.Error("Invalid 'size' parameter !");
  476. return;
  477. }
  478. var scene = camera.getScene();
  479. var previousCamera: Camera = null;
  480. if (scene.activeCamera !== camera) {
  481. previousCamera = scene.activeCamera;
  482. scene.activeCamera = camera;
  483. }
  484. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  485. var texture = new RenderTargetTexture("screenShot", size, scene, false, false);
  486. texture.renderList = scene.meshes;
  487. texture.onAfterRender = () => {
  488. Tools.DumpFramebuffer(width, height, engine, successCallback);
  489. };
  490. scene.incrementRenderId();
  491. texture.render(true);
  492. texture.dispose();
  493. if (previousCamera) {
  494. scene.activeCamera = previousCamera;
  495. }
  496. }
  497. // XHR response validator for local file scenario
  498. public static ValidateXHRData(xhr: XMLHttpRequest, dataType = 7): boolean {
  499. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  500. try {
  501. if (dataType & 1) {
  502. if (xhr.responseText && xhr.responseText.length > 0) {
  503. return true;
  504. } else if (dataType === 1) {
  505. return false;
  506. }
  507. }
  508. if (dataType & 2) {
  509. // Check header width and height since there is no "TGA" magic number
  510. var tgaHeader = Internals.TGATools.GetTGAHeader(xhr.response);
  511. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  512. return true;
  513. } else if (dataType === 2) {
  514. return false;
  515. }
  516. }
  517. if (dataType & 4) {
  518. // Check for the "DDS" magic number
  519. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  520. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  521. return true;
  522. } else {
  523. return false;
  524. }
  525. }
  526. } catch (e) {
  527. // Global protection
  528. }
  529. return false;
  530. }
  531. // Logs
  532. private static _NoneLogLevel = 0;
  533. private static _MessageLogLevel = 1;
  534. private static _WarningLogLevel = 2;
  535. private static _ErrorLogLevel = 4;
  536. private static _LogCache = "";
  537. public static errorsCount = 0;
  538. public static OnNewCacheEntry: (entry: string) => void;
  539. static get NoneLogLevel(): number {
  540. return Tools._NoneLogLevel;
  541. }
  542. static get MessageLogLevel(): number {
  543. return Tools._MessageLogLevel;
  544. }
  545. static get WarningLogLevel(): number {
  546. return Tools._WarningLogLevel;
  547. }
  548. static get ErrorLogLevel(): number {
  549. return Tools._ErrorLogLevel;
  550. }
  551. static get AllLogLevel(): number {
  552. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  553. }
  554. private static _AddLogEntry(entry: string) {
  555. Tools._LogCache = entry + Tools._LogCache;
  556. if (Tools.OnNewCacheEntry) {
  557. Tools.OnNewCacheEntry(entry);
  558. }
  559. }
  560. private static _FormatMessage(message: string): string {
  561. var padStr = i => (i < 10) ? "0" + i : "" + i;
  562. var date = new Date();
  563. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  564. }
  565. public static Log: (message: string) => void = Tools._LogEnabled;
  566. private static _LogDisabled(message: string): void {
  567. // nothing to do
  568. }
  569. private static _LogEnabled(message: string): void {
  570. var formattedMessage = Tools._FormatMessage(message);
  571. console.log("BJS - " + formattedMessage);
  572. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  573. Tools._AddLogEntry(entry);
  574. }
  575. public static Warn: (message: string) => void = Tools._WarnEnabled;
  576. private static _WarnDisabled(message: string): void {
  577. // nothing to do
  578. }
  579. private static _WarnEnabled(message: string): void {
  580. var formattedMessage = Tools._FormatMessage(message);
  581. console.warn("BJS - " + formattedMessage);
  582. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  583. Tools._AddLogEntry(entry);
  584. }
  585. public static Error: (message: string) => void = Tools._ErrorEnabled;
  586. private static _ErrorDisabled(message: string): void {
  587. // nothing to do
  588. }
  589. private static _ErrorEnabled(message: string): void {
  590. Tools.errorsCount++;
  591. var formattedMessage = Tools._FormatMessage(message);
  592. console.error("BJS - " + formattedMessage);
  593. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  594. Tools._AddLogEntry(entry);
  595. }
  596. public static get LogCache(): string {
  597. return Tools._LogCache;
  598. }
  599. public static ClearLogCache(): void {
  600. Tools._LogCache = "";
  601. Tools.errorsCount = 0;
  602. }
  603. public static set LogLevels(level: number) {
  604. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  605. Tools.Log = Tools._LogEnabled;
  606. }
  607. else {
  608. Tools.Log = Tools._LogDisabled;
  609. }
  610. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  611. Tools.Warn = Tools._WarnEnabled;
  612. }
  613. else {
  614. Tools.Warn = Tools._WarnDisabled;
  615. }
  616. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  617. Tools.Error = Tools._ErrorEnabled;
  618. }
  619. else {
  620. Tools.Error = Tools._ErrorDisabled;
  621. }
  622. }
  623. // Performances
  624. private static _PerformanceNoneLogLevel = 0;
  625. private static _PerformanceUserMarkLogLevel = 1;
  626. private static _PerformanceConsoleLogLevel = 2;
  627. private static _performance: Performance = window.performance;
  628. static get PerformanceNoneLogLevel(): number {
  629. return Tools._PerformanceNoneLogLevel;
  630. }
  631. static get PerformanceUserMarkLogLevel(): number {
  632. return Tools._PerformanceUserMarkLogLevel;
  633. }
  634. static get PerformanceConsoleLogLevel(): number {
  635. return Tools._PerformanceConsoleLogLevel;
  636. }
  637. public static set PerformanceLogLevel(level: number) {
  638. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  639. Tools.StartPerformanceCounter = Tools._StartUserMark;
  640. Tools.EndPerformanceCounter = Tools._EndUserMark;
  641. return;
  642. }
  643. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  644. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  645. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  646. return;
  647. }
  648. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  649. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  650. }
  651. static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  652. }
  653. static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  654. }
  655. static _StartUserMark(counterName: string, condition = true): void {
  656. if (!condition || !Tools._performance.mark) {
  657. return;
  658. }
  659. Tools._performance.mark(counterName + "-Begin");
  660. }
  661. static _EndUserMark(counterName: string, condition = true): void {
  662. if (!condition || !Tools._performance.mark) {
  663. return;
  664. }
  665. Tools._performance.mark(counterName + "-End");
  666. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  667. }
  668. static _StartPerformanceConsole(counterName: string, condition = true): void {
  669. if (!condition) {
  670. return;
  671. }
  672. Tools._StartUserMark(counterName, condition);
  673. if (console.time) {
  674. console.time(counterName);
  675. }
  676. }
  677. static _EndPerformanceConsole(counterName: string, condition = true): void {
  678. if (!condition) {
  679. return;
  680. }
  681. Tools._EndUserMark(counterName, condition);
  682. if (console.time) {
  683. console.timeEnd(counterName);
  684. }
  685. }
  686. public static StartPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._StartPerformanceCounterDisabled;
  687. public static EndPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._EndPerformanceCounterDisabled;
  688. public static get Now(): number {
  689. if (window.performance && window.performance.now) {
  690. return window.performance.now();
  691. }
  692. return new Date().getTime();
  693. }
  694. // Deprecated
  695. public static GetFps(): number {
  696. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  697. return 0;
  698. }
  699. }
  700. /**
  701. * An implementation of a loop for asynchronous functions.
  702. */
  703. export class AsyncLoop {
  704. public index: number;
  705. private _done: boolean;
  706. /**
  707. * Constroctor.
  708. * @param iterations the number of iterations.
  709. * @param _fn the function to run each iteration
  710. * @param _successCallback the callback that will be called upon succesful execution
  711. * @param offset starting offset.
  712. */
  713. constructor(public iterations: number, private _fn: (asyncLoop: AsyncLoop) => void, private _successCallback: () => void, offset: number = 0) {
  714. this.index = offset - 1;
  715. this._done = false;
  716. }
  717. /**
  718. * Execute the next iteration. Must be called after the last iteration was finished.
  719. */
  720. public executeNext(): void {
  721. if (!this._done) {
  722. if (this.index + 1 < this.iterations) {
  723. ++this.index;
  724. this._fn(this);
  725. } else {
  726. this.breakLoop();
  727. }
  728. }
  729. }
  730. /**
  731. * Break the loop and run the success callback.
  732. */
  733. public breakLoop(): void {
  734. this._done = true;
  735. this._successCallback();
  736. }
  737. /**
  738. * Helper function
  739. */
  740. public static Run(iterations: number, _fn: (asyncLoop: AsyncLoop) => void, _successCallback: () => void, offset: number = 0): AsyncLoop {
  741. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  742. loop.executeNext();
  743. return loop;
  744. }
  745. /**
  746. * A for-loop that will run a given number of iterations synchronous and the rest async.
  747. * @param iterations total number of iterations
  748. * @param syncedIterations number of synchronous iterations in each async iteration.
  749. * @param fn the function to call each iteration.
  750. * @param callback a success call back that will be called when iterating stops.
  751. * @param breakFunction a break condition (optional)
  752. * @param timeout timeout settings for the setTimeout function. default - 0.
  753. * @constructor
  754. */
  755. public static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout: number = 0) {
  756. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop: AsyncLoop) => {
  757. if (breakFunction && breakFunction()) loop.breakLoop();
  758. else {
  759. setTimeout(() => {
  760. for (var i = 0; i < syncedIterations; ++i) {
  761. var iteration = (loop.index * syncedIterations) + i;
  762. if (iteration >= iterations) break;
  763. fn(iteration);
  764. if (breakFunction && breakFunction()) {
  765. loop.breakLoop();
  766. break;
  767. }
  768. }
  769. loop.executeNext();
  770. }, timeout);
  771. }
  772. }, callback);
  773. }
  774. }
  775. }