less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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