babylon.tools.ts 20 KB

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