less copy protection, more size visualization
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

1845 satır
56 KiB

  1. let selected = null;
  2. let selectedEntity = null;
  3. let entityIndex = 0;
  4. let clicked = null;
  5. let dragging = false;
  6. let clickTimeout = null;
  7. let dragOffsetX = null;
  8. let dragOffsetY = null;
  9. let shiftHeld = false;
  10. let altHeld = false;
  11. let entityX;
  12. let canvasWidth;
  13. let canvasHeight;
  14. let dragScale = 1;
  15. let dragScaleHandle = null;
  16. let dragEntityScale = 1;
  17. let dragEntityScaleHandle = null;
  18. math.createUnit("humans", {
  19. definition: "5.75 feet"
  20. })
  21. const unitChoices = {
  22. length: [
  23. "meters",
  24. "angstroms",
  25. "millimeters",
  26. "centimeters",
  27. "kilometers",
  28. "inches",
  29. "feet",
  30. "humans",
  31. "stories",
  32. "miles",
  33. "solarradii",
  34. "AUs",
  35. "lightyears",
  36. "parsecs",
  37. "galaxies",
  38. "universes"
  39. ],
  40. area: [
  41. "meters^2",
  42. "cm^2",
  43. "kilometers^2",
  44. "acres",
  45. "miles^2"
  46. ],
  47. mass: [
  48. "kilograms",
  49. "milligrams",
  50. "grams",
  51. "tonnes",
  52. "lbs",
  53. "ounces",
  54. "tons"
  55. ]
  56. }
  57. const config = {
  58. height: math.unit(1500, "meters"),
  59. minLineSize: 100,
  60. maxLineSize: 150,
  61. autoFit: false,
  62. autoFitMode: "max"
  63. }
  64. const availableEntities = {
  65. }
  66. const availableEntitiesByName = {
  67. }
  68. const entities = {
  69. }
  70. function constrainRel(coords) {
  71. if (altHeld) {
  72. return coords;
  73. }
  74. return {
  75. x: Math.min(Math.max(coords.x, 0), 1),
  76. y: Math.min(Math.max(coords.y, 0), 1)
  77. }
  78. }
  79. function snapRel(coords) {
  80. return constrainRel({
  81. x: coords.x,
  82. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  83. });
  84. }
  85. function adjustAbs(coords, oldHeight, newHeight) {
  86. const ratio = math.divide(oldHeight, newHeight);
  87. return { x: 0.5 + (coords.x - 0.5) * math.divide(oldHeight, newHeight), y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  88. }
  89. function rel2abs(coords) {
  90. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  91. }
  92. function abs2rel(coords) {
  93. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  94. }
  95. function updateEntityElement(entity, element) {
  96. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  97. const view = entity.view;
  98. element.style.left = position.x + "px";
  99. element.style.top = position.y + "px";
  100. element.style.setProperty("--xpos", position.x + "px");
  101. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({precision: 2}) + "'");
  102. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  103. const extra = entity.views[view].image.extra;
  104. const bottom = entity.views[view].image.bottom;
  105. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  106. element.style.setProperty("--height", pixels * bonus + "px");
  107. element.style.setProperty("--extra", pixels * bonus - pixels + "px");
  108. if (entity.views[view].rename)
  109. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  110. else
  111. element.querySelector(".entity-name").innerText = entity.name;
  112. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  113. bottomName.style.left = position.x + entityX + "px";
  114. bottomName.style.bottom = "0vh";
  115. bottomName.innerText = entity.name;
  116. const topName = document.querySelector("#top-name-" + element.dataset.key);
  117. topName.style.left = position.x + entityX + "px";
  118. topName.style.top = "20vh";
  119. topName.innerText = entity.name;
  120. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  121. topName.classList.add("top-name-needed");
  122. } else {
  123. topName.classList.remove("top-name-needed");
  124. }
  125. }
  126. function updateSizes(dirtyOnly = false) {
  127. drawScale();
  128. let ordered = Object.entries(entities);
  129. ordered.sort((e1, e2) => {
  130. if (e1[1].priority != e2[1].priority) {
  131. return e2[1].priority - e1[1].priority;
  132. } else {
  133. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  134. }
  135. });
  136. let zIndex = ordered.length;
  137. ordered.forEach(entity => {
  138. const element = document.querySelector("#entity-" + entity[0]);
  139. element.style.zIndex = zIndex;
  140. if (!dirtyOnly || entity[1].dirty) {
  141. updateEntityElement(entity[1], element, zIndex);
  142. entity[1].dirty = false;
  143. }
  144. zIndex -= 1;
  145. });
  146. }
  147. function drawScale() {
  148. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  149. let total = heightPer.clone();
  150. total.value = 0;
  151. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  152. drawTick(ctx, 50, y, total);
  153. total = math.add(total, heightPer);
  154. }
  155. }
  156. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  157. const oldStroke = ctx.strokeStyle;
  158. const oldFill = ctx.fillStyle;
  159. ctx.beginPath();
  160. ctx.moveTo(x, y);
  161. ctx.lineTo(x + 20, y);
  162. ctx.strokeStyle = "#000000";
  163. ctx.stroke();
  164. ctx.beginPath();
  165. ctx.moveTo(x + 20, y);
  166. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  167. ctx.strokeStyle = "#aaaaaa";
  168. ctx.stroke();
  169. ctx.beginPath();
  170. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  171. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  172. ctx.strokeStyle = "#000000";
  173. ctx.stroke();
  174. const oldFont = ctx.font;
  175. ctx.font = 'normal 24pt coda';
  176. ctx.fillStyle = "#dddddd";
  177. ctx.beginPath();
  178. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  179. ctx.font = oldFont;
  180. ctx.strokeStyle = oldStroke;
  181. ctx.fillStyle = oldFill;
  182. }
  183. const canvas = document.querySelector("#display");
  184. /** @type {CanvasRenderingContext2D} */
  185. const ctx = canvas.getContext("2d");
  186. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  187. heightPer = 1;
  188. if (pixelsPer < config.minLineSize) {
  189. const factor = math.ceil(config.minLineSize / pixelsPer);
  190. heightPer *= factor;
  191. pixelsPer *= factor;
  192. }
  193. if (pixelsPer > config.maxLineSize) {
  194. const factor = math.ceil(pixelsPer / config.maxLineSize);
  195. heightPer /= factor;
  196. pixelsPer /= factor;
  197. }
  198. heightPer = math.unit(heightPer, config.height.units[0].unit.name)
  199. ctx.clearRect(0, 0, canvas.width, canvas.height);
  200. ctx.scale(1, 1);
  201. ctx.canvas.width = canvas.clientWidth;
  202. ctx.canvas.height = canvas.clientHeight;
  203. ctx.beginPath();
  204. ctx.moveTo(50, 50);
  205. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  206. ctx.stroke();
  207. ctx.beginPath();
  208. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  209. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  210. ctx.stroke();
  211. drawTicks(ctx, pixelsPer, heightPer);
  212. }
  213. function makeEntity(info, views, sizes) {
  214. const entityTemplate = {
  215. name: info.name,
  216. identifier: info.name,
  217. scale: 1,
  218. info: info,
  219. views: views,
  220. sizes: sizes === undefined ? [] : sizes,
  221. init: function () {
  222. const entity = this;
  223. Object.entries(this.views).forEach(([viewKey, view]) => {
  224. view.parent = this;
  225. if (this.defaultView === undefined) {
  226. this.defaultView = viewKey;
  227. this.view = viewKey;
  228. }
  229. Object.entries(view.attributes).forEach(([key, val]) => {
  230. Object.defineProperty(
  231. view,
  232. key,
  233. {
  234. get: function () {
  235. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  236. },
  237. set: function (value) {
  238. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  239. this.parent.scale = newScale;
  240. }
  241. }
  242. )
  243. });
  244. });
  245. this.sizes.forEach(size => {
  246. if (size.default === true) {
  247. this.views[this.defaultView].height = size.height;
  248. this.size = size;
  249. }
  250. });
  251. if (this.size === undefined && this.sizes.length > 0) {
  252. this.views[this.defaultView].height = this.sizes[0].height;
  253. this.size = this.sizes[0];
  254. console.warn("No default size set for " + info.name);
  255. } else if (this.sizes.length == 0) {
  256. this.sizes = [
  257. {
  258. name: "Normal",
  259. height: this.views[this.defaultView].height
  260. }
  261. ];
  262. this.size = this.sizes[0];
  263. }
  264. this.desc = {};
  265. Object.entries(this.info).forEach(([key, value]) => {
  266. Object.defineProperty(
  267. this.desc,
  268. key,
  269. {
  270. get: function () {
  271. let text = value.text;
  272. if (entity.views[entity.view].info) {
  273. if (entity.views[entity.view].info[key]) {
  274. text = combineInfo(text, entity.views[entity.view].info[key]);
  275. }
  276. }
  277. if (entity.size.info) {
  278. if (entity.size.info[key]) {
  279. text = combineInfo(text, entity.size.info[key]);
  280. }
  281. }
  282. return { title: value.title, text: text };
  283. }
  284. }
  285. )
  286. });
  287. delete this.init;
  288. return this;
  289. }
  290. }.init();
  291. return entityTemplate;
  292. }
  293. function combineInfo(existing, next) {
  294. switch (next.mode) {
  295. case "replace":
  296. return next.text;
  297. case "prepend":
  298. return next.text + existing;
  299. case "append":
  300. return existing + next.text;
  301. }
  302. return existing;
  303. }
  304. function clickDown(target, x, y) {
  305. clicked = target;
  306. const rect = target.getBoundingClientRect();
  307. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  308. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  309. dragOffsetX = x - rect.left + entX;
  310. dragOffsetY = y - rect.top + entY;
  311. clickTimeout = setTimeout(() => { dragging = true }, 200)
  312. target.classList.add("no-transition");
  313. }
  314. // could we make this actually detect the menu area?
  315. function hoveringInDeleteArea(e) {
  316. return e.clientY < document.body.clientHeight / 10;
  317. }
  318. function clickUp(e) {
  319. clearTimeout(clickTimeout);
  320. if (clicked) {
  321. if (dragging) {
  322. dragging = false;
  323. if (hoveringInDeleteArea(e)) {
  324. removeEntity(clicked);
  325. document.querySelector("#menubar").classList.remove("hover-delete");
  326. }
  327. } else {
  328. select(clicked);
  329. }
  330. clicked.classList.remove("no-transition");
  331. clicked = null;
  332. }
  333. }
  334. function deselect() {
  335. if (selected) {
  336. selected.classList.remove("selected");
  337. }
  338. document.getElementById("options-selected-entity-none").selected = "selected";
  339. clearAttribution();
  340. selected = null;
  341. clearViewList();
  342. clearEntityOptions();
  343. clearViewOptions();
  344. }
  345. function select(target) {
  346. deselect();
  347. selected = target;
  348. selectedEntity = entities[target.dataset.key];
  349. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  350. selected.classList.add("selected");
  351. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  352. configViewList(selectedEntity, selectedEntity.view);
  353. configEntityOptions(selectedEntity, selectedEntity.view);
  354. configViewOptions(selectedEntity, selectedEntity.view);
  355. }
  356. function configViewList(entity, selectedView) {
  357. const list = document.querySelector("#entity-view");
  358. list.innerHTML = "";
  359. list.style.display = "block";
  360. Object.keys(entity.views).forEach(view => {
  361. const option = document.createElement("option");
  362. option.innerText = entity.views[view].name;
  363. option.value = view;
  364. if (view === selectedView) {
  365. option.selected = true;
  366. }
  367. list.appendChild(option);
  368. });
  369. }
  370. function clearViewList() {
  371. const list = document.querySelector("#entity-view");
  372. list.innerHTML = "";
  373. list.style.display = "none";
  374. }
  375. function updateWorldOptions(entity, view) {
  376. const heightInput = document.querySelector("#options-height-value");
  377. const heightSelect = document.querySelector("#options-height-unit");
  378. const converted = config.height.toNumber(heightSelect.value);
  379. setNumericInput(heightInput, converted);
  380. }
  381. function configEntityOptions(entity, view) {
  382. const holder = document.querySelector("#options-entity");
  383. document.querySelector("#entity-category-header").style.display = "block";
  384. document.querySelector("#entity-category").style.display = "block";
  385. holder.innerHTML = "";
  386. const scaleLabel = document.createElement("div");
  387. scaleLabel.classList.add("options-label");
  388. scaleLabel.innerText = "Scale";
  389. const scaleRow = document.createElement("div");
  390. scaleRow.classList.add("options-row");
  391. const scaleInput = document.createElement("input");
  392. scaleInput.classList.add("options-field-numeric");
  393. scaleInput.id = "options-entity-scale";
  394. scaleInput.addEventListener("input", e => {
  395. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  396. entity.dirty = true;
  397. if (config.autoFit) {
  398. fitWorld();
  399. } else {
  400. updateSizes(true);
  401. }
  402. updateEntityOptions(entity, view);
  403. updateViewOptions(entity, view);
  404. });
  405. scaleInput.setAttribute("min", 1);
  406. scaleInput.setAttribute("type", "number");
  407. setNumericInput(scaleInput, entity.scale);
  408. scaleRow.appendChild(scaleInput);
  409. holder.appendChild(scaleLabel);
  410. holder.appendChild(scaleRow);
  411. const nameLabel = document.createElement("div");
  412. nameLabel.classList.add("options-label");
  413. nameLabel.innerText = "Name";
  414. const nameRow = document.createElement("div");
  415. nameRow.classList.add("options-row");
  416. const nameInput = document.createElement("input");
  417. nameInput.classList.add("options-field-text");
  418. nameInput.value = entity.name;
  419. nameInput.addEventListener("input", e => {
  420. entity.name = e.target.value;
  421. entity.dirty = true;
  422. updateSizes(true);
  423. })
  424. nameRow.appendChild(nameInput);
  425. holder.appendChild(nameLabel);
  426. holder.appendChild(nameRow);
  427. const defaultHolder = document.querySelector("#options-entity-defaults");
  428. defaultHolder.innerHTML = "";
  429. entity.sizes.forEach(defaultInfo => {
  430. const button = document.createElement("button");
  431. button.classList.add("options-button");
  432. button.innerText = defaultInfo.name;
  433. button.addEventListener("click", e => {
  434. entity.views[entity.defaultView].height = defaultInfo.height;
  435. entity.dirty = true;
  436. updateEntityOptions(entity, entity.view);
  437. updateViewOptions(entity, entity.view);
  438. if (!checkFitWorld()){
  439. updateSizes(true);
  440. }
  441. });
  442. defaultHolder.appendChild(button);
  443. });
  444. document.querySelector("#options-order-display").innerText = entity.priority;
  445. document.querySelector("#options-ordering").style.display = "flex";
  446. }
  447. function updateEntityOptions(entity, view) {
  448. const scaleInput = document.querySelector("#options-entity-scale");
  449. setNumericInput(scaleInput, entity.scale);
  450. document.querySelector("#options-order-display").innerText = entity.priority;
  451. }
  452. function clearEntityOptions() {
  453. document.querySelector("#entity-category-header").style.display = "none";
  454. document.querySelector("#entity-category").style.display = "none";
  455. /*
  456. const holder = document.querySelector("#options-entity");
  457. holder.innerHTML = "";
  458. document.querySelector("#options-entity-defaults").innerHTML = "";
  459. document.querySelector("#options-ordering").style.display = "none";
  460. document.querySelector("#options-ordering").style.display = "none";*/
  461. }
  462. function configViewOptions(entity, view) {
  463. const holder = document.querySelector("#options-view");
  464. document.querySelector("#view-category-header").style.display = "block";
  465. document.querySelector("#view-category").style.display = "block";
  466. holder.innerHTML = "";
  467. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  468. const label = document.createElement("div");
  469. label.classList.add("options-label");
  470. label.innerText = val.name;
  471. holder.appendChild(label);
  472. const row = document.createElement("div");
  473. row.classList.add("options-row");
  474. holder.appendChild(row);
  475. const input = document.createElement("input");
  476. input.classList.add("options-field-numeric");
  477. input.id = "options-view-" + key + "-input";
  478. input.setAttribute("type", "number");
  479. input.setAttribute("min", 1);
  480. setNumericInput(input, entity.views[view][key].value);
  481. const select = document.createElement("select");
  482. select.classList.add("options-field-unit");
  483. select.id = "options-view-" + key + "-select"
  484. unitChoices[val.type].forEach(name => {
  485. const option = document.createElement("option");
  486. option.innerText = name;
  487. select.appendChild(option);
  488. });
  489. input.addEventListener("change", e => {
  490. const value = input.value == 0 ? 1 : input.value;
  491. entity.views[view][key] = math.unit(value, select.value);
  492. entity.dirty = true;
  493. if (config.autoFit) {
  494. fitWorld();
  495. } else {
  496. updateSizes(true);
  497. }
  498. updateEntityOptions(entity, view);
  499. updateViewOptions(entity, view, key);
  500. });
  501. select.setAttribute("oldUnit", select.value);
  502. // TODO does this ever cause a change in the world?
  503. select.addEventListener("input", e => {
  504. const value = input.value == 0 ? 1 : input.value;
  505. const oldUnit = select.getAttribute("oldUnit");
  506. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  507. entity.dirty = true;
  508. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  509. select.setAttribute("oldUnit", select.value);
  510. if (config.autoFit) {
  511. fitWorld();
  512. } else {
  513. updateSizes(true);
  514. }
  515. updateEntityOptions(entity, view);
  516. updateViewOptions(entity, view, key);
  517. });
  518. row.appendChild(input);
  519. row.appendChild(select);
  520. });
  521. }
  522. function updateViewOptions(entity, view, changed) {
  523. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  524. if (key != changed) {
  525. const input = document.querySelector("#options-view-" + key + "-input");
  526. const select = document.querySelector("#options-view-" + key + "-select");
  527. const currentUnit = select.value;
  528. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  529. setNumericInput(input, convertedAmount);
  530. }
  531. });
  532. }
  533. function setNumericInput(input, value, round=3) {
  534. input.value = math.round(value, round);
  535. }
  536. function getSortedEntities() {
  537. return Object.keys(entities).sort((a, b) => {
  538. const entA = entities[a];
  539. const entB = entities[b];
  540. const viewA = entA.view;
  541. const viewB = entB.view;
  542. const heightA = entA.views[viewA].height.to("meter").value;
  543. const heightB = entB.views[viewB].height.to("meter").value;
  544. return heightA - heightB;
  545. });
  546. }
  547. function clearViewOptions() {
  548. document.querySelector("#view-category-header").style.display = "none";
  549. document.querySelector("#view-category").style.display = "none";
  550. }
  551. // this is a crime against humanity, and also stolen from
  552. // stack overflow
  553. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  554. const testCanvas = document.createElement("canvas");
  555. testCanvas.id = "test-canvas";
  556. const testCtx = testCanvas.getContext("2d");
  557. function testClick(event) {
  558. // oh my god I can't believe I'm doing this
  559. const target = event.target;
  560. if (navigator.userAgent.indexOf("Firefox") != -1) {
  561. clickDown(target.parentElement, event.clientX, event.clientY);
  562. return;
  563. }
  564. // Get click coordinates
  565. let w = target.width;
  566. let h = target.height;
  567. let ratioW = 1, ratioH = 1;
  568. // Limit the size of the canvas so that very large images don't cause problems)
  569. if (w > 1000) {
  570. ratioW = w / 1000;
  571. w /= ratioW;
  572. h /= ratioW;
  573. }
  574. if (h > 1000) {
  575. ratioH = h / 1000;
  576. w /= ratioH;
  577. h /= ratioH;
  578. }
  579. const ratio = ratioW * ratioH;
  580. var x = event.clientX - target.getBoundingClientRect().x,
  581. y = event.clientY - target.getBoundingClientRect().y,
  582. alpha;
  583. testCtx.canvas.width = w;
  584. testCtx.canvas.height = h;
  585. // Draw image to canvas
  586. // and read Alpha channel value
  587. testCtx.drawImage(target, 0, 0, w, h);
  588. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  589. // If pixel is transparent,
  590. // retrieve the element underneath and trigger its click event
  591. if (alpha === 0) {
  592. const oldDisplay = target.style.display;
  593. target.style.display = "none";
  594. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  595. newTarget.dispatchEvent(new MouseEvent(event.type, {
  596. "clientX": event.clientX,
  597. "clientY": event.clientY
  598. }));
  599. target.style.display = oldDisplay;
  600. } else {
  601. clickDown(target.parentElement, event.clientX, event.clientY);
  602. }
  603. }
  604. function arrangeEntities(order) {
  605. let x = 0.1;
  606. order.forEach(key => {
  607. document.querySelector("#entity-" + key).dataset.x = x;
  608. x += 0.8 / (order.length - 1);
  609. });
  610. updateSizes();
  611. }
  612. function removeAllEntities() {
  613. Object.keys(entities).forEach(key => {
  614. removeEntity(document.querySelector("#entity-" + key));
  615. });
  616. }
  617. function clearAttribution() {
  618. document.querySelector("#attribution-category-header").style.display = "none";
  619. document.querySelector("#options-attribution").style.display = "none";
  620. }
  621. function displayAttribution(file) {
  622. document.querySelector("#attribution-category-header").style.display = "block";
  623. document.querySelector("#options-attribution").style.display = "inline";
  624. const authors = authorsOfFull(file);
  625. const owners = ownersOfFull(file);
  626. const source = sourceOf(file);
  627. const authorHolder = document.querySelector("#options-attribution-authors");
  628. const ownerHolder = document.querySelector("#options-attribution-owners");
  629. const sourceHolder = document.querySelector("#options-attribution-source");
  630. if (authors === []) {
  631. const div = document.createElement("div");
  632. div.innerText = "Unknown";
  633. authorHolder.innerHTML = "";
  634. authorHolder.appendChild(div);
  635. } else if (authors === undefined) {
  636. const div = document.createElement("div");
  637. div.innerText = "Not yet entered";
  638. authorHolder.innerHTML = "";
  639. authorHolder.appendChild(div);
  640. } else {
  641. authorHolder.innerHTML = "";
  642. const list = document.createElement("ul");
  643. authorHolder.appendChild(list);
  644. authors.forEach(author => {
  645. const authorEntry = document.createElement("li");
  646. if (author.url) {
  647. const link = document.createElement("a");
  648. link.href = author.url;
  649. link.innerText = author.name;
  650. authorEntry.appendChild(link);
  651. } else {
  652. const div = document.createElement("div");
  653. div.innerText = author.name;
  654. authorEntry.appendChild(div);
  655. }
  656. list.appendChild(authorEntry);
  657. });
  658. }
  659. if (owners === []) {
  660. const div = document.createElement("div");
  661. div.innerText = "Unknown";
  662. ownerHolder.innerHTML = "";
  663. ownerHolder.appendChild(div);
  664. } else if (owners === undefined) {
  665. const div = document.createElement("div");
  666. div.innerText = "Not yet entered";
  667. ownerHolder.innerHTML = "";
  668. ownerHolder.appendChild(div);
  669. } else {
  670. ownerHolder.innerHTML = "";
  671. const list = document.createElement("ul");
  672. ownerHolder.appendChild(list);
  673. owners.forEach(owner => {
  674. const ownerEntry = document.createElement("li");
  675. if (owner.url) {
  676. const link = document.createElement("a");
  677. link.href = owner.url;
  678. link.innerText = owner.name;
  679. ownerEntry.appendChild(link);
  680. } else {
  681. const div = document.createElement("div");
  682. div.innerText = owner.name;
  683. ownerEntry.appendChild(div);
  684. }
  685. list.appendChild(ownerEntry);
  686. });
  687. }
  688. if (source === null) {
  689. const div = document.createElement("div");
  690. div.innerText = "No link";
  691. sourceHolder.innerHTML = "";
  692. sourceHolder.appendChild(div);
  693. } else if (source === undefined) {
  694. const div = document.createElement("div");
  695. div.innerText = "Not yet entered";
  696. sourceHolder.innerHTML = "";
  697. sourceHolder.appendChild(div);
  698. } else {
  699. sourceHolder.innerHTML = "";
  700. const link = document.createElement("a");
  701. link.style.display = "block";
  702. link.href = source;
  703. link.innerText = new URL(source).host;
  704. sourceHolder.appendChild(link);
  705. }
  706. }
  707. function removeEntity(element) {
  708. if (selected == element) {
  709. deselect();
  710. }
  711. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  712. option.parentElement.removeChild(option);
  713. delete entities[element.dataset.key];
  714. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  715. bottomName.parentElement.removeChild(bottomName);
  716. element.parentElement.removeChild(element);
  717. }
  718. function checkEntity(entity) {
  719. Object.values(entity.views).forEach(view => {
  720. if (authorsOf(view.image.source) === undefined) {
  721. console.warn("No authors: " + view.image.source);
  722. }
  723. });
  724. }
  725. function displayEntity(entity, view, x, y, selectEntity=false) {
  726. checkEntity(entity);
  727. const box = document.createElement("div");
  728. box.classList.add("entity-box");
  729. const img = document.createElement("img");
  730. img.classList.add("entity-image");
  731. img.addEventListener("dragstart", e => {
  732. e.preventDefault();
  733. });
  734. const nameTag = document.createElement("div");
  735. nameTag.classList.add("entity-name");
  736. nameTag.innerText = entity.name;
  737. box.appendChild(img);
  738. box.appendChild(nameTag);
  739. const image = entity.views[view].image;
  740. img.src = image.source;
  741. displayAttribution(image.source);
  742. if (image.bottom !== undefined) {
  743. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  744. } else {
  745. img.style.setProperty("--offset", ((-1) * 100) + "%")
  746. }
  747. box.dataset.x = x;
  748. box.dataset.y = y;
  749. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  750. img.addEventListener("touchstart", e => {
  751. const fakeEvent = {
  752. target: e.target,
  753. clientX: e.touches[0].clientX,
  754. clientY: e.touches[0].clientY
  755. };
  756. testClick(fakeEvent);
  757. });
  758. const heightBar = document.createElement("div");
  759. heightBar.classList.add("height-bar");
  760. box.appendChild(heightBar);
  761. box.id = "entity-" + entityIndex;
  762. box.dataset.key = entityIndex;
  763. entity.view = view;
  764. entity.priority = 0;
  765. entities[entityIndex] = entity;
  766. entity.index = entityIndex;
  767. const world = document.querySelector("#entities");
  768. world.appendChild(box);
  769. const bottomName = document.createElement("div");
  770. bottomName.classList.add("bottom-name");
  771. bottomName.id = "bottom-name-" + entityIndex;
  772. bottomName.innerText = entity.name;
  773. bottomName.addEventListener("click", () => select(box));
  774. world.appendChild(bottomName);
  775. const topName = document.createElement("div");
  776. topName.classList.add("top-name");
  777. topName.id = "top-name-" + entityIndex;
  778. topName.innerText = entity.name;
  779. topName.addEventListener("click", () => select(box));
  780. world.appendChild(topName);
  781. const entityOption = document.createElement("option");
  782. entityOption.id = "options-selected-entity-" + entityIndex;
  783. entityOption.value = entityIndex;
  784. entityOption.innerText = entity.name;
  785. document.getElementById("options-selected-entity").appendChild(entityOption);
  786. entityIndex += 1;
  787. if (config.autoFit) {
  788. fitWorld();
  789. }
  790. if (selectEntity)
  791. select(box);
  792. entity.dirty = true;
  793. updateSizes(true);
  794. }
  795. window.onblur = function () {
  796. altHeld = false;
  797. shiftHeld = false;
  798. }
  799. window.onfocus = function () {
  800. window.dispatchEvent(new Event("keydown"));
  801. }
  802. function doSliderScale() {
  803. if (sliderScale == 1) {
  804. clearInterval(dragScaleHandle);
  805. }
  806. setWorldHeight(config.height, math.multiply(config.height, (9 + sliderScale) / 10));
  807. }
  808. function doSliderEntityScale() {
  809. if (sliderEntityScale == 1) {
  810. clearInterval(dragEntityScaleHandle);
  811. }
  812. if (selected) {
  813. const entity = entities[selected.dataset.key];
  814. entity.scale *= (9 + sliderEntityScale) / 10;
  815. entity.dirty = true;
  816. updateSizes(true);
  817. updateEntityOptions(entity, entity.view);
  818. updateViewOptions(entity, entity.view);
  819. }
  820. }
  821. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  822. function toggleFullScreen() {
  823. var doc = window.document;
  824. var docEl = doc.documentElement;
  825. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  826. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  827. if(!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  828. requestFullScreen.call(docEl);
  829. }
  830. else {
  831. cancelFullScreen.call(doc);
  832. }
  833. }
  834. function handleResize() {
  835. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  836. canvasWidth = document.querySelector("#display").clientWidth - 100;
  837. canvasHeight = document.querySelector("#display").clientHeight - 50;
  838. updateSizes();
  839. }
  840. function prepareMenu() {
  841. const menubar = document.querySelector("#menubar");
  842. const help = document.querySelector("#help-icons");
  843. const spawners = document.querySelector("#spawners");
  844. [
  845. [
  846. {
  847. name: "Show/hide sidebar",
  848. id: "menu-toggle-sidebar",
  849. icon: "fas fa-chevron-circle-down",
  850. rotates: true
  851. },
  852. {
  853. name: "Fullscreen",
  854. id: "menu-fullscreen",
  855. icon: "fas fa-compress"
  856. }
  857. ],
  858. [
  859. {
  860. name: "Clear",
  861. id: "menu-clear",
  862. icon: "fas fa-trash-alt"
  863. }
  864. ],
  865. [
  866. {
  867. name: "Sort by height",
  868. id: "menu-order-height",
  869. icon: "fas fa-sort-numeric-up"
  870. }
  871. ],
  872. [
  873. {
  874. name: "Permalink",
  875. id: "menu-permalink",
  876. icon: "fas fa-link"
  877. },
  878. {
  879. name: "Export",
  880. id: "menu-export",
  881. icon: "fas fa-share"
  882. },
  883. {
  884. name: "Save",
  885. id: "menu-save",
  886. icon: "fas fa-download"
  887. },
  888. {
  889. name: "Load",
  890. id: "menu-load",
  891. icon: "fas fa-upload"
  892. }
  893. ]
  894. ].forEach(group => {
  895. const span = document.createElement("span");
  896. span.classList.add("menubar-group");
  897. group.forEach(entry => {
  898. const button = document.createElement("button");
  899. button.id = entry.id;
  900. const icon = document.createElement("i");
  901. icon.classList.add(...entry.icon.split(" "));
  902. if (entry.rotates) {
  903. icon.classList.add("rotate-backward", "transitions");
  904. }
  905. const srText = document.createElement("span");
  906. srText.classList.add("sr-only");
  907. srText.innerText = entry.name;
  908. button.appendChild(icon);
  909. button.appendChild(srText);
  910. span.appendChild(button);
  911. const helperEntry = document.createElement("div");
  912. const helperIcon = document.createElement("icon");
  913. const helperText = document.createElement("span");
  914. helperIcon.classList.add(...entry.icon.split(" "));
  915. helperText.innerText = entry.name;
  916. helperEntry.appendChild(helperIcon);
  917. helperEntry.appendChild(helperText);
  918. help.appendChild(helperEntry);
  919. });
  920. menubar.insertBefore(span, spawners);
  921. });
  922. if (checkHelpDate()) {
  923. document.querySelector("#open-help").classList.add("highlighted");
  924. }
  925. }
  926. const lastHelpChange = 1585150501917;
  927. function checkHelpDate() {
  928. try {
  929. const old = localStorage.getItem("help-viewed");
  930. if (old === null || old < lastHelpChange) {
  931. return true;
  932. }
  933. return false;
  934. } catch {
  935. console.warn("Could not set the help-viewed date");
  936. return false;
  937. }
  938. }
  939. function setHelpDate() {
  940. try {
  941. localStorage.setItem("help-viewed", Date.now());
  942. } catch {
  943. console.warn("Could not set the help-viewed date");
  944. }
  945. }
  946. document.addEventListener("DOMContentLoaded", () => {
  947. prepareMenu();
  948. prepareEntities();
  949. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  950. if (e.target.value == "none") {
  951. deselect()
  952. } else {
  953. select(document.querySelector("#entity-" + e.target.value));
  954. }
  955. });
  956. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  957. const sidebar = document.querySelector("#options");
  958. if (sidebar.classList.contains("hidden")) {
  959. sidebar.classList.remove("hidden");
  960. e.target.classList.remove("rotate-forward");
  961. e.target.classList.add("rotate-backward");
  962. } else {
  963. sidebar.classList.add("hidden");
  964. e.target.classList.add("rotate-forward");
  965. e.target.classList.remove("rotate-backward");
  966. }
  967. handleResize();
  968. });
  969. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  970. document.querySelector("#options-show-extra").addEventListener("input", e => {
  971. document.body.classList[e.target.checked ? "add" : "remove"]("show-extra-options");
  972. });
  973. document.querySelector("#options-world-show-names").addEventListener("input", e => {
  974. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-name");
  975. });
  976. document.querySelector("#options-world-show-bottom-names").addEventListener("input", e => {
  977. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-name");
  978. });
  979. document.querySelector("#options-world-show-top-names").addEventListener("input", e => {
  980. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-top-name");
  981. });
  982. document.querySelector("#options-world-show-height-bars").addEventListener("input", e => {
  983. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-height-bars");
  984. });
  985. document.querySelector("#options-world-show-entity-glow").addEventListener("input", e => {
  986. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-glow");
  987. });
  988. document.querySelector("#options-world-show-scale-sliders").addEventListener("input", e => {
  989. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale-sliders");
  990. });
  991. document.querySelector("#options-world-show-bottom-cover").addEventListener("input", e => {
  992. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-cover");
  993. });
  994. document.querySelector("#options-world-show-scale").addEventListener("input", e => {
  995. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale");
  996. });
  997. document.querySelector("#options-order-forward").addEventListener("click", e => {
  998. if (selected) {
  999. entities[selected.dataset.key].priority += 1;
  1000. }
  1001. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1002. updateSizes();
  1003. });
  1004. document.querySelector("#options-order-back").addEventListener("click", e => {
  1005. if (selected) {
  1006. entities[selected.dataset.key].priority -= 1;
  1007. }
  1008. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1009. updateSizes();
  1010. });
  1011. document.querySelector("#slider-scale").addEventListener("mousedown", e => {
  1012. clearInterval(dragScaleHandle);
  1013. dragScaleHandle = setInterval(doSliderScale, 50);
  1014. e.stopPropagation();
  1015. });
  1016. document.querySelector("#slider-scale").addEventListener("touchstart", e => {
  1017. clearInterval(dragScaleHandle);
  1018. dragScaleHandle = setInterval(doSliderScale, 50);
  1019. e.stopPropagation();
  1020. });
  1021. document.querySelector("#slider-scale").addEventListener("input", e => {
  1022. const val = Number(e.target.value);
  1023. if (val < 1) {
  1024. sliderScale = (val + 1) / 2;
  1025. } else {
  1026. sliderScale = val;
  1027. }
  1028. });
  1029. document.querySelector("#slider-scale").addEventListener("change", e => {
  1030. clearInterval(dragScaleHandle);
  1031. dragScaleHandle = null;
  1032. e.target.value = 1;
  1033. });
  1034. document.querySelector("#slider-entity-scale").addEventListener("mousedown", e => {
  1035. clearInterval(dragEntityScaleHandle);
  1036. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  1037. e.stopPropagation();
  1038. });
  1039. document.querySelector("#slider-entity-scale").addEventListener("touchstart", e => {
  1040. clearInterval(dragEntityScaleHandle);
  1041. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  1042. e.stopPropagation();
  1043. });
  1044. document.querySelector("#slider-entity-scale").addEventListener("input", e => {
  1045. const val = Number(e.target.value);
  1046. if (val < 1) {
  1047. sliderEntityScale = (val + 1) / 2;
  1048. } else {
  1049. sliderEntityScale = val;
  1050. }
  1051. });
  1052. document.querySelector("#slider-entity-scale").addEventListener("change", e => {
  1053. clearInterval(dragEntityScaleHandle);
  1054. dragEntityScaleHandle = null;
  1055. e.target.value = 1;
  1056. });
  1057. const sceneChoices = document.querySelector("#scene-choices");
  1058. Object.entries(scenes).forEach(([id, scene]) => {
  1059. const option = document.createElement("option");
  1060. option.innerText = id;
  1061. option.value = id;
  1062. sceneChoices.appendChild(option);
  1063. });
  1064. document.querySelector("#load-scene").addEventListener("click", e => {
  1065. const chosen = sceneChoices.value;
  1066. removeAllEntities();
  1067. scenes[chosen]();
  1068. });
  1069. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1070. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1071. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1072. document.querySelector("#open-help").addEventListener("click", e => {
  1073. setHelpDate();
  1074. document.querySelector("#open-help").classList.remove("highlighted");
  1075. document.querySelector("#help").classList.add("visible");
  1076. });
  1077. document.querySelector("#close-help").addEventListener("click", e => {
  1078. document.querySelector("#help").classList.remove("visible");
  1079. });
  1080. const unitSelector = document.querySelector("#options-height-unit");
  1081. unitChoices.length.forEach(lengthOption => {
  1082. const option = document.createElement("option");
  1083. option.innerText = lengthOption;
  1084. option.value = lengthOption;
  1085. if (lengthOption === "meters") {
  1086. option.selected = true;
  1087. }
  1088. unitSelector.appendChild(option);
  1089. });
  1090. param = new URL(window.location.href).searchParams.get("scene");
  1091. if (param === null)
  1092. scenes["Default"]();
  1093. else {
  1094. try {
  1095. const data = JSON.parse(b64DecodeUnicode(param));
  1096. if (data.entities === undefined) {
  1097. return;
  1098. }
  1099. if (data.world === undefined) {
  1100. return;
  1101. }
  1102. importScene(data);
  1103. } catch (err) {
  1104. console.error(err);
  1105. scenes["Default"]();
  1106. // probably wasn't valid data
  1107. }
  1108. }
  1109. document.querySelector("#world").addEventListener("wheel", e => {
  1110. if (shiftHeld) {
  1111. const dir = e.deltaY > 0 ? 10/11 : 11/10;
  1112. if (selected) {
  1113. const entity = entities[selected.dataset.key];
  1114. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1115. entity.dirty = true;
  1116. updateEntityOptions(entity, entity.view);
  1117. updateViewOptions(entity, entity.view);
  1118. updateSizes(true);
  1119. }
  1120. } else {
  1121. const dir = e.deltaY < 0 ? 10/11 : 11/10;
  1122. setWorldHeight(config.height, math.multiply(config.height, dir));
  1123. updateWorldOptions();
  1124. }
  1125. checkFitWorld();
  1126. })
  1127. document.querySelector("body").appendChild(testCtx.canvas);
  1128. updateSizes();
  1129. document.querySelector("#options-height-value").addEventListener("change", e => {
  1130. updateWorldHeight();
  1131. })
  1132. unitSelector.addEventListener("input", e => {
  1133. checkFitWorld();
  1134. updateWorldHeight();
  1135. })
  1136. world.addEventListener("mousedown", e => deselect());
  1137. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1138. document.querySelector("#display").addEventListener("mousedown", deselect);
  1139. document.addEventListener("mouseup", e => clickUp(e));
  1140. document.addEventListener("touchend", e => {
  1141. const fakeEvent = {
  1142. target: e.target,
  1143. clientX: e.changedTouches[0].clientX,
  1144. clientY: e.changedTouches[0].clientY
  1145. };
  1146. clickUp(fakeEvent);
  1147. });
  1148. document.querySelector("#entity-view").addEventListener("input", e => {
  1149. const entity = entities[selected.dataset.key];
  1150. entity.view = e.target.value;
  1151. const image = entities[selected.dataset.key].views[e.target.value].image;
  1152. selected.querySelector(".entity-image").src = image.source;
  1153. displayAttribution(image.source);
  1154. if (image.bottom !== undefined) {
  1155. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1156. } else {
  1157. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1158. }
  1159. updateSizes();
  1160. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1161. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1162. });
  1163. clearViewList();
  1164. document.querySelector("#menu-clear").addEventListener("click", e => {
  1165. removeAllEntities();
  1166. });
  1167. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1168. const order = Object.keys(entities).sort((a, b) => {
  1169. const entA = entities[a];
  1170. const entB = entities[b];
  1171. const viewA = entA.view;
  1172. const viewB = entB.view;
  1173. const heightA = entA.views[viewA].height.to("meter").value;
  1174. const heightB = entB.views[viewB].height.to("meter").value;
  1175. return heightA - heightB;
  1176. });
  1177. arrangeEntities(order);
  1178. });
  1179. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1180. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  1181. config.autoFit = e.target.checked;
  1182. if (config.autoFit) {
  1183. fitWorld();
  1184. }
  1185. });
  1186. document.addEventListener("keydown", e => {
  1187. if (e.key == "Delete") {
  1188. if (selected) {
  1189. removeEntity(selected);
  1190. selected = null;
  1191. }
  1192. }
  1193. })
  1194. document.addEventListener("keydown", e => {
  1195. if (e.key == "Shift") {
  1196. shiftHeld = true;
  1197. e.preventDefault();
  1198. } else if (e.key == "Alt") {
  1199. altHeld = true;
  1200. e.preventDefault();
  1201. }
  1202. });
  1203. document.addEventListener("keyup", e => {
  1204. if (e.key == "Shift") {
  1205. shiftHeld = false;
  1206. e.preventDefault();
  1207. } else if (e.key == "Alt") {
  1208. altHeld = false;
  1209. e.preventDefault();
  1210. }
  1211. });
  1212. document.addEventListener("paste", e => {
  1213. try {
  1214. const data = JSON.parse(e.clipboardData.getData("text"));
  1215. if (data.entities === undefined) {
  1216. return;
  1217. }
  1218. if (data.world === undefined) {
  1219. return;
  1220. }
  1221. importScene(data);
  1222. } catch (err) {
  1223. console.error(err);
  1224. // probably wasn't valid data
  1225. }
  1226. });
  1227. window.addEventListener("resize", handleResize);
  1228. // TODO: further investigate why the tool initially starts out with wrong
  1229. // values under certain circumstances (seems to be narrow aspect ratios -
  1230. // maybe the menu bar is animating when it shouldn't)
  1231. setTimeout(handleResize, 250);
  1232. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1233. linkScene();
  1234. });
  1235. document.querySelector("#menu-export").addEventListener("click", e => {
  1236. copyScene();
  1237. });
  1238. document.querySelector("#menu-save").addEventListener("click", e => {
  1239. saveScene();
  1240. });
  1241. document.querySelector("#menu-load").addEventListener("click", e => {
  1242. loadScene();
  1243. });
  1244. clearEntityOptions();
  1245. clearViewOptions();
  1246. clearAttribution();
  1247. });
  1248. function prepareEntities() {
  1249. availableEntities["buildings"] = makeBuildings();
  1250. availableEntities["landmarks"] = makeLandmarks();
  1251. availableEntities["characters"] = makeCharacters();
  1252. availableEntities["objects"] = makeObjects();
  1253. availableEntities["fiction"] = makeFiction();
  1254. availableEntities["food"] = makeFood();
  1255. availableEntities["naturals"] = makeNaturals();
  1256. availableEntities["vehicles"] = makeVehicles();
  1257. availableEntities["cities"] = makeCities();
  1258. availableEntities["pokemon"] = makePokemon();
  1259. availableEntities["characters"].sort((x, y) => {
  1260. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1261. });
  1262. const holder = document.querySelector("#spawners");
  1263. const categorySelect = document.createElement("select");
  1264. categorySelect.id = "category-picker";
  1265. holder.appendChild(categorySelect);
  1266. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1267. const select = document.createElement("select");
  1268. select.id = "create-entity-" + category;
  1269. for (let i = 0; i < entityList.length; i++) {
  1270. const entity = entityList[i];
  1271. const option = document.createElement("option");
  1272. option.value = i;
  1273. option.innerText = entity.name;
  1274. select.appendChild(option);
  1275. availableEntitiesByName[entity.name] = entity;
  1276. };
  1277. const button = document.createElement("button");
  1278. button.id = "create-entity-" + category + "-button";
  1279. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1280. button.addEventListener("click", e => {
  1281. const newEntity = entityList[select.value].constructor()
  1282. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true);
  1283. });
  1284. const categoryOption = document.createElement("option");
  1285. categoryOption.value = category
  1286. categoryOption.innerText = category;
  1287. if (category == "characters") {
  1288. categoryOption.selected = true;
  1289. select.classList.add("category-visible");
  1290. button.classList.add("category-visible");
  1291. }
  1292. categorySelect.appendChild(categoryOption);
  1293. holder.appendChild(select);
  1294. holder.appendChild(button);
  1295. });
  1296. categorySelect.addEventListener("input", e => {
  1297. const oldSelect = document.querySelector("select.category-visible");
  1298. oldSelect.classList.remove("category-visible");
  1299. const oldButton = document.querySelector("button.category-visible");
  1300. oldButton.classList.remove("category-visible");
  1301. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1302. newSelect.classList.add("category-visible");
  1303. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1304. newButton.classList.add("category-visible");
  1305. });
  1306. }
  1307. document.addEventListener("mousemove", (e) => {
  1308. if (clicked) {
  1309. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1310. clicked.dataset.x = position.x;
  1311. clicked.dataset.y = position.y;
  1312. updateEntityElement(entities[clicked.dataset.key], clicked);
  1313. if (hoveringInDeleteArea(e)) {
  1314. document.querySelector("#menubar").classList.add("hover-delete");
  1315. } else {
  1316. document.querySelector("#menubar").classList.remove("hover-delete");
  1317. }
  1318. }
  1319. });
  1320. document.addEventListener("touchmove", (e) => {
  1321. if (clicked) {
  1322. e.preventDefault();
  1323. let x = e.touches[0].clientX;
  1324. let y = e.touches[0].clientY;
  1325. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1326. clicked.dataset.x = position.x;
  1327. clicked.dataset.y = position.y;
  1328. updateEntityElement(entities[clicked.dataset.key], clicked);
  1329. // what a hack
  1330. // I should centralize this 'fake event' creation...
  1331. if (hoveringInDeleteArea({ clientY: y })) {
  1332. document.querySelector("#menubar").classList.add("hover-delete");
  1333. } else {
  1334. document.querySelector("#menubar").classList.remove("hover-delete");
  1335. }
  1336. }
  1337. }, { passive: false });
  1338. function checkFitWorld() {
  1339. if (config.autoFit) {
  1340. fitWorld();
  1341. return true;
  1342. }
  1343. return false;
  1344. }
  1345. const fitModes = {
  1346. "max": {
  1347. start: 0,
  1348. binop: Math.max,
  1349. final: (total, count) => total
  1350. },
  1351. "arithmetic mean": {
  1352. start: 0,
  1353. binop: math.add,
  1354. final: (total, count) => total / count
  1355. },
  1356. "geometric mean": {
  1357. start: 1,
  1358. binop: math.multiply,
  1359. final: (total, count) => math.pow(total, 1 / count)
  1360. }
  1361. }
  1362. function fitWorld(manual=false, factor=1.1) {
  1363. const fitMode = fitModes[config.autoFitMode]
  1364. let max = fitMode.start
  1365. let count = 0;
  1366. Object.entries(entities).forEach(([key, entity]) => {
  1367. const view = entity.view;
  1368. let extra = entity.views[view].image.extra;
  1369. extra = extra === undefined ? 1 : extra;
  1370. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1371. count += 1;
  1372. });
  1373. max = fitMode.final(max, count)
  1374. max = math.unit(max, "meter")
  1375. if (manual)
  1376. altHeld = true;
  1377. setWorldHeight(config.height, math.multiply(max, factor));
  1378. if (manual)
  1379. altHeld = false;
  1380. }
  1381. function updateWorldHeight() {
  1382. const unit = document.querySelector("#options-height-unit").value;
  1383. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1384. const oldHeight = config.height;
  1385. setWorldHeight(oldHeight, math.unit(value, unit));
  1386. }
  1387. function setWorldHeight(oldHeight, newHeight) {
  1388. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1389. const unit = document.querySelector("#options-height-unit").value;
  1390. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  1391. Object.entries(entities).forEach(([key, entity]) => {
  1392. const element = document.querySelector("#entity-" + key);
  1393. let newPosition;
  1394. if (!altHeld) {
  1395. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1396. } else {
  1397. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1398. }
  1399. element.dataset.x = newPosition.x;
  1400. element.dataset.y = newPosition.y;
  1401. });
  1402. updateSizes();
  1403. }
  1404. function loadScene() {
  1405. try {
  1406. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  1407. importScene(data);
  1408. } catch (err) {
  1409. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1410. console.error(err);
  1411. }
  1412. }
  1413. function saveScene() {
  1414. try {
  1415. const string = JSON.stringify(exportScene());
  1416. localStorage.setItem("macrovision-save", string);
  1417. } catch (err) {
  1418. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1419. console.error(err);
  1420. }
  1421. }
  1422. function exportScene() {
  1423. const results = {};
  1424. results.entities = [];
  1425. Object.entries(entities).forEach(([key, entity]) => {
  1426. const element = document.querySelector("#entity-" + key);
  1427. results.entities.push({
  1428. name: entity.identifier,
  1429. scale: entity.scale,
  1430. view: entity.view,
  1431. x: element.dataset.x,
  1432. y: element.dataset.y
  1433. });
  1434. });
  1435. const unit = document.querySelector("#options-height-unit").value;
  1436. results.world = {
  1437. height: config.height.toNumber(unit),
  1438. unit: unit
  1439. }
  1440. return results;
  1441. }
  1442. // btoa doesn't like anything that isn't ASCII
  1443. // great
  1444. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1445. // for providing an alternative
  1446. function b64EncodeUnicode(str) {
  1447. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1448. // then we convert the percent encodings into raw bytes which
  1449. // can be fed into btoa.
  1450. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1451. function toSolidBytes(match, p1) {
  1452. return String.fromCharCode('0x' + p1);
  1453. }));
  1454. }
  1455. function b64DecodeUnicode(str) {
  1456. // Going backwards: from bytestream, to percent-encoding, to original string.
  1457. return decodeURIComponent(atob(str).split('').map(function(c) {
  1458. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1459. }).join(''));
  1460. }
  1461. function linkScene() {
  1462. loc = new URL(window.location);
  1463. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1464. }
  1465. function copyScene() {
  1466. const results = exportScene();
  1467. navigator.clipboard.writeText(JSON.stringify(results))
  1468. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  1469. }
  1470. // TODO - don't just search through every single entity
  1471. // probably just have a way to do lookups directly
  1472. function findEntity(name) {
  1473. return availableEntitiesByName[name];
  1474. }
  1475. function importScene(data) {
  1476. removeAllEntities();
  1477. data.entities.forEach(entityInfo => {
  1478. const entity = findEntity(entityInfo.name).constructor();
  1479. entity.scale = entityInfo.scale
  1480. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1481. });
  1482. config.height = math.unit(data.world.height, data.world.unit);
  1483. document.querySelector("#options-height-unit").value = data.world.unit;
  1484. updateSizes();
  1485. }