babylon.tools.ts 21 KB

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