babylon.tools.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. var BABYLON;
  2. (function (BABYLON) {
  3. // FPS
  4. var fpsRange = 60;
  5. var previousFramesDuration = [];
  6. var fps = 60;
  7. var deltaTime = 0;
  8. var cloneValue = function (source, destinationObject) {
  9. if (!source)
  10. return null;
  11. if (source instanceof BABYLON.Mesh) {
  12. return null;
  13. }
  14. if (source instanceof BABYLON.SubMesh) {
  15. return source.clone(destinationObject);
  16. } else if (source.clone) {
  17. return source.clone();
  18. }
  19. return null;
  20. };
  21. var Tools = (function () {
  22. function Tools() {
  23. }
  24. Tools.GetFilename = function (path) {
  25. var index = path.lastIndexOf("/");
  26. if (index < 0)
  27. return path;
  28. return path.substring(index + 1);
  29. };
  30. Tools.GetDOMTextContent = function (element) {
  31. var result = "";
  32. var child = element.firstChild;
  33. while (child) {
  34. if (child.nodeType == 3) {
  35. result += child.textContent;
  36. }
  37. child = child.nextSibling;
  38. }
  39. return result;
  40. };
  41. Tools.ToDegrees = function (angle) {
  42. return angle * 180 / Math.PI;
  43. };
  44. Tools.ToRadians = function (angle) {
  45. return angle * Math.PI / 180;
  46. };
  47. Tools.ExtractMinAndMax = function (positions, start, count) {
  48. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  50. for (var index = start; index < start + count; index++) {
  51. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  52. minimum = BABYLON.Vector3.Minimize(current, minimum);
  53. maximum = BABYLON.Vector3.Maximize(current, maximum);
  54. }
  55. return {
  56. minimum: minimum,
  57. maximum: maximum
  58. };
  59. };
  60. Tools.MakeArray = function (obj, allowsNullUndefined) {
  61. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  62. return undefined;
  63. return Array.isArray(obj) ? obj : [obj];
  64. };
  65. // Misc.
  66. Tools.GetPointerPrefix = function () {
  67. var eventPrefix = "pointer";
  68. // Check if hand.js is referenced or if the browser natively supports pointer events
  69. if (!navigator.pointerEnabled) {
  70. eventPrefix = "mouse";
  71. }
  72. return eventPrefix;
  73. };
  74. Tools.QueueNewFrame = function (func) {
  75. if (window.requestAnimationFrame)
  76. window.requestAnimationFrame(func);
  77. else if (window.msRequestAnimationFrame)
  78. window.msRequestAnimationFrame(func);
  79. else if (window.webkitRequestAnimationFrame)
  80. window.webkitRequestAnimationFrame(func);
  81. else if (window.mozRequestAnimationFrame)
  82. window.mozRequestAnimationFrame(func);
  83. else if (window.oRequestAnimationFrame)
  84. window.oRequestAnimationFrame(func);
  85. else {
  86. window.setTimeout(func, 16);
  87. }
  88. };
  89. Tools.RequestFullscreen = function (element) {
  90. if (element.requestFullscreen)
  91. element.requestFullscreen();
  92. else if (element.msRequestFullscreen)
  93. element.msRequestFullscreen();
  94. else if (element.webkitRequestFullscreen)
  95. element.webkitRequestFullscreen();
  96. else if (element.mozRequestFullScreen)
  97. element.mozRequestFullScreen();
  98. };
  99. Tools.ExitFullscreen = function () {
  100. if (document.exitFullscreen) {
  101. document.exitFullscreen();
  102. } else if (document.mozCancelFullScreen) {
  103. document.mozCancelFullScreen();
  104. } else if (document.webkitCancelFullScreen) {
  105. document.webkitCancelFullScreen();
  106. } else if (document.msCancelFullScreen) {
  107. document.msCancelFullScreen();
  108. }
  109. };
  110. // External files
  111. Tools.LoadImage = function (url, onload, onerror, database) {
  112. var img = new Image();
  113. img.crossOrigin = 'anonymous';
  114. img.onload = function () {
  115. onload(img);
  116. };
  117. img.onerror = function (err) {
  118. onerror(img, err);
  119. };
  120. var noIndexedDB = function () {
  121. img.src = url;
  122. };
  123. var loadFromIndexedDB = function () {
  124. database.loadImageFromDB(url, img);
  125. };
  126. //ANY database to do!
  127. if (database && database.enableTexturesOffline) {
  128. database.openAsync(loadFromIndexedDB, noIndexedDB);
  129. } else {
  130. if (url.indexOf("file:") === -1) {
  131. noIndexedDB();
  132. } else {
  133. try {
  134. var textureName = url.substring(5);
  135. var blobURL;
  136. try {
  137. blobURL = URL.createObjectURL(FilesTextures[textureName], { oneTimeOnly: true });
  138. } catch (ex) {
  139. // Chrome doesn't support oneTimeOnly parameter
  140. blobURL = URL.createObjectURL(FilesTextures[textureName]);
  141. }
  142. img.src = blobURL;
  143. } catch (e) {
  144. console.log("Error while trying to load texture: " + textureName);
  145. img.src = null;
  146. }
  147. }
  148. }
  149. return img;
  150. };
  151. //ANY
  152. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer) {
  153. var noIndexedDB = function () {
  154. var request = new XMLHttpRequest();
  155. var loadUrl = Tools.BaseUrl + url;
  156. request.open('GET', loadUrl, true);
  157. if (useArrayBuffer) {
  158. request.responseType = "arraybuffer";
  159. }
  160. request.onprogress = progressCallBack;
  161. request.onreadystatechange = function () {
  162. if (request.readyState == 4) {
  163. if (request.status == 200) {
  164. callback(!useArrayBuffer ? request.responseText : request.response);
  165. } else {
  166. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  167. }
  168. }
  169. };
  170. request.send(null);
  171. };
  172. var loadFromIndexedDB = function () {
  173. database.loadSceneFromDB(url, callback, progressCallBack, noIndexedDB);
  174. };
  175. // Caching only scenes files
  176. if (database && url.indexOf(".babylon") !== -1 && (database.enableSceneOffline)) {
  177. database.openAsync(loadFromIndexedDB, noIndexedDB);
  178. } else {
  179. noIndexedDB();
  180. }
  181. };
  182. Tools.ReadFile = function (fileToLoad, callback, progressCallBack) {
  183. var reader = new FileReader();
  184. reader.onload = function (e) {
  185. callback(e.target.result);
  186. };
  187. reader.onprogress = progressCallBack;
  188. // Asynchronous read
  189. reader.readAsText(fileToLoad);
  190. };
  191. // Misc.
  192. Tools.WithinEpsilon = function (a, b) {
  193. var num = a - b;
  194. return -1.401298E-45 <= num && num <= 1.401298E-45;
  195. };
  196. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  197. for (var prop in source) {
  198. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  199. continue;
  200. }
  201. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  202. continue;
  203. }
  204. var sourceValue = source[prop];
  205. var typeOfSourceValue = typeof sourceValue;
  206. if (typeOfSourceValue == "function") {
  207. continue;
  208. }
  209. if (typeOfSourceValue == "object") {
  210. if (sourceValue instanceof Array) {
  211. destination[prop] = [];
  212. if (sourceValue.length > 0) {
  213. if (typeof sourceValue[0] == "object") {
  214. for (var index = 0; index < sourceValue.length; index++) {
  215. var clonedValue = cloneValue(sourceValue[index], destination);
  216. if (destination[prop].indexOf(clonedValue) === -1) {
  217. destination[prop].push(clonedValue);
  218. }
  219. }
  220. } else {
  221. destination[prop] = sourceValue.slice(0);
  222. }
  223. }
  224. } else {
  225. destination[prop] = cloneValue(sourceValue, destination);
  226. }
  227. } else {
  228. destination[prop] = sourceValue;
  229. }
  230. }
  231. };
  232. Tools.IsEmpty = function (obj) {
  233. for (var i in obj) {
  234. return false;
  235. }
  236. return true;
  237. };
  238. Tools.GetFps = function () {
  239. return fps;
  240. };
  241. Tools.GetDeltaTime = function () {
  242. return deltaTime;
  243. };
  244. Tools._MeasureFps = function () {
  245. previousFramesDuration.push((new Date).getTime());
  246. var length = previousFramesDuration.length;
  247. if (length >= 2) {
  248. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  249. }
  250. if (length >= fpsRange) {
  251. if (length > fpsRange) {
  252. previousFramesDuration.splice(0, 1);
  253. length = previousFramesDuration.length;
  254. }
  255. var sum = 0;
  256. for (var id = 0; id < length - 1; id++) {
  257. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  258. }
  259. fps = 1000.0 / (sum / (length - 1));
  260. }
  261. };
  262. Tools.CreateScreenshot = function (engine, camera, size) {
  263. var width;
  264. var height;
  265. //If a zoom value is specified
  266. if (size.zoom) {
  267. width = Math.round(engine.getRenderWidth() * size.zoom);
  268. height = Math.round(width / engine.getAspectRatio(camera));
  269. size = { width: width, height: height };
  270. } else if (size.width && size.height) {
  271. width = size.width;
  272. height = size.height;
  273. } else if (size.width && !size.height) {
  274. width = size.width;
  275. height = Math.round(width / engine.getAspectRatio(camera));
  276. size = { width: width, height: height };
  277. } else if (size.height && !size.width) {
  278. height = size.height;
  279. width = Math.round(height * engine.getAspectRatio(camera));
  280. size = { width: width, height: height };
  281. } else if (!isNaN(size)) {
  282. height = size;
  283. width = size;
  284. } else {
  285. console.error("Invalid 'size' parameter !");
  286. }
  287. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0]);
  288. texture.renderList = engine.scenes[0].meshes;
  289. texture.onAfterRender = function () {
  290. // Read the contents of the framebuffer
  291. var numberOfChannelsByLine = width * 4;
  292. var halfHeight = height / 2;
  293. //Reading datas from WebGL
  294. var data = engine.ReadPixels(0, 0, width, height);
  295. for (var i = 0; i < halfHeight; i++) {
  296. for (var j = 0; j < numberOfChannelsByLine; j++) {
  297. var currentCell = j + i * numberOfChannelsByLine;
  298. var targetLine = height - i - 1;
  299. var targetCell = j + targetLine * numberOfChannelsByLine;
  300. ;
  301. var temp = data[currentCell];
  302. data[currentCell] = data[targetCell];
  303. data[targetCell] = temp;
  304. }
  305. }
  306. // Create a 2D canvas to store the result
  307. if (!Tools._ScreenshotCanvas) {
  308. Tools._ScreenshotCanvas = document.createElement('canvas');
  309. }
  310. Tools._ScreenshotCanvas.width = width;
  311. Tools._ScreenshotCanvas.height = height;
  312. var context = Tools._ScreenshotCanvas.getContext('2d');
  313. // Copy the pixels to a 2D canvas
  314. var imageData = context.createImageData(width, height);
  315. imageData.data.set(data);
  316. context.putImageData(imageData, 0, 0);
  317. var base64Image = Tools._ScreenshotCanvas.toDataURL();
  318. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  319. if (("download" in document.createElement("a"))) {
  320. var a = window.document.createElement("a");
  321. a.href = base64Image;
  322. var date = new Date();
  323. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  324. a.setAttribute("download", "screenshot-" + stringDate);
  325. window.document.body.appendChild(a);
  326. a.addEventListener("click", function () {
  327. a.parentElement.removeChild(a);
  328. });
  329. a.click();
  330. //Or opening a new tab with the image if it is not possible to automatically start download.
  331. } else {
  332. var newWindow = window.open("");
  333. var img = newWindow.document.createElement("img");
  334. img.src = base64Image;
  335. newWindow.document.body.appendChild(img);
  336. }
  337. };
  338. texture.render();
  339. texture.dispose();
  340. };
  341. Tools.BaseUrl = "";
  342. return Tools;
  343. })();
  344. BABYLON.Tools = Tools;
  345. })(BABYLON || (BABYLON = {}));
  346. //# sourceMappingURL=babylon.tools.js.map