babylon.tools.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. module BABYLON {
  2. //class FilesTextures { } //ANY
  3. export interface IAnimatable {
  4. animations: Array<Animation>;
  5. }
  6. export interface ISize {
  7. width: number;
  8. height: number;
  9. }
  10. // Screenshots
  11. var screenshotCanvas: HTMLCanvasElement;
  12. // FPS
  13. var fpsRange = 60;
  14. var previousFramesDuration = [];
  15. var fps = 60;
  16. var deltaTime = 0;
  17. var cloneValue = (source, destinationObject) => {
  18. if (!source)
  19. return null;
  20. if (source instanceof Mesh) {
  21. return null;
  22. }
  23. if (source instanceof SubMesh) {
  24. return source.clone(destinationObject);
  25. } else if (source.clone) {
  26. return source.clone();
  27. }
  28. return null;
  29. };
  30. export class Tools {
  31. public static BaseUrl = "";
  32. public static GetFilename(path: string): string {
  33. var index = path.lastIndexOf("/");
  34. if (index < 0)
  35. return path;
  36. return path.substring(index + 1);
  37. }
  38. public static GetDOMTextContent(element: HTMLElement): string {
  39. var result = "";
  40. var child = element.firstChild;
  41. while (child) {
  42. if (child.nodeType == 3) {
  43. result += child.textContent;
  44. }
  45. child = child.nextSibling;
  46. }
  47. return result;
  48. }
  49. public static ToDegrees(angle: number): number {
  50. return angle * 180 / Math.PI;
  51. }
  52. public static ToRadians(angle: number): number {
  53. return angle * Math.PI / 180;
  54. }
  55. public static ExtractMinAndMaxIndexed(positions: number[], indices: number[], indexStart: number, indexCount: number): { minimum: Vector3; maximum: Vector3 } {
  56. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  57. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  58. for (var index = indexStart; index < indexStart + indexCount; index++) {
  59. var current = new Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  60. minimum = BABYLON.Vector3.Minimize(current, minimum);
  61. maximum = BABYLON.Vector3.Maximize(current, maximum);
  62. }
  63. return {
  64. minimum: minimum,
  65. maximum: maximum
  66. };
  67. }
  68. public static ExtractMinAndMax(positions: number[], start: number, count: number): { minimum: Vector3; maximum: Vector3 } {
  69. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  71. for (var index = start; index < start + count; index++) {
  72. var current = new Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  73. minimum = BABYLON.Vector3.Minimize(current, minimum);
  74. maximum = BABYLON.Vector3.Maximize(current, maximum);
  75. }
  76. return {
  77. minimum: minimum,
  78. maximum: maximum
  79. };
  80. }
  81. public static MakeArray(obj, allowsNullUndefined?: boolean): Array<any> {
  82. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  83. return undefined;
  84. return Array.isArray(obj) ? obj : [obj];
  85. }
  86. // Misc.
  87. public static GetPointerPrefix(): string {
  88. var eventPrefix = "pointer";
  89. // Check if hand.js is referenced or if the browser natively supports pointer events
  90. if (!navigator.pointerEnabled) {
  91. eventPrefix = "mouse";
  92. }
  93. return eventPrefix;
  94. }
  95. public static QueueNewFrame(func): void {
  96. if (window.requestAnimationFrame)
  97. window.requestAnimationFrame(func);
  98. else if (window.msRequestAnimationFrame)
  99. window.msRequestAnimationFrame(func);
  100. else if (window.webkitRequestAnimationFrame)
  101. window.webkitRequestAnimationFrame(func);
  102. else if (window.mozRequestAnimationFrame)
  103. window.mozRequestAnimationFrame(func);
  104. else if (window.oRequestAnimationFrame)
  105. window.oRequestAnimationFrame(func);
  106. else {
  107. window.setTimeout(func, 16);
  108. }
  109. }
  110. public static RequestFullscreen(element): void {
  111. if (element.requestFullscreen)
  112. element.requestFullscreen();
  113. else if (element.msRequestFullscreen)
  114. element.msRequestFullscreen();
  115. else if (element.webkitRequestFullscreen)
  116. element.webkitRequestFullscreen();
  117. else if (element.mozRequestFullScreen)
  118. element.mozRequestFullScreen();
  119. }
  120. public static ExitFullscreen(): void {
  121. if (document.exitFullscreen) {
  122. document.exitFullscreen();
  123. }
  124. else if (document.mozCancelFullScreen) {
  125. document.mozCancelFullScreen();
  126. }
  127. else if (document.webkitCancelFullScreen) {
  128. document.webkitCancelFullScreen();
  129. }
  130. else if (document.msCancelFullScreen) {
  131. document.msCancelFullScreen();
  132. }
  133. }
  134. // External files
  135. public static CleanUrl(url: string): string {
  136. url = url.replace(/#/mg, "%23");
  137. return url;
  138. }
  139. public static LoadImage(url: string, onload, onerror, database): HTMLImageElement {
  140. url = Tools.CleanUrl(url);
  141. var img = new Image();
  142. img.crossOrigin = 'anonymous';
  143. img.onload = () => {
  144. onload(img);
  145. };
  146. img.onerror = err => {
  147. onerror(img, err);
  148. };
  149. var noIndexedDB = () => {
  150. img.src = url;
  151. };
  152. var loadFromIndexedDB = () => {
  153. database.loadImageFromDB(url, img);
  154. };
  155. //ANY database to do!
  156. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  157. database.openAsync(loadFromIndexedDB, noIndexedDB);
  158. }
  159. else {
  160. if (url.indexOf("file:") === -1) {
  161. noIndexedDB();
  162. }
  163. else {
  164. try {
  165. var textureName = url.substring(5);
  166. var blobURL;
  167. try {
  168. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  169. }
  170. catch (ex) {
  171. // Chrome doesn't support oneTimeOnly parameter
  172. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  173. }
  174. img.src = blobURL;
  175. }
  176. catch (e) {
  177. Tools.Log("Error while trying to load texture: " + textureName);
  178. img.src = null;
  179. }
  180. }
  181. }
  182. return img;
  183. }
  184. //ANY
  185. public static LoadFile(url: string, callback: (data: any) => void, progressCallBack?: () => void, database?, useArrayBuffer?: boolean): void {
  186. url = Tools.CleanUrl(url);
  187. var noIndexedDB = () => {
  188. var request = new XMLHttpRequest();
  189. var loadUrl = Tools.BaseUrl + url;
  190. request.open('GET', loadUrl, true);
  191. if (useArrayBuffer) {
  192. request.responseType = "arraybuffer";
  193. }
  194. request.onprogress = progressCallBack;
  195. request.onreadystatechange = () => {
  196. if (request.readyState == 4) {
  197. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  198. callback(!useArrayBuffer ? request.responseText : request.response);
  199. } else { // Failed
  200. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  201. }
  202. }
  203. };
  204. request.send(null);
  205. };
  206. var loadFromIndexedDB = () => {
  207. database.loadSceneFromDB(url, callback, progressCallBack, noIndexedDB);
  208. };
  209. if (url.indexOf("file:") !== -1) {
  210. var fileName = url.substring(5);
  211. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  212. }
  213. else {
  214. // Caching only scenes files
  215. if (database && url.indexOf(".babylon") !== -1 && (database.enableSceneOffline)) {
  216. database.openAsync(loadFromIndexedDB, noIndexedDB);
  217. }
  218. else {
  219. noIndexedDB();
  220. }
  221. }
  222. }
  223. public static ReadFile(fileToLoad, callback, progressCallBack, useArrayBuffer?: boolean): void {
  224. var reader = new FileReader();
  225. reader.onload = e => {
  226. callback(e.target.result);
  227. };
  228. reader.onprogress = progressCallBack;
  229. if (!useArrayBuffer) {
  230. // Asynchronous read
  231. reader.readAsText(fileToLoad);
  232. }
  233. else {
  234. reader.readAsArrayBuffer(fileToLoad);
  235. }
  236. }
  237. // Misc.
  238. public static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void {
  239. if (v.x < min.x)
  240. min.x = v.x;
  241. if (v.y < min.y)
  242. min.y = v.y;
  243. if (v.z < min.z)
  244. min.z = v.z;
  245. if (v.x > max.x)
  246. max.x = v.x;
  247. if (v.y > max.y)
  248. max.y = v.y;
  249. if (v.z > max.z)
  250. max.z = v.z;
  251. }
  252. public static WithinEpsilon(a: number, b: number): boolean {
  253. var num = a - b;
  254. return -1.401298E-45 <= num && num <= 1.401298E-45;
  255. }
  256. public static DeepCopy(source, destination, doNotCopyList?: string[], mustCopyList?: string[]): void {
  257. for (var prop in source) {
  258. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  259. continue;
  260. }
  261. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  262. continue;
  263. }
  264. var sourceValue = source[prop];
  265. var typeOfSourceValue = typeof sourceValue;
  266. if (typeOfSourceValue == "function") {
  267. continue;
  268. }
  269. if (typeOfSourceValue == "object") {
  270. if (sourceValue instanceof Array) {
  271. destination[prop] = [];
  272. if (sourceValue.length > 0) {
  273. if (typeof sourceValue[0] == "object") {
  274. for (var index = 0; index < sourceValue.length; index++) {
  275. var clonedValue = cloneValue(sourceValue[index], destination);
  276. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  277. destination[prop].push(clonedValue);
  278. }
  279. }
  280. } else {
  281. destination[prop] = sourceValue.slice(0);
  282. }
  283. }
  284. } else {
  285. destination[prop] = cloneValue(sourceValue, destination);
  286. }
  287. } else {
  288. destination[prop] = sourceValue;
  289. }
  290. }
  291. }
  292. public static IsEmpty(obj): boolean {
  293. for (var i in obj) {
  294. return false;
  295. }
  296. return true;
  297. }
  298. public static RegisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  299. for (var index = 0; index < events.length; index++) {
  300. var event = events[index];
  301. window.addEventListener(event.name, event.handler, false);
  302. try {
  303. if (window.parent) {
  304. window.parent.addEventListener(event.name, event.handler, false);
  305. }
  306. } catch (e) {
  307. // Silently fails...
  308. }
  309. }
  310. }
  311. public static UnregisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  312. for (var index = 0; index < events.length; index++) {
  313. var event = events[index];
  314. window.removeEventListener(event.name, event.handler);
  315. try {
  316. if (window.parent) {
  317. window.parent.removeEventListener(event.name, event.handler);
  318. }
  319. } catch (e) {
  320. // Silently fails...
  321. }
  322. }
  323. }
  324. public static GetFps(): number {
  325. return fps;
  326. }
  327. public static GetDeltaTime(): number {
  328. return deltaTime;
  329. }
  330. public static _MeasureFps(): void {
  331. previousFramesDuration.push((new Date).getTime());
  332. var length = previousFramesDuration.length;
  333. if (length >= 2) {
  334. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  335. }
  336. if (length >= fpsRange) {
  337. if (length > fpsRange) {
  338. previousFramesDuration.splice(0, 1);
  339. length = previousFramesDuration.length;
  340. }
  341. var sum = 0;
  342. for (var id = 0; id < length - 1; id++) {
  343. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  344. }
  345. fps = 1000.0 / (sum / (length - 1));
  346. }
  347. }
  348. public static CreateScreenshot(engine: Engine, camera: Camera, size: any): void {
  349. var width: number;
  350. var height: number;
  351. var scene = camera.getScene();
  352. var previousCamera: BABYLON.Camera = null;
  353. if (scene.activeCamera !== camera) {
  354. previousCamera = scene.activeCamera;
  355. scene.activeCamera = camera;
  356. }
  357. //If a precision value is specified
  358. if (size.precision) {
  359. width = Math.round(engine.getRenderWidth() * size.precision);
  360. height = Math.round(width / engine.getAspectRatio(camera));
  361. size = { width: width, height: height };
  362. }
  363. else if (size.width && size.height) {
  364. width = size.width;
  365. height = size.height;
  366. }
  367. //If passing only width, computing height to keep display canvas ratio.
  368. else if (size.width && !size.height) {
  369. width = size.width;
  370. height = Math.round(width / engine.getAspectRatio(camera));
  371. size = { width: width, height: height };
  372. }
  373. //If passing only height, computing width to keep display canvas ratio.
  374. else if (size.height && !size.width) {
  375. height = size.height;
  376. width = Math.round(height * engine.getAspectRatio(camera));
  377. size = { width: width, height: height };
  378. }
  379. //Assuming here that "size" parameter is a number
  380. else if (!isNaN(size)) {
  381. height = size;
  382. width = size;
  383. }
  384. else {
  385. Tools.Error("Invalid 'size' parameter !");
  386. return;
  387. }
  388. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  389. var texture = new RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  390. texture.renderList = engine.scenes[0].meshes;
  391. texture.onAfterRender = () => {
  392. // Read the contents of the framebuffer
  393. var numberOfChannelsByLine = width * 4;
  394. var halfHeight = height / 2;
  395. //Reading datas from WebGL
  396. var data = engine.readPixels(0, 0, width, height);
  397. //To flip image on Y axis.
  398. for (var i = 0; i < halfHeight; i++) {
  399. for (var j = 0; j < numberOfChannelsByLine; j++) {
  400. var currentCell = j + i * numberOfChannelsByLine;
  401. var targetLine = height - i - 1;
  402. var targetCell = j + targetLine * numberOfChannelsByLine;
  403. var temp = data[currentCell];
  404. data[currentCell] = data[targetCell];
  405. data[targetCell] = temp;
  406. }
  407. }
  408. // Create a 2D canvas to store the result
  409. if (!screenshotCanvas) {
  410. screenshotCanvas = document.createElement('canvas');
  411. }
  412. screenshotCanvas.width = width;
  413. screenshotCanvas.height = height;
  414. var context = screenshotCanvas.getContext('2d');
  415. // Copy the pixels to a 2D canvas
  416. var imageData = context.createImageData(width, height);
  417. imageData.data.set(data);
  418. context.putImageData(imageData, 0, 0);
  419. var base64Image = screenshotCanvas.toDataURL();
  420. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  421. if (("download" in document.createElement("a"))) {
  422. var a = window.document.createElement("a");
  423. a.href = base64Image;
  424. var date = new Date();
  425. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  426. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  427. window.document.body.appendChild(a);
  428. a.addEventListener("click", () => {
  429. a.parentElement.removeChild(a);
  430. });
  431. a.click();
  432. //Or opening a new tab with the image if it is not possible to automatically start download.
  433. } else {
  434. var newWindow = window.open("");
  435. var img = newWindow.document.createElement("img");
  436. img.src = base64Image;
  437. newWindow.document.body.appendChild(img);
  438. }
  439. };
  440. texture.render(true);
  441. texture.dispose();
  442. if (previousCamera) {
  443. scene.activeCamera = previousCamera;
  444. }
  445. }
  446. // XHR response validator for local file scenario
  447. public static ValidateXHRData(xhr: XMLHttpRequest, dataType = 7): boolean {
  448. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  449. try {
  450. if (dataType & 1) {
  451. if (xhr.responseText && xhr.responseText.length > 0) {
  452. return true;
  453. } else if (dataType === 1) {
  454. return false;
  455. }
  456. }
  457. if (dataType & 2) {
  458. // Check header width and height since there is no "TGA" magic number
  459. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  460. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  461. return true;
  462. } else if (dataType === 2) {
  463. return false;
  464. }
  465. }
  466. if (dataType & 4) {
  467. // Check for the "DDS" magic number
  468. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  469. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  470. return true;
  471. } else {
  472. return false;
  473. }
  474. }
  475. } catch (e) {
  476. // Global protection
  477. }
  478. return false;
  479. }
  480. // Logs
  481. private static _NoneLogLevel = 0;
  482. private static _MessageLogLevel = 1;
  483. private static _WarningLogLevel = 2;
  484. private static _ErrorLogLevel = 4;
  485. static get NoneLogLevel(): number {
  486. return Tools._NoneLogLevel;
  487. }
  488. static get MessageLogLevel(): number {
  489. return Tools._MessageLogLevel;
  490. }
  491. static get WarningLogLevel(): number {
  492. return Tools._WarningLogLevel;
  493. }
  494. static get ErrorLogLevel(): number {
  495. return Tools._ErrorLogLevel;
  496. }
  497. static get AllLogLevel(): number {
  498. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  499. }
  500. private static _FormatMessage(message: string): string {
  501. var padStr = i => (i < 10) ? "0" + i : "" + i;
  502. var date = new Date();
  503. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  504. }
  505. public static Log: (message: string) => void = Tools._LogEnabled;
  506. private static _LogDisabled(message: string): void {
  507. // nothing to do
  508. }
  509. private static _LogEnabled(message: string): void {
  510. console.log(Tools._FormatMessage(message));
  511. }
  512. public static Warn: (message: string) => void = Tools._WarnEnabled;
  513. private static _WarnDisabled(message: string): void {
  514. // nothing to do
  515. }
  516. private static _WarnEnabled(message: string): void {
  517. console.warn(Tools._FormatMessage(message));
  518. }
  519. public static Error: (message: string) => void = Tools._ErrorEnabled;
  520. private static _ErrorDisabled(message: string): void {
  521. // nothing to do
  522. }
  523. private static _ErrorEnabled(message: string): void {
  524. console.error(Tools._FormatMessage(message));
  525. }
  526. public static set LogLevels(level: number) {
  527. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  528. Tools.Log = Tools._LogEnabled;
  529. }
  530. else {
  531. Tools.Log = Tools._LogDisabled;
  532. }
  533. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  534. Tools.Warn = Tools._WarnEnabled;
  535. }
  536. else {
  537. Tools.Warn = Tools._WarnDisabled;
  538. }
  539. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  540. Tools.Error = Tools._ErrorEnabled;
  541. }
  542. else {
  543. Tools.Error = Tools._ErrorDisabled;
  544. }
  545. }
  546. }
  547. }