}
+ */
+ this.allEntities = [];
+
+ this.root.signals.entityAdded.add(this.internalPushEntityIfMatching, this);
+ this.root.signals.entityGotNewComponent.add(this.internalReconsiderEntityToAdd, this);
+ this.root.signals.entityComponentRemoved.add(this.internalCheckEntityAfterComponentRemoval, this);
+ this.root.signals.entityQueuedForDestroy.add(this.internalPopEntityIfMatching, this);
+
+ this.root.signals.postLoadHook.add(this.internalPostLoadHook, this);
+ this.root.signals.bulkOperationFinished.add(this.refreshCaches, this);
+ }
+
+ /**
+ * @param {Entity} entity
+ */
+ internalPushEntityIfMatching(entity) {
+ for (let i = 0; i < this.requiredComponentIds.length; ++i) {
+ if (!entity.components[this.requiredComponentIds[i]]) {
+ return;
+ }
+ }
+
+ // This is slow!
+ if (G_IS_DEV && !globalConfig.debug.disableSlowAsserts) {
+ assert(this.allEntities.indexOf(entity) < 0, "entity already in list: " + entity);
+ }
+
+ this.internalRegisterEntity(entity);
+ }
+
+ /**
+ *
+ * @param {Entity} entity
+ */
+ internalCheckEntityAfterComponentRemoval(entity) {
+ if (this.allEntities.indexOf(entity) < 0) {
+ // Entity wasn't interesting anyways
+ return;
+ }
+
+ for (let i = 0; i < this.requiredComponentIds.length; ++i) {
+ if (!entity.components[this.requiredComponentIds[i]]) {
+ // Entity is not interesting anymore
+ arrayDeleteValue(this.allEntities, entity);
+ }
+ }
+ }
+
+ /**
+ *
+ * @param {Entity} entity
+ */
+ internalReconsiderEntityToAdd(entity) {
+ for (let i = 0; i < this.requiredComponentIds.length; ++i) {
+ if (!entity.components[this.requiredComponentIds[i]]) {
+ return;
+ }
+ }
+ if (this.allEntities.indexOf(entity) >= 0) {
+ return;
+ }
+ this.internalRegisterEntity(entity);
+ }
+
+ refreshCaches() {
+ // Remove all entities which are queued for destroy
+ for (let i = 0; i < this.allEntities.length; ++i) {
+ const entity = this.allEntities[i];
+ if (entity.queuedForDestroy || entity.destroyed) {
+ this.allEntities.splice(i, 1);
+ i -= 1;
+ }
+ }
+
+ this.allEntities.sort((a, b) => a.uid - b.uid);
+ }
+
+ /**
+ * Recomputes all target entities after the game has loaded
+ */
+ internalPostLoadHook() {
+ this.refreshCaches();
+ }
+
+ /**
+ *
+ * @param {Entity} entity
+ */
+ internalRegisterEntity(entity) {
+ this.allEntities.push(entity);
+
+ if (this.root.gameInitialized && !this.root.bulkOperationRunning) {
+ // Sort entities by uid so behaviour is predictable
+ this.allEntities.sort((a, b) => a.uid - b.uid);
+ }
+ }
+
+ /**
+ *
+ * @param {Entity} entity
+ */
+ internalPopEntityIfMatching(entity) {
+ if (this.root.bulkOperationRunning) {
+ // We do this in refreshCaches afterwards
+ return;
+ }
+ const index = this.allEntities.indexOf(entity);
+ if (index >= 0) {
+ arrayDelete(this.allEntities, index);
+ }
+ }
+}
diff --git a/src/js/game/hints.js b/src/js/game/hints.js
new file mode 100644
index 00000000..c2e7e4e5
--- /dev/null
+++ b/src/js/game/hints.js
@@ -0,0 +1,22 @@
+import { randomChoice } from "../core/utils";
+import { T } from "../translations";
+
+const hintsShown = [];
+
+/**
+ * Finds a new hint to show about the game which the user hasn't seen within this session
+ */
+export function getRandomHint() {
+ let maxTries = 100 * T.tips.length;
+
+ while (maxTries-- > 0) {
+ const hint = randomChoice(T.tips);
+ if (!hintsShown.includes(hint)) {
+ hintsShown.push(hint);
+ return hint;
+ }
+ }
+
+ // All tips shown so far
+ return randomChoice(T.tips);
+}
diff --git a/src/js/game/hub_goals.js b/src/js/game/hub_goals.js
index 71817ebd..16947f24 100644
--- a/src/js/game/hub_goals.js
+++ b/src/js/game/hub_goals.js
@@ -43,11 +43,11 @@ export class HubGoals extends BasicSerializableObject {
// Compute upgrade improvements
for (const upgradeId in UPGRADES) {
- const upgradeHandle = UPGRADES[upgradeId];
+ const tiers = UPGRADES[upgradeId];
const level = this.upgradeLevels[upgradeId] || 0;
- let totalImprovement = upgradeHandle.baseValue || 1;
+ let totalImprovement = 1;
for (let i = 0; i < level; ++i) {
- totalImprovement += upgradeHandle.tiers[i].improvement;
+ totalImprovement += tiers[i].improvement;
}
this.upgradeImprovements[upgradeId] = totalImprovement;
}
@@ -98,7 +98,7 @@ export class HubGoals extends BasicSerializableObject {
*/
this.upgradeImprovements = {};
for (const key in UPGRADES) {
- this.upgradeImprovements[key] = UPGRADES[key].baseValue || 1;
+ this.upgradeImprovements[key] = 1;
}
this.createNextGoal();
@@ -212,7 +212,7 @@ export class HubGoals extends BasicSerializableObject {
this.currentGoal = {
/** @type {ShapeDefinition} */
definition: this.createRandomShape(),
- required: 10000 + findNiceIntegerValue(this.level * 2000),
+ required: findNiceIntegerValue(5000 + Math.pow(this.level * 2000, 0.75)),
reward: enumHubGoalRewards.no_reward_freeplay,
};
}
@@ -243,10 +243,10 @@ export class HubGoals extends BasicSerializableObject {
* @param {string} upgradeId
*/
canUnlockUpgrade(upgradeId) {
- const handle = UPGRADES[upgradeId];
+ const tiers = UPGRADES[upgradeId];
const currentLevel = this.getUpgradeLevel(upgradeId);
- if (currentLevel >= handle.tiers.length) {
+ if (currentLevel >= tiers.length) {
// Max level
return false;
}
@@ -255,7 +255,7 @@ export class HubGoals extends BasicSerializableObject {
return true;
}
- const tierData = handle.tiers[currentLevel];
+ const tierData = tiers[currentLevel];
for (let i = 0; i < tierData.required.length; ++i) {
const requirement = tierData.required[i];
@@ -290,10 +290,10 @@ export class HubGoals extends BasicSerializableObject {
return false;
}
- const handle = UPGRADES[upgradeId];
+ const upgradeTiers = UPGRADES[upgradeId];
const currentLevel = this.getUpgradeLevel(upgradeId);
- const tierData = handle.tiers[currentLevel];
+ const tierData = upgradeTiers[currentLevel];
if (!tierData) {
return false;
}
@@ -396,15 +396,11 @@ export class HubGoals extends BasicSerializableObject {
*/
getProcessorBaseSpeed(processorType) {
switch (processorType) {
- case enumItemProcessorTypes.splitterWires:
- return globalConfig.wiresSpeedItemsPerSecond * 2;
-
case enumItemProcessorTypes.trash:
case enumItemProcessorTypes.hub:
return 1e30;
- case enumItemProcessorTypes.splitter:
+ case enumItemProcessorTypes.balancer:
return globalConfig.beltSpeedItemsPerSecond * this.upgradeImprovements.belt * 2;
- case enumItemProcessorTypes.filter:
case enumItemProcessorTypes.reader:
return globalConfig.beltSpeedItemsPerSecond * this.upgradeImprovements.belt;
@@ -427,7 +423,7 @@ export class HubGoals extends BasicSerializableObject {
case enumItemProcessorTypes.cutterQuad:
case enumItemProcessorTypes.rotater:
case enumItemProcessorTypes.rotaterCCW:
- case enumItemProcessorTypes.rotaterFL:
+ case enumItemProcessorTypes.rotater180:
case enumItemProcessorTypes.stacker: {
assert(
globalConfig.buildingSpeeds[processorType],
diff --git a/src/js/game/hud/hud.js b/src/js/game/hud/hud.js
index 3edc4e17..e0ddfd9d 100644
--- a/src/js/game/hud/hud.js
+++ b/src/js/game/hud/hud.js
@@ -194,9 +194,6 @@ export class GameHUD {
* Returns true if the rendering can be paused
*/
hasBlockingOverlayOpen() {
- if (this.root.camera.getIsMapOverlayActive()) {
- return true;
- }
for (const key in this.parts) {
if (this.parts[key].isBlockingOverlay()) {
return true;
diff --git a/src/js/game/hud/parts/building_placer_logic.js b/src/js/game/hud/parts/building_placer_logic.js
index 6031e555..8e8e72c3 100644
--- a/src/js/game/hud/parts/building_placer_logic.js
+++ b/src/js/game/hud/parts/building_placer_logic.js
@@ -253,6 +253,12 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart {
* @see BaseHUDPart.update
*/
update() {
+ // Abort placement if a dialog was shown in the meantime
+ if (this.root.hud.hasBlockingOverlayOpen()) {
+ this.abortPlacement();
+ return;
+ }
+
// Always update since the camera might have moved
const mousePos = this.root.app.mousePosition;
if (mousePos) {
@@ -330,7 +336,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart {
if (tileBelow && this.root.app.settings.getAllSettings().pickMinerOnPatch) {
this.currentMetaBuilding.set(gMetaBuildingRegistry.findByClass(MetaMinerBuilding));
- // Select chained miner if available, since thats always desired once unlocked
+ // Select chained miner if available, since that's always desired once unlocked
if (this.root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_miner_chainable)) {
this.currentVariant.set(enumMinerVariants.chainable);
}
diff --git a/src/js/game/hud/parts/buildings_toolbar.js b/src/js/game/hud/parts/buildings_toolbar.js
index f8953204..19754436 100644
--- a/src/js/game/hud/parts/buildings_toolbar.js
+++ b/src/js/game/hud/parts/buildings_toolbar.js
@@ -1,22 +1,22 @@
-import { MetaBeltBaseBuilding } from "../../buildings/belt_base";
+import { MetaBeltBuilding } from "../../buildings/belt";
import { MetaCutterBuilding } from "../../buildings/cutter";
+import { MetaDisplayBuilding } from "../../buildings/display";
+import { MetaFilterBuilding } from "../../buildings/filter";
+import { MetaLeverBuilding } from "../../buildings/lever";
import { MetaMinerBuilding } from "../../buildings/miner";
import { MetaMixerBuilding } from "../../buildings/mixer";
import { MetaPainterBuilding } from "../../buildings/painter";
+import { MetaReaderBuilding } from "../../buildings/reader";
import { MetaRotaterBuilding } from "../../buildings/rotater";
-import { MetaSplitterBuilding } from "../../buildings/splitter";
+import { MetaBalancerBuilding } from "../../buildings/balancer";
import { MetaStackerBuilding } from "../../buildings/stacker";
import { MetaTrashBuilding } from "../../buildings/trash";
import { MetaUndergroundBeltBuilding } from "../../buildings/underground_belt";
import { HUDBaseToolbar } from "./base_toolbar";
-import { MetaLeverBuilding } from "../../buildings/lever";
-import { MetaFilterBuilding } from "../../buildings/filter";
-import { MetaDisplayBuilding } from "../../buildings/display";
-import { MetaReaderBuilding } from "../../buildings/reader";
const supportedBuildings = [
- MetaBeltBaseBuilding,
- MetaSplitterBuilding,
+ MetaBeltBuilding,
+ MetaBalancerBuilding,
MetaUndergroundBeltBuilding,
MetaMinerBuilding,
MetaCutterBuilding,
diff --git a/src/js/game/hud/parts/entity_debugger.js b/src/js/game/hud/parts/entity_debugger.js
index 80f15eea..640ad4d6 100644
--- a/src/js/game/hud/parts/entity_debugger.js
+++ b/src/js/game/hud/parts/entity_debugger.js
@@ -1,7 +1,13 @@
-import { BaseHUDPart } from "../base_hud_part";
+/* dev:start */
import { makeDiv, removeAllChildren } from "../../../core/utils";
-import { globalConfig } from "../../../core/config";
+import { Vector } from "../../../core/vector";
+import { Entity } from "../../entity";
+import { BaseHUDPart } from "../base_hud_part";
+import { DynamicDomAttach } from "../dynamic_dom_attach";
+/**
+ * Allows to inspect entities by pressing F8 while hovering them
+ */
export class HUDEntityDebugger extends BaseHUDPart {
createElements(parent) {
this.element = makeDiv(
@@ -9,65 +15,147 @@ export class HUDEntityDebugger extends BaseHUDPart {
"ingame_HUD_EntityDebugger",
[],
`
- Tile below cursor:
- Chunk below cursor:
-
+ Entity Debugger
+ Use F8 to toggle this overlay
+
+
`
);
-
- /** @type {HTMLElement} */
- this.mousePosElem = this.element.querySelector(".mousePos");
- /** @type {HTMLElement} */
- this.chunkPosElem = this.element.querySelector(".chunkPos");
- this.entityInfoElem = this.element.querySelector(".entityInfo");
+ this.componentsElem = this.element.querySelector(".entityComponents");
}
initialize() {
- this.root.camera.downPreHandler.add(this.onMouseDown, this);
+ this.root.gameState.inputReciever.keydown.add(key => {
+ if (key.keyCode === 119) {
+ // F8
+ this.pickEntity();
+ }
+ });
+
+ /**
+ * The currently selected entity
+ * @type {Entity}
+ */
+ this.selectedEntity = null;
+
+ this.lastUpdate = 0;
+
+ this.domAttach = new DynamicDomAttach(this.root, this.element);
}
- update() {
+ pickEntity() {
const mousePos = this.root.app.mousePosition;
if (!mousePos) {
return;
}
const worldPos = this.root.camera.screenToWorld(mousePos);
const worldTile = worldPos.toTileSpace();
-
- const chunk = worldTile.divideScalar(globalConfig.mapChunkSize).floor();
- this.mousePosElem.innerText = worldTile.x + " / " + worldTile.y;
- this.chunkPosElem.innerText = chunk.x + " / " + chunk.y;
-
const entity = this.root.map.getTileContent(worldTile, this.root.currentLayer);
+
+ this.selectedEntity = entity;
if (entity) {
- removeAllChildren(this.entityInfoElem);
- let html = "Entity";
-
- const flag = (name, val) =>
- `${name} ${val} `;
-
- html += "";
- html += flag("registered", entity.registered);
- html += flag("uid", entity.uid);
- html += flag("destroyed", entity.destroyed);
- html += "
";
-
- html += "";
-
- for (const componentId in entity.components) {
- const data = entity.components[componentId];
- html += "
";
- html += "" + componentId + " ";
- html += "";
-
- html += "
";
- }
-
- html += "
";
-
- this.entityInfoElem.innerHTML = html;
+ this.rerenderFull(entity);
}
}
- onMouseDown() {}
+ /**
+ *
+ * @param {string} name
+ * @param {any} val
+ * @param {number} indent
+ * @param {Array} recursion
+ */
+ propertyToHTML(name, val, indent = 0, recursion = []) {
+ if (indent > 20) {
+ return;
+ }
+
+ if (val !== null && typeof val === "object") {
+ // Array is displayed like object, with indexes
+ recursion.push(val);
+
+ // Get type class name (like Array, Object, Vector...)
+ let typeName = `(${val.constructor ? val.constructor.name : "unknown"})`;
+
+ if (Array.isArray(val)) {
+ typeName = `(Array[${val.length}])`;
+ }
+
+ if (val instanceof Vector) {
+ typeName = `(Vector[${val.x}, ${val.y}])`;
+ }
+
+ const colorStyle = `color: hsl(${30 * indent}, 100%, 80%)`;
+
+ let html = `
+ ${name} ${typeName}
+ `;
+
+ for (const property in val) {
+ const isRoot = val[property] == this.root;
+ const isRecursive = recursion.includes(val[property]);
+
+ let hiddenValue = isRoot ? "" : null;
+ if (isRecursive) {
+ // Avoid recursion by not "expanding" object more than once
+ hiddenValue = "";
+ }
+
+ html += this.propertyToHTML(
+ property,
+ hiddenValue ? hiddenValue : val[property],
+ indent + 1,
+ [...recursion] // still expand same value in other "branches"
+ );
+ }
+
+ html += "
";
+
+ return html;
+ }
+
+ const displayValue = (val + "")
+ .replaceAll("&", "&")
+ .replaceAll("<", "<")
+ .replaceAll(">", ">");
+ return `${name} ${displayValue} `;
+ }
+
+ /**
+ * Rerenders the whole container
+ * @param {Entity} entity
+ */
+ rerenderFull(entity) {
+ removeAllChildren(this.componentsElem);
+ let html = "";
+
+ const property = (strings, val) => `${strings[0]} ${val} `;
+
+ html += property`registered ${!!entity.registered}`;
+ html += property`uid ${entity.uid}`;
+ html += property`destroyed ${!!entity.destroyed}`;
+
+ for (const componentId in entity.components) {
+ const data = entity.components[componentId];
+ html += "";
+ html += "" + componentId + " ";
+
+ for (const property in data) {
+ // Put entity into recursion list, so it won't get "expanded"
+ html += this.propertyToHTML(property, data[property], 0, [entity]);
+ }
+
+ html += "
";
+ }
+
+ this.componentsElem.innerHTML = html;
+ }
+
+ update() {
+ this.domAttach.update(!!this.selectedEntity);
+ }
}
+
+/* dev:end */
diff --git a/src/js/game/hud/parts/game_menu.js b/src/js/game/hud/parts/game_menu.js
index 59ba0232..2a172ab2 100644
--- a/src/js/game/hud/parts/game_menu.js
+++ b/src/js/game/hud/parts/game_menu.js
@@ -5,6 +5,7 @@ import { enumNotificationType } from "./notifications";
import { T } from "../../../translations";
import { KEYMAPPINGS } from "../../key_action_mapper";
import { DynamicDomAttach } from "../dynamic_dom_attach";
+import { TrackedState } from "../../../core/tracked_state";
export class HUDGameMenu extends BaseHUDPart {
createElements(parent) {
@@ -51,18 +52,15 @@ export class HUDGameMenu extends BaseHUDPart {
* }>} */
this.visibilityToUpdate = [];
- this.buttonsElement = makeDiv(this.element, null, ["buttonContainer"]);
-
buttons.forEach(({ id, label, handler, keybinding, badge, notification, visible }) => {
const button = document.createElement("button");
- button.setAttribute("data-button-id", id);
- this.buttonsElement.appendChild(button);
+ button.classList.add(id);
+ this.element.appendChild(button);
this.trackClicks(button, handler);
if (keybinding) {
const binding = this.root.keyMapper.getBinding(keybinding);
binding.add(handler);
- binding.appendLabelToElement(button);
}
if (visible) {
@@ -86,10 +84,8 @@ export class HUDGameMenu extends BaseHUDPart {
}
});
- const menuButtons = makeDiv(this.element, null, ["menuButtons"]);
-
- this.saveButton = makeDiv(menuButtons, null, ["button", "save", "animEven"]);
- this.settingsButton = makeDiv(menuButtons, null, ["button", "settings"]);
+ this.saveButton = makeDiv(this.element, null, ["button", "save", "animEven"]);
+ this.settingsButton = makeDiv(this.element, null, ["button", "settings"]);
this.trackClicks(this.saveButton, this.startSave);
this.trackClicks(this.settingsButton, this.openSettings);
@@ -97,12 +93,17 @@ export class HUDGameMenu extends BaseHUDPart {
initialize() {
this.root.signals.gameSaved.add(this.onGameSaved, this);
+
+ this.trackedIsSaving = new TrackedState(this.onIsSavingChanged, this);
}
update() {
let playSound = false;
let notifications = new Set();
+ // Check whether we are saving
+ this.trackedIsSaving.set(!!this.root.gameState.currentSavePromise);
+
// Update visibility of buttons
for (let i = 0; i < this.visibilityToUpdate.length; ++i) {
const { condition, domAttach } = this.visibilityToUpdate[i];
@@ -154,6 +155,10 @@ export class HUDGameMenu extends BaseHUDPart {
});
}
+ onIsSavingChanged(isSaving) {
+ this.saveButton.classList.toggle("saving", isSaving);
+ }
+
onGameSaved() {
this.saveButton.classList.toggle("animEven");
this.saveButton.classList.toggle("animOdd");
diff --git a/src/js/game/hud/parts/keybinding_overlay.js b/src/js/game/hud/parts/keybinding_overlay.js
index d31ee746..834a7385 100644
--- a/src/js/game/hud/parts/keybinding_overlay.js
+++ b/src/js/game/hud/parts/keybinding_overlay.js
@@ -162,13 +162,6 @@ export class HUDKeybindingOverlay extends BaseHUDPart {
condition: () => this.mapOverviewActive && !this.blueprintPlacementActive,
},
- {
- // Pipette
- label: T.ingame.keybindingsOverlay.pipette,
- keys: [k.placement.pipette],
- condition: () => !this.mapOverviewActive && !this.blueprintPlacementActive,
- },
-
{
// Cancel placement
label: T.ingame.keybindingsOverlay.stopPlacement,
@@ -184,6 +177,13 @@ export class HUDKeybindingOverlay extends BaseHUDPart {
!this.anyPlacementActive && !this.mapOverviewActive && !this.anythingSelectedOnMap,
},
+ {
+ // Pipette
+ label: T.ingame.keybindingsOverlay.pipette,
+ keys: [k.placement.pipette],
+ condition: () => !this.mapOverviewActive && !this.blueprintPlacementActive,
+ },
+
{
// Area select
label: T.ingame.keybindingsOverlay.selectBuildings,
diff --git a/src/js/game/hud/parts/mass_selector.js b/src/js/game/hud/parts/mass_selector.js
index a8972434..08a11769 100644
--- a/src/js/game/hud/parts/mass_selector.js
+++ b/src/js/game/hud/parts/mass_selector.js
@@ -48,6 +48,9 @@ export class HUDMassSelector extends BaseHUDPart {
* @param {Entity} entity
*/
onEntityDestroyed(entity) {
+ if (this.root.bulkOperationRunning) {
+ return;
+ }
this.selectedUids.delete(entity.uid);
}
@@ -90,14 +93,30 @@ export class HUDMassSelector extends BaseHUDPart {
doDelete() {
const entityUids = Array.from(this.selectedUids);
- for (let i = 0; i < entityUids.length; ++i) {
- const uid = entityUids[i];
- const entity = this.root.entityMgr.findByUid(uid);
- if (!this.root.logic.tryDeleteBuilding(entity)) {
- logger.error("Error in mass delete, could not remove building");
- this.selectedUids.delete(uid);
+
+ // Build mapping from uid to entity
+ /**
+ * @type {Map}
+ */
+ const mapUidToEntity = this.root.entityMgr.getFrozenUidSearchMap();
+
+ this.root.logic.performBulkOperation(() => {
+ for (let i = 0; i < entityUids.length; ++i) {
+ const uid = entityUids[i];
+ const entity = mapUidToEntity.get(uid);
+ if (!entity) {
+ logger.error("Entity not found by uid:", uid);
+ continue;
+ }
+
+ if (!this.root.logic.tryDeleteBuilding(entity)) {
+ logger.error("Error in mass delete, could not remove building");
+ }
}
- }
+ });
+
+ // Clear uids later
+ this.selectedUids = new Set();
}
startCopy() {
diff --git a/src/js/game/hud/parts/miner_highlight.js b/src/js/game/hud/parts/miner_highlight.js
index c2b23583..a0c6919d 100644
--- a/src/js/game/hud/parts/miner_highlight.js
+++ b/src/js/game/hud/parts/miner_highlight.js
@@ -45,6 +45,12 @@ export class HUDMinerHighlight extends BaseHUDPart {
return;
}
+ const lowerContents = this.root.map.getLowerLayerContentXY(hoveredTile.x, hoveredTile.y);
+ if (!lowerContents) {
+ // Not connected
+ return;
+ }
+
parameters.context.fillStyle = THEME.map.connectedMiners.overlay;
const connectedEntities = this.findConnectedMiners(contents);
@@ -67,7 +73,7 @@ export class HUDMinerHighlight extends BaseHUDPart {
const maxThroughput = this.root.hubGoals.getBeltBaseSpeed();
- const screenPos = this.root.camera.screenToWorld(mousePos);
+ const tooltipLocation = this.root.camera.screenToWorld(mousePos);
const scale = (1 / this.root.camera.zoomLevel) * this.root.app.getEffectiveUiScale();
@@ -76,8 +82,8 @@ export class HUDMinerHighlight extends BaseHUDPart {
// Background
parameters.context.fillStyle = THEME.map.connectedMiners.background;
parameters.context.beginRoundedRect(
- screenPos.x + 5 * scale,
- screenPos.y - 3 * scale,
+ tooltipLocation.x + 5 * scale,
+ tooltipLocation.y - 3 * scale,
(isCapped ? 100 : 65) * scale,
(isCapped ? 45 : 30) * scale,
2
@@ -89,8 +95,8 @@ export class HUDMinerHighlight extends BaseHUDPart {
parameters.context.font = "bold " + scale * 10 + "px GameFont";
parameters.context.fillText(
formatItemsPerSecond(throughput),
- screenPos.x + 10 * scale,
- screenPos.y + 10 * scale
+ tooltipLocation.x + 10 * scale,
+ tooltipLocation.y + 10 * scale
);
// Amount of miners
@@ -100,8 +106,8 @@ export class HUDMinerHighlight extends BaseHUDPart {
connectedEntities.length === 1
? T.ingame.connectedMiners.one_miner
: T.ingame.connectedMiners.n_miners.replace("", String(connectedEntities.length)),
- screenPos.x + 10 * scale,
- screenPos.y + 22 * scale
+ tooltipLocation.x + 10 * scale,
+ tooltipLocation.y + 22 * scale
);
parameters.context.globalAlpha = 1;
@@ -113,8 +119,8 @@ export class HUDMinerHighlight extends BaseHUDPart {
"",
formatItemsPerSecond(maxThroughput)
),
- screenPos.x + 10 * scale,
- screenPos.y + 34 * scale
+ tooltipLocation.x + 10 * scale,
+ tooltipLocation.y + 34 * scale
);
}
}
diff --git a/src/js/game/hud/parts/modal_dialogs.js b/src/js/game/hud/parts/modal_dialogs.js
index 95428691..06993616 100644
--- a/src/js/game/hud/parts/modal_dialogs.js
+++ b/src/js/game/hud/parts/modal_dialogs.js
@@ -1,211 +1,215 @@
-/* typehints:start */
-import { Application } from "../../../application";
-/* typehints:end */
-
-import { SOUNDS } from "../../../platform/sound";
-import { DynamicDomAttach } from "../dynamic_dom_attach";
-import { BaseHUDPart } from "../base_hud_part";
-import { Dialog, DialogLoading, DialogOptionChooser } from "../../../core/modal_dialog_elements";
-import { makeDiv } from "../../../core/utils";
-import { T } from "../../../translations";
-import { THIRDPARTY_URLS } from "../../../core/config";
-
-export class HUDModalDialogs extends BaseHUDPart {
- constructor(root, app) {
- // Important: Root is not always available here! Its also used in the main menu
- super(root);
-
- /** @type {Application} */
- this.app = root ? root.app : app;
-
- this.dialogParent = null;
- this.dialogStack = [];
- }
-
- // For use inside of the game, implementation of base hud part
- initialize() {
- this.dialogParent = document.getElementById("ingame_HUD_ModalDialogs");
- this.domWatcher = new DynamicDomAttach(this.root, this.dialogParent);
- }
-
- shouldPauseRendering() {
- return this.dialogStack.length > 0;
- }
-
- shouldPauseGame() {
- return this.shouldPauseRendering();
- }
-
- createElements(parent) {
- return makeDiv(parent, "ingame_HUD_ModalDialogs");
- }
-
- // For use outside of the game
- initializeToElement(element) {
- assert(element, "No element for dialogs given");
- this.dialogParent = element;
- }
-
- // Methods
-
- /**
- * @param {string} title
- * @param {string} text
- * @param {Array} buttons
- */
- showInfo(title, text, buttons = ["ok:good"]) {
- const dialog = new Dialog({
- app: this.app,
- title: title,
- contentHTML: text,
- buttons: buttons,
- type: "info",
- });
- this.internalShowDialog(dialog);
-
- if (this.app) {
- this.app.sound.playUiSound(SOUNDS.dialogOk);
- }
-
- return dialog.buttonSignals;
- }
-
- /**
- * @param {string} title
- * @param {string} text
- * @param {Array} buttons
- */
- showWarning(title, text, buttons = ["ok:good"]) {
- const dialog = new Dialog({
- app: this.app,
- title: title,
- contentHTML: text,
- buttons: buttons,
- type: "warning",
- });
- this.internalShowDialog(dialog);
-
- if (this.app) {
- this.app.sound.playUiSound(SOUNDS.dialogError);
- }
-
- return dialog.buttonSignals;
- }
-
- /**
- * @param {string} feature
- * @param {string} textPrefab
- */
- showFeatureRestrictionInfo(feature, textPrefab = T.dialogs.featureRestriction.desc) {
- const dialog = new Dialog({
- app: this.app,
- title: T.dialogs.featureRestriction.title,
- contentHTML: textPrefab.replace("", feature),
- buttons: ["cancel:bad", "getStandalone:good"],
- type: "warning",
- });
- this.internalShowDialog(dialog);
-
- if (this.app) {
- this.app.sound.playUiSound(SOUNDS.dialogOk);
- }
-
- this.app.analytics.trackUiClick("demo_dialog_show");
-
- dialog.buttonSignals.cancel.add(() => {
- this.app.analytics.trackUiClick("demo_dialog_cancel");
- });
-
- dialog.buttonSignals.getStandalone.add(() => {
- this.app.analytics.trackUiClick("demo_dialog_click");
- window.open(THIRDPARTY_URLS.standaloneStorePage);
- });
-
- return dialog.buttonSignals;
- }
-
- showOptionChooser(title, options) {
- const dialog = new DialogOptionChooser({
- app: this.app,
- title,
- options,
- });
- this.internalShowDialog(dialog);
- return dialog.buttonSignals;
- }
-
- // Returns method to be called when laoding finishd
- showLoadingDialog() {
- const dialog = new DialogLoading(this.app);
- this.internalShowDialog(dialog);
- return this.closeDialog.bind(this, dialog);
- }
-
- internalShowDialog(dialog) {
- const elem = dialog.createElement();
- dialog.setIndex(this.dialogStack.length);
-
- // Hide last dialog in queue
- if (this.dialogStack.length > 0) {
- this.dialogStack[this.dialogStack.length - 1].hide();
- }
-
- this.dialogStack.push(dialog);
-
- // Append dialog
- dialog.show();
- dialog.closeRequested.add(this.closeDialog.bind(this, dialog));
-
- // Append to HTML
- this.dialogParent.appendChild(elem);
-
- document.body.classList.toggle("modalDialogActive", this.dialogStack.length > 0);
-
- // IMPORTANT: Attach element directly, otherwise double submit is possible
- this.update();
- }
-
- update() {
- if (this.domWatcher) {
- this.domWatcher.update(this.dialogStack.length > 0);
- }
- }
-
- closeDialog(dialog) {
- dialog.destroy();
-
- let index = -1;
- for (let i = 0; i < this.dialogStack.length; ++i) {
- if (this.dialogStack[i] === dialog) {
- index = i;
- break;
- }
- }
- assert(index >= 0, "Dialog not in dialog stack");
- this.dialogStack.splice(index, 1);
-
- if (this.dialogStack.length > 0) {
- // Show the dialog which was previously open
- this.dialogStack[this.dialogStack.length - 1].show();
- }
-
- document.body.classList.toggle("modalDialogActive", this.dialogStack.length > 0);
- }
-
- close() {
- for (let i = 0; i < this.dialogStack.length; ++i) {
- const dialog = this.dialogStack[i];
- dialog.destroy();
- }
- this.dialogStack = [];
- }
-
- cleanup() {
- super.cleanup();
- for (let i = 0; i < this.dialogStack.length; ++i) {
- this.dialogStack[i].destroy();
- }
- this.dialogStack = [];
- this.dialogParent = null;
- }
-}
+/* typehints:start */
+import { Application } from "../../../application";
+/* typehints:end */
+
+import { SOUNDS } from "../../../platform/sound";
+import { DynamicDomAttach } from "../dynamic_dom_attach";
+import { BaseHUDPart } from "../base_hud_part";
+import { Dialog, DialogLoading, DialogOptionChooser } from "../../../core/modal_dialog_elements";
+import { makeDiv } from "../../../core/utils";
+import { T } from "../../../translations";
+import { THIRDPARTY_URLS } from "../../../core/config";
+
+export class HUDModalDialogs extends BaseHUDPart {
+ constructor(root, app) {
+ // Important: Root is not always available here! Its also used in the main menu
+ super(root);
+
+ /** @type {Application} */
+ this.app = root ? root.app : app;
+
+ this.dialogParent = null;
+ this.dialogStack = [];
+ }
+
+ // For use inside of the game, implementation of base hud part
+ initialize() {
+ this.dialogParent = document.getElementById("ingame_HUD_ModalDialogs");
+ this.domWatcher = new DynamicDomAttach(this.root, this.dialogParent);
+ }
+
+ shouldPauseRendering() {
+ return this.dialogStack.length > 0;
+ }
+
+ shouldPauseGame() {
+ return this.shouldPauseRendering();
+ }
+
+ createElements(parent) {
+ return makeDiv(parent, "ingame_HUD_ModalDialogs");
+ }
+
+ // For use outside of the game
+ initializeToElement(element) {
+ assert(element, "No element for dialogs given");
+ this.dialogParent = element;
+ }
+
+ isBlockingOverlay() {
+ return this.dialogStack.length > 0;
+ }
+
+ // Methods
+
+ /**
+ * @param {string} title
+ * @param {string} text
+ * @param {Array} buttons
+ */
+ showInfo(title, text, buttons = ["ok:good"]) {
+ const dialog = new Dialog({
+ app: this.app,
+ title: title,
+ contentHTML: text,
+ buttons: buttons,
+ type: "info",
+ });
+ this.internalShowDialog(dialog);
+
+ if (this.app) {
+ this.app.sound.playUiSound(SOUNDS.dialogOk);
+ }
+
+ return dialog.buttonSignals;
+ }
+
+ /**
+ * @param {string} title
+ * @param {string} text
+ * @param {Array} buttons
+ */
+ showWarning(title, text, buttons = ["ok:good"]) {
+ const dialog = new Dialog({
+ app: this.app,
+ title: title,
+ contentHTML: text,
+ buttons: buttons,
+ type: "warning",
+ });
+ this.internalShowDialog(dialog);
+
+ if (this.app) {
+ this.app.sound.playUiSound(SOUNDS.dialogError);
+ }
+
+ return dialog.buttonSignals;
+ }
+
+ /**
+ * @param {string} feature
+ * @param {string} textPrefab
+ */
+ showFeatureRestrictionInfo(feature, textPrefab = T.dialogs.featureRestriction.desc) {
+ const dialog = new Dialog({
+ app: this.app,
+ title: T.dialogs.featureRestriction.title,
+ contentHTML: textPrefab.replace("", feature),
+ buttons: ["cancel:bad", "getStandalone:good"],
+ type: "warning",
+ });
+ this.internalShowDialog(dialog);
+
+ if (this.app) {
+ this.app.sound.playUiSound(SOUNDS.dialogOk);
+ }
+
+ this.app.analytics.trackUiClick("demo_dialog_show");
+
+ dialog.buttonSignals.cancel.add(() => {
+ this.app.analytics.trackUiClick("demo_dialog_cancel");
+ });
+
+ dialog.buttonSignals.getStandalone.add(() => {
+ this.app.analytics.trackUiClick("demo_dialog_click");
+ window.open(THIRDPARTY_URLS.standaloneStorePage);
+ });
+
+ return dialog.buttonSignals;
+ }
+
+ showOptionChooser(title, options) {
+ const dialog = new DialogOptionChooser({
+ app: this.app,
+ title,
+ options,
+ });
+ this.internalShowDialog(dialog);
+ return dialog.buttonSignals;
+ }
+
+ // Returns method to be called when laoding finishd
+ showLoadingDialog() {
+ const dialog = new DialogLoading(this.app);
+ this.internalShowDialog(dialog);
+ return this.closeDialog.bind(this, dialog);
+ }
+
+ internalShowDialog(dialog) {
+ const elem = dialog.createElement();
+ dialog.setIndex(this.dialogStack.length);
+
+ // Hide last dialog in queue
+ if (this.dialogStack.length > 0) {
+ this.dialogStack[this.dialogStack.length - 1].hide();
+ }
+
+ this.dialogStack.push(dialog);
+
+ // Append dialog
+ dialog.show();
+ dialog.closeRequested.add(this.closeDialog.bind(this, dialog));
+
+ // Append to HTML
+ this.dialogParent.appendChild(elem);
+
+ document.body.classList.toggle("modalDialogActive", this.dialogStack.length > 0);
+
+ // IMPORTANT: Attach element directly, otherwise double submit is possible
+ this.update();
+ }
+
+ update() {
+ if (this.domWatcher) {
+ this.domWatcher.update(this.dialogStack.length > 0);
+ }
+ }
+
+ closeDialog(dialog) {
+ dialog.destroy();
+
+ let index = -1;
+ for (let i = 0; i < this.dialogStack.length; ++i) {
+ if (this.dialogStack[i] === dialog) {
+ index = i;
+ break;
+ }
+ }
+ assert(index >= 0, "Dialog not in dialog stack");
+ this.dialogStack.splice(index, 1);
+
+ if (this.dialogStack.length > 0) {
+ // Show the dialog which was previously open
+ this.dialogStack[this.dialogStack.length - 1].show();
+ }
+
+ document.body.classList.toggle("modalDialogActive", this.dialogStack.length > 0);
+ }
+
+ close() {
+ for (let i = 0; i < this.dialogStack.length; ++i) {
+ const dialog = this.dialogStack[i];
+ dialog.destroy();
+ }
+ this.dialogStack = [];
+ }
+
+ cleanup() {
+ super.cleanup();
+ for (let i = 0; i < this.dialogStack.length; ++i) {
+ this.dialogStack[i].destroy();
+ }
+ this.dialogStack = [];
+ this.dialogParent = null;
+ }
+}
diff --git a/src/js/game/hud/parts/notifications.js b/src/js/game/hud/parts/notifications.js
index aef0cc75..bef8dd0f 100644
--- a/src/js/game/hud/parts/notifications.js
+++ b/src/js/game/hud/parts/notifications.js
@@ -1,56 +1,55 @@
-import { BaseHUDPart } from "../base_hud_part";
-import { makeDiv } from "../../../core/utils";
-import { T } from "../../../translations";
-import { IS_DEMO } from "../../../core/config";
-
-/** @enum {string} */
-export const enumNotificationType = {
- saved: "saved",
- upgrade: "upgrade",
- success: "success",
-};
-
-const notificationDuration = 3;
-
-export class HUDNotifications extends BaseHUDPart {
- createElements(parent) {
- this.element = makeDiv(parent, "ingame_HUD_Notifications", [], ``);
- }
-
- initialize() {
- this.root.hud.signals.notification.add(this.onNotification, this);
-
- /** @type {Array<{ element: HTMLElement, expireAt: number}>} */
- this.notificationElements = [];
-
- // Automatic notifications
- this.root.signals.gameSaved.add(() =>
- this.onNotification(T.ingame.notifications.gameSaved, enumNotificationType.saved)
- );
- }
-
- /**
- * @param {string} message
- * @param {enumNotificationType} type
- */
- onNotification(message, type) {
- const element = makeDiv(this.element, null, ["notification", "type-" + type], message);
- element.setAttribute("data-icon", "icons/notification_" + type + ".png");
-
- this.notificationElements.push({
- element,
- expireAt: this.root.time.realtimeNow() + notificationDuration,
- });
- }
-
- update() {
- const now = this.root.time.realtimeNow();
- for (let i = 0; i < this.notificationElements.length; ++i) {
- const handle = this.notificationElements[i];
- if (handle.expireAt <= now) {
- handle.element.remove();
- this.notificationElements.splice(i, 1);
- }
- }
- }
-}
+import { makeDiv } from "../../../core/utils";
+import { T } from "../../../translations";
+import { BaseHUDPart } from "../base_hud_part";
+
+/** @enum {string} */
+export const enumNotificationType = {
+ saved: "saved",
+ upgrade: "upgrade",
+ success: "success",
+};
+
+const notificationDuration = 3;
+
+export class HUDNotifications extends BaseHUDPart {
+ createElements(parent) {
+ this.element = makeDiv(parent, "ingame_HUD_Notifications", [], ``);
+ }
+
+ initialize() {
+ this.root.hud.signals.notification.add(this.onNotification, this);
+
+ /** @type {Array<{ element: HTMLElement, expireAt: number}>} */
+ this.notificationElements = [];
+
+ // Automatic notifications
+ this.root.signals.gameSaved.add(() =>
+ this.onNotification(T.ingame.notifications.gameSaved, enumNotificationType.saved)
+ );
+ }
+
+ /**
+ * @param {string} message
+ * @param {enumNotificationType} type
+ */
+ onNotification(message, type) {
+ const element = makeDiv(this.element, null, ["notification", "type-" + type], message);
+ element.setAttribute("data-icon", "icons/notification_" + type + ".png");
+
+ this.notificationElements.push({
+ element,
+ expireAt: this.root.time.realtimeNow() + notificationDuration,
+ });
+ }
+
+ update() {
+ const now = this.root.time.realtimeNow();
+ for (let i = 0; i < this.notificationElements.length; ++i) {
+ const handle = this.notificationElements[i];
+ if (handle.expireAt <= now) {
+ handle.element.remove();
+ this.notificationElements.splice(i, 1);
+ }
+ }
+ }
+}
diff --git a/src/js/game/hud/parts/pinned_shapes.js b/src/js/game/hud/parts/pinned_shapes.js
index 2f7dd11e..c54554bf 100644
--- a/src/js/game/hud/parts/pinned_shapes.js
+++ b/src/js/game/hud/parts/pinned_shapes.js
@@ -1,291 +1,291 @@
-import { ClickDetector } from "../../../core/click_detector";
-import { formatBigNumber, makeDiv, arrayDeleteValue } from "../../../core/utils";
-import { ShapeDefinition } from "../../shape_definition";
-import { BaseHUDPart } from "../base_hud_part";
-import { blueprintShape, UPGRADES } from "../../upgrades";
-import { enumHubGoalRewards } from "../../tutorial_goals";
-
-/**
- * Manages the pinned shapes on the left side of the screen
- */
-export class HUDPinnedShapes extends BaseHUDPart {
- constructor(root) {
- super(root);
- /**
- * Store a list of pinned shapes
- * @type {Array}
- */
- this.pinnedShapes = [];
-
- /**
- * Store handles to the currently rendered elements, so we can update them more
- * convenient. Also allows for cleaning up handles.
- * @type {Array<{
- * key: string,
- * amountLabel: HTMLElement,
- * lastRenderedValue: string,
- * element: HTMLElement,
- * detector?: ClickDetector,
- * infoDetector?: ClickDetector
- * }>}
- */
- this.handles = [];
- }
-
- createElements(parent) {
- this.element = makeDiv(parent, "ingame_HUD_PinnedShapes", []);
- }
-
- /**
- * Serializes the pinned shapes
- */
- serialize() {
- return {
- shapes: this.pinnedShapes,
- };
- }
-
- /**
- * Deserializes the pinned shapes
- * @param {{ shapes: Array}} data
- */
- deserialize(data) {
- if (!data || !data.shapes || !Array.isArray(data.shapes)) {
- return "Invalid pinned shapes data";
- }
- this.pinnedShapes = data.shapes;
- }
-
- /**
- * Initializes the hud component
- */
- initialize() {
- // Connect to any relevant signals
- this.root.signals.storyGoalCompleted.add(this.rerenderFull, this);
- this.root.signals.upgradePurchased.add(this.updateShapesAfterUpgrade, this);
- this.root.signals.postLoadHook.add(this.rerenderFull, this);
- this.root.hud.signals.shapePinRequested.add(this.pinNewShape, this);
- this.root.hud.signals.shapeUnpinRequested.add(this.unpinShape, this);
-
- // Perform initial render
- this.updateShapesAfterUpgrade();
- }
-
- /**
- * Updates all shapes after an upgrade has been purchased and removes the unused ones
- */
- updateShapesAfterUpgrade() {
- for (let i = 0; i < this.pinnedShapes.length; ++i) {
- const key = this.pinnedShapes[i];
- if (key === blueprintShape) {
- // Ignore blueprint shapes
- continue;
- }
- let goal = this.findGoalValueForShape(key);
- if (!goal) {
- // Seems no longer relevant
- this.pinnedShapes.splice(i, 1);
- i -= 1;
- }
- }
-
- this.rerenderFull();
- }
-
- /**
- * Finds the current goal for the given key. If the key is the story goal, returns
- * the story goal. If its the blueprint shape, no goal is returned. Otherwise
- * it's searched for upgrades.
- * @param {string} key
- */
- findGoalValueForShape(key) {
- if (key === this.root.hubGoals.currentGoal.definition.getHash()) {
- return this.root.hubGoals.currentGoal.required;
- }
- if (key === blueprintShape) {
- return null;
- }
-
- // Check if this shape is required for any upgrade
- for (const upgradeId in UPGRADES) {
- const { tiers } = UPGRADES[upgradeId];
- const currentTier = this.root.hubGoals.getUpgradeLevel(upgradeId);
- const tierHandle = tiers[currentTier];
-
- if (!tierHandle) {
- // Max level
- continue;
- }
-
- for (let i = 0; i < tierHandle.required.length; ++i) {
- const { shape, amount } = tierHandle.required[i];
- if (shape === key) {
- return amount;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Returns whether a given shape is currently pinned
- * @param {string} key
- */
- isShapePinned(key) {
- if (key === this.root.hubGoals.currentGoal.definition.getHash() || key === blueprintShape) {
- // This is a "special" shape which is always pinned
- return true;
- }
-
- return this.pinnedShapes.indexOf(key) >= 0;
- }
-
- /**
- * Rerenders the whole component
- */
- rerenderFull() {
- const currentGoal = this.root.hubGoals.currentGoal;
- const currentKey = currentGoal.definition.getHash();
-
- // First, remove all old shapes
- for (let i = 0; i < this.handles.length; ++i) {
- this.handles[i].element.remove();
- const detector = this.handles[i].detector;
- if (detector) {
- detector.cleanup();
- }
- const infoDetector = this.handles[i].infoDetector;
- if (infoDetector) {
- infoDetector.cleanup();
- }
- }
- this.handles = [];
-
- // Pin story goal
- this.internalPinShape(currentKey, false, "goal");
-
- // Pin blueprint shape as well
- if (this.root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_blueprints)) {
- this.internalPinShape(blueprintShape, false, "blueprint");
- }
-
- // Pin manually pinned shapes
- for (let i = 0; i < this.pinnedShapes.length; ++i) {
- const key = this.pinnedShapes[i];
- if (key !== currentKey) {
- this.internalPinShape(key);
- }
- }
- }
-
- /**
- * Pins a new shape
- * @param {string} key
- * @param {boolean} canUnpin
- * @param {string=} className
- */
- internalPinShape(key, canUnpin = true, className = null) {
- const definition = this.root.shapeDefinitionMgr.getShapeFromShortKey(key);
-
- const element = makeDiv(this.element, null, ["shape"]);
- const canvas = definition.generateAsCanvas(120);
- element.appendChild(canvas);
-
- if (className) {
- element.classList.add(className);
- }
-
- let detector = null;
- if (canUnpin) {
- element.classList.add("unpinable");
- detector = new ClickDetector(element, {
- consumeEvents: true,
- preventDefault: true,
- targetOnly: true,
- });
- detector.click.add(() => this.unpinShape(key));
- } else {
- element.classList.add("marked");
- }
-
- // Show small info icon
- const infoButton = document.createElement("button");
- infoButton.classList.add("infoButton");
- element.appendChild(infoButton);
- const infoDetector = new ClickDetector(infoButton, {
- consumeEvents: true,
- preventDefault: true,
- targetOnly: true,
- });
- infoDetector.click.add(() => this.root.hud.signals.viewShapeDetailsRequested.dispatch(definition));
-
- const amountLabel = makeDiv(element, null, ["amountLabel"], "");
-
- const goal = this.findGoalValueForShape(key);
- if (goal) {
- makeDiv(element, null, ["goalLabel"], "/" + formatBigNumber(goal));
- }
-
- this.handles.push({
- key,
- element,
- amountLabel,
- lastRenderedValue: "",
- detector,
- infoDetector,
- });
- }
-
- /**
- * Updates all amount labels
- */
- update() {
- for (let i = 0; i < this.handles.length; ++i) {
- const handle = this.handles[i];
-
- const currentValue = this.root.hubGoals.getShapesStoredByKey(handle.key);
- const currentValueFormatted = formatBigNumber(currentValue);
- if (currentValueFormatted !== handle.lastRenderedValue) {
- handle.lastRenderedValue = currentValueFormatted;
- handle.amountLabel.innerText = currentValueFormatted;
- const goal = this.findGoalValueForShape(handle.key);
- handle.element.classList.toggle("completed", goal && currentValue > goal);
- }
- }
- }
-
- /**
- * Unpins a shape
- * @param {string} key
- */
- unpinShape(key) {
- arrayDeleteValue(this.pinnedShapes, key);
- this.rerenderFull();
- }
-
- /**
- * Requests to pin a new shape
- * @param {ShapeDefinition} definition
- */
- pinNewShape(definition) {
- const key = definition.getHash();
- if (key === this.root.hubGoals.currentGoal.definition.getHash()) {
- // Can not pin current goal
- return;
- }
-
- if (key === blueprintShape) {
- // Can not pin the blueprint shape
- return;
- }
-
- // Check if its already pinned
- if (this.pinnedShapes.indexOf(key) >= 0) {
- return;
- }
-
- this.pinnedShapes.push(key);
- this.rerenderFull();
- }
-}
+import { ClickDetector } from "../../../core/click_detector";
+import { formatBigNumber, makeDiv, arrayDeleteValue } from "../../../core/utils";
+import { ShapeDefinition } from "../../shape_definition";
+import { BaseHUDPart } from "../base_hud_part";
+import { blueprintShape, UPGRADES } from "../../upgrades";
+import { enumHubGoalRewards } from "../../tutorial_goals";
+
+/**
+ * Manages the pinned shapes on the left side of the screen
+ */
+export class HUDPinnedShapes extends BaseHUDPart {
+ constructor(root) {
+ super(root);
+ /**
+ * Store a list of pinned shapes
+ * @type {Array}
+ */
+ this.pinnedShapes = [];
+
+ /**
+ * Store handles to the currently rendered elements, so we can update them more
+ * convenient. Also allows for cleaning up handles.
+ * @type {Array<{
+ * key: string,
+ * amountLabel: HTMLElement,
+ * lastRenderedValue: string,
+ * element: HTMLElement,
+ * detector?: ClickDetector,
+ * infoDetector?: ClickDetector
+ * }>}
+ */
+ this.handles = [];
+ }
+
+ createElements(parent) {
+ this.element = makeDiv(parent, "ingame_HUD_PinnedShapes", []);
+ }
+
+ /**
+ * Serializes the pinned shapes
+ */
+ serialize() {
+ return {
+ shapes: this.pinnedShapes,
+ };
+ }
+
+ /**
+ * Deserializes the pinned shapes
+ * @param {{ shapes: Array}} data
+ */
+ deserialize(data) {
+ if (!data || !data.shapes || !Array.isArray(data.shapes)) {
+ return "Invalid pinned shapes data";
+ }
+ this.pinnedShapes = data.shapes;
+ }
+
+ /**
+ * Initializes the hud component
+ */
+ initialize() {
+ // Connect to any relevant signals
+ this.root.signals.storyGoalCompleted.add(this.rerenderFull, this);
+ this.root.signals.upgradePurchased.add(this.updateShapesAfterUpgrade, this);
+ this.root.signals.postLoadHook.add(this.rerenderFull, this);
+ this.root.hud.signals.shapePinRequested.add(this.pinNewShape, this);
+ this.root.hud.signals.shapeUnpinRequested.add(this.unpinShape, this);
+
+ // Perform initial render
+ this.updateShapesAfterUpgrade();
+ }
+
+ /**
+ * Updates all shapes after an upgrade has been purchased and removes the unused ones
+ */
+ updateShapesAfterUpgrade() {
+ for (let i = 0; i < this.pinnedShapes.length; ++i) {
+ const key = this.pinnedShapes[i];
+ if (key === blueprintShape) {
+ // Ignore blueprint shapes
+ continue;
+ }
+ let goal = this.findGoalValueForShape(key);
+ if (!goal) {
+ // Seems no longer relevant
+ this.pinnedShapes.splice(i, 1);
+ i -= 1;
+ }
+ }
+
+ this.rerenderFull();
+ }
+
+ /**
+ * Finds the current goal for the given key. If the key is the story goal, returns
+ * the story goal. If its the blueprint shape, no goal is returned. Otherwise
+ * it's searched for upgrades.
+ * @param {string} key
+ */
+ findGoalValueForShape(key) {
+ if (key === this.root.hubGoals.currentGoal.definition.getHash()) {
+ return this.root.hubGoals.currentGoal.required;
+ }
+ if (key === blueprintShape) {
+ return null;
+ }
+
+ // Check if this shape is required for any upgrade
+ for (const upgradeId in UPGRADES) {
+ const upgradeTiers = UPGRADES[upgradeId];
+ const currentTier = this.root.hubGoals.getUpgradeLevel(upgradeId);
+ const tierHandle = upgradeTiers[currentTier];
+
+ if (!tierHandle) {
+ // Max level
+ continue;
+ }
+
+ for (let i = 0; i < tierHandle.required.length; ++i) {
+ const { shape, amount } = tierHandle.required[i];
+ if (shape === key) {
+ return amount;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Returns whether a given shape is currently pinned
+ * @param {string} key
+ */
+ isShapePinned(key) {
+ if (key === this.root.hubGoals.currentGoal.definition.getHash() || key === blueprintShape) {
+ // This is a "special" shape which is always pinned
+ return true;
+ }
+
+ return this.pinnedShapes.indexOf(key) >= 0;
+ }
+
+ /**
+ * Rerenders the whole component
+ */
+ rerenderFull() {
+ const currentGoal = this.root.hubGoals.currentGoal;
+ const currentKey = currentGoal.definition.getHash();
+
+ // First, remove all old shapes
+ for (let i = 0; i < this.handles.length; ++i) {
+ this.handles[i].element.remove();
+ const detector = this.handles[i].detector;
+ if (detector) {
+ detector.cleanup();
+ }
+ const infoDetector = this.handles[i].infoDetector;
+ if (infoDetector) {
+ infoDetector.cleanup();
+ }
+ }
+ this.handles = [];
+
+ // Pin story goal
+ this.internalPinShape(currentKey, false, "goal");
+
+ // Pin blueprint shape as well
+ if (this.root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_blueprints)) {
+ this.internalPinShape(blueprintShape, false, "blueprint");
+ }
+
+ // Pin manually pinned shapes
+ for (let i = 0; i < this.pinnedShapes.length; ++i) {
+ const key = this.pinnedShapes[i];
+ if (key !== currentKey) {
+ this.internalPinShape(key);
+ }
+ }
+ }
+
+ /**
+ * Pins a new shape
+ * @param {string} key
+ * @param {boolean} canUnpin
+ * @param {string=} className
+ */
+ internalPinShape(key, canUnpin = true, className = null) {
+ const definition = this.root.shapeDefinitionMgr.getShapeFromShortKey(key);
+
+ const element = makeDiv(this.element, null, ["shape"]);
+ const canvas = definition.generateAsCanvas(120);
+ element.appendChild(canvas);
+
+ if (className) {
+ element.classList.add(className);
+ }
+
+ let detector = null;
+ if (canUnpin) {
+ element.classList.add("unpinable");
+ detector = new ClickDetector(element, {
+ consumeEvents: true,
+ preventDefault: true,
+ targetOnly: true,
+ });
+ detector.click.add(() => this.unpinShape(key));
+ } else {
+ element.classList.add("marked");
+ }
+
+ // Show small info icon
+ const infoButton = document.createElement("button");
+ infoButton.classList.add("infoButton");
+ element.appendChild(infoButton);
+ const infoDetector = new ClickDetector(infoButton, {
+ consumeEvents: true,
+ preventDefault: true,
+ targetOnly: true,
+ });
+ infoDetector.click.add(() => this.root.hud.signals.viewShapeDetailsRequested.dispatch(definition));
+
+ const amountLabel = makeDiv(element, null, ["amountLabel"], "");
+
+ const goal = this.findGoalValueForShape(key);
+ if (goal) {
+ makeDiv(element, null, ["goalLabel"], "/" + formatBigNumber(goal));
+ }
+
+ this.handles.push({
+ key,
+ element,
+ amountLabel,
+ lastRenderedValue: "",
+ detector,
+ infoDetector,
+ });
+ }
+
+ /**
+ * Updates all amount labels
+ */
+ update() {
+ for (let i = 0; i < this.handles.length; ++i) {
+ const handle = this.handles[i];
+
+ const currentValue = this.root.hubGoals.getShapesStoredByKey(handle.key);
+ const currentValueFormatted = formatBigNumber(currentValue);
+ if (currentValueFormatted !== handle.lastRenderedValue) {
+ handle.lastRenderedValue = currentValueFormatted;
+ handle.amountLabel.innerText = currentValueFormatted;
+ const goal = this.findGoalValueForShape(handle.key);
+ handle.element.classList.toggle("completed", goal && currentValue > goal);
+ }
+ }
+ }
+
+ /**
+ * Unpins a shape
+ * @param {string} key
+ */
+ unpinShape(key) {
+ arrayDeleteValue(this.pinnedShapes, key);
+ this.rerenderFull();
+ }
+
+ /**
+ * Requests to pin a new shape
+ * @param {ShapeDefinition} definition
+ */
+ pinNewShape(definition) {
+ const key = definition.getHash();
+ if (key === this.root.hubGoals.currentGoal.definition.getHash()) {
+ // Can not pin current goal
+ return;
+ }
+
+ if (key === blueprintShape) {
+ // Can not pin the blueprint shape
+ return;
+ }
+
+ // Check if its already pinned
+ if (this.pinnedShapes.indexOf(key) >= 0) {
+ return;
+ }
+
+ this.pinnedShapes.push(key);
+ this.rerenderFull();
+ }
+}
diff --git a/src/js/game/hud/parts/sandbox_controller.js b/src/js/game/hud/parts/sandbox_controller.js
index dd521655..c382cf84 100644
--- a/src/js/game/hud/parts/sandbox_controller.js
+++ b/src/js/game/hud/parts/sandbox_controller.js
@@ -1,158 +1,158 @@
-import { BaseHUDPart } from "../base_hud_part";
-import { makeDiv } from "../../../core/utils";
-import { DynamicDomAttach } from "../dynamic_dom_attach";
-import { blueprintShape, UPGRADES } from "../../upgrades";
-import { enumNotificationType } from "./notifications";
-import { tutorialGoals } from "../../tutorial_goals";
-
-export class HUDSandboxController extends BaseHUDPart {
- createElements(parent) {
- this.element = makeDiv(
- parent,
- "ingame_HUD_SandboxController",
- [],
- `
- Sandbox Options
- Use F6 to toggle this overlay
-
-
- `
- );
-
- const bind = (selector, handler) => this.trackClicks(this.element.querySelector(selector), handler);
-
- bind(".giveBlueprints", this.giveBlueprints);
- bind(".maxOutAll", this.maxOutAll);
- bind(".levelToggle .minus", () => this.modifyLevel(-1));
- bind(".levelToggle .plus", () => this.modifyLevel(1));
-
- bind(".upgradesBelt .minus", () => this.modifyUpgrade("belt", -1));
- bind(".upgradesBelt .plus", () => this.modifyUpgrade("belt", 1));
-
- bind(".upgradesExtraction .minus", () => this.modifyUpgrade("miner", -1));
- bind(".upgradesExtraction .plus", () => this.modifyUpgrade("miner", 1));
-
- bind(".upgradesProcessing .minus", () => this.modifyUpgrade("processors", -1));
- bind(".upgradesProcessing .plus", () => this.modifyUpgrade("processors", 1));
-
- bind(".upgradesPainting .minus", () => this.modifyUpgrade("painting", -1));
- bind(".upgradesPainting .plus", () => this.modifyUpgrade("painting", 1));
- }
-
- giveBlueprints() {
- if (!this.root.hubGoals.storedShapes[blueprintShape]) {
- this.root.hubGoals.storedShapes[blueprintShape] = 0;
- }
- this.root.hubGoals.storedShapes[blueprintShape] += 1e9;
- }
-
- maxOutAll() {
- this.modifyUpgrade("belt", 100);
- this.modifyUpgrade("miner", 100);
- this.modifyUpgrade("processors", 100);
- this.modifyUpgrade("painting", 100);
- }
-
- modifyUpgrade(id, amount) {
- const handle = UPGRADES[id];
- const maxLevel = handle.tiers.length;
-
- this.root.hubGoals.upgradeLevels[id] = Math.max(
- 0,
- Math.min(maxLevel, (this.root.hubGoals.upgradeLevels[id] || 0) + amount)
- );
-
- // Compute improvement
- let improvement = 1;
- for (let i = 0; i < this.root.hubGoals.upgradeLevels[id]; ++i) {
- improvement += handle.tiers[i].improvement;
- }
- this.root.hubGoals.upgradeImprovements[id] = improvement;
- this.root.signals.upgradePurchased.dispatch(id);
- this.root.hud.signals.notification.dispatch(
- "Upgrade '" + id + "' is now at tier " + (this.root.hubGoals.upgradeLevels[id] + 1),
- enumNotificationType.upgrade
- );
- }
-
- modifyLevel(amount) {
- const hubGoals = this.root.hubGoals;
- hubGoals.level = Math.max(1, hubGoals.level + amount);
- hubGoals.createNextGoal();
-
- // Clear all shapes of this level
- hubGoals.storedShapes[hubGoals.currentGoal.definition.getHash()] = 0;
-
- this.root.hud.parts.pinnedShapes.rerenderFull();
-
- // Compute gained rewards
- hubGoals.gainedRewards = {};
- for (let i = 0; i < hubGoals.level - 1; ++i) {
- if (i < tutorialGoals.length) {
- const reward = tutorialGoals[i].reward;
- hubGoals.gainedRewards[reward] = (hubGoals.gainedRewards[reward] || 0) + 1;
- }
- }
-
- this.root.hud.signals.notification.dispatch(
- "Changed level to " + hubGoals.level,
- enumNotificationType.upgrade
- );
- }
-
- initialize() {
- // Allow toggling the controller overlay
- this.root.gameState.inputReciever.keydown.add(key => {
- if (key.keyCode === 117) {
- // F6
- this.toggle();
- }
- });
-
- this.visible = !G_IS_DEV;
- this.domAttach = new DynamicDomAttach(this.root, this.element);
- }
-
- toggle() {
- this.visible = !this.visible;
- }
-
- update() {
- this.domAttach.update(this.visible);
- }
-}
+import { BaseHUDPart } from "../base_hud_part";
+import { makeDiv } from "../../../core/utils";
+import { DynamicDomAttach } from "../dynamic_dom_attach";
+import { blueprintShape, UPGRADES } from "../../upgrades";
+import { enumNotificationType } from "./notifications";
+import { tutorialGoals } from "../../tutorial_goals";
+
+export class HUDSandboxController extends BaseHUDPart {
+ createElements(parent) {
+ this.element = makeDiv(
+ parent,
+ "ingame_HUD_SandboxController",
+ [],
+ `
+ Sandbox Options
+ Use F6 to toggle this overlay
+
+
+ `
+ );
+
+ const bind = (selector, handler) => this.trackClicks(this.element.querySelector(selector), handler);
+
+ bind(".giveBlueprints", this.giveBlueprints);
+ bind(".maxOutAll", this.maxOutAll);
+ bind(".levelToggle .minus", () => this.modifyLevel(-1));
+ bind(".levelToggle .plus", () => this.modifyLevel(1));
+
+ bind(".upgradesBelt .minus", () => this.modifyUpgrade("belt", -1));
+ bind(".upgradesBelt .plus", () => this.modifyUpgrade("belt", 1));
+
+ bind(".upgradesExtraction .minus", () => this.modifyUpgrade("miner", -1));
+ bind(".upgradesExtraction .plus", () => this.modifyUpgrade("miner", 1));
+
+ bind(".upgradesProcessing .minus", () => this.modifyUpgrade("processors", -1));
+ bind(".upgradesProcessing .plus", () => this.modifyUpgrade("processors", 1));
+
+ bind(".upgradesPainting .minus", () => this.modifyUpgrade("painting", -1));
+ bind(".upgradesPainting .plus", () => this.modifyUpgrade("painting", 1));
+ }
+
+ giveBlueprints() {
+ if (!this.root.hubGoals.storedShapes[blueprintShape]) {
+ this.root.hubGoals.storedShapes[blueprintShape] = 0;
+ }
+ this.root.hubGoals.storedShapes[blueprintShape] += 1e9;
+ }
+
+ maxOutAll() {
+ this.modifyUpgrade("belt", 100);
+ this.modifyUpgrade("miner", 100);
+ this.modifyUpgrade("processors", 100);
+ this.modifyUpgrade("painting", 100);
+ }
+
+ modifyUpgrade(id, amount) {
+ const upgradeTiers = UPGRADES[id];
+ const maxLevel = upgradeTiers.length;
+
+ this.root.hubGoals.upgradeLevels[id] = Math.max(
+ 0,
+ Math.min(maxLevel, (this.root.hubGoals.upgradeLevels[id] || 0) + amount)
+ );
+
+ // Compute improvement
+ let improvement = 1;
+ for (let i = 0; i < this.root.hubGoals.upgradeLevels[id]; ++i) {
+ improvement += upgradeTiers[i].improvement;
+ }
+ this.root.hubGoals.upgradeImprovements[id] = improvement;
+ this.root.signals.upgradePurchased.dispatch(id);
+ this.root.hud.signals.notification.dispatch(
+ "Upgrade '" + id + "' is now at tier " + (this.root.hubGoals.upgradeLevels[id] + 1),
+ enumNotificationType.upgrade
+ );
+ }
+
+ modifyLevel(amount) {
+ const hubGoals = this.root.hubGoals;
+ hubGoals.level = Math.max(1, hubGoals.level + amount);
+ hubGoals.createNextGoal();
+
+ // Clear all shapes of this level
+ hubGoals.storedShapes[hubGoals.currentGoal.definition.getHash()] = 0;
+
+ this.root.hud.parts.pinnedShapes.rerenderFull();
+
+ // Compute gained rewards
+ hubGoals.gainedRewards = {};
+ for (let i = 0; i < hubGoals.level - 1; ++i) {
+ if (i < tutorialGoals.length) {
+ const reward = tutorialGoals[i].reward;
+ hubGoals.gainedRewards[reward] = (hubGoals.gainedRewards[reward] || 0) + 1;
+ }
+ }
+
+ this.root.hud.signals.notification.dispatch(
+ "Changed level to " + hubGoals.level,
+ enumNotificationType.upgrade
+ );
+ }
+
+ initialize() {
+ // Allow toggling the controller overlay
+ this.root.gameState.inputReciever.keydown.add(key => {
+ if (key.keyCode === 117) {
+ // F6
+ this.toggle();
+ }
+ });
+
+ this.visible = !G_IS_DEV;
+ this.domAttach = new DynamicDomAttach(this.root, this.element);
+ }
+
+ toggle() {
+ this.visible = !this.visible;
+ }
+
+ update() {
+ this.domAttach.update(this.visible);
+ }
+}
diff --git a/src/js/game/hud/parts/screenshot_exporter.js b/src/js/game/hud/parts/screenshot_exporter.js
index a3310204..59e76c63 100644
--- a/src/js/game/hud/parts/screenshot_exporter.js
+++ b/src/js/game/hud/parts/screenshot_exporter.js
@@ -87,7 +87,7 @@ export class HUDScreenshotExporter extends BaseHUDPart {
const parameters = new DrawParameters({
context,
visibleRect,
- desiredAtlasScale: "1",
+ desiredAtlasScale: chunkScale,
root: this.root,
zoomLevel: chunkScale,
});
diff --git a/src/js/game/hud/parts/settings_menu.js b/src/js/game/hud/parts/settings_menu.js
index 391fde01..31afe348 100644
--- a/src/js/game/hud/parts/settings_menu.js
+++ b/src/js/game/hud/parts/settings_menu.js
@@ -1,127 +1,131 @@
-import { BaseHUDPart } from "../base_hud_part";
-import { makeDiv, formatBigNumberFull } from "../../../core/utils";
-import { DynamicDomAttach } from "../dynamic_dom_attach";
-import { InputReceiver } from "../../../core/input_receiver";
-import { KeyActionMapper, KEYMAPPINGS } from "../../key_action_mapper";
-import { T } from "../../../translations";
-import { StaticMapEntityComponent } from "../../components/static_map_entity";
-import { BeltComponent } from "../../components/belt";
-
-export class HUDSettingsMenu extends BaseHUDPart {
- createElements(parent) {
- this.background = makeDiv(parent, "ingame_HUD_SettingsMenu", ["ingameDialog"]);
-
- this.menuElement = makeDiv(this.background, null, ["menuElement"]);
-
- this.statsElement = makeDiv(
- this.background,
- null,
- ["statsElement"],
- `
- ${T.ingame.settingsMenu.beltsPlaced}
- ${T.ingame.settingsMenu.buildingsPlaced}
- ${T.ingame.settingsMenu.playtime}
-
- `
- );
-
- this.buttonContainer = makeDiv(this.menuElement, null, ["buttons"]);
-
- const buttons = [
- {
- title: T.ingame.settingsMenu.buttons.continue,
- action: () => this.close(),
- },
- {
- title: T.ingame.settingsMenu.buttons.settings,
- action: () => this.goToSettings(),
- },
- {
- title: T.ingame.settingsMenu.buttons.menu,
- action: () => this.returnToMenu(),
- },
- ];
-
- for (let i = 0; i < buttons.length; ++i) {
- const { title, action } = buttons[i];
-
- const element = document.createElement("button");
- element.classList.add("styledButton");
- element.innerText = title;
- this.buttonContainer.appendChild(element);
-
- this.trackClicks(element, action);
- }
- }
-
- returnToMenu() {
- this.root.gameState.goBackToMenu();
- }
-
- goToSettings() {
- this.root.gameState.goToSettings();
- }
-
- shouldPauseGame() {
- return this.visible;
- }
-
- shouldPauseRendering() {
- return this.visible;
- }
-
- initialize() {
- this.root.keyMapper.getBinding(KEYMAPPINGS.general.back).add(this.show, this);
-
- this.domAttach = new DynamicDomAttach(this.root, this.background, {
- attachClass: "visible",
- });
-
- this.inputReciever = new InputReceiver("settingsmenu");
- this.keyActionMapper = new KeyActionMapper(this.root, this.inputReciever);
- this.keyActionMapper.getBinding(KEYMAPPINGS.general.back).add(this.close, this);
-
- this.close();
- }
-
- cleanup() {
- document.body.classList.remove("ingameDialogOpen");
- }
-
- show() {
- this.visible = true;
- document.body.classList.add("ingameDialogOpen");
- this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever);
-
- const totalMinutesPlayed = Math.ceil(this.root.time.now() / 60);
-
- /** @type {HTMLElement} */
- const playtimeElement = this.statsElement.querySelector(".playtime");
- /** @type {HTMLElement} */
- const buildingsPlacedElement = this.statsElement.querySelector(".buildingsPlaced");
- /** @type {HTMLElement} */
- const beltsPlacedElement = this.statsElement.querySelector(".beltsPlaced");
-
- playtimeElement.innerText = T.global.time.xMinutes.replace("", `${totalMinutesPlayed}`);
-
- buildingsPlacedElement.innerText = formatBigNumberFull(
- this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent).length -
- this.root.entityMgr.getAllWithComponent(BeltComponent).length
- );
-
- beltsPlacedElement.innerText = formatBigNumberFull(
- this.root.entityMgr.getAllWithComponent(BeltComponent).length
- );
- }
-
- close() {
- this.visible = false;
- document.body.classList.remove("ingameDialogOpen");
- this.root.app.inputMgr.makeSureDetached(this.inputReciever);
- this.update();
- }
-
- update() {
- this.domAttach.update(this.visible);
- }
-}
+import { BaseHUDPart } from "../base_hud_part";
+import { makeDiv, formatBigNumberFull } from "../../../core/utils";
+import { DynamicDomAttach } from "../dynamic_dom_attach";
+import { InputReceiver } from "../../../core/input_receiver";
+import { KeyActionMapper, KEYMAPPINGS } from "../../key_action_mapper";
+import { T } from "../../../translations";
+import { StaticMapEntityComponent } from "../../components/static_map_entity";
+import { BeltComponent } from "../../components/belt";
+
+export class HUDSettingsMenu extends BaseHUDPart {
+ createElements(parent) {
+ this.background = makeDiv(parent, "ingame_HUD_SettingsMenu", ["ingameDialog"]);
+
+ this.menuElement = makeDiv(this.background, null, ["menuElement"]);
+
+ this.statsElement = makeDiv(
+ this.background,
+ null,
+ ["statsElement"],
+ `
+ ${T.ingame.settingsMenu.beltsPlaced}
+ ${T.ingame.settingsMenu.buildingsPlaced}
+ ${T.ingame.settingsMenu.playtime}
+
+ `
+ );
+
+ this.buttonContainer = makeDiv(this.menuElement, null, ["buttons"]);
+
+ const buttons = [
+ {
+ id: "continue",
+ action: () => this.close(),
+ },
+ {
+ id: "settings",
+ action: () => this.goToSettings(),
+ },
+ {
+ id: "menu",
+ action: () => this.returnToMenu(),
+ },
+ ];
+
+ for (let i = 0; i < buttons.length; ++i) {
+ const { title, action, id } = buttons[i];
+
+ const element = document.createElement("button");
+ element.classList.add("styledButton");
+ element.classList.add(id);
+ this.buttonContainer.appendChild(element);
+
+ this.trackClicks(element, action);
+ }
+ }
+
+ isBlockingOverlay() {
+ return this.visible;
+ }
+
+ returnToMenu() {
+ this.root.gameState.goBackToMenu();
+ }
+
+ goToSettings() {
+ this.root.gameState.goToSettings();
+ }
+
+ shouldPauseGame() {
+ return this.visible;
+ }
+
+ shouldPauseRendering() {
+ return this.visible;
+ }
+
+ initialize() {
+ this.root.keyMapper.getBinding(KEYMAPPINGS.general.back).add(this.show, this);
+
+ this.domAttach = new DynamicDomAttach(this.root, this.background, {
+ attachClass: "visible",
+ });
+
+ this.inputReciever = new InputReceiver("settingsmenu");
+ this.keyActionMapper = new KeyActionMapper(this.root, this.inputReciever);
+ this.keyActionMapper.getBinding(KEYMAPPINGS.general.back).add(this.close, this);
+
+ this.close();
+ }
+
+ cleanup() {
+ document.body.classList.remove("ingameDialogOpen");
+ }
+
+ show() {
+ this.visible = true;
+ document.body.classList.add("ingameDialogOpen");
+ this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever);
+
+ const totalMinutesPlayed = Math.ceil(this.root.time.now() / 60);
+
+ /** @type {HTMLElement} */
+ const playtimeElement = this.statsElement.querySelector(".playtime");
+ /** @type {HTMLElement} */
+ const buildingsPlacedElement = this.statsElement.querySelector(".buildingsPlaced");
+ /** @type {HTMLElement} */
+ const beltsPlacedElement = this.statsElement.querySelector(".beltsPlaced");
+
+ playtimeElement.innerText = T.global.time.xMinutes.replace("", `${totalMinutesPlayed}`);
+
+ buildingsPlacedElement.innerText = formatBigNumberFull(
+ this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent).length -
+ this.root.entityMgr.getAllWithComponent(BeltComponent).length
+ );
+
+ beltsPlacedElement.innerText = formatBigNumberFull(
+ this.root.entityMgr.getAllWithComponent(BeltComponent).length
+ );
+ }
+
+ close() {
+ this.visible = false;
+ document.body.classList.remove("ingameDialogOpen");
+ this.root.app.inputMgr.makeSureDetached(this.inputReciever);
+ this.update();
+ }
+
+ update() {
+ this.domAttach.update(this.visible);
+ }
+}
diff --git a/src/js/game/hud/parts/shape_viewer.js b/src/js/game/hud/parts/shape_viewer.js
index ea4273aa..18f55c74 100644
--- a/src/js/game/hud/parts/shape_viewer.js
+++ b/src/js/game/hud/parts/shape_viewer.js
@@ -48,6 +48,10 @@ export class HUDShapeViewer extends BaseHUDPart {
this.close();
}
+ isBlockingOverlay() {
+ return this.visible;
+ }
+
/**
* Called when the copying of a key was requested
*/
diff --git a/src/js/game/hud/parts/shop.js b/src/js/game/hud/parts/shop.js
index e2b8837b..cfa78c29 100644
--- a/src/js/game/hud/parts/shop.js
+++ b/src/js/game/hud/parts/shop.js
@@ -1,251 +1,255 @@
-import { ClickDetector } from "../../../core/click_detector";
-import { InputReceiver } from "../../../core/input_receiver";
-import { formatBigNumber, makeDiv } from "../../../core/utils";
-import { T } from "../../../translations";
-import { KeyActionMapper, KEYMAPPINGS } from "../../key_action_mapper";
-import { UPGRADES } from "../../upgrades";
-import { BaseHUDPart } from "../base_hud_part";
-import { DynamicDomAttach } from "../dynamic_dom_attach";
-
-export class HUDShop extends BaseHUDPart {
- createElements(parent) {
- this.background = makeDiv(parent, "ingame_HUD_Shop", ["ingameDialog"]);
-
- // DIALOG Inner / Wrapper
- this.dialogInner = makeDiv(this.background, null, ["dialogInner"]);
- this.title = makeDiv(this.dialogInner, null, ["title"], T.ingame.shop.title);
- this.closeButton = makeDiv(this.title, null, ["closeButton"]);
- this.trackClicks(this.closeButton, this.close);
- this.contentDiv = makeDiv(this.dialogInner, null, ["content"]);
-
- this.upgradeToElements = {};
-
- // Upgrades
- for (const upgradeId in UPGRADES) {
- const handle = {};
- handle.requireIndexToElement = [];
-
- // Wrapper
- handle.elem = makeDiv(this.contentDiv, null, ["upgrade"]);
- handle.elem.setAttribute("data-upgrade-id", upgradeId);
-
- // Title
- const title = makeDiv(handle.elem, null, ["title"], T.shopUpgrades[upgradeId].name);
-
- // Title > Tier
- handle.elemTierLabel = makeDiv(title, null, ["tier"]);
-
- // Icon
- handle.icon = makeDiv(handle.elem, null, ["icon"]);
- handle.icon.setAttribute("data-icon", "upgrades/" + upgradeId + ".png");
-
- // Description
- handle.elemDescription = makeDiv(handle.elem, null, ["description"], "??");
- handle.elemRequirements = makeDiv(handle.elem, null, ["requirements"]);
-
- // Buy button
- handle.buyButton = document.createElement("button");
- handle.buyButton.classList.add("buy", "styledButton");
- handle.buyButton.innerText = T.ingame.shop.buttonUnlock;
- handle.elem.appendChild(handle.buyButton);
-
- this.trackClicks(handle.buyButton, () => this.tryUnlockNextTier(upgradeId));
-
- // Assign handle
- this.upgradeToElements[upgradeId] = handle;
- }
- }
-
- rerenderFull() {
- for (const upgradeId in this.upgradeToElements) {
- const handle = this.upgradeToElements[upgradeId];
- const { tiers } = UPGRADES[upgradeId];
-
- const currentTier = this.root.hubGoals.getUpgradeLevel(upgradeId);
- const currentTierMultiplier = this.root.hubGoals.upgradeImprovements[upgradeId];
- const tierHandle = tiers[currentTier];
-
- // Set tier
- handle.elemTierLabel.innerText = T.ingame.shop.tier.replace(
- "",
- "" + T.ingame.shop.tierLabels[currentTier]
- );
-
- handle.elemTierLabel.setAttribute("data-tier", currentTier);
-
- // Cleanup detectors
- for (let i = 0; i < handle.requireIndexToElement.length; ++i) {
- const requiredHandle = handle.requireIndexToElement[i];
- requiredHandle.container.remove();
- requiredHandle.pinDetector.cleanup();
- requiredHandle.infoDetector.cleanup();
- }
-
- // Cleanup
- handle.requireIndexToElement = [];
-
- handle.elem.classList.toggle("maxLevel", !tierHandle);
-
- if (!tierHandle) {
- // Max level
- handle.elemDescription.innerText = T.ingame.shop.maximumLevel.replace(
- "",
- currentTierMultiplier.toString()
- );
- continue;
- }
-
- // Set description
- handle.elemDescription.innerText = T.shopUpgrades[upgradeId].description
- .replace("", currentTierMultiplier.toString())
- .replace("", (currentTierMultiplier + tierHandle.improvement).toString())
- // Backwards compatibility
- .replace("", (tierHandle.improvement * 100.0).toString());
-
- tierHandle.required.forEach(({ shape, amount }) => {
- const container = makeDiv(handle.elemRequirements, null, ["requirement"]);
-
- const shapeDef = this.root.shapeDefinitionMgr.getShapeFromShortKey(shape);
- const shapeCanvas = shapeDef.generateAsCanvas(120);
- shapeCanvas.classList.add();
- container.appendChild(shapeCanvas);
-
- const progressContainer = makeDiv(container, null, ["amount"]);
- const progressBar = document.createElement("label");
- progressBar.classList.add("progressBar");
- progressContainer.appendChild(progressBar);
-
- const progressLabel = document.createElement("label");
- progressContainer.appendChild(progressLabel);
-
- const pinButton = document.createElement("button");
- pinButton.classList.add("pin");
- container.appendChild(pinButton);
-
- const viewInfoButton = document.createElement("button");
- viewInfoButton.classList.add("showInfo");
- container.appendChild(viewInfoButton);
-
- const currentGoalShape = this.root.hubGoals.currentGoal.definition.getHash();
- if (shape === currentGoalShape) {
- pinButton.classList.add("isGoal");
- } else if (this.root.hud.parts.pinnedShapes.isShapePinned(shape)) {
- pinButton.classList.add("alreadyPinned");
- }
-
- const pinDetector = new ClickDetector(pinButton, {
- consumeEvents: true,
- preventDefault: true,
- });
- pinDetector.click.add(() => {
- if (this.root.hud.parts.pinnedShapes.isShapePinned(shape)) {
- this.root.hud.signals.shapeUnpinRequested.dispatch(shape);
- pinButton.classList.add("unpinned");
- pinButton.classList.remove("pinned", "alreadyPinned");
- } else {
- this.root.hud.signals.shapePinRequested.dispatch(shapeDef);
- pinButton.classList.add("pinned");
- pinButton.classList.remove("unpinned");
- }
- });
-
- const infoDetector = new ClickDetector(viewInfoButton, {
- consumeEvents: true,
- preventDefault: true,
- });
- infoDetector.click.add(() =>
- this.root.hud.signals.viewShapeDetailsRequested.dispatch(shapeDef)
- );
-
- handle.requireIndexToElement.push({
- container,
- progressLabel,
- progressBar,
- definition: shapeDef,
- required: amount,
- pinDetector,
- infoDetector,
- });
- });
- }
- }
-
- renderCountsAndStatus() {
- for (const upgradeId in this.upgradeToElements) {
- const handle = this.upgradeToElements[upgradeId];
- for (let i = 0; i < handle.requireIndexToElement.length; ++i) {
- const { progressLabel, progressBar, definition, required } = handle.requireIndexToElement[i];
-
- const haveAmount = this.root.hubGoals.getShapesStored(definition);
- const progress = Math.min(haveAmount / required, 1.0);
-
- progressLabel.innerText = formatBigNumber(haveAmount) + " / " + formatBigNumber(required);
- progressBar.style.width = progress * 100.0 + "%";
- progressBar.classList.toggle("complete", progress >= 1.0);
- }
-
- handle.buyButton.classList.toggle("buyable", this.root.hubGoals.canUnlockUpgrade(upgradeId));
- }
- }
-
- initialize() {
- this.domAttach = new DynamicDomAttach(this.root, this.background, {
- attachClass: "visible",
- });
-
- this.inputReciever = new InputReceiver("shop");
- this.keyActionMapper = new KeyActionMapper(this.root, this.inputReciever);
-
- this.keyActionMapper.getBinding(KEYMAPPINGS.general.back).add(this.close, this);
- this.keyActionMapper.getBinding(KEYMAPPINGS.ingame.menuClose).add(this.close, this);
- this.keyActionMapper.getBinding(KEYMAPPINGS.ingame.menuOpenShop).add(this.close, this);
-
- this.close();
-
- this.rerenderFull();
- this.root.signals.upgradePurchased.add(this.rerenderFull, this);
- }
-
- cleanup() {
- document.body.classList.remove("ingameDialogOpen");
-
- // Cleanup detectors
- for (const upgradeId in this.upgradeToElements) {
- const handle = this.upgradeToElements[upgradeId];
- for (let i = 0; i < handle.requireIndexToElement.length; ++i) {
- const requiredHandle = handle.requireIndexToElement[i];
- requiredHandle.container.remove();
- requiredHandle.pinDetector.cleanup();
- requiredHandle.infoDetector.cleanup();
- }
- handle.requireIndexToElement = [];
- }
- }
-
- show() {
- this.visible = true;
- document.body.classList.add("ingameDialogOpen");
- // this.background.classList.add("visible");
- this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever);
- this.rerenderFull();
- }
-
- close() {
- this.visible = false;
- document.body.classList.remove("ingameDialogOpen");
- this.root.app.inputMgr.makeSureDetached(this.inputReciever);
- this.update();
- }
-
- update() {
- this.domAttach.update(this.visible);
- if (this.visible) {
- this.renderCountsAndStatus();
- }
- }
-
- tryUnlockNextTier(upgradeId) {
- // Nothing
- this.root.hubGoals.tryUnlockUpgrade(upgradeId);
- }
-}
+import { ClickDetector } from "../../../core/click_detector";
+import { InputReceiver } from "../../../core/input_receiver";
+import { formatBigNumber, makeDiv } from "../../../core/utils";
+import { T } from "../../../translations";
+import { KeyActionMapper, KEYMAPPINGS } from "../../key_action_mapper";
+import { UPGRADES } from "../../upgrades";
+import { BaseHUDPart } from "../base_hud_part";
+import { DynamicDomAttach } from "../dynamic_dom_attach";
+
+export class HUDShop extends BaseHUDPart {
+ createElements(parent) {
+ this.background = makeDiv(parent, "ingame_HUD_Shop", ["ingameDialog"]);
+
+ // DIALOG Inner / Wrapper
+ this.dialogInner = makeDiv(this.background, null, ["dialogInner"]);
+ this.title = makeDiv(this.dialogInner, null, ["title"], T.ingame.shop.title);
+ this.closeButton = makeDiv(this.title, null, ["closeButton"]);
+ this.trackClicks(this.closeButton, this.close);
+ this.contentDiv = makeDiv(this.dialogInner, null, ["content"]);
+
+ this.upgradeToElements = {};
+
+ // Upgrades
+ for (const upgradeId in UPGRADES) {
+ const handle = {};
+ handle.requireIndexToElement = [];
+
+ // Wrapper
+ handle.elem = makeDiv(this.contentDiv, null, ["upgrade"]);
+ handle.elem.setAttribute("data-upgrade-id", upgradeId);
+
+ // Title
+ const title = makeDiv(handle.elem, null, ["title"], T.shopUpgrades[upgradeId].name);
+
+ // Title > Tier
+ handle.elemTierLabel = makeDiv(title, null, ["tier"]);
+
+ // Icon
+ handle.icon = makeDiv(handle.elem, null, ["icon"]);
+ handle.icon.setAttribute("data-icon", "upgrades/" + upgradeId + ".png");
+
+ // Description
+ handle.elemDescription = makeDiv(handle.elem, null, ["description"], "??");
+ handle.elemRequirements = makeDiv(handle.elem, null, ["requirements"]);
+
+ // Buy button
+ handle.buyButton = document.createElement("button");
+ handle.buyButton.classList.add("buy", "styledButton");
+ handle.buyButton.innerText = T.ingame.shop.buttonUnlock;
+ handle.elem.appendChild(handle.buyButton);
+
+ this.trackClicks(handle.buyButton, () => this.tryUnlockNextTier(upgradeId));
+
+ // Assign handle
+ this.upgradeToElements[upgradeId] = handle;
+ }
+ }
+
+ rerenderFull() {
+ for (const upgradeId in this.upgradeToElements) {
+ const handle = this.upgradeToElements[upgradeId];
+ const upgradeTiers = UPGRADES[upgradeId];
+
+ const currentTier = this.root.hubGoals.getUpgradeLevel(upgradeId);
+ const currentTierMultiplier = this.root.hubGoals.upgradeImprovements[upgradeId];
+ const tierHandle = upgradeTiers[currentTier];
+
+ // Set tier
+ handle.elemTierLabel.innerText = T.ingame.shop.tier.replace(
+ "",
+ "" + T.ingame.shop.tierLabels[currentTier]
+ );
+
+ handle.elemTierLabel.setAttribute("data-tier", currentTier);
+
+ // Cleanup detectors
+ for (let i = 0; i < handle.requireIndexToElement.length; ++i) {
+ const requiredHandle = handle.requireIndexToElement[i];
+ requiredHandle.container.remove();
+ requiredHandle.pinDetector.cleanup();
+ requiredHandle.infoDetector.cleanup();
+ }
+
+ // Cleanup
+ handle.requireIndexToElement = [];
+
+ handle.elem.classList.toggle("maxLevel", !tierHandle);
+
+ if (!tierHandle) {
+ // Max level
+ handle.elemDescription.innerText = T.ingame.shop.maximumLevel.replace(
+ "",
+ currentTierMultiplier.toString()
+ );
+ continue;
+ }
+
+ // Set description
+ handle.elemDescription.innerText = T.shopUpgrades[upgradeId].description
+ .replace("", currentTierMultiplier.toString())
+ .replace("", (currentTierMultiplier + tierHandle.improvement).toString())
+ // Backwards compatibility
+ .replace("", (tierHandle.improvement * 100.0).toString());
+
+ tierHandle.required.forEach(({ shape, amount }) => {
+ const container = makeDiv(handle.elemRequirements, null, ["requirement"]);
+
+ const shapeDef = this.root.shapeDefinitionMgr.getShapeFromShortKey(shape);
+ const shapeCanvas = shapeDef.generateAsCanvas(120);
+ shapeCanvas.classList.add();
+ container.appendChild(shapeCanvas);
+
+ const progressContainer = makeDiv(container, null, ["amount"]);
+ const progressBar = document.createElement("label");
+ progressBar.classList.add("progressBar");
+ progressContainer.appendChild(progressBar);
+
+ const progressLabel = document.createElement("label");
+ progressContainer.appendChild(progressLabel);
+
+ const pinButton = document.createElement("button");
+ pinButton.classList.add("pin");
+ container.appendChild(pinButton);
+
+ const viewInfoButton = document.createElement("button");
+ viewInfoButton.classList.add("showInfo");
+ container.appendChild(viewInfoButton);
+
+ const currentGoalShape = this.root.hubGoals.currentGoal.definition.getHash();
+ if (shape === currentGoalShape) {
+ pinButton.classList.add("isGoal");
+ } else if (this.root.hud.parts.pinnedShapes.isShapePinned(shape)) {
+ pinButton.classList.add("alreadyPinned");
+ }
+
+ const pinDetector = new ClickDetector(pinButton, {
+ consumeEvents: true,
+ preventDefault: true,
+ });
+ pinDetector.click.add(() => {
+ if (this.root.hud.parts.pinnedShapes.isShapePinned(shape)) {
+ this.root.hud.signals.shapeUnpinRequested.dispatch(shape);
+ pinButton.classList.add("unpinned");
+ pinButton.classList.remove("pinned", "alreadyPinned");
+ } else {
+ this.root.hud.signals.shapePinRequested.dispatch(shapeDef);
+ pinButton.classList.add("pinned");
+ pinButton.classList.remove("unpinned");
+ }
+ });
+
+ const infoDetector = new ClickDetector(viewInfoButton, {
+ consumeEvents: true,
+ preventDefault: true,
+ });
+ infoDetector.click.add(() =>
+ this.root.hud.signals.viewShapeDetailsRequested.dispatch(shapeDef)
+ );
+
+ handle.requireIndexToElement.push({
+ container,
+ progressLabel,
+ progressBar,
+ definition: shapeDef,
+ required: amount,
+ pinDetector,
+ infoDetector,
+ });
+ });
+ }
+ }
+
+ renderCountsAndStatus() {
+ for (const upgradeId in this.upgradeToElements) {
+ const handle = this.upgradeToElements[upgradeId];
+ for (let i = 0; i < handle.requireIndexToElement.length; ++i) {
+ const { progressLabel, progressBar, definition, required } = handle.requireIndexToElement[i];
+
+ const haveAmount = this.root.hubGoals.getShapesStored(definition);
+ const progress = Math.min(haveAmount / required, 1.0);
+
+ progressLabel.innerText = formatBigNumber(haveAmount) + " / " + formatBigNumber(required);
+ progressBar.style.width = progress * 100.0 + "%";
+ progressBar.classList.toggle("complete", progress >= 1.0);
+ }
+
+ handle.buyButton.classList.toggle("buyable", this.root.hubGoals.canUnlockUpgrade(upgradeId));
+ }
+ }
+
+ initialize() {
+ this.domAttach = new DynamicDomAttach(this.root, this.background, {
+ attachClass: "visible",
+ });
+
+ this.inputReciever = new InputReceiver("shop");
+ this.keyActionMapper = new KeyActionMapper(this.root, this.inputReciever);
+
+ this.keyActionMapper.getBinding(KEYMAPPINGS.general.back).add(this.close, this);
+ this.keyActionMapper.getBinding(KEYMAPPINGS.ingame.menuClose).add(this.close, this);
+ this.keyActionMapper.getBinding(KEYMAPPINGS.ingame.menuOpenShop).add(this.close, this);
+
+ this.close();
+
+ this.rerenderFull();
+ this.root.signals.upgradePurchased.add(this.rerenderFull, this);
+ }
+
+ cleanup() {
+ document.body.classList.remove("ingameDialogOpen");
+
+ // Cleanup detectors
+ for (const upgradeId in this.upgradeToElements) {
+ const handle = this.upgradeToElements[upgradeId];
+ for (let i = 0; i < handle.requireIndexToElement.length; ++i) {
+ const requiredHandle = handle.requireIndexToElement[i];
+ requiredHandle.container.remove();
+ requiredHandle.pinDetector.cleanup();
+ requiredHandle.infoDetector.cleanup();
+ }
+ handle.requireIndexToElement = [];
+ }
+ }
+
+ show() {
+ this.visible = true;
+ document.body.classList.add("ingameDialogOpen");
+ // this.background.classList.add("visible");
+ this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever);
+ this.rerenderFull();
+ }
+
+ close() {
+ this.visible = false;
+ document.body.classList.remove("ingameDialogOpen");
+ this.root.app.inputMgr.makeSureDetached(this.inputReciever);
+ this.update();
+ }
+
+ update() {
+ this.domAttach.update(this.visible);
+ if (this.visible) {
+ this.renderCountsAndStatus();
+ }
+ }
+
+ tryUnlockNextTier(upgradeId) {
+ // Nothing
+ this.root.hubGoals.tryUnlockUpgrade(upgradeId);
+ }
+
+ isBlockingOverlay() {
+ return this.visible;
+ }
+}
diff --git a/src/js/game/hud/parts/statistics.js b/src/js/game/hud/parts/statistics.js
index c5136312..910c49d0 100644
--- a/src/js/game/hud/parts/statistics.js
+++ b/src/js/game/hud/parts/statistics.js
@@ -4,7 +4,7 @@ import { KeyActionMapper, KEYMAPPINGS } from "../../key_action_mapper";
import { enumAnalyticsDataSource } from "../../production_analytics";
import { BaseHUDPart } from "../base_hud_part";
import { DynamicDomAttach } from "../dynamic_dom_attach";
-import { enumDisplayMode, HUDShapeStatisticsHandle } from "./statistics_handle";
+import { enumDisplayMode, HUDShapeStatisticsHandle, statisticsUnitsSeconds } from "./statistics_handle";
import { T } from "../../../translations";
/**
@@ -47,10 +47,12 @@ export class HUDStatistics extends BaseHUDPart {
this.trackClicks(button, () => this.setDataSource(dataSource));
}
+ const buttonIterateUnit = makeButton(this.filtersDisplayMode, ["displayIterateUnit"]);
const buttonDisplaySorted = makeButton(this.filtersDisplayMode, ["displaySorted"]);
const buttonDisplayDetailed = makeButton(this.filtersDisplayMode, ["displayDetailed"]);
const buttonDisplayIcons = makeButton(this.filtersDisplayMode, ["displayIcons"]);
+ this.trackClicks(buttonIterateUnit, () => this.iterateUnit());
this.trackClicks(buttonDisplaySorted, () => this.toggleSorted());
this.trackClicks(buttonDisplayIcons, () => this.setDisplayMode(enumDisplayMode.icons));
this.trackClicks(buttonDisplayDetailed, () => this.setDisplayMode(enumDisplayMode.detailed));
@@ -97,6 +99,17 @@ export class HUDStatistics extends BaseHUDPart {
this.setSorted(!this.sorted);
}
+ /**
+ * Chooses the next unit
+ */
+ iterateUnit() {
+ const units = Array.from(Object.keys(statisticsUnitsSeconds));
+ const newIndex = (units.indexOf(this.currentUnit) + 1) % units.length;
+ this.currentUnit = units[newIndex];
+
+ this.rerenderPartial();
+ }
+
initialize() {
this.domAttach = new DynamicDomAttach(this.root, this.background, {
attachClass: "visible",
@@ -112,6 +125,8 @@ export class HUDStatistics extends BaseHUDPart {
/** @type {Object.} */
this.activeHandles = {};
+ this.currentUnit = "second";
+
this.setSorted(true);
this.setDataSource(enumAnalyticsDataSource.produced);
this.setDisplayMode(enumDisplayMode.detailed);
@@ -140,6 +155,10 @@ export class HUDStatistics extends BaseHUDPart {
document.body.classList.remove("ingameDialogOpen");
}
+ isBlockingOverlay() {
+ return this.visible;
+ }
+
show() {
this.visible = true;
document.body.classList.add("ingameDialogOpen");
@@ -173,7 +192,7 @@ export class HUDStatistics extends BaseHUDPart {
rerenderPartial() {
for (const key in this.activeHandles) {
const handle = this.activeHandles[key];
- handle.update(this.displayMode, this.dataSource);
+ handle.update(this.displayMode, this.dataSource, this.currentUnit);
}
}
diff --git a/src/js/game/hud/parts/statistics_handle.js b/src/js/game/hud/parts/statistics_handle.js
index 6f49f8d3..a64a5f5b 100644
--- a/src/js/game/hud/parts/statistics_handle.js
+++ b/src/js/game/hud/parts/statistics_handle.js
@@ -12,6 +12,16 @@ export const enumDisplayMode = {
detailed: "detailed",
};
+/**
+ * Stores how many seconds one unit is
+ * @type {Object}
+ */
+export const statisticsUnitsSeconds = {
+ second: 1,
+ minute: 60,
+ hour: 3600,
+};
+
/**
* Simple wrapper for a shape definition within the shape statistics
*/
@@ -64,9 +74,10 @@ export class HUDShapeStatisticsHandle {
*
* @param {enumDisplayMode} displayMode
* @param {enumAnalyticsDataSource} dataSource
+ * @param {string} unit
* @param {boolean=} forced
*/
- update(displayMode, dataSource, forced = false) {
+ update(displayMode, dataSource, unit, forced = false) {
if (!this.element) {
return;
}
@@ -89,12 +100,12 @@ export class HUDShapeStatisticsHandle {
case enumAnalyticsDataSource.delivered:
case enumAnalyticsDataSource.produced: {
let rate =
- (this.root.productionAnalytics.getCurrentShapeRate(dataSource, this.definition) /
- globalConfig.analyticsSliceDurationSeconds) *
- 60;
- this.counter.innerText = T.ingame.statistics.shapesPerSecond.replace(
+ this.root.productionAnalytics.getCurrentShapeRate(dataSource, this.definition) /
+ globalConfig.analyticsSliceDurationSeconds;
+
+ this.counter.innerText = T.ingame.statistics.shapesDisplayUnits[unit].replace(
"",
- formatBigNumber(rate / 60)
+ formatBigNumber(rate * statisticsUnitsSeconds[unit])
);
break;
}
diff --git a/src/js/game/hud/parts/unlock_notification.js b/src/js/game/hud/parts/unlock_notification.js
index 7a5c923b..d88e2dbb 100644
--- a/src/js/game/hud/parts/unlock_notification.js
+++ b/src/js/game/hud/parts/unlock_notification.js
@@ -1,156 +1,160 @@
-import { globalConfig } from "../../../core/config";
-import { gMetaBuildingRegistry } from "../../../core/global_registries";
-import { makeDiv } from "../../../core/utils";
-import { SOUNDS } from "../../../platform/sound";
-import { T } from "../../../translations";
-import { defaultBuildingVariant } from "../../meta_building";
-import { enumHubGoalRewards } from "../../tutorial_goals";
-import { BaseHUDPart } from "../base_hud_part";
-import { DynamicDomAttach } from "../dynamic_dom_attach";
-import { enumHubGoalRewardsToContentUnlocked } from "../../tutorial_goals_mappings";
-import { InputReceiver } from "../../../core/input_receiver";
-
-export class HUDUnlockNotification extends BaseHUDPart {
- initialize() {
- this.visible = false;
-
- this.domAttach = new DynamicDomAttach(this.root, this.element, {
- timeToKeepSeconds: 0,
- });
-
- if (!(G_IS_DEV && globalConfig.debug.disableUnlockDialog)) {
- this.root.signals.storyGoalCompleted.add(this.showForLevel, this);
- }
-
- this.buttonShowTimeout = null;
- }
-
- createElements(parent) {
- this.inputReciever = new InputReceiver("unlock-notification");
-
- this.element = makeDiv(parent, "ingame_HUD_UnlockNotification", ["noBlur"]);
-
- const dialog = makeDiv(this.element, null, ["dialog"]);
-
- this.elemTitle = makeDiv(dialog, null, ["title"]);
- this.elemSubTitle = makeDiv(dialog, null, ["subTitle"], T.ingame.levelCompleteNotification.completed);
-
- this.elemContents = makeDiv(dialog, null, ["contents"]);
-
- this.btnClose = document.createElement("button");
- this.btnClose.classList.add("close", "styledButton");
- this.btnClose.innerText = T.ingame.levelCompleteNotification.buttonNextLevel;
- dialog.appendChild(this.btnClose);
-
- this.trackClicks(this.btnClose, this.requestClose);
- }
-
- /**
- * @param {number} level
- * @param {enumHubGoalRewards} reward
- */
- showForLevel(level, reward) {
- this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever);
- this.elemTitle.innerText = T.ingame.levelCompleteNotification.levelTitle.replace(
- "",
- ("" + level).padStart(2, "0")
- );
-
- const rewardName = T.storyRewards[reward].title;
-
- let html = `
-
- ${T.ingame.levelCompleteNotification.unlockText.replace("", rewardName)}
-
-
-
- ${T.storyRewards[reward].desc}
-
-
- `;
-
- html += "";
- const gained = enumHubGoalRewardsToContentUnlocked[reward];
- if (gained) {
- gained.forEach(([metaBuildingClass, variant]) => {
- const metaBuilding = gMetaBuildingRegistry.findByClass(metaBuildingClass);
- html += `
`;
- });
- }
- html += "
";
-
- this.elemContents.innerHTML = html;
- this.visible = true;
- this.root.soundProxy.playUi(SOUNDS.levelComplete);
-
- if (this.buttonShowTimeout) {
- clearTimeout(this.buttonShowTimeout);
- }
-
- this.element.querySelector("button.close").classList.remove("unlocked");
-
- if (this.root.app.settings.getAllSettings().offerHints) {
- this.buttonShowTimeout = setTimeout(
- () => this.element.querySelector("button.close").classList.add("unlocked"),
- G_IS_DEV ? 100 : 5000
- );
- } else {
- this.element.querySelector("button.close").classList.add("unlocked");
- }
- }
-
- cleanup() {
- this.root.app.inputMgr.makeSureDetached(this.inputReciever);
- if (this.buttonShowTimeout) {
- clearTimeout(this.buttonShowTimeout);
- this.buttonShowTimeout = null;
- }
- }
-
- requestClose() {
- this.root.app.adProvider.showVideoAd().then(() => {
- this.close();
-
- if (!this.root.app.settings.getAllSettings().offerHints) {
- return;
- }
-
- if (this.root.hubGoals.level === 3) {
- const { showUpgrades } = this.root.hud.parts.dialogs.showInfo(
- T.dialogs.upgradesIntroduction.title,
- T.dialogs.upgradesIntroduction.desc,
- ["showUpgrades:good:timeout"]
- );
- showUpgrades.add(() => this.root.hud.parts.shop.show());
- }
-
- if (this.root.hubGoals.level === 5) {
- const { showKeybindings } = this.root.hud.parts.dialogs.showInfo(
- T.dialogs.keybindingsIntroduction.title,
- T.dialogs.keybindingsIntroduction.desc,
- ["showKeybindings:misc", "ok:good:timeout"]
- );
- showKeybindings.add(() => this.root.gameState.goToKeybindings());
- }
- });
- }
-
- close() {
- this.root.app.inputMgr.makeSureDetached(this.inputReciever);
- if (this.buttonShowTimeout) {
- clearTimeout(this.buttonShowTimeout);
- this.buttonShowTimeout = null;
- }
- this.visible = false;
- }
-
- update() {
- this.domAttach.update(this.visible);
- if (!this.visible && this.buttonShowTimeout) {
- clearTimeout(this.buttonShowTimeout);
- this.buttonShowTimeout = null;
- }
- }
-}
+import { globalConfig } from "../../../core/config";
+import { gMetaBuildingRegistry } from "../../../core/global_registries";
+import { makeDiv } from "../../../core/utils";
+import { SOUNDS } from "../../../platform/sound";
+import { T } from "../../../translations";
+import { defaultBuildingVariant } from "../../meta_building";
+import { enumHubGoalRewards } from "../../tutorial_goals";
+import { BaseHUDPart } from "../base_hud_part";
+import { DynamicDomAttach } from "../dynamic_dom_attach";
+import { enumHubGoalRewardsToContentUnlocked } from "../../tutorial_goals_mappings";
+import { InputReceiver } from "../../../core/input_receiver";
+
+export class HUDUnlockNotification extends BaseHUDPart {
+ initialize() {
+ this.visible = false;
+
+ this.domAttach = new DynamicDomAttach(this.root, this.element, {
+ timeToKeepSeconds: 0,
+ });
+
+ if (!(G_IS_DEV && globalConfig.debug.disableUnlockDialog)) {
+ this.root.signals.storyGoalCompleted.add(this.showForLevel, this);
+ }
+
+ this.buttonShowTimeout = null;
+ }
+
+ createElements(parent) {
+ this.inputReciever = new InputReceiver("unlock-notification");
+
+ this.element = makeDiv(parent, "ingame_HUD_UnlockNotification", ["noBlur"]);
+
+ const dialog = makeDiv(this.element, null, ["dialog"]);
+
+ this.elemTitle = makeDiv(dialog, null, ["title"]);
+ this.elemSubTitle = makeDiv(dialog, null, ["subTitle"], T.ingame.levelCompleteNotification.completed);
+
+ this.elemContents = makeDiv(dialog, null, ["contents"]);
+
+ this.btnClose = document.createElement("button");
+ this.btnClose.classList.add("close", "styledButton");
+ this.btnClose.innerText = T.ingame.levelCompleteNotification.buttonNextLevel;
+ dialog.appendChild(this.btnClose);
+
+ this.trackClicks(this.btnClose, this.requestClose);
+ }
+
+ /**
+ * @param {number} level
+ * @param {enumHubGoalRewards} reward
+ */
+ showForLevel(level, reward) {
+ this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever);
+ this.elemTitle.innerText = T.ingame.levelCompleteNotification.levelTitle.replace(
+ "",
+ ("" + level).padStart(2, "0")
+ );
+
+ const rewardName = T.storyRewards[reward].title;
+
+ let html = `
+
+ ${T.ingame.levelCompleteNotification.unlockText.replace("", rewardName)}
+
+
+
+ ${T.storyRewards[reward].desc}
+
+
+ `;
+
+ html += "";
+ const gained = enumHubGoalRewardsToContentUnlocked[reward];
+ if (gained) {
+ gained.forEach(([metaBuildingClass, variant]) => {
+ const metaBuilding = gMetaBuildingRegistry.findByClass(metaBuildingClass);
+ html += `
`;
+ });
+ }
+ html += "
";
+
+ this.elemContents.innerHTML = html;
+ this.visible = true;
+ this.root.soundProxy.playUi(SOUNDS.levelComplete);
+
+ if (this.buttonShowTimeout) {
+ clearTimeout(this.buttonShowTimeout);
+ }
+
+ this.element.querySelector("button.close").classList.remove("unlocked");
+
+ if (this.root.app.settings.getAllSettings().offerHints) {
+ this.buttonShowTimeout = setTimeout(
+ () => this.element.querySelector("button.close").classList.add("unlocked"),
+ G_IS_DEV ? 100 : 5000
+ );
+ } else {
+ this.element.querySelector("button.close").classList.add("unlocked");
+ }
+ }
+
+ cleanup() {
+ this.root.app.inputMgr.makeSureDetached(this.inputReciever);
+ if (this.buttonShowTimeout) {
+ clearTimeout(this.buttonShowTimeout);
+ this.buttonShowTimeout = null;
+ }
+ }
+
+ isBlockingOverlay() {
+ return this.visible;
+ }
+
+ requestClose() {
+ this.root.app.adProvider.showVideoAd().then(() => {
+ this.close();
+
+ if (!this.root.app.settings.getAllSettings().offerHints) {
+ return;
+ }
+
+ if (this.root.hubGoals.level === 3) {
+ const { showUpgrades } = this.root.hud.parts.dialogs.showInfo(
+ T.dialogs.upgradesIntroduction.title,
+ T.dialogs.upgradesIntroduction.desc,
+ ["showUpgrades:good:timeout"]
+ );
+ showUpgrades.add(() => this.root.hud.parts.shop.show());
+ }
+
+ if (this.root.hubGoals.level === 5) {
+ const { showKeybindings } = this.root.hud.parts.dialogs.showInfo(
+ T.dialogs.keybindingsIntroduction.title,
+ T.dialogs.keybindingsIntroduction.desc,
+ ["showKeybindings:misc", "ok:good:timeout"]
+ );
+ showKeybindings.add(() => this.root.gameState.goToKeybindings());
+ }
+ });
+ }
+
+ close() {
+ this.root.app.inputMgr.makeSureDetached(this.inputReciever);
+ if (this.buttonShowTimeout) {
+ clearTimeout(this.buttonShowTimeout);
+ this.buttonShowTimeout = null;
+ }
+ this.visible = false;
+ }
+
+ update() {
+ this.domAttach.update(this.visible);
+ if (!this.visible && this.buttonShowTimeout) {
+ clearTimeout(this.buttonShowTimeout);
+ this.buttonShowTimeout = null;
+ }
+ }
+}
diff --git a/src/js/game/hud/parts/waypoints.js b/src/js/game/hud/parts/waypoints.js
index abf05b1f..116cd087 100644
--- a/src/js/game/hud/parts/waypoints.js
+++ b/src/js/game/hud/parts/waypoints.js
@@ -1,627 +1,626 @@
-import { makeOffscreenBuffer } from "../../../core/buffer_utils";
-import { globalConfig, IS_DEMO } from "../../../core/config";
-import { DrawParameters } from "../../../core/draw_parameters";
-import { Loader } from "../../../core/loader";
-import { DialogWithForm } from "../../../core/modal_dialog_elements";
-import { FormElementInput } from "../../../core/modal_dialog_forms";
-import { Rectangle } from "../../../core/rectangle";
-import { STOP_PROPAGATION } from "../../../core/signal";
-import { arrayDeleteValue, lerp, makeDiv, removeAllChildren, clamp } from "../../../core/utils";
-import { Vector } from "../../../core/vector";
-import { T } from "../../../translations";
-import { enumMouseButton } from "../../camera";
-import { KEYMAPPINGS } from "../../key_action_mapper";
-import { BaseHUDPart } from "../base_hud_part";
-import { DynamicDomAttach } from "../dynamic_dom_attach";
-import { enumNotificationType } from "./notifications";
-import { ShapeDefinition } from "../../shape_definition";
-import { BaseItem } from "../../base_item";
-import { ShapeItem } from "../../items/shape_item";
-
-/** @typedef {{
- * label: string | null,
- * center: { x: number, y: number },
- * zoomLevel: number
- * }} Waypoint */
-
-/**
- * Used when a shape icon is rendered instead
- */
-const MAX_LABEL_LENGTH = 71;
-
-export class HUDWaypoints extends BaseHUDPart {
- /**
- * Creates the overview of waypoints
- * @param {HTMLElement} parent
- */
- createElements(parent) {
- // Create the helper box on the lower right when zooming out
- if (this.root.app.settings.getAllSettings().offerHints) {
- this.hintElement = makeDiv(
- parent,
- "ingame_HUD_Waypoints_Hint",
- [],
- `
- ${T.ingame.waypoints.waypoints}
- ${T.ingame.waypoints.description.replace(
- "",
- `${this.root.keyMapper
- .getBinding(KEYMAPPINGS.navigation.createMarker)
- .getKeyCodeString()}
`
- )}
- `
- );
- }
-
- // Create the waypoint list on the upper right
- this.waypointsListElement = makeDiv(parent, "ingame_HUD_Waypoints", [], "Waypoints");
- }
-
- /**
- * Serializes the waypoints
- */
- serialize() {
- return {
- waypoints: this.waypoints,
- };
- }
-
- /**
- * Deserializes the waypoints
- * @param {{waypoints: Array}} data
- */
- deserialize(data) {
- if (!data || !data.waypoints || !Array.isArray(data.waypoints)) {
- return "Invalid waypoints data";
- }
- this.waypoints = data.waypoints;
- this.rerenderWaypointList();
- }
-
- /**
- * Initializes everything
- */
- initialize() {
- // Cache the sprite for the waypoints
- this.waypointSprite = Loader.getSprite("sprites/misc/waypoint.png");
- this.directionIndicatorSprite = Loader.getSprite("sprites/misc/hub_direction_indicator.png");
-
- /** @type {Array}
- */
- this.waypoints = [
- {
- label: null,
- center: { x: 0, y: 0 },
- zoomLevel: 3,
- },
- ];
-
- // Create a buffer we can use to measure text
- this.dummyBuffer = makeOffscreenBuffer(1, 1, {
- reusable: false,
- label: "waypoints-measure-canvas",
- })[1];
-
- // Dynamically attach/detach the lower right hint in the map overview
- if (this.hintElement) {
- this.domAttach = new DynamicDomAttach(this.root, this.hintElement);
- }
-
- // Catch mouse and key events
- this.root.camera.downPreHandler.add(this.onMouseDown, this);
- this.root.keyMapper
- .getBinding(KEYMAPPINGS.navigation.createMarker)
- .add(() => this.requestSaveMarker({}));
-
- /**
- * Stores at how much opacity the markers should be rendered on the map.
- * This is interpolated over multiple frames so we have some sort of fade effect
- */
- this.currentMarkerOpacity = 1;
- this.currentCompassOpacity = 0;
-
- // Create buffer which is used to indicate the hub direction
- const [canvas, context] = makeOffscreenBuffer(48, 48, {
- smooth: true,
- reusable: false,
- label: "waypoints-compass",
- });
- this.compassBuffer = { canvas, context };
-
- /**
- * Stores a cache from a shape short key to its canvas representation
- */
- this.cachedKeyToCanvas = {};
-
- /**
- * Store cached text widths
- * @type {Object}
- */
- this.cachedTextWidths = {};
-
- // Initial render
- this.rerenderWaypointList();
- }
-
- /**
- * Returns how long a text will be rendered
- * @param {string} text
- * @returns {number}
- */
- getTextWidth(text) {
- if (this.cachedTextWidths[text]) {
- return this.cachedTextWidths[text];
- }
-
- this.dummyBuffer.font = "bold " + this.getTextScale() + "px GameFont";
- return (this.cachedTextWidths[text] = this.dummyBuffer.measureText(text).width);
- }
-
- /**
- * Returns how big the text should be rendered
- */
- getTextScale() {
- return this.getWaypointUiScale() * 12;
- }
-
- /**
- * Returns the scale for rendering waypoints
- */
- getWaypointUiScale() {
- return this.root.app.getEffectiveUiScale();
- }
-
- /**
- * Re-renders the waypoint list to account for changes
- */
- rerenderWaypointList() {
- removeAllChildren(this.waypointsListElement);
- this.cleanupClickDetectors();
-
- for (let i = 0; i < this.waypoints.length; ++i) {
- const waypoint = this.waypoints[i];
- const label = this.getWaypointLabel(waypoint);
-
- const element = makeDiv(this.waypointsListElement, null, ["waypoint"]);
-
- if (ShapeDefinition.isValidShortKey(label)) {
- const canvas = this.getWaypointCanvas(waypoint);
- /**
- * Create a clone of the cached canvas, as calling appendElement when a canvas is
- * already in the document will move the existing canvas to the new position.
- */
- const [newCanvas, context] = makeOffscreenBuffer(48, 48, {
- smooth: true,
- label: label + "-waypoint-" + i,
- });
- context.drawImage(canvas, 0, 0);
- element.appendChild(newCanvas);
- element.classList.add("shapeIcon");
- } else {
- element.innerText = label;
- }
-
- if (this.isWaypointDeletable(waypoint)) {
- const editButton = makeDiv(element, null, ["editButton"]);
- this.trackClicks(editButton, () => this.requestSaveMarker({ waypoint }));
- }
-
- if (!waypoint.label) {
- // This must be the hub label
- element.classList.add("hub");
- element.insertBefore(this.compassBuffer.canvas, element.childNodes[0]);
- }
-
- this.trackClicks(element, () => this.moveToWaypoint(waypoint), {
- targetOnly: true,
- });
- }
- }
-
- /**
- * Moves the camera to a given waypoint
- * @param {Waypoint} waypoint
- */
- moveToWaypoint(waypoint) {
- this.root.camera.setDesiredCenter(new Vector(waypoint.center.x, waypoint.center.y));
- this.root.camera.setDesiredZoom(waypoint.zoomLevel);
- }
-
- /**
- * Deletes a waypoint from the list
- * @param {Waypoint} waypoint
- */
- deleteWaypoint(waypoint) {
- arrayDeleteValue(this.waypoints, waypoint);
- this.rerenderWaypointList();
- }
-
- /**
- * Gets the canvas for a given waypoint
- * @param {Waypoint} waypoint
- * @returns {HTMLCanvasElement}
- */
- getWaypointCanvas(waypoint) {
- const key = waypoint.label;
- if (this.cachedKeyToCanvas[key]) {
- return this.cachedKeyToCanvas[key];
- }
-
- assert(ShapeDefinition.isValidShortKey(key), "Invalid short key: " + key);
- const definition = this.root.shapeDefinitionMgr.getShapeFromShortKey(key);
- const preRendered = definition.generateAsCanvas(48);
- return (this.cachedKeyToCanvas[key] = preRendered);
- }
-
- /**
- * Requests to save a marker at the current camera position. If worldPos is set,
- * uses that position instead.
- * @param {object} param0
- * @param {Vector=} param0.worldPos Override the world pos, otherwise it is the camera position
- * @param {Waypoint=} param0.waypoint Waypoint to be edited. If omitted, create new
- */
- requestSaveMarker({ worldPos = null, waypoint = null }) {
- // Construct dialog with input field
- const markerNameInput = new FormElementInput({
- id: "markerName",
- label: null,
- placeholder: "",
- defaultValue: waypoint ? waypoint.label : "",
- validator: val =>
- val.length > 0 && (val.length < MAX_LABEL_LENGTH || ShapeDefinition.isValidShortKey(val)),
- });
- const dialog = new DialogWithForm({
- app: this.root.app,
- title: waypoint ? T.dialogs.createMarker.titleEdit : T.dialogs.createMarker.title,
- desc: T.dialogs.createMarker.desc,
- formElements: [markerNameInput],
- buttons: waypoint ? ["delete:bad", "cancel", "ok:good"] : ["cancel", "ok:good"],
- });
- this.root.hud.parts.dialogs.internalShowDialog(dialog);
-
- // Edit marker
- if (waypoint) {
- dialog.buttonSignals.ok.add(() => {
- // Actually rename the waypoint
- this.renameWaypoint(waypoint, markerNameInput.getValue());
- });
- dialog.buttonSignals.delete.add(() => {
- // Actually delete the waypoint
- this.deleteWaypoint(waypoint);
- });
- } else {
- // Compute where to create the marker
- const center = worldPos || this.root.camera.center;
-
- dialog.buttonSignals.ok.add(() => {
- // Show info that you can have only N markers in the demo,
- // actually show this *after* entering the name so you want the
- // standalone even more (I'm evil :P)
- if (IS_DEMO && this.waypoints.length > 2) {
- this.root.hud.parts.dialogs.showFeatureRestrictionInfo(
- "",
- T.dialogs.markerDemoLimit.desc
- );
- return;
- }
-
- // Actually create the waypoint
- this.addWaypoint(markerNameInput.getValue(), center);
- });
- }
- }
-
- /**
- * Adds a new waypoint at the given location with the given label
- * @param {string} label
- * @param {Vector} position
- */
- addWaypoint(label, position) {
- this.waypoints.push({
- label,
- center: { x: position.x, y: position.y },
- // Make sure the zoom is *just* a bit above the zoom level where the map overview
- // starts, so you always see all buildings
- zoomLevel: Math.max(this.root.camera.zoomLevel, globalConfig.mapChunkOverviewMinZoom + 0.05),
- });
-
- this.sortWaypoints();
-
- // Show notification about creation
- this.root.hud.signals.notification.dispatch(
- T.ingame.waypoints.creationSuccessNotification,
- enumNotificationType.success
- );
-
- // Re-render the list and thus add it
- this.rerenderWaypointList();
- }
-
- /**
- * Renames a waypoint with the given label
- * @param {Waypoint} waypoint
- * @param {string} label
- */
- renameWaypoint(waypoint, label) {
- waypoint.label = label;
-
- this.sortWaypoints();
-
- // Show notification about renamed
- this.root.hud.signals.notification.dispatch(
- T.ingame.waypoints.creationSuccessNotification,
- enumNotificationType.success
- );
-
- // Re-render the list and thus add it
- this.rerenderWaypointList();
- }
-
- /**
- * Called every frame to update stuff
- */
- update() {
- if (this.domAttach) {
- this.domAttach.update(this.root.camera.getIsMapOverlayActive());
- }
- }
-
- /**
- * Sort waypoints by name
- */
- sortWaypoints() {
- this.waypoints.sort((a, b) => {
- if (!a.label) {
- return -1;
- }
- if (!b.label) {
- return 1;
- }
- return this.getWaypointLabel(a)
- .padEnd(MAX_LABEL_LENGTH, "0")
- .localeCompare(this.getWaypointLabel(b).padEnd(MAX_LABEL_LENGTH, "0"));
- });
- }
-
- /**
- * Returns the label for a given waypoint
- * @param {Waypoint} waypoint
- * @returns {string}
- */
- getWaypointLabel(waypoint) {
- return waypoint.label || T.ingame.waypoints.hub;
- }
-
- /**
- * Returns if a waypoint is deletable
- * @param {Waypoint} waypoint
- * @returns {boolean}
- */
- isWaypointDeletable(waypoint) {
- return waypoint.label !== null;
- }
-
- /**
- * Returns the screen space bounds of the given waypoint or null
- * if it couldn't be determined. Also returns wheter its a shape or not
- * @param {Waypoint} waypoint
- * @return {{
- * screenBounds: Rectangle
- * item: BaseItem|null,
- * text: string
- * }}
- */
- getWaypointScreenParams(waypoint) {
- if (!this.root.camera.getIsMapOverlayActive()) {
- return null;
- }
-
- // Find parameters
- const scale = this.getWaypointUiScale();
- const screenPos = this.root.camera.worldToScreen(new Vector(waypoint.center.x, waypoint.center.y));
-
- // Distinguish between text and item waypoints -> Figure out parameters
- const originalLabel = this.getWaypointLabel(waypoint);
- let text, item, textWidth;
-
- if (ShapeDefinition.isValidShortKey(originalLabel)) {
- // If the label is actually a key, render the shape icon
- item = this.root.shapeDefinitionMgr.getShapeItemFromShortKey(originalLabel);
- textWidth = 40;
- } else {
- // Otherwise render a regular waypoint
- text = originalLabel;
- textWidth = this.getTextWidth(text);
- }
-
- return {
- screenBounds: new Rectangle(
- screenPos.x - 7 * scale,
- screenPos.y - 12 * scale,
- 15 * scale + textWidth,
- 15 * scale
- ),
- item,
- text,
- };
- }
-
- /**
- * Finds the currently intersected waypoint on the map overview under
- * the cursor.
- *
- * @returns {Waypoint | null}
- */
- findCurrentIntersectedWaypoint() {
- const mousePos = this.root.app.mousePosition;
- if (!mousePos) {
- return;
- }
-
- for (let i = 0; i < this.waypoints.length; ++i) {
- const waypoint = this.waypoints[i];
- const params = this.getWaypointScreenParams(waypoint);
- if (params && params.screenBounds.containsPoint(mousePos.x, mousePos.y)) {
- return waypoint;
- }
- }
- }
-
- /**
- * Mouse-Down handler
- * @param {Vector} pos
- * @param {enumMouseButton} button
- */
- onMouseDown(pos, button) {
- const waypoint = this.findCurrentIntersectedWaypoint();
- if (waypoint) {
- if (button === enumMouseButton.left) {
- this.root.soundProxy.playUiClick();
- this.moveToWaypoint(waypoint);
- } else if (button === enumMouseButton.right) {
- if (this.isWaypointDeletable(waypoint)) {
- this.root.soundProxy.playUiClick();
- this.requestSaveMarker({ waypoint });
- } else {
- this.root.soundProxy.playUiError();
- }
- }
-
- return STOP_PROPAGATION;
- } else {
- // Allow right click to create a marker
- if (button === enumMouseButton.right) {
- if (this.root.camera.getIsMapOverlayActive()) {
- const worldPos = this.root.camera.screenToWorld(pos);
- this.requestSaveMarker({ worldPos });
- return STOP_PROPAGATION;
- }
- }
- }
- }
-
- /**
- * Rerenders the compass
- */
- rerenderWaypointsCompass() {
- const dims = 48;
- const indicatorSize = 30;
- const cameraPos = this.root.camera.center;
-
- const context = this.compassBuffer.context;
- context.clearRect(0, 0, dims, dims);
-
- const distanceToHub = cameraPos.length();
- const compassVisible = distanceToHub > (10 * globalConfig.tileSize) / this.root.camera.zoomLevel;
- const targetCompassAlpha = compassVisible ? 1 : 0;
-
- // Fade the compas in / out
- this.currentCompassOpacity = lerp(this.currentCompassOpacity, targetCompassAlpha, 0.08);
-
- // Render the compass
- if (this.currentCompassOpacity > 0.01) {
- context.globalAlpha = this.currentCompassOpacity;
- const angle = cameraPos.angle() + Math.radians(45) + Math.PI / 2;
- context.translate(dims / 2, dims / 2);
- context.rotate(angle);
- this.directionIndicatorSprite.drawCentered(context, 0, 0, indicatorSize);
- context.rotate(-angle);
- context.translate(-dims / 2, -dims / 2);
- context.globalAlpha = 1;
- }
-
- // Render the regualr icon
- const iconOpacity = 1 - this.currentCompassOpacity;
- if (iconOpacity > 0.01) {
- context.globalAlpha = iconOpacity;
- this.waypointSprite.drawCentered(context, dims / 2, dims / 2, dims * 0.7);
- context.globalAlpha = 1;
- }
- }
-
- /**
- * Draws the waypoints on the map
- * @param {DrawParameters} parameters
- */
- drawOverlays(parameters) {
- const mousePos = this.root.app.mousePosition;
- const desiredOpacity = this.root.camera.getIsMapOverlayActive() ? 1 : 0;
- this.currentMarkerOpacity = lerp(this.currentMarkerOpacity, desiredOpacity, 0.08);
-
- this.rerenderWaypointsCompass();
-
- // Don't render with low opacity
- if (this.currentMarkerOpacity < 0.01) {
- return;
- }
-
- // Determine rendering scale
- const scale = this.getWaypointUiScale();
-
- // Set the font size
- const textSize = this.getTextScale();
- parameters.context.font = "bold " + textSize + "px GameFont";
- parameters.context.textBaseline = "middle";
-
- // Loop over all waypoints
- for (let i = 0; i < this.waypoints.length; ++i) {
- const waypoint = this.waypoints[i];
-
- const waypointData = this.getWaypointScreenParams(waypoint);
- if (!waypointData) {
- // Not relevant
- continue;
- }
-
- if (!parameters.visibleRect.containsRect(waypointData.screenBounds)) {
- // Out of screen
- continue;
- }
-
- const bounds = waypointData.screenBounds;
- const contentPaddingX = 7 * scale;
- const isSelected = mousePos && bounds.containsPoint(mousePos.x, mousePos.y);
-
- // Render the background rectangle
- parameters.context.globalAlpha = this.currentMarkerOpacity * (isSelected ? 1 : 0.7);
- parameters.context.fillStyle = "rgba(255, 255, 255, 0.7)";
- parameters.context.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
-
- // Render the text
- if (waypointData.item) {
- const canvas = this.getWaypointCanvas(waypoint);
- const itemSize = 14 * scale;
- parameters.context.drawImage(
- canvas,
- bounds.x + contentPaddingX + 6 * scale,
- bounds.y + bounds.h / 2 - itemSize / 2,
- itemSize,
- itemSize
- );
- } else if (waypointData.text) {
- // Render the text
- parameters.context.fillStyle = "#000";
- parameters.context.textBaseline = "middle";
- parameters.context.fillText(
- waypointData.text,
- bounds.x + contentPaddingX + 6 * scale,
- bounds.y + bounds.h / 2
- );
- parameters.context.textBaseline = "alphabetic";
- } else {
- assertAlways(false, "Waypoint has no item and text");
- }
-
- // Render the small icon on the left
- this.waypointSprite.drawCentered(
- parameters.context,
- bounds.x + contentPaddingX,
- bounds.y + bounds.h / 2,
- bounds.h * 0.7
- );
- }
-
- parameters.context.textBaseline = "alphabetic";
- parameters.context.globalAlpha = 1;
- }
-}
+import { makeOffscreenBuffer } from "../../../core/buffer_utils";
+import { globalConfig, IS_DEMO } from "../../../core/config";
+import { DrawParameters } from "../../../core/draw_parameters";
+import { Loader } from "../../../core/loader";
+import { DialogWithForm } from "../../../core/modal_dialog_elements";
+import { FormElementInput } from "../../../core/modal_dialog_forms";
+import { Rectangle } from "../../../core/rectangle";
+import { STOP_PROPAGATION } from "../../../core/signal";
+import { arrayDeleteValue, lerp, makeDiv, removeAllChildren } from "../../../core/utils";
+import { Vector } from "../../../core/vector";
+import { T } from "../../../translations";
+import { BaseItem } from "../../base_item";
+import { enumMouseButton } from "../../camera";
+import { KEYMAPPINGS } from "../../key_action_mapper";
+import { ShapeDefinition } from "../../shape_definition";
+import { BaseHUDPart } from "../base_hud_part";
+import { DynamicDomAttach } from "../dynamic_dom_attach";
+import { enumNotificationType } from "./notifications";
+
+/** @typedef {{
+ * label: string | null,
+ * center: { x: number, y: number },
+ * zoomLevel: number
+ * }} Waypoint */
+
+/**
+ * Used when a shape icon is rendered instead
+ */
+const MAX_LABEL_LENGTH = 71;
+
+export class HUDWaypoints extends BaseHUDPart {
+ /**
+ * Creates the overview of waypoints
+ * @param {HTMLElement} parent
+ */
+ createElements(parent) {
+ // Create the helper box on the lower right when zooming out
+ if (this.root.app.settings.getAllSettings().offerHints) {
+ this.hintElement = makeDiv(
+ parent,
+ "ingame_HUD_Waypoints_Hint",
+ [],
+ `
+ ${T.ingame.waypoints.waypoints}
+ ${T.ingame.waypoints.description.replace(
+ "",
+ `${this.root.keyMapper
+ .getBinding(KEYMAPPINGS.navigation.createMarker)
+ .getKeyCodeString()}
`
+ )}
+ `
+ );
+ }
+
+ // Create the waypoint list on the upper right
+ this.waypointsListElement = makeDiv(parent, "ingame_HUD_Waypoints", [], "Waypoints");
+ }
+
+ /**
+ * Serializes the waypoints
+ */
+ serialize() {
+ return {
+ waypoints: this.waypoints,
+ };
+ }
+
+ /**
+ * Deserializes the waypoints
+ * @param {{waypoints: Array}} data
+ */
+ deserialize(data) {
+ if (!data || !data.waypoints || !Array.isArray(data.waypoints)) {
+ return "Invalid waypoints data";
+ }
+ this.waypoints = data.waypoints;
+ this.rerenderWaypointList();
+ }
+
+ /**
+ * Initializes everything
+ */
+ initialize() {
+ // Cache the sprite for the waypoints
+ this.waypointSprite = Loader.getSprite("sprites/misc/waypoint.png");
+ this.directionIndicatorSprite = Loader.getSprite("sprites/misc/hub_direction_indicator.png");
+
+ /** @type {Array}
+ */
+ this.waypoints = [
+ {
+ label: null,
+ center: { x: 0, y: 0 },
+ zoomLevel: 3,
+ },
+ ];
+
+ // Create a buffer we can use to measure text
+ this.dummyBuffer = makeOffscreenBuffer(1, 1, {
+ reusable: false,
+ label: "waypoints-measure-canvas",
+ })[1];
+
+ // Dynamically attach/detach the lower right hint in the map overview
+ if (this.hintElement) {
+ this.domAttach = new DynamicDomAttach(this.root, this.hintElement);
+ }
+
+ // Catch mouse and key events
+ this.root.camera.downPreHandler.add(this.onMouseDown, this);
+ this.root.keyMapper
+ .getBinding(KEYMAPPINGS.navigation.createMarker)
+ .add(() => this.requestSaveMarker({}));
+
+ /**
+ * Stores at how much opacity the markers should be rendered on the map.
+ * This is interpolated over multiple frames so we have some sort of fade effect
+ */
+ this.currentMarkerOpacity = 1;
+ this.currentCompassOpacity = 0;
+
+ // Create buffer which is used to indicate the hub direction
+ const [canvas, context] = makeOffscreenBuffer(48, 48, {
+ smooth: true,
+ reusable: false,
+ label: "waypoints-compass",
+ });
+ this.compassBuffer = { canvas, context };
+
+ /**
+ * Stores a cache from a shape short key to its canvas representation
+ */
+ this.cachedKeyToCanvas = {};
+
+ /**
+ * Store cached text widths
+ * @type {Object}
+ */
+ this.cachedTextWidths = {};
+
+ // Initial render
+ this.rerenderWaypointList();
+ }
+
+ /**
+ * Returns how long a text will be rendered
+ * @param {string} text
+ * @returns {number}
+ */
+ getTextWidth(text) {
+ if (this.cachedTextWidths[text]) {
+ return this.cachedTextWidths[text];
+ }
+
+ this.dummyBuffer.font = "bold " + this.getTextScale() + "px GameFont";
+ return (this.cachedTextWidths[text] = this.dummyBuffer.measureText(text).width);
+ }
+
+ /**
+ * Returns how big the text should be rendered
+ */
+ getTextScale() {
+ return this.getWaypointUiScale() * 12;
+ }
+
+ /**
+ * Returns the scale for rendering waypoints
+ */
+ getWaypointUiScale() {
+ return this.root.app.getEffectiveUiScale();
+ }
+
+ /**
+ * Re-renders the waypoint list to account for changes
+ */
+ rerenderWaypointList() {
+ removeAllChildren(this.waypointsListElement);
+ this.cleanupClickDetectors();
+
+ for (let i = 0; i < this.waypoints.length; ++i) {
+ const waypoint = this.waypoints[i];
+ const label = this.getWaypointLabel(waypoint);
+
+ const element = makeDiv(this.waypointsListElement, null, ["waypoint"]);
+
+ if (ShapeDefinition.isValidShortKey(label)) {
+ const canvas = this.getWaypointCanvas(waypoint);
+ /**
+ * Create a clone of the cached canvas, as calling appendElement when a canvas is
+ * already in the document will move the existing canvas to the new position.
+ */
+ const [newCanvas, context] = makeOffscreenBuffer(48, 48, {
+ smooth: true,
+ label: label + "-waypoint-" + i,
+ });
+ context.drawImage(canvas, 0, 0);
+ element.appendChild(newCanvas);
+ element.classList.add("shapeIcon");
+ } else {
+ element.innerText = label;
+ }
+
+ if (this.isWaypointDeletable(waypoint)) {
+ const editButton = makeDiv(element, null, ["editButton"]);
+ this.trackClicks(editButton, () => this.requestSaveMarker({ waypoint }));
+ }
+
+ if (!waypoint.label) {
+ // This must be the hub label
+ element.classList.add("hub");
+ element.insertBefore(this.compassBuffer.canvas, element.childNodes[0]);
+ }
+
+ this.trackClicks(element, () => this.moveToWaypoint(waypoint), {
+ targetOnly: true,
+ });
+ }
+ }
+
+ /**
+ * Moves the camera to a given waypoint
+ * @param {Waypoint} waypoint
+ */
+ moveToWaypoint(waypoint) {
+ this.root.camera.setDesiredCenter(new Vector(waypoint.center.x, waypoint.center.y));
+ this.root.camera.setDesiredZoom(waypoint.zoomLevel);
+ }
+
+ /**
+ * Deletes a waypoint from the list
+ * @param {Waypoint} waypoint
+ */
+ deleteWaypoint(waypoint) {
+ arrayDeleteValue(this.waypoints, waypoint);
+ this.rerenderWaypointList();
+ }
+
+ /**
+ * Gets the canvas for a given waypoint
+ * @param {Waypoint} waypoint
+ * @returns {HTMLCanvasElement}
+ */
+ getWaypointCanvas(waypoint) {
+ const key = waypoint.label;
+ if (this.cachedKeyToCanvas[key]) {
+ return this.cachedKeyToCanvas[key];
+ }
+
+ assert(ShapeDefinition.isValidShortKey(key), "Invalid short key: " + key);
+ const definition = this.root.shapeDefinitionMgr.getShapeFromShortKey(key);
+ const preRendered = definition.generateAsCanvas(48);
+ return (this.cachedKeyToCanvas[key] = preRendered);
+ }
+
+ /**
+ * Requests to save a marker at the current camera position. If worldPos is set,
+ * uses that position instead.
+ * @param {object} param0
+ * @param {Vector=} param0.worldPos Override the world pos, otherwise it is the camera position
+ * @param {Waypoint=} param0.waypoint Waypoint to be edited. If omitted, create new
+ */
+ requestSaveMarker({ worldPos = null, waypoint = null }) {
+ // Construct dialog with input field
+ const markerNameInput = new FormElementInput({
+ id: "markerName",
+ label: null,
+ placeholder: "",
+ defaultValue: waypoint ? waypoint.label : "",
+ validator: val =>
+ val.length > 0 && (val.length < MAX_LABEL_LENGTH || ShapeDefinition.isValidShortKey(val)),
+ });
+ const dialog = new DialogWithForm({
+ app: this.root.app,
+ title: waypoint ? T.dialogs.createMarker.titleEdit : T.dialogs.createMarker.title,
+ desc: T.dialogs.createMarker.desc,
+ formElements: [markerNameInput],
+ buttons: waypoint ? ["delete:bad", "cancel", "ok:good"] : ["cancel", "ok:good"],
+ });
+ this.root.hud.parts.dialogs.internalShowDialog(dialog);
+
+ // Edit marker
+ if (waypoint) {
+ dialog.buttonSignals.ok.add(() => {
+ // Actually rename the waypoint
+ this.renameWaypoint(waypoint, markerNameInput.getValue());
+ });
+ dialog.buttonSignals.delete.add(() => {
+ // Actually delete the waypoint
+ this.deleteWaypoint(waypoint);
+ });
+ } else {
+ // Compute where to create the marker
+ const center = worldPos || this.root.camera.center;
+
+ dialog.buttonSignals.ok.add(() => {
+ // Show info that you can have only N markers in the demo,
+ // actually show this *after* entering the name so you want the
+ // standalone even more (I'm evil :P)
+ if (IS_DEMO && this.waypoints.length > 2) {
+ this.root.hud.parts.dialogs.showFeatureRestrictionInfo(
+ "",
+ T.dialogs.markerDemoLimit.desc
+ );
+ return;
+ }
+
+ // Actually create the waypoint
+ this.addWaypoint(markerNameInput.getValue(), center);
+ });
+ }
+ }
+
+ /**
+ * Adds a new waypoint at the given location with the given label
+ * @param {string} label
+ * @param {Vector} position
+ */
+ addWaypoint(label, position) {
+ this.waypoints.push({
+ label,
+ center: { x: position.x, y: position.y },
+ // Make sure the zoom is *just* a bit above the zoom level where the map overview
+ // starts, so you always see all buildings
+ zoomLevel: Math.max(this.root.camera.zoomLevel, globalConfig.mapChunkOverviewMinZoom + 0.05),
+ });
+
+ this.sortWaypoints();
+
+ // Show notification about creation
+ this.root.hud.signals.notification.dispatch(
+ T.ingame.waypoints.creationSuccessNotification,
+ enumNotificationType.success
+ );
+
+ // Re-render the list and thus add it
+ this.rerenderWaypointList();
+ }
+
+ /**
+ * Renames a waypoint with the given label
+ * @param {Waypoint} waypoint
+ * @param {string} label
+ */
+ renameWaypoint(waypoint, label) {
+ waypoint.label = label;
+
+ this.sortWaypoints();
+
+ // Show notification about renamed
+ this.root.hud.signals.notification.dispatch(
+ T.ingame.waypoints.creationSuccessNotification,
+ enumNotificationType.success
+ );
+
+ // Re-render the list and thus add it
+ this.rerenderWaypointList();
+ }
+
+ /**
+ * Called every frame to update stuff
+ */
+ update() {
+ if (this.domAttach) {
+ this.domAttach.update(this.root.camera.getIsMapOverlayActive());
+ }
+ }
+
+ /**
+ * Sort waypoints by name
+ */
+ sortWaypoints() {
+ this.waypoints.sort((a, b) => {
+ if (!a.label) {
+ return -1;
+ }
+ if (!b.label) {
+ return 1;
+ }
+ return this.getWaypointLabel(a)
+ .padEnd(MAX_LABEL_LENGTH, "0")
+ .localeCompare(this.getWaypointLabel(b).padEnd(MAX_LABEL_LENGTH, "0"));
+ });
+ }
+
+ /**
+ * Returns the label for a given waypoint
+ * @param {Waypoint} waypoint
+ * @returns {string}
+ */
+ getWaypointLabel(waypoint) {
+ return waypoint.label || T.ingame.waypoints.hub;
+ }
+
+ /**
+ * Returns if a waypoint is deletable
+ * @param {Waypoint} waypoint
+ * @returns {boolean}
+ */
+ isWaypointDeletable(waypoint) {
+ return waypoint.label !== null;
+ }
+
+ /**
+ * Returns the screen space bounds of the given waypoint or null
+ * if it couldn't be determined. Also returns wheter its a shape or not
+ * @param {Waypoint} waypoint
+ * @return {{
+ * screenBounds: Rectangle
+ * item: BaseItem|null,
+ * text: string
+ * }}
+ */
+ getWaypointScreenParams(waypoint) {
+ if (!this.root.camera.getIsMapOverlayActive()) {
+ return null;
+ }
+
+ // Find parameters
+ const scale = this.getWaypointUiScale();
+ const screenPos = this.root.camera.worldToScreen(new Vector(waypoint.center.x, waypoint.center.y));
+
+ // Distinguish between text and item waypoints -> Figure out parameters
+ const originalLabel = this.getWaypointLabel(waypoint);
+ let text, item, textWidth;
+
+ if (ShapeDefinition.isValidShortKey(originalLabel)) {
+ // If the label is actually a key, render the shape icon
+ item = this.root.shapeDefinitionMgr.getShapeItemFromShortKey(originalLabel);
+ textWidth = 40;
+ } else {
+ // Otherwise render a regular waypoint
+ text = originalLabel;
+ textWidth = this.getTextWidth(text);
+ }
+
+ return {
+ screenBounds: new Rectangle(
+ screenPos.x - 7 * scale,
+ screenPos.y - 12 * scale,
+ 15 * scale + textWidth,
+ 15 * scale
+ ),
+ item,
+ text,
+ };
+ }
+
+ /**
+ * Finds the currently intersected waypoint on the map overview under
+ * the cursor.
+ *
+ * @returns {Waypoint | null}
+ */
+ findCurrentIntersectedWaypoint() {
+ const mousePos = this.root.app.mousePosition;
+ if (!mousePos) {
+ return;
+ }
+
+ for (let i = 0; i < this.waypoints.length; ++i) {
+ const waypoint = this.waypoints[i];
+ const params = this.getWaypointScreenParams(waypoint);
+ if (params && params.screenBounds.containsPoint(mousePos.x, mousePos.y)) {
+ return waypoint;
+ }
+ }
+ }
+
+ /**
+ * Mouse-Down handler
+ * @param {Vector} pos
+ * @param {enumMouseButton} button
+ */
+ onMouseDown(pos, button) {
+ const waypoint = this.findCurrentIntersectedWaypoint();
+ if (waypoint) {
+ if (button === enumMouseButton.left) {
+ this.root.soundProxy.playUiClick();
+ this.moveToWaypoint(waypoint);
+ } else if (button === enumMouseButton.right) {
+ if (this.isWaypointDeletable(waypoint)) {
+ this.root.soundProxy.playUiClick();
+ this.requestSaveMarker({ waypoint });
+ } else {
+ this.root.soundProxy.playUiError();
+ }
+ }
+
+ return STOP_PROPAGATION;
+ } else {
+ // Allow right click to create a marker
+ if (button === enumMouseButton.right) {
+ if (this.root.camera.getIsMapOverlayActive()) {
+ const worldPos = this.root.camera.screenToWorld(pos);
+ this.requestSaveMarker({ worldPos });
+ return STOP_PROPAGATION;
+ }
+ }
+ }
+ }
+
+ /**
+ * Rerenders the compass
+ */
+ rerenderWaypointsCompass() {
+ const dims = 48;
+ const indicatorSize = 30;
+ const cameraPos = this.root.camera.center;
+
+ const context = this.compassBuffer.context;
+ context.clearRect(0, 0, dims, dims);
+
+ const distanceToHub = cameraPos.length();
+ const compassVisible = distanceToHub > (10 * globalConfig.tileSize) / this.root.camera.zoomLevel;
+ const targetCompassAlpha = compassVisible ? 1 : 0;
+
+ // Fade the compas in / out
+ this.currentCompassOpacity = lerp(this.currentCompassOpacity, targetCompassAlpha, 0.08);
+
+ // Render the compass
+ if (this.currentCompassOpacity > 0.01) {
+ context.globalAlpha = this.currentCompassOpacity;
+ const angle = cameraPos.angle() + Math.radians(45) + Math.PI / 2;
+ context.translate(dims / 2, dims / 2);
+ context.rotate(angle);
+ this.directionIndicatorSprite.drawCentered(context, 0, 0, indicatorSize);
+ context.rotate(-angle);
+ context.translate(-dims / 2, -dims / 2);
+ context.globalAlpha = 1;
+ }
+
+ // Render the regualr icon
+ const iconOpacity = 1 - this.currentCompassOpacity;
+ if (iconOpacity > 0.01) {
+ context.globalAlpha = iconOpacity;
+ this.waypointSprite.drawCentered(context, dims / 2, dims / 2, dims * 0.7);
+ context.globalAlpha = 1;
+ }
+ }
+
+ /**
+ * Draws the waypoints on the map
+ * @param {DrawParameters} parameters
+ */
+ drawOverlays(parameters) {
+ const mousePos = this.root.app.mousePosition;
+ const desiredOpacity = this.root.camera.getIsMapOverlayActive() ? 1 : 0;
+ this.currentMarkerOpacity = lerp(this.currentMarkerOpacity, desiredOpacity, 0.08);
+
+ this.rerenderWaypointsCompass();
+
+ // Don't render with low opacity
+ if (this.currentMarkerOpacity < 0.01) {
+ return;
+ }
+
+ // Determine rendering scale
+ const scale = this.getWaypointUiScale();
+
+ // Set the font size
+ const textSize = this.getTextScale();
+ parameters.context.font = "bold " + textSize + "px GameFont";
+ parameters.context.textBaseline = "middle";
+
+ // Loop over all waypoints
+ for (let i = 0; i < this.waypoints.length; ++i) {
+ const waypoint = this.waypoints[i];
+
+ const waypointData = this.getWaypointScreenParams(waypoint);
+ if (!waypointData) {
+ // Not relevant
+ continue;
+ }
+
+ if (!parameters.visibleRect.containsRect(waypointData.screenBounds)) {
+ // Out of screen
+ continue;
+ }
+
+ const bounds = waypointData.screenBounds;
+ const contentPaddingX = 7 * scale;
+ const isSelected = mousePos && bounds.containsPoint(mousePos.x, mousePos.y);
+
+ // Render the background rectangle
+ parameters.context.globalAlpha = this.currentMarkerOpacity * (isSelected ? 1 : 0.7);
+ parameters.context.fillStyle = "rgba(255, 255, 255, 0.7)";
+ parameters.context.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
+
+ // Render the text
+ if (waypointData.item) {
+ const canvas = this.getWaypointCanvas(waypoint);
+ const itemSize = 14 * scale;
+ parameters.context.drawImage(
+ canvas,
+ bounds.x + contentPaddingX + 6 * scale,
+ bounds.y + bounds.h / 2 - itemSize / 2,
+ itemSize,
+ itemSize
+ );
+ } else if (waypointData.text) {
+ // Render the text
+ parameters.context.fillStyle = "#000";
+ parameters.context.textBaseline = "middle";
+ parameters.context.fillText(
+ waypointData.text,
+ bounds.x + contentPaddingX + 6 * scale,
+ bounds.y + bounds.h / 2
+ );
+ parameters.context.textBaseline = "alphabetic";
+ } else {
+ assertAlways(false, "Waypoint has no item and text");
+ }
+
+ // Render the small icon on the left
+ this.waypointSprite.drawCentered(
+ parameters.context,
+ bounds.x + contentPaddingX,
+ bounds.y + bounds.h / 2,
+ bounds.h * 0.7
+ );
+ }
+
+ parameters.context.textBaseline = "alphabetic";
+ parameters.context.globalAlpha = 1;
+ }
+}
diff --git a/src/js/game/hud/trailer_maker.js b/src/js/game/hud/trailer_maker.js
index 8655def4..e9193a93 100644
--- a/src/js/game/hud/trailer_maker.js
+++ b/src/js/game/hud/trailer_maker.js
@@ -1,125 +1,122 @@
-import { GameRoot } from "../root";
-import { globalConfig } from "../../core/config";
-import { Vector, mixVector } from "../../core/vector";
-import { lerp } from "../../core/utils";
-
-/* dev:start */
-import trailerPoints from "./trailer_points";
-import { gMetaBuildingRegistry } from "../../core/global_registries";
-import { MetaBeltBaseBuilding } from "../buildings/belt_base";
-import { MinerComponent } from "../components/miner";
-
-const tickrate = 1 / 165;
-
-export class TrailerMaker {
- /**
- *
- * @param {GameRoot} root
- */
- constructor(root) {
- this.root = root;
-
- this.markers = [];
- this.playbackMarkers = null;
- this.currentPlaybackOrigin = new Vector();
- this.currentPlaybackZoom = 3;
-
- window.addEventListener("keydown", ev => {
- if (ev.key === "j") {
- console.log("Record");
- this.markers.push({
- pos: this.root.camera.center.copy(),
- zoom: this.root.camera.zoomLevel,
- time: 1,
- wait: 0,
- });
- } else if (ev.key === "k") {
- console.log("Export");
- const json = JSON.stringify(this.markers);
- const handle = window.open("about:blank");
- handle.document.write(json);
- } else if (ev.key === "u") {
- if (this.playbackMarkers && this.playbackMarkers.length > 0) {
- this.playbackMarkers = [];
- return;
- }
- console.log("Playback");
- this.playbackMarkers = trailerPoints.map(p => Object.assign({}, p));
- this.playbackMarkers.unshift(this.playbackMarkers[0]);
- this.currentPlaybackOrigin = Vector.fromSerializedObject(this.playbackMarkers[0].pos);
-
- this.currentPlaybackZoom = this.playbackMarkers[0].zoom;
- this.root.camera.center = this.currentPlaybackOrigin.copy();
- this.root.camera.zoomLevel = this.currentPlaybackZoom;
- console.log("STart at", this.currentPlaybackOrigin);
-
- // this.root.entityMgr.getAllWithComponent(MinerComponent).forEach(miner => {
- // miner.components.Miner.itemChainBuffer = [];
- // miner.components.Miner.lastMiningTime = this.root.time.now() + 5;
- // miner.components.ItemEjector.slots.forEach(slot => (slot.item = null));
- // });
-
- // this.root.logic.tryPlaceBuilding({
- // origin: new Vector(-428, -15),
- // building: gMetaBuildingRegistry.findByClass(MetaBeltBaseBuilding),
- // originalRotation: 0,
- // rotation: 0,
- // variant: "default",
- // rotationVariant: 0,
- // });
-
- // this.root.logic.tryPlaceBuilding({
- // origin: new Vector(-427, -15),
- // building: gMetaBuildingRegistry.findByClass(MetaBeltBaseBuilding),
- // originalRotation: 0,
- // rotation: 0,
- // variant: "default",
- // rotationVariant: 0,
- // });
- }
- });
- }
-
- update() {
- if (this.playbackMarkers && this.playbackMarkers.length > 0) {
- const nextMarker = this.playbackMarkers[0];
-
- if (!nextMarker.startTime) {
- console.log("Starting to approach", nextMarker.pos);
- nextMarker.startTime = performance.now() / 1000.0;
- }
-
- const speed =
- globalConfig.tileSize *
- globalConfig.beltSpeedItemsPerSecond *
- globalConfig.itemSpacingOnBelts;
- // let time =
- // this.currentPlaybackOrigin.distance(Vector.fromSerializedObject(nextMarker.pos)) / speed;
- const time = nextMarker.time;
-
- const progress = (performance.now() / 1000.0 - nextMarker.startTime) / time;
-
- if (progress > 1.0) {
- if (nextMarker.wait > 0) {
- nextMarker.wait -= tickrate;
- } else {
- console.log("Approached");
- this.currentPlaybackOrigin = this.root.camera.center.copy();
- this.currentPlaybackZoom = this.root.camera.zoomLevel;
- this.playbackMarkers.shift();
- }
- return;
- }
-
- const targetPos = Vector.fromSerializedObject(nextMarker.pos);
- const targetZoom = nextMarker.zoom;
-
- const pos = mixVector(this.currentPlaybackOrigin, targetPos, progress);
- const zoom = lerp(this.currentPlaybackZoom, targetZoom, progress);
- this.root.camera.zoomLevel = zoom;
- this.root.camera.center = pos;
- }
- }
-}
-
-/* dev:end */
+import { GameRoot } from "../root";
+import { globalConfig } from "../../core/config";
+import { Vector, mixVector } from "../../core/vector";
+import { lerp } from "../../core/utils";
+
+/* dev:start */
+import trailerPoints from "./trailer_points";
+
+const tickrate = 1 / 165;
+
+export class TrailerMaker {
+ /**
+ *
+ * @param {GameRoot} root
+ */
+ constructor(root) {
+ this.root = root;
+
+ this.markers = [];
+ this.playbackMarkers = null;
+ this.currentPlaybackOrigin = new Vector();
+ this.currentPlaybackZoom = 3;
+
+ window.addEventListener("keydown", ev => {
+ if (ev.key === "j") {
+ console.log("Record");
+ this.markers.push({
+ pos: this.root.camera.center.copy(),
+ zoom: this.root.camera.zoomLevel,
+ time: 1,
+ wait: 0,
+ });
+ } else if (ev.key === "k") {
+ console.log("Export");
+ const json = JSON.stringify(this.markers);
+ const handle = window.open("about:blank");
+ handle.document.write(json);
+ } else if (ev.key === "u") {
+ if (this.playbackMarkers && this.playbackMarkers.length > 0) {
+ this.playbackMarkers = [];
+ return;
+ }
+ console.log("Playback");
+ this.playbackMarkers = trailerPoints.map(p => Object.assign({}, p));
+ this.playbackMarkers.unshift(this.playbackMarkers[0]);
+ this.currentPlaybackOrigin = Vector.fromSerializedObject(this.playbackMarkers[0].pos);
+
+ this.currentPlaybackZoom = this.playbackMarkers[0].zoom;
+ this.root.camera.center = this.currentPlaybackOrigin.copy();
+ this.root.camera.zoomLevel = this.currentPlaybackZoom;
+ console.log("STart at", this.currentPlaybackOrigin);
+
+ // this.root.entityMgr.getAllWithComponent(MinerComponent).forEach(miner => {
+ // miner.components.Miner.itemChainBuffer = [];
+ // miner.components.Miner.lastMiningTime = this.root.time.now() + 5;
+ // miner.components.ItemEjector.slots.forEach(slot => (slot.item = null));
+ // });
+
+ // this.root.logic.tryPlaceBuilding({
+ // origin: new Vector(-428, -15),
+ // building: gMetaBuildingRegistry.findByClass(MetaBeltBaseBuilding),
+ // originalRotation: 0,
+ // rotation: 0,
+ // variant: "default",
+ // rotationVariant: 0,
+ // });
+
+ // this.root.logic.tryPlaceBuilding({
+ // origin: new Vector(-427, -15),
+ // building: gMetaBuildingRegistry.findByClass(MetaBeltBaseBuilding),
+ // originalRotation: 0,
+ // rotation: 0,
+ // variant: "default",
+ // rotationVariant: 0,
+ // });
+ }
+ });
+ }
+
+ update() {
+ if (this.playbackMarkers && this.playbackMarkers.length > 0) {
+ const nextMarker = this.playbackMarkers[0];
+
+ if (!nextMarker.startTime) {
+ console.log("Starting to approach", nextMarker.pos);
+ nextMarker.startTime = performance.now() / 1000.0;
+ }
+
+ const speed =
+ globalConfig.tileSize *
+ globalConfig.beltSpeedItemsPerSecond *
+ globalConfig.itemSpacingOnBelts;
+ // let time =
+ // this.currentPlaybackOrigin.distance(Vector.fromSerializedObject(nextMarker.pos)) / speed;
+ const time = nextMarker.time;
+
+ const progress = (performance.now() / 1000.0 - nextMarker.startTime) / time;
+
+ if (progress > 1.0) {
+ if (nextMarker.wait > 0) {
+ nextMarker.wait -= tickrate;
+ } else {
+ console.log("Approached");
+ this.currentPlaybackOrigin = this.root.camera.center.copy();
+ this.currentPlaybackZoom = this.root.camera.zoomLevel;
+ this.playbackMarkers.shift();
+ }
+ return;
+ }
+
+ const targetPos = Vector.fromSerializedObject(nextMarker.pos);
+ const targetZoom = nextMarker.zoom;
+
+ const pos = mixVector(this.currentPlaybackOrigin, targetPos, progress);
+ const zoom = lerp(this.currentPlaybackZoom, targetZoom, progress);
+ this.root.camera.zoomLevel = zoom;
+ this.root.camera.center = pos;
+ }
+ }
+}
+
+/* dev:end */
diff --git a/src/js/game/items/color_item.js b/src/js/game/items/color_item.js
index 19d26286..02104282 100644
--- a/src/js/game/items/color_item.js
+++ b/src/js/game/items/color_item.js
@@ -1,122 +1,73 @@
-import { globalConfig } from "../../core/config";
-import { smoothenDpi } from "../../core/dpi_manager";
-import { DrawParameters } from "../../core/draw_parameters";
-import { types } from "../../savegame/serialization";
-import { BaseItem } from "../base_item";
-import { enumColors, enumColorsToHexCode } from "../colors";
-import { THEME } from "../theme";
-import { drawSpriteClipped } from "../../core/draw_utils";
-
-export class ColorItem extends BaseItem {
- static getId() {
- return "color";
- }
-
- static getSchema() {
- return types.enum(enumColors);
- }
-
- serialize() {
- return this.color;
- }
-
- deserialize(data) {
- this.color = data;
- }
-
- /** @returns {"color"} **/
- getItemType() {
- return "color";
- }
-
- /**
- * @param {BaseItem} other
- */
- equalsImpl(other) {
- return this.color === /** @type {ColorItem} */ (other).color;
- }
-
- /**
- * @param {enumColors} color
- */
- constructor(color) {
- super();
- this.color = color;
- this.bufferGenerator = null;
- }
-
- getBackgroundColorAsResource() {
- return THEME.map.resources[this.color];
- }
-
- /**
- * @param {number} x
- * @param {number} y
- * @param {number} diameter
- * @param {DrawParameters} parameters
- */
- drawItemCenteredImpl(x, y, parameters, diameter = globalConfig.defaultItemDiameter) {
- if (!this.bufferGenerator) {
- this.bufferGenerator = this.internalGenerateColorBuffer.bind(this);
- }
-
- const realDiameter = diameter * 0.6;
- const dpi = smoothenDpi(globalConfig.shapesSharpness * parameters.zoomLevel);
- const key = realDiameter + "/" + dpi + "/" + this.color;
- const canvas = parameters.root.buffers.getForKey({
- key: "coloritem",
- subKey: key,
- w: realDiameter,
- h: realDiameter,
- dpi,
- redrawMethod: this.bufferGenerator,
- });
-
- drawSpriteClipped({
- parameters,
- sprite: canvas,
- x: x - realDiameter / 2,
- y: y - realDiameter / 2,
- w: realDiameter,
- h: realDiameter,
- originalW: realDiameter * dpi,
- originalH: realDiameter * dpi,
- });
- }
- /**
- *
- * @param {HTMLCanvasElement} canvas
- * @param {CanvasRenderingContext2D} context
- * @param {number} w
- * @param {number} h
- * @param {number} dpi
- */
- internalGenerateColorBuffer(canvas, context, w, h, dpi) {
- context.translate((w * dpi) / 2, (h * dpi) / 2);
- context.scale((dpi * w) / 12, (dpi * h) / 12);
-
- context.fillStyle = enumColorsToHexCode[this.color];
- context.strokeStyle = THEME.items.outline;
- context.lineWidth = 2 * THEME.items.outlineWidth;
- context.beginCircle(2, -1, 3);
- context.stroke();
- context.fill();
- context.beginCircle(-2, -1, 3);
- context.stroke();
- context.fill();
- context.beginCircle(0, 2, 3);
- context.closePath();
- context.stroke();
- context.fill();
- }
-}
-
-/**
- * Singleton instances
- * @type {Object}
- */
-export const COLOR_ITEM_SINGLETONS = {};
-
-for (const color in enumColors) {
- COLOR_ITEM_SINGLETONS[color] = new ColorItem(color);
-}
+import { globalConfig } from "../../core/config";
+import { DrawParameters } from "../../core/draw_parameters";
+import { Loader } from "../../core/loader";
+import { types } from "../../savegame/serialization";
+import { BaseItem } from "../base_item";
+import { enumColors } from "../colors";
+import { THEME } from "../theme";
+
+export class ColorItem extends BaseItem {
+ static getId() {
+ return "color";
+ }
+
+ static getSchema() {
+ return types.enum(enumColors);
+ }
+
+ serialize() {
+ return this.color;
+ }
+
+ deserialize(data) {
+ this.color = data;
+ }
+
+ /** @returns {"color"} **/
+ getItemType() {
+ return "color";
+ }
+
+ /**
+ * @param {BaseItem} other
+ */
+ equalsImpl(other) {
+ return this.color === /** @type {ColorItem} */ (other).color;
+ }
+
+ /**
+ * @param {enumColors} color
+ */
+ constructor(color) {
+ super();
+ this.color = color;
+ }
+
+ getBackgroundColorAsResource() {
+ return THEME.map.resources[this.color];
+ }
+
+ /**
+ * @param {number} x
+ * @param {number} y
+ * @param {number} diameter
+ * @param {DrawParameters} parameters
+ */
+ drawItemCenteredClipped(x, y, parameters, diameter = globalConfig.defaultItemDiameter) {
+ const realDiameter = diameter * 0.6;
+ if (!this.cachedSprite) {
+ this.cachedSprite = Loader.getSprite("sprites/colors/" + this.color + ".png");
+ }
+ this.cachedSprite.drawCachedCentered(parameters, x, y, realDiameter);
+ }
+}
+
+/**
+ * Singleton instances
+ * @type {Object}
+ */
+export const COLOR_ITEM_SINGLETONS = {};
+
+for (const color in enumColors) {
+ COLOR_ITEM_SINGLETONS[color] = new ColorItem(color);
+}
diff --git a/src/js/game/key_action_mapper.js b/src/js/game/key_action_mapper.js
index d5a758a5..074c4b84 100644
--- a/src/js/game/key_action_mapper.js
+++ b/src/js/game/key_action_mapper.js
@@ -45,7 +45,7 @@ export const KEYMAPPINGS = {
buildings: {
belt: { keyCode: key("1") },
- splitter: { keyCode: key("2") },
+ balancer: { keyCode: key("2") },
underground_belt: { keyCode: key("3") },
miner: { keyCode: key("4") },
cutter: { keyCode: key("5") },
@@ -204,22 +204,20 @@ export function getStringForKeyCode(code) {
case 115:
return "F4";
case 116:
- return "F4";
- case 117:
return "F5";
- case 118:
+ case 117:
return "F6";
- case 119:
+ case 118:
return "F7";
- case 120:
+ case 119:
return "F8";
- case 121:
+ case 120:
return "F9";
- case 122:
+ case 121:
return "F10";
- case 123:
+ case 122:
return "F11";
- case 124:
+ case 123:
return "F12";
case 144:
diff --git a/src/js/game/map.js b/src/js/game/map.js
index 5ff51ce8..a5ec8f21 100644
--- a/src/js/game/map.js
+++ b/src/js/game/map.js
@@ -1,236 +1,236 @@
-import { globalConfig } from "../core/config";
-import { Vector } from "../core/vector";
-import { BasicSerializableObject, types } from "../savegame/serialization";
-import { BaseItem } from "./base_item";
-import { Entity } from "./entity";
-import { MapChunkView } from "./map_chunk_view";
-import { GameRoot } from "./root";
-
-export class BaseMap extends BasicSerializableObject {
- static getId() {
- return "Map";
- }
-
- static getSchema() {
- return {
- seed: types.uint,
- };
- }
-
- /**
- *
- * @param {GameRoot} root
- */
- constructor(root) {
- super();
- this.root = root;
-
- this.seed = 0;
-
- /**
- * Mapping of 'X|Y' to chunk
- * @type {Map} */
- this.chunksById = new Map();
- }
-
- /**
- * Returns the given chunk by index
- * @param {number} chunkX
- * @param {number} chunkY
- */
- getChunk(chunkX, chunkY, createIfNotExistent = false) {
- const chunkIdentifier = chunkX + "|" + chunkY;
- let storedChunk;
-
- if ((storedChunk = this.chunksById.get(chunkIdentifier))) {
- return storedChunk;
- }
-
- if (createIfNotExistent) {
- const instance = new MapChunkView(this.root, chunkX, chunkY);
- this.chunksById.set(chunkIdentifier, instance);
- return instance;
- }
-
- return null;
- }
-
- /**
- * Gets or creates a new chunk if not existent for the given tile
- * @param {number} tileX
- * @param {number} tileY
- * @returns {MapChunkView}
- */
- getOrCreateChunkAtTile(tileX, tileY) {
- const chunkX = Math.floor(tileX / globalConfig.mapChunkSize);
- const chunkY = Math.floor(tileY / globalConfig.mapChunkSize);
- return this.getChunk(chunkX, chunkY, true);
- }
-
- /**
- * Gets a chunk if not existent for the given tile
- * @param {number} tileX
- * @param {number} tileY
- * @returns {MapChunkView?}
- */
- getChunkAtTileOrNull(tileX, tileY) {
- const chunkX = Math.floor(tileX / globalConfig.mapChunkSize);
- const chunkY = Math.floor(tileY / globalConfig.mapChunkSize);
- return this.getChunk(chunkX, chunkY, false);
- }
-
- /**
- * Checks if a given tile is within the map bounds
- * @param {Vector} tile
- * @returns {boolean}
- */
- isValidTile(tile) {
- if (G_IS_DEV) {
- assert(tile instanceof Vector, "tile is not a vector");
- }
- return Number.isInteger(tile.x) && Number.isInteger(tile.y);
- }
-
- /**
- * Returns the tile content of a given tile
- * @param {Vector} tile
- * @param {Layer} layer
- * @returns {Entity} Entity or null
- */
- getTileContent(tile, layer) {
- if (G_IS_DEV) {
- this.internalCheckTile(tile);
- }
- const chunk = this.getChunkAtTileOrNull(tile.x, tile.y);
- return chunk && chunk.getLayerContentFromWorldCoords(tile.x, tile.y, layer);
- }
-
- /**
- * Returns the lower layers content of the given tile
- * @param {number} x
- * @param {number} y
- * @returns {BaseItem=}
- */
- getLowerLayerContentXY(x, y) {
- return this.getOrCreateChunkAtTile(x, y).getLowerLayerFromWorldCoords(x, y);
- }
-
- /**
- * Returns the tile content of a given tile
- * @param {number} x
- * @param {number} y
- * @param {Layer} layer
- * @returns {Entity} Entity or null
- */
- getLayerContentXY(x, y, layer) {
- const chunk = this.getChunkAtTileOrNull(x, y);
- return chunk && chunk.getLayerContentFromWorldCoords(x, y, layer);
- }
-
- /**
- * Returns the tile contents of a given tile
- * @param {number} x
- * @param {number} y
- * @returns {Array} Entity or null
- */
- getLayersContentsMultipleXY(x, y) {
- const chunk = this.getChunkAtTileOrNull(x, y);
- if (!chunk) {
- return [];
- }
- return chunk.getLayersContentsMultipleFromWorldCoords(x, y);
- }
-
- /**
- * Checks if the tile is used
- * @param {Vector} tile
- * @param {Layer} layer
- * @returns {boolean}
- */
- isTileUsed(tile, layer) {
- if (G_IS_DEV) {
- this.internalCheckTile(tile);
- }
- const chunk = this.getChunkAtTileOrNull(tile.x, tile.y);
- return chunk && chunk.getLayerContentFromWorldCoords(tile.x, tile.y, layer) != null;
- }
-
- /**
- * Checks if the tile is used
- * @param {number} x
- * @param {number} y
- * @param {Layer} layer
- * @returns {boolean}
- */
- isTileUsedXY(x, y, layer) {
- const chunk = this.getChunkAtTileOrNull(x, y);
- return chunk && chunk.getLayerContentFromWorldCoords(x, y, layer) != null;
- }
-
- /**
- * Sets the tiles content
- * @param {Vector} tile
- * @param {Entity} entity
- */
- setTileContent(tile, entity) {
- if (G_IS_DEV) {
- this.internalCheckTile(tile);
- }
-
- this.getOrCreateChunkAtTile(tile.x, tile.y).setLayerContentFromWorldCords(
- tile.x,
- tile.y,
- entity,
- entity.layer
- );
-
- const staticComponent = entity.components.StaticMapEntity;
- assert(staticComponent, "Can only place static map entities in tiles");
- }
-
- /**
- * Places an entity with the StaticMapEntity component
- * @param {Entity} entity
- */
- placeStaticEntity(entity) {
- assert(entity.components.StaticMapEntity, "Entity is not static");
- const staticComp = entity.components.StaticMapEntity;
- const rect = staticComp.getTileSpaceBounds();
- for (let dx = 0; dx < rect.w; ++dx) {
- for (let dy = 0; dy < rect.h; ++dy) {
- const x = rect.x + dx;
- const y = rect.y + dy;
- this.getOrCreateChunkAtTile(x, y).setLayerContentFromWorldCords(x, y, entity, entity.layer);
- }
- }
- }
-
- /**
- * Removes an entity with the StaticMapEntity component
- * @param {Entity} entity
- */
- removeStaticEntity(entity) {
- assert(entity.components.StaticMapEntity, "Entity is not static");
- const staticComp = entity.components.StaticMapEntity;
- const rect = staticComp.getTileSpaceBounds();
- for (let dx = 0; dx < rect.w; ++dx) {
- for (let dy = 0; dy < rect.h; ++dy) {
- const x = rect.x + dx;
- const y = rect.y + dy;
- this.getOrCreateChunkAtTile(x, y).setLayerContentFromWorldCords(x, y, null, entity.layer);
- }
- }
- }
-
- // Internal
-
- /**
- * Checks a given tile for validty
- * @param {Vector} tile
- */
- internalCheckTile(tile) {
- assert(tile instanceof Vector, "tile is not a vector: " + tile);
- assert(tile.x % 1 === 0, "Tile X is not a valid integer: " + tile.x);
- assert(tile.y % 1 === 0, "Tile Y is not a valid integer: " + tile.y);
- }
-}
+import { globalConfig } from "../core/config";
+import { Vector } from "../core/vector";
+import { BasicSerializableObject, types } from "../savegame/serialization";
+import { BaseItem } from "./base_item";
+import { Entity } from "./entity";
+import { MapChunkView } from "./map_chunk_view";
+import { GameRoot } from "./root";
+
+export class BaseMap extends BasicSerializableObject {
+ static getId() {
+ return "Map";
+ }
+
+ static getSchema() {
+ return {
+ seed: types.uint,
+ };
+ }
+
+ /**
+ *
+ * @param {GameRoot} root
+ */
+ constructor(root) {
+ super();
+ this.root = root;
+
+ this.seed = 0;
+
+ /**
+ * Mapping of 'X|Y' to chunk
+ * @type {Map} */
+ this.chunksById = new Map();
+ }
+
+ /**
+ * Returns the given chunk by index
+ * @param {number} chunkX
+ * @param {number} chunkY
+ */
+ getChunk(chunkX, chunkY, createIfNotExistent = false) {
+ const chunkIdentifier = chunkX + "|" + chunkY;
+ let storedChunk;
+
+ if ((storedChunk = this.chunksById.get(chunkIdentifier))) {
+ return storedChunk;
+ }
+
+ if (createIfNotExistent) {
+ const instance = new MapChunkView(this.root, chunkX, chunkY);
+ this.chunksById.set(chunkIdentifier, instance);
+ return instance;
+ }
+
+ return null;
+ }
+
+ /**
+ * Gets or creates a new chunk if not existent for the given tile
+ * @param {number} tileX
+ * @param {number} tileY
+ * @returns {MapChunkView}
+ */
+ getOrCreateChunkAtTile(tileX, tileY) {
+ const chunkX = Math.floor(tileX / globalConfig.mapChunkSize);
+ const chunkY = Math.floor(tileY / globalConfig.mapChunkSize);
+ return this.getChunk(chunkX, chunkY, true);
+ }
+
+ /**
+ * Gets a chunk if not existent for the given tile
+ * @param {number} tileX
+ * @param {number} tileY
+ * @returns {MapChunkView?}
+ */
+ getChunkAtTileOrNull(tileX, tileY) {
+ const chunkX = Math.floor(tileX / globalConfig.mapChunkSize);
+ const chunkY = Math.floor(tileY / globalConfig.mapChunkSize);
+ return this.getChunk(chunkX, chunkY, false);
+ }
+
+ /**
+ * Checks if a given tile is within the map bounds
+ * @param {Vector} tile
+ * @returns {boolean}
+ */
+ isValidTile(tile) {
+ if (G_IS_DEV) {
+ assert(tile instanceof Vector, "tile is not a vector");
+ }
+ return Number.isInteger(tile.x) && Number.isInteger(tile.y);
+ }
+
+ /**
+ * Returns the tile content of a given tile
+ * @param {Vector} tile
+ * @param {Layer} layer
+ * @returns {Entity} Entity or null
+ */
+ getTileContent(tile, layer) {
+ if (G_IS_DEV) {
+ this.internalCheckTile(tile);
+ }
+ const chunk = this.getChunkAtTileOrNull(tile.x, tile.y);
+ return chunk && chunk.getLayerContentFromWorldCoords(tile.x, tile.y, layer);
+ }
+
+ /**
+ * Returns the lower layers content of the given tile
+ * @param {number} x
+ * @param {number} y
+ * @returns {BaseItem=}
+ */
+ getLowerLayerContentXY(x, y) {
+ return this.getOrCreateChunkAtTile(x, y).getLowerLayerFromWorldCoords(x, y);
+ }
+
+ /**
+ * Returns the tile content of a given tile
+ * @param {number} x
+ * @param {number} y
+ * @param {Layer} layer
+ * @returns {Entity} Entity or null
+ */
+ getLayerContentXY(x, y, layer) {
+ const chunk = this.getChunkAtTileOrNull(x, y);
+ return chunk && chunk.getLayerContentFromWorldCoords(x, y, layer);
+ }
+
+ /**
+ * Returns the tile contents of a given tile
+ * @param {number} x
+ * @param {number} y
+ * @returns {Array} Entity or null
+ */
+ getLayersContentsMultipleXY(x, y) {
+ const chunk = this.getChunkAtTileOrNull(x, y);
+ if (!chunk) {
+ return [];
+ }
+ return chunk.getLayersContentsMultipleFromWorldCoords(x, y);
+ }
+
+ /**
+ * Checks if the tile is used
+ * @param {Vector} tile
+ * @param {Layer} layer
+ * @returns {boolean}
+ */
+ isTileUsed(tile, layer) {
+ if (G_IS_DEV) {
+ this.internalCheckTile(tile);
+ }
+ const chunk = this.getChunkAtTileOrNull(tile.x, tile.y);
+ return chunk && chunk.getLayerContentFromWorldCoords(tile.x, tile.y, layer) != null;
+ }
+
+ /**
+ * Checks if the tile is used
+ * @param {number} x
+ * @param {number} y
+ * @param {Layer} layer
+ * @returns {boolean}
+ */
+ isTileUsedXY(x, y, layer) {
+ const chunk = this.getChunkAtTileOrNull(x, y);
+ return chunk && chunk.getLayerContentFromWorldCoords(x, y, layer) != null;
+ }
+
+ /**
+ * Sets the tiles content
+ * @param {Vector} tile
+ * @param {Entity} entity
+ */
+ setTileContent(tile, entity) {
+ if (G_IS_DEV) {
+ this.internalCheckTile(tile);
+ }
+
+ this.getOrCreateChunkAtTile(tile.x, tile.y).setLayerContentFromWorldCords(
+ tile.x,
+ tile.y,
+ entity,
+ entity.layer
+ );
+
+ const staticComponent = entity.components.StaticMapEntity;
+ assert(staticComponent, "Can only place static map entities in tiles");
+ }
+
+ /**
+ * Places an entity with the StaticMapEntity component
+ * @param {Entity} entity
+ */
+ placeStaticEntity(entity) {
+ assert(entity.components.StaticMapEntity, "Entity is not static");
+ const staticComp = entity.components.StaticMapEntity;
+ const rect = staticComp.getTileSpaceBounds();
+ for (let dx = 0; dx < rect.w; ++dx) {
+ for (let dy = 0; dy < rect.h; ++dy) {
+ const x = rect.x + dx;
+ const y = rect.y + dy;
+ this.getOrCreateChunkAtTile(x, y).setLayerContentFromWorldCords(x, y, entity, entity.layer);
+ }
+ }
+ }
+
+ /**
+ * Removes an entity with the StaticMapEntity component
+ * @param {Entity} entity
+ */
+ removeStaticEntity(entity) {
+ assert(entity.components.StaticMapEntity, "Entity is not static");
+ const staticComp = entity.components.StaticMapEntity;
+ const rect = staticComp.getTileSpaceBounds();
+ for (let dx = 0; dx < rect.w; ++dx) {
+ for (let dy = 0; dy < rect.h; ++dy) {
+ const x = rect.x + dx;
+ const y = rect.y + dy;
+ this.getOrCreateChunkAtTile(x, y).setLayerContentFromWorldCords(x, y, null, entity.layer);
+ }
+ }
+ }
+
+ // Internal
+
+ /**
+ * Checks a given tile for validty
+ * @param {Vector} tile
+ */
+ internalCheckTile(tile) {
+ assert(tile instanceof Vector, "tile is not a vector: " + tile);
+ assert(tile.x % 1 === 0, "Tile X is not a valid integer: " + tile.x);
+ assert(tile.y % 1 === 0, "Tile Y is not a valid integer: " + tile.y);
+ }
+}
diff --git a/src/js/game/map_chunk_view.js b/src/js/game/map_chunk_view.js
index 7d74e224..58730f90 100644
--- a/src/js/game/map_chunk_view.js
+++ b/src/js/game/map_chunk_view.js
@@ -88,16 +88,17 @@ export class MapChunkView extends MapChunk {
});
const dims = globalConfig.mapChunkWorldSize;
+ const extrude = 0.05;
// Draw chunk "pixel" art
parameters.context.imageSmoothingEnabled = false;
drawSpriteClipped({
parameters,
sprite,
- x: this.x * dims,
- y: this.y * dims,
- w: dims,
- h: dims,
+ x: this.x * dims - extrude,
+ y: this.y * dims - extrude,
+ w: dims + 2 * extrude,
+ h: dims + 2 * extrude,
originalW: overlaySize,
originalH: overlaySize,
});
@@ -108,12 +109,12 @@ export class MapChunkView extends MapChunk {
if (this.root.currentLayer === "regular") {
for (let i = 0; i < this.patches.length; ++i) {
const patch = this.patches[i];
-
- const destX = this.x * dims + patch.pos.x * globalConfig.tileSize;
- const destY = this.y * dims + patch.pos.y * globalConfig.tileSize;
- const diameter = Math.min(80, 30 / parameters.zoomLevel);
-
- patch.item.drawItemCenteredClipped(destX, destY, parameters, diameter);
+ if (patch.item.getItemType() === "shape") {
+ const destX = this.x * dims + patch.pos.x * globalConfig.tileSize;
+ const destY = this.y * dims + patch.pos.y * globalConfig.tileSize;
+ const diameter = 80 / Math.pow(parameters.zoomLevel, 0.35);
+ patch.item.drawItemCenteredClipped(destX, destY, parameters, diameter);
+ }
}
}
}
diff --git a/src/js/game/map_view.js b/src/js/game/map_view.js
index 0e0f3d5b..0f2ceb89 100644
--- a/src/js/game/map_view.js
+++ b/src/js/game/map_view.js
@@ -66,32 +66,34 @@ export class MapView extends BaseMap {
* @param {DrawParameters} drawParameters
*/
drawStaticEntityDebugOverlays(drawParameters) {
- const cullRange = drawParameters.visibleRect.toTileCullRectangle();
- const top = cullRange.top();
- const right = cullRange.right();
- const bottom = cullRange.bottom();
- const left = cullRange.left();
+ if (G_IS_DEV && (globalConfig.debug.showAcceptorEjectors || globalConfig.debug.showEntityBounds)) {
+ const cullRange = drawParameters.visibleRect.toTileCullRectangle();
+ const top = cullRange.top();
+ const right = cullRange.right();
+ const bottom = cullRange.bottom();
+ const left = cullRange.left();
- const border = 1;
+ const border = 1;
- const minY = top - border;
- const maxY = bottom + border;
- const minX = left - border;
- const maxX = right + border - 1;
+ const minY = top - border;
+ const maxY = bottom + border;
+ const minX = left - border;
+ const maxX = right + border - 1;
- // Render y from top down for proper blending
- for (let y = minY; y <= maxY; ++y) {
- for (let x = minX; x <= maxX; ++x) {
- // const content = this.tiles[x][y];
- const chunk = this.getChunkAtTileOrNull(x, y);
- if (!chunk) {
- continue;
- }
- const content = chunk.getTileContentFromWorldCoords(x, y);
- if (content) {
- let isBorder = x <= left - 1 || x >= right + 1 || y <= top - 1 || y >= bottom + 1;
- if (!isBorder) {
- content.drawDebugOverlays(drawParameters);
+ // Render y from top down for proper blending
+ for (let y = minY; y <= maxY; ++y) {
+ for (let x = minX; x <= maxX; ++x) {
+ // const content = this.tiles[x][y];
+ const chunk = this.getChunkAtTileOrNull(x, y);
+ if (!chunk) {
+ continue;
+ }
+ const content = chunk.getTileContentFromWorldCoords(x, y);
+ if (content) {
+ let isBorder = x <= left - 1 || x >= right + 1 || y <= top - 1 || y >= bottom + 1;
+ if (!isBorder) {
+ content.drawDebugOverlays(drawParameters);
+ }
}
}
}
diff --git a/src/js/game/meta_building_registry.js b/src/js/game/meta_building_registry.js
index 647e55f5..4b7095df 100644
--- a/src/js/game/meta_building_registry.js
+++ b/src/js/game/meta_building_registry.js
@@ -1,19 +1,18 @@
import { gMetaBuildingRegistry } from "../core/global_registries";
import { createLogger } from "../core/logging";
import { MetaBeltBuilding } from "./buildings/belt";
-import { MetaBeltBaseBuilding } from "./buildings/belt_base";
import { enumCutterVariants, MetaCutterBuilding } from "./buildings/cutter";
import { MetaHubBuilding } from "./buildings/hub";
import { enumMinerVariants, MetaMinerBuilding } from "./buildings/miner";
import { MetaMixerBuilding } from "./buildings/mixer";
import { enumPainterVariants, MetaPainterBuilding } from "./buildings/painter";
import { enumRotaterVariants, MetaRotaterBuilding } from "./buildings/rotater";
-import { enumSplitterVariants, MetaSplitterBuilding } from "./buildings/splitter";
+import { enumBalancerVariants, MetaBalancerBuilding } from "./buildings/balancer";
import { MetaStackerBuilding } from "./buildings/stacker";
import { enumTrashVariants, MetaTrashBuilding } from "./buildings/trash";
import { enumUndergroundBeltVariants, MetaUndergroundBeltBuilding } from "./buildings/underground_belt";
import { MetaWireBuilding } from "./buildings/wire";
-import { gBuildingVariants, registerBuildingVariant } from "./building_codes";
+import { buildBuildingCodeCache, gBuildingVariants, registerBuildingVariant } from "./building_codes";
import { defaultBuildingVariant } from "./meta_building";
import { MetaConstantSignalBuilding } from "./buildings/constant_signal";
import { MetaLogicGateBuilding, enumLogicGateVariants } from "./buildings/logic_gate";
@@ -27,7 +26,7 @@ import { MetaReaderBuilding } from "./buildings/reader";
const logger = createLogger("building_registry");
export function initMetaBuildingRegistry() {
- gMetaBuildingRegistry.register(MetaSplitterBuilding);
+ gMetaBuildingRegistry.register(MetaBalancerBuilding);
gMetaBuildingRegistry.register(MetaMinerBuilding);
gMetaBuildingRegistry.register(MetaCutterBuilding);
gMetaBuildingRegistry.register(MetaRotaterBuilding);
@@ -49,16 +48,16 @@ export function initMetaBuildingRegistry() {
gMetaBuildingRegistry.register(MetaReaderBuilding);
// Belt
- registerBuildingVariant(1, MetaBeltBaseBuilding, defaultBuildingVariant, 0);
- registerBuildingVariant(2, MetaBeltBaseBuilding, defaultBuildingVariant, 1);
- registerBuildingVariant(3, MetaBeltBaseBuilding, defaultBuildingVariant, 2);
+ registerBuildingVariant(1, MetaBeltBuilding, defaultBuildingVariant, 0);
+ registerBuildingVariant(2, MetaBeltBuilding, defaultBuildingVariant, 1);
+ registerBuildingVariant(3, MetaBeltBuilding, defaultBuildingVariant, 2);
- // Splitter
- registerBuildingVariant(4, MetaSplitterBuilding);
- registerBuildingVariant(5, MetaSplitterBuilding, enumSplitterVariants.compact);
- registerBuildingVariant(6, MetaSplitterBuilding, enumSplitterVariants.compactInverse);
- registerBuildingVariant(47, MetaSplitterBuilding, enumSplitterVariants.compactMerge);
- registerBuildingVariant(48, MetaSplitterBuilding, enumSplitterVariants.compactMergeInverse);
+ // Balancer
+ registerBuildingVariant(4, MetaBalancerBuilding);
+ registerBuildingVariant(5, MetaBalancerBuilding, enumBalancerVariants.merger);
+ registerBuildingVariant(6, MetaBalancerBuilding, enumBalancerVariants.mergerInverse);
+ registerBuildingVariant(47, MetaBalancerBuilding, enumBalancerVariants.splitter);
+ registerBuildingVariant(48, MetaBalancerBuilding, enumBalancerVariants.splitterInverse);
// Miner
registerBuildingVariant(7, MetaMinerBuilding);
@@ -71,7 +70,7 @@ export function initMetaBuildingRegistry() {
// Rotater
registerBuildingVariant(11, MetaRotaterBuilding);
registerBuildingVariant(12, MetaRotaterBuilding, enumRotaterVariants.ccw);
- registerBuildingVariant(13, MetaRotaterBuilding, enumRotaterVariants.fl);
+ registerBuildingVariant(13, MetaRotaterBuilding, enumRotaterVariants.rotate180);
// Stacker
registerBuildingVariant(14, MetaStackerBuilding);
@@ -133,6 +132,8 @@ export function initMetaBuildingRegistry() {
registerBuildingVariant(44, MetaVirtualProcessorBuilding, enumVirtualProcessorVariants.rotater);
registerBuildingVariant(45, MetaVirtualProcessorBuilding, enumVirtualProcessorVariants.unstacker);
registerBuildingVariant(46, MetaVirtualProcessorBuilding, enumVirtualProcessorVariants.shapecompare);
+ registerBuildingVariant(50, MetaVirtualProcessorBuilding, enumVirtualProcessorVariants.stacker);
+ registerBuildingVariant(51, MetaVirtualProcessorBuilding, enumVirtualProcessorVariants.painter);
// Reader
registerBuildingVariant(49, MetaReaderBuilding);
@@ -175,4 +176,7 @@ export function initBuildingCodesAfterResourcesLoaded() {
);
variant.silhouetteColor = variant.metaInstance.getSilhouetteColor();
}
+
+ // Update caches
+ buildBuildingCodeCache();
}
diff --git a/src/js/game/shape_definition.js b/src/js/game/shape_definition.js
index 65b72a1a..9060a1b5 100644
--- a/src/js/game/shape_definition.js
+++ b/src/js/game/shape_definition.js
@@ -487,10 +487,10 @@ export class ShapeDefinition extends BasicSerializableObject {
}
/**
- * Returns a definition which was rotated 180 degrees (flipped)
+ * Returns a definition which was rotated 180 degrees
* @returns {ShapeDefinition}
*/
- cloneRotateFL() {
+ cloneRotate180() {
const newLayers = this.internalCloneLayers();
for (let layerIndex = 0; layerIndex < newLayers.length; ++layerIndex) {
const quadrants = newLayers[layerIndex];
diff --git a/src/js/game/shape_definition_manager.js b/src/js/game/shape_definition_manager.js
index ef0d592f..86723fcd 100644
--- a/src/js/game/shape_definition_manager.js
+++ b/src/js/game/shape_definition_manager.js
@@ -1,259 +1,259 @@
-import { createLogger } from "../core/logging";
-import { BasicSerializableObject } from "../savegame/serialization";
-import { enumColors } from "./colors";
-import { ShapeItem } from "./items/shape_item";
-import { GameRoot } from "./root";
-import { enumSubShape, ShapeDefinition } from "./shape_definition";
-
-const logger = createLogger("shape_definition_manager");
-
-export class ShapeDefinitionManager extends BasicSerializableObject {
- static getId() {
- return "ShapeDefinitionManager";
- }
-
- /**
- *
- * @param {GameRoot} root
- */
- constructor(root) {
- super();
- this.root = root;
-
- /**
- * Store a cache from key -> definition
- * @type {Object}
- */
- this.shapeKeyToDefinition = {};
-
- /**
- * Store a cache from key -> item
- */
- this.shapeKeyToItem = {};
-
- // Caches operations in the form of 'operation:def1[:def2]'
- /** @type {Object.|ShapeDefinition>} */
- this.operationCache = {};
- }
-
- /**
- * Returns a shape instance from a given short key
- * @param {string} hash
- * @returns {ShapeDefinition}
- */
- getShapeFromShortKey(hash) {
- const cached = this.shapeKeyToDefinition[hash];
- if (cached) {
- return cached;
- }
- return (this.shapeKeyToDefinition[hash] = ShapeDefinition.fromShortKey(hash));
- }
-
- /**
- * Returns a item instance from a given short key
- * @param {string} hash
- * @returns {ShapeItem}
- */
- getShapeItemFromShortKey(hash) {
- const cached = this.shapeKeyToItem[hash];
- if (cached) {
- return cached;
- }
- const definition = this.getShapeFromShortKey(hash);
- return (this.shapeKeyToItem[hash] = new ShapeItem(definition));
- }
-
- /**
- * Returns a shape item for a given definition
- * @param {ShapeDefinition} definition
- * @returns {ShapeItem}
- */
- getShapeItemFromDefinition(definition) {
- return this.getShapeItemFromShortKey(definition.getHash());
- }
-
- /**
- * Registers a new shape definition
- * @param {ShapeDefinition} definition
- */
- registerShapeDefinition(definition) {
- const id = definition.getHash();
- assert(!this.shapeKeyToDefinition[id], "Shape Definition " + id + " already exists");
- this.shapeKeyToDefinition[id] = definition;
- // logger.log("Registered shape with key", id);
- }
-
- /**
- * Generates a definition for splitting a shape definition in two halfs
- * @param {ShapeDefinition} definition
- * @returns {[ShapeDefinition, ShapeDefinition]}
- */
- shapeActionCutHalf(definition) {
- const key = "cut:" + definition.getHash();
- if (this.operationCache[key]) {
- return /** @type {[ShapeDefinition, ShapeDefinition]} */ (this.operationCache[key]);
- }
- const rightSide = definition.cloneFilteredByQuadrants([2, 3]);
- const leftSide = definition.cloneFilteredByQuadrants([0, 1]);
-
- return /** @type {[ShapeDefinition, ShapeDefinition]} */ (this.operationCache[key] = [
- this.registerOrReturnHandle(rightSide),
- this.registerOrReturnHandle(leftSide),
- ]);
- }
-
- /**
- * Generates a definition for splitting a shape definition in four quads
- * @param {ShapeDefinition} definition
- * @returns {[ShapeDefinition, ShapeDefinition, ShapeDefinition, ShapeDefinition]}
- */
- shapeActionCutQuad(definition) {
- const key = "cut-quad:" + definition.getHash();
- if (this.operationCache[key]) {
- return /** @type {[ShapeDefinition, ShapeDefinition, ShapeDefinition, ShapeDefinition]} */ (this
- .operationCache[key]);
- }
-
- return /** @type {[ShapeDefinition, ShapeDefinition, ShapeDefinition, ShapeDefinition]} */ (this.operationCache[
- key
- ] = [
- this.registerOrReturnHandle(definition.cloneFilteredByQuadrants([0])),
- this.registerOrReturnHandle(definition.cloneFilteredByQuadrants([1])),
- this.registerOrReturnHandle(definition.cloneFilteredByQuadrants([2])),
- this.registerOrReturnHandle(definition.cloneFilteredByQuadrants([3])),
- ]);
- }
-
- /**
- * Generates a definition for rotating a shape clockwise
- * @param {ShapeDefinition} definition
- * @returns {ShapeDefinition}
- */
- shapeActionRotateCW(definition) {
- const key = "rotate-cw:" + definition.getHash();
- if (this.operationCache[key]) {
- return /** @type {ShapeDefinition} */ (this.operationCache[key]);
- }
-
- const rotated = definition.cloneRotateCW();
-
- return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
- rotated
- ));
- }
-
- /**
- * Generates a definition for rotating a shape counter clockwise
- * @param {ShapeDefinition} definition
- * @returns {ShapeDefinition}
- */
- shapeActionRotateCCW(definition) {
- const key = "rotate-ccw:" + definition.getHash();
- if (this.operationCache[key]) {
- return /** @type {ShapeDefinition} */ (this.operationCache[key]);
- }
-
- const rotated = definition.cloneRotateCCW();
-
- return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
- rotated
- ));
- }
-
- /**
- * Generates a definition for rotating a shape counter clockwise
- * @param {ShapeDefinition} definition
- * @returns {ShapeDefinition}
- */
- shapeActionRotateFL(definition) {
- const key = "rotate-fl:" + definition.getHash();
- if (this.operationCache[key]) {
- return /** @type {ShapeDefinition} */ (this.operationCache[key]);
- }
-
- const rotated = definition.cloneRotateFL();
-
- return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
- rotated
- ));
- }
-
- /**
- * Generates a definition for stacking the upper definition onto the lower one
- * @param {ShapeDefinition} lowerDefinition
- * @param {ShapeDefinition} upperDefinition
- * @returns {ShapeDefinition}
- */
- shapeActionStack(lowerDefinition, upperDefinition) {
- const key = "stack:" + lowerDefinition.getHash() + ":" + upperDefinition.getHash();
- if (this.operationCache[key]) {
- return /** @type {ShapeDefinition} */ (this.operationCache[key]);
- }
- const stacked = lowerDefinition.cloneAndStackWith(upperDefinition);
- return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
- stacked
- ));
- }
-
- /**
- * Generates a definition for painting it with the given color
- * @param {ShapeDefinition} definition
- * @param {enumColors} color
- * @returns {ShapeDefinition}
- */
- shapeActionPaintWith(definition, color) {
- const key = "paint:" + definition.getHash() + ":" + color;
- if (this.operationCache[key]) {
- return /** @type {ShapeDefinition} */ (this.operationCache[key]);
- }
- const colorized = definition.cloneAndPaintWith(color);
- return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
- colorized
- ));
- }
-
- /**
- * Generates a definition for painting it with the 4 colors
- * @param {ShapeDefinition} definition
- * @param {[enumColors, enumColors, enumColors, enumColors]} colors
- * @returns {ShapeDefinition}
- */
- shapeActionPaintWith4Colors(definition, colors) {
- const key = "paint4:" + definition.getHash() + ":" + colors.join(",");
- if (this.operationCache[key]) {
- return /** @type {ShapeDefinition} */ (this.operationCache[key]);
- }
- const colorized = definition.cloneAndPaintWith4Colors(colors);
- return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
- colorized
- ));
- }
-
- /**
- * Checks if we already have cached this definition, and if so throws it away and returns the already
- * cached variant
- * @param {ShapeDefinition} definition
- */
- registerOrReturnHandle(definition) {
- const id = definition.getHash();
- if (this.shapeKeyToDefinition[id]) {
- return this.shapeKeyToDefinition[id];
- }
- this.shapeKeyToDefinition[id] = definition;
- // logger.log("Registered shape with key (2)", id);
- return definition;
- }
-
- /**
- *
- * @param {[enumSubShape, enumSubShape, enumSubShape, enumSubShape]} subShapes
- * @returns {ShapeDefinition}
- */
- getDefinitionFromSimpleShapes(subShapes, color = enumColors.uncolored) {
- const shapeLayer = /** @type {import("./shape_definition").ShapeLayer} */ (subShapes.map(
- subShape => ({ subShape, color })
- ));
-
- return this.registerOrReturnHandle(new ShapeDefinition({ layers: [shapeLayer] }));
- }
-}
+import { createLogger } from "../core/logging";
+import { BasicSerializableObject } from "../savegame/serialization";
+import { enumColors } from "./colors";
+import { ShapeItem } from "./items/shape_item";
+import { GameRoot } from "./root";
+import { enumSubShape, ShapeDefinition } from "./shape_definition";
+
+const logger = createLogger("shape_definition_manager");
+
+export class ShapeDefinitionManager extends BasicSerializableObject {
+ static getId() {
+ return "ShapeDefinitionManager";
+ }
+
+ /**
+ *
+ * @param {GameRoot} root
+ */
+ constructor(root) {
+ super();
+ this.root = root;
+
+ /**
+ * Store a cache from key -> definition
+ * @type {Object}
+ */
+ this.shapeKeyToDefinition = {};
+
+ /**
+ * Store a cache from key -> item
+ */
+ this.shapeKeyToItem = {};
+
+ // Caches operations in the form of 'operation:def1[:def2]'
+ /** @type {Object.|ShapeDefinition>} */
+ this.operationCache = {};
+ }
+
+ /**
+ * Returns a shape instance from a given short key
+ * @param {string} hash
+ * @returns {ShapeDefinition}
+ */
+ getShapeFromShortKey(hash) {
+ const cached = this.shapeKeyToDefinition[hash];
+ if (cached) {
+ return cached;
+ }
+ return (this.shapeKeyToDefinition[hash] = ShapeDefinition.fromShortKey(hash));
+ }
+
+ /**
+ * Returns a item instance from a given short key
+ * @param {string} hash
+ * @returns {ShapeItem}
+ */
+ getShapeItemFromShortKey(hash) {
+ const cached = this.shapeKeyToItem[hash];
+ if (cached) {
+ return cached;
+ }
+ const definition = this.getShapeFromShortKey(hash);
+ return (this.shapeKeyToItem[hash] = new ShapeItem(definition));
+ }
+
+ /**
+ * Returns a shape item for a given definition
+ * @param {ShapeDefinition} definition
+ * @returns {ShapeItem}
+ */
+ getShapeItemFromDefinition(definition) {
+ return this.getShapeItemFromShortKey(definition.getHash());
+ }
+
+ /**
+ * Registers a new shape definition
+ * @param {ShapeDefinition} definition
+ */
+ registerShapeDefinition(definition) {
+ const id = definition.getHash();
+ assert(!this.shapeKeyToDefinition[id], "Shape Definition " + id + " already exists");
+ this.shapeKeyToDefinition[id] = definition;
+ // logger.log("Registered shape with key", id);
+ }
+
+ /**
+ * Generates a definition for splitting a shape definition in two halfs
+ * @param {ShapeDefinition} definition
+ * @returns {[ShapeDefinition, ShapeDefinition]}
+ */
+ shapeActionCutHalf(definition) {
+ const key = "cut:" + definition.getHash();
+ if (this.operationCache[key]) {
+ return /** @type {[ShapeDefinition, ShapeDefinition]} */ (this.operationCache[key]);
+ }
+ const rightSide = definition.cloneFilteredByQuadrants([2, 3]);
+ const leftSide = definition.cloneFilteredByQuadrants([0, 1]);
+
+ return /** @type {[ShapeDefinition, ShapeDefinition]} */ (this.operationCache[key] = [
+ this.registerOrReturnHandle(rightSide),
+ this.registerOrReturnHandle(leftSide),
+ ]);
+ }
+
+ /**
+ * Generates a definition for splitting a shape definition in four quads
+ * @param {ShapeDefinition} definition
+ * @returns {[ShapeDefinition, ShapeDefinition, ShapeDefinition, ShapeDefinition]}
+ */
+ shapeActionCutQuad(definition) {
+ const key = "cut-quad:" + definition.getHash();
+ if (this.operationCache[key]) {
+ return /** @type {[ShapeDefinition, ShapeDefinition, ShapeDefinition, ShapeDefinition]} */ (this
+ .operationCache[key]);
+ }
+
+ return /** @type {[ShapeDefinition, ShapeDefinition, ShapeDefinition, ShapeDefinition]} */ (this.operationCache[
+ key
+ ] = [
+ this.registerOrReturnHandle(definition.cloneFilteredByQuadrants([0])),
+ this.registerOrReturnHandle(definition.cloneFilteredByQuadrants([1])),
+ this.registerOrReturnHandle(definition.cloneFilteredByQuadrants([2])),
+ this.registerOrReturnHandle(definition.cloneFilteredByQuadrants([3])),
+ ]);
+ }
+
+ /**
+ * Generates a definition for rotating a shape clockwise
+ * @param {ShapeDefinition} definition
+ * @returns {ShapeDefinition}
+ */
+ shapeActionRotateCW(definition) {
+ const key = "rotate-cw:" + definition.getHash();
+ if (this.operationCache[key]) {
+ return /** @type {ShapeDefinition} */ (this.operationCache[key]);
+ }
+
+ const rotated = definition.cloneRotateCW();
+
+ return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
+ rotated
+ ));
+ }
+
+ /**
+ * Generates a definition for rotating a shape counter clockwise
+ * @param {ShapeDefinition} definition
+ * @returns {ShapeDefinition}
+ */
+ shapeActionRotateCCW(definition) {
+ const key = "rotate-ccw:" + definition.getHash();
+ if (this.operationCache[key]) {
+ return /** @type {ShapeDefinition} */ (this.operationCache[key]);
+ }
+
+ const rotated = definition.cloneRotateCCW();
+
+ return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
+ rotated
+ ));
+ }
+
+ /**
+ * Generates a definition for rotating a shape FL
+ * @param {ShapeDefinition} definition
+ * @returns {ShapeDefinition}
+ */
+ shapeActionRotate180(definition) {
+ const key = "rotate-fl:" + definition.getHash();
+ if (this.operationCache[key]) {
+ return /** @type {ShapeDefinition} */ (this.operationCache[key]);
+ }
+
+ const rotated = definition.cloneRotate180();
+
+ return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
+ rotated
+ ));
+ }
+
+ /**
+ * Generates a definition for stacking the upper definition onto the lower one
+ * @param {ShapeDefinition} lowerDefinition
+ * @param {ShapeDefinition} upperDefinition
+ * @returns {ShapeDefinition}
+ */
+ shapeActionStack(lowerDefinition, upperDefinition) {
+ const key = "stack:" + lowerDefinition.getHash() + ":" + upperDefinition.getHash();
+ if (this.operationCache[key]) {
+ return /** @type {ShapeDefinition} */ (this.operationCache[key]);
+ }
+ const stacked = lowerDefinition.cloneAndStackWith(upperDefinition);
+ return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
+ stacked
+ ));
+ }
+
+ /**
+ * Generates a definition for painting it with the given color
+ * @param {ShapeDefinition} definition
+ * @param {enumColors} color
+ * @returns {ShapeDefinition}
+ */
+ shapeActionPaintWith(definition, color) {
+ const key = "paint:" + definition.getHash() + ":" + color;
+ if (this.operationCache[key]) {
+ return /** @type {ShapeDefinition} */ (this.operationCache[key]);
+ }
+ const colorized = definition.cloneAndPaintWith(color);
+ return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
+ colorized
+ ));
+ }
+
+ /**
+ * Generates a definition for painting it with the 4 colors
+ * @param {ShapeDefinition} definition
+ * @param {[enumColors, enumColors, enumColors, enumColors]} colors
+ * @returns {ShapeDefinition}
+ */
+ shapeActionPaintWith4Colors(definition, colors) {
+ const key = "paint4:" + definition.getHash() + ":" + colors.join(",");
+ if (this.operationCache[key]) {
+ return /** @type {ShapeDefinition} */ (this.operationCache[key]);
+ }
+ const colorized = definition.cloneAndPaintWith4Colors(colors);
+ return /** @type {ShapeDefinition} */ (this.operationCache[key] = this.registerOrReturnHandle(
+ colorized
+ ));
+ }
+
+ /**
+ * Checks if we already have cached this definition, and if so throws it away and returns the already
+ * cached variant
+ * @param {ShapeDefinition} definition
+ */
+ registerOrReturnHandle(definition) {
+ const id = definition.getHash();
+ if (this.shapeKeyToDefinition[id]) {
+ return this.shapeKeyToDefinition[id];
+ }
+ this.shapeKeyToDefinition[id] = definition;
+ // logger.log("Registered shape with key (2)", id);
+ return definition;
+ }
+
+ /**
+ *
+ * @param {[enumSubShape, enumSubShape, enumSubShape, enumSubShape]} subShapes
+ * @returns {ShapeDefinition}
+ */
+ getDefinitionFromSimpleShapes(subShapes, color = enumColors.uncolored) {
+ const shapeLayer = /** @type {import("./shape_definition").ShapeLayer} */ (subShapes.map(
+ subShape => ({ subShape, color })
+ ));
+
+ return this.registerOrReturnHandle(new ShapeDefinition({ layers: [shapeLayer] }));
+ }
+}
diff --git a/src/js/game/systems/belt.js b/src/js/game/systems/belt.js
index 4d8151f6..10543e6c 100644
--- a/src/js/game/systems/belt.js
+++ b/src/js/game/systems/belt.js
@@ -1,520 +1,554 @@
-import { globalConfig } from "../../core/config";
-import { DrawParameters } from "../../core/draw_parameters";
-import { gMetaBuildingRegistry } from "../../core/global_registries";
-import { Loader } from "../../core/loader";
-import { createLogger } from "../../core/logging";
-import { AtlasSprite } from "../../core/sprites";
-import { fastArrayDeleteValue } from "../../core/utils";
-import { enumDirection, enumDirectionToVector, enumInvertedDirections, Vector } from "../../core/vector";
-import { BeltPath } from "../belt_path";
-import { arrayBeltVariantToRotation, MetaBeltBaseBuilding } from "../buildings/belt_base";
-import { BeltComponent } from "../components/belt";
-import { Entity } from "../entity";
-import { GameSystemWithFilter } from "../game_system_with_filter";
-import { MapChunkView } from "../map_chunk_view";
-import { defaultBuildingVariant } from "../meta_building";
-import { getCodeFromBuildingData } from "../building_codes";
-
-export const BELT_ANIM_COUNT = 14;
-
-const logger = createLogger("belt");
-
-/**
- * Manages all belts
- */
-export class BeltSystem extends GameSystemWithFilter {
- constructor(root) {
- super(root, [BeltComponent]);
- /**
- * @type {Object.>}
- */
- this.beltSprites = {
- [enumDirection.top]: Loader.getSprite("sprites/belt/built/forward_0.png"),
- [enumDirection.left]: Loader.getSprite("sprites/belt/built/left_0.png"),
- [enumDirection.right]: Loader.getSprite("sprites/belt/built/right_0.png"),
- };
-
- /**
- * @type {Object.>}
- */
- this.beltAnimations = {
- [enumDirection.top]: [],
- [enumDirection.left]: [],
- [enumDirection.right]: [],
- };
-
- for (let i = 0; i < BELT_ANIM_COUNT; ++i) {
- this.beltAnimations[enumDirection.top].push(
- Loader.getSprite("sprites/belt/built/forward_" + i + ".png")
- );
- this.beltAnimations[enumDirection.left].push(
- Loader.getSprite("sprites/belt/built/left_" + i + ".png")
- );
- this.beltAnimations[enumDirection.right].push(
- Loader.getSprite("sprites/belt/built/right_" + i + ".png")
- );
- }
-
- this.root.signals.entityDestroyed.add(this.onEntityDestroyed, this);
- this.root.signals.entityDestroyed.add(this.updateSurroundingBeltPlacement, this);
-
- // Notice: These must come *after* the entity destroyed signals
- this.root.signals.entityAdded.add(this.onEntityAdded, this);
- this.root.signals.entityAdded.add(this.updateSurroundingBeltPlacement, this);
-
- /** @type {Array} */
- this.beltPaths = [];
- }
-
- /**
- * Serializes all belt paths
- * @returns {Array}
- */
- serializePaths() {
- let data = [];
- for (let i = 0; i < this.beltPaths.length; ++i) {
- data.push(this.beltPaths[i].serialize());
- }
- return data;
- }
-
- /**
- * Deserializes all belt paths
- * @param {Array} data
- */
- deserializePaths(data) {
- if (!Array.isArray(data)) {
- return "Belt paths are not an array: " + typeof data;
- }
-
- for (let i = 0; i < data.length; ++i) {
- const path = BeltPath.fromSerialized(this.root, data[i]);
- // If path is a string, that means its an error
- if (!(path instanceof BeltPath)) {
- return "Failed to create path from belt data: " + path;
- }
- this.beltPaths.push(path);
- }
-
- if (this.beltPaths.length === 0) {
- // Old savegames might not have paths yet
- logger.warn("Recomputing belt paths (most likely the savegame is old or empty)");
- this.recomputeAllBeltPaths();
- } else {
- logger.warn("Restored", this.beltPaths.length, "belt paths");
- }
-
- if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
- this.debug_verifyBeltPaths();
- }
- }
-
- /**
- * Updates the belt placement after an entity has been added / deleted
- * @param {Entity} entity
- */
- updateSurroundingBeltPlacement(entity) {
- if (!this.root.gameInitialized) {
- return;
- }
-
- const staticComp = entity.components.StaticMapEntity;
- if (!staticComp) {
- return;
- }
-
- const metaBelt = gMetaBuildingRegistry.findByClass(MetaBeltBaseBuilding);
- // Compute affected area
- const originalRect = staticComp.getTileSpaceBounds();
- const affectedArea = originalRect.expandedInAllDirections(1);
-
- /** @type {Set} */
- const changedPaths = new Set();
-
- for (let x = affectedArea.x; x < affectedArea.right(); ++x) {
- for (let y = affectedArea.y; y < affectedArea.bottom(); ++y) {
- if (originalRect.containsPoint(x, y)) {
- // Make sure we don't update the original entity
- continue;
- }
-
- const targetEntities = this.root.map.getLayersContentsMultipleXY(x, y);
- for (let i = 0; i < targetEntities.length; ++i) {
- const targetEntity = targetEntities[i];
-
- const targetBeltComp = targetEntity.components.Belt;
- const targetStaticComp = targetEntity.components.StaticMapEntity;
-
- if (!targetBeltComp) {
- // Not a belt
- continue;
- }
-
- const {
- rotation,
- rotationVariant,
- } = metaBelt.computeOptimalDirectionAndRotationVariantAtTile({
- root: this.root,
- tile: new Vector(x, y),
- rotation: targetStaticComp.originalRotation,
- variant: defaultBuildingVariant,
- layer: targetEntity.layer,
- });
-
- // Compute delta to see if anything changed
- const newDirection = arrayBeltVariantToRotation[rotationVariant];
-
- if (targetStaticComp.rotation !== rotation || newDirection !== targetBeltComp.direction) {
- // Ok, first remove it from its current path
- this.deleteEntityFromPath(targetBeltComp.assignedPath, targetEntity);
-
- // Change stuff
- targetStaticComp.rotation = rotation;
- metaBelt.updateVariants(targetEntity, rotationVariant, defaultBuildingVariant);
-
- // Update code as well
- targetStaticComp.code = getCodeFromBuildingData(
- metaBelt,
- defaultBuildingVariant,
- rotationVariant
- );
-
- // Now add it again
- this.addEntityToPaths(targetEntity);
-
- // Sanity
- if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
- this.debug_verifyBeltPaths();
- }
-
- // Make sure the chunks know about the update
- this.root.signals.entityChanged.dispatch(targetEntity);
- }
-
- if (targetBeltComp.assignedPath) {
- changedPaths.add(targetBeltComp.assignedPath);
- }
- }
- }
- }
-
- // notify all paths *afterwards* to avoid multi-updates
- changedPaths.forEach(path => path.onSurroundingsChanged());
-
- if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
- this.debug_verifyBeltPaths();
- }
- }
-
- /**
- * Called when an entity got destroyed
- * @param {Entity} entity
- */
- onEntityDestroyed(entity) {
- if (!this.root.gameInitialized) {
- return;
- }
-
- if (!entity.components.Belt) {
- return;
- }
-
- const assignedPath = entity.components.Belt.assignedPath;
- assert(assignedPath, "Entity has no belt path assigned");
- this.deleteEntityFromPath(assignedPath, entity);
- if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
- this.debug_verifyBeltPaths();
- }
- }
-
- /**
- * Attempts to delete the belt from its current path
- * @param {BeltPath} path
- * @param {Entity} entity
- */
- deleteEntityFromPath(path, entity) {
- if (path.entityPath.length === 1) {
- // This is a single entity path, easy to do, simply erase whole path
- fastArrayDeleteValue(this.beltPaths, path);
- return;
- }
-
- // Notice: Since there might be circular references, it is important to check
- // which role the entity has
- if (path.isStartEntity(entity)) {
- // We tried to delete the start
- path.deleteEntityOnStart(entity);
- } else if (path.isEndEntity(entity)) {
- // We tried to delete the end
- path.deleteEntityOnEnd(entity);
- } else {
- // We tried to delete something inbetween
- const newPath = path.deleteEntityOnPathSplitIntoTwo(entity);
- this.beltPaths.push(newPath);
- }
-
- // Sanity
- entity.components.Belt.assignedPath = null;
- }
-
- /**
- * Adds the given entity to the appropriate paths
- * @param {Entity} entity
- */
- addEntityToPaths(entity) {
- const fromEntity = this.findSupplyingEntity(entity);
- const toEntity = this.findFollowUpEntity(entity);
-
- // Check if we can add the entity to the previous path
- if (fromEntity) {
- const fromPath = fromEntity.components.Belt.assignedPath;
- fromPath.extendOnEnd(entity);
-
- // Check if we now can extend the current path by the next path
- if (toEntity) {
- const toPath = toEntity.components.Belt.assignedPath;
-
- if (fromPath === toPath) {
- // This is a circular dependency -> Ignore
- } else {
- fromPath.extendByPath(toPath);
-
- // Delete now obsolete path
- fastArrayDeleteValue(this.beltPaths, toPath);
- }
- }
- } else {
- if (toEntity) {
- // Prepend it to the other path
- const toPath = toEntity.components.Belt.assignedPath;
- toPath.extendOnBeginning(entity);
- } else {
- // This is an empty belt path
- const path = new BeltPath(this.root, [entity]);
- this.beltPaths.push(path);
- }
- }
- }
-
- /**
- * Called when an entity got added
- * @param {Entity} entity
- */
- onEntityAdded(entity) {
- if (!this.root.gameInitialized) {
- return;
- }
-
- if (!entity.components.Belt) {
- return;
- }
-
- this.addEntityToPaths(entity);
- if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
- this.debug_verifyBeltPaths();
- }
- }
-
- /**
- * Draws all belt paths
- * @param {DrawParameters} parameters
- */
- drawBeltItems(parameters) {
- for (let i = 0; i < this.beltPaths.length; ++i) {
- this.beltPaths[i].draw(parameters);
- }
- }
-
- /**
- * Verifies all belt paths
- */
- debug_verifyBeltPaths() {
- for (let i = 0; i < this.beltPaths.length; ++i) {
- this.beltPaths[i].debug_checkIntegrity("general-verify");
- }
-
- const belts = this.root.entityMgr.getAllWithComponent(BeltComponent);
- for (let i = 0; i < belts.length; ++i) {
- const path = belts[i].components.Belt.assignedPath;
- if (!path) {
- throw new Error("Belt has no path: " + belts[i].uid);
- }
- if (this.beltPaths.indexOf(path) < 0) {
- throw new Error("Path of entity not contained: " + belts[i].uid);
- }
- }
- }
-
- /**
- * Finds the follow up entity for a given belt. Used for building the dependencies
- * @param {Entity} entity
- * @returns {Entity|null}
- */
- findFollowUpEntity(entity) {
- const staticComp = entity.components.StaticMapEntity;
- const beltComp = entity.components.Belt;
-
- const followUpDirection = staticComp.localDirectionToWorld(beltComp.direction);
- const followUpVector = enumDirectionToVector[followUpDirection];
-
- const followUpTile = staticComp.origin.add(followUpVector);
- const followUpEntity = this.root.map.getLayerContentXY(followUpTile.x, followUpTile.y, entity.layer);
-
- // Check if theres a belt at the tile we point to
- if (followUpEntity) {
- const followUpBeltComp = followUpEntity.components.Belt;
- if (followUpBeltComp) {
- const followUpStatic = followUpEntity.components.StaticMapEntity;
-
- const acceptedDirection = followUpStatic.localDirectionToWorld(enumDirection.top);
- if (acceptedDirection === followUpDirection) {
- return followUpEntity;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Finds the supplying belt for a given belt. Used for building the dependencies
- * @param {Entity} entity
- * @returns {Entity|null}
- */
- findSupplyingEntity(entity) {
- const staticComp = entity.components.StaticMapEntity;
-
- const supplyDirection = staticComp.localDirectionToWorld(enumDirection.bottom);
- const supplyVector = enumDirectionToVector[supplyDirection];
-
- const supplyTile = staticComp.origin.add(supplyVector);
- const supplyEntity = this.root.map.getLayerContentXY(supplyTile.x, supplyTile.y, entity.layer);
-
- // Check if theres a belt at the tile we point to
- if (supplyEntity) {
- const supplyBeltComp = supplyEntity.components.Belt;
- if (supplyBeltComp) {
- const supplyStatic = supplyEntity.components.StaticMapEntity;
- const otherDirection = supplyStatic.localDirectionToWorld(
- enumInvertedDirections[supplyBeltComp.direction]
- );
-
- if (otherDirection === supplyDirection) {
- return supplyEntity;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Recomputes the belt path network. Only required for old savegames
- */
- recomputeAllBeltPaths() {
- logger.warn("Recomputing all belt paths");
- const visitedUids = new Set();
-
- const result = [];
-
- for (let i = 0; i < this.allEntities.length; ++i) {
- const entity = this.allEntities[i];
- if (visitedUids.has(entity.uid)) {
- continue;
- }
-
- // Mark entity as visited
- visitedUids.add(entity.uid);
-
- // Compute path, start with entity and find precedors / successors
- const path = [entity];
-
- // Prevent infinite loops
- let maxIter = 99999;
-
- // Find precedors
- let prevEntity = this.findSupplyingEntity(entity);
- while (prevEntity && --maxIter > 0) {
- if (visitedUids.has(prevEntity.uid)) {
- break;
- }
- path.unshift(prevEntity);
- visitedUids.add(prevEntity.uid);
- prevEntity = this.findSupplyingEntity(prevEntity);
- }
-
- // Find succedors
- let nextEntity = this.findFollowUpEntity(entity);
- while (nextEntity && --maxIter > 0) {
- if (visitedUids.has(nextEntity.uid)) {
- break;
- }
-
- path.push(nextEntity);
- visitedUids.add(nextEntity.uid);
- nextEntity = this.findFollowUpEntity(nextEntity);
- }
-
- assert(maxIter > 1, "Ran out of iterations");
- result.push(new BeltPath(this.root, path));
- }
-
- logger.log("Found", this.beltPaths.length, "belt paths");
- this.beltPaths = result;
- }
-
- /**
- * Updates all belts
- */
- update() {
- if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
- this.debug_verifyBeltPaths();
- }
-
- for (let i = 0; i < this.beltPaths.length; ++i) {
- this.beltPaths[i].update();
- }
-
- if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
- this.debug_verifyBeltPaths();
- }
- }
-
- /**
- * Draws a given chunk
- * @param {DrawParameters} parameters
- * @param {MapChunkView} chunk
- */
- drawChunk(parameters, chunk) {
- // Limit speed to avoid belts going backwards
- const speedMultiplier = Math.min(this.root.hubGoals.getBeltBaseSpeed(), 10);
-
- // SYNC with systems/item_acceptor.js:drawEntityUnderlays!
- // 126 / 42 is the exact animation speed of the png animation
- const animationIndex = Math.floor(
- ((this.root.time.realtimeNow() * speedMultiplier * BELT_ANIM_COUNT * 126) / 42) *
- globalConfig.itemSpacingOnBelts
- );
- const contents = chunk.containedEntitiesByLayer.regular;
- for (let i = 0; i < contents.length; ++i) {
- const entity = contents[i];
- if (entity.components.Belt) {
- const direction = entity.components.Belt.direction;
- const sprite = this.beltAnimations[direction][animationIndex % BELT_ANIM_COUNT];
-
- // Culling happens within the static map entity component
- entity.components.StaticMapEntity.drawSpriteOnBoundsClipped(parameters, sprite, 0);
- }
- }
- }
-
- /**
- * Draws the belt path debug overlays
- * @param {DrawParameters} parameters
- */
- drawBeltPathDebug(parameters) {
- for (let i = 0; i < this.beltPaths.length; ++i) {
- this.beltPaths[i].drawDebug(parameters);
- }
- }
-}
+import { globalConfig } from "../../core/config";
+import { DrawParameters } from "../../core/draw_parameters";
+import { gMetaBuildingRegistry } from "../../core/global_registries";
+import { Loader } from "../../core/loader";
+import { createLogger } from "../../core/logging";
+import { AtlasSprite } from "../../core/sprites";
+import { fastArrayDeleteValue } from "../../core/utils";
+import { enumDirection, enumDirectionToVector, enumInvertedDirections, Vector } from "../../core/vector";
+import { BeltPath } from "../belt_path";
+import { arrayBeltVariantToRotation, MetaBeltBuilding } from "../buildings/belt";
+import { getCodeFromBuildingData } from "../building_codes";
+import { BeltComponent } from "../components/belt";
+import { Entity } from "../entity";
+import { GameSystemWithFilter } from "../game_system_with_filter";
+import { MapChunkView } from "../map_chunk_view";
+import { defaultBuildingVariant } from "../meta_building";
+
+export const BELT_ANIM_COUNT = 14;
+
+const logger = createLogger("belt");
+
+/**
+ * Manages all belts
+ */
+export class BeltSystem extends GameSystemWithFilter {
+ constructor(root) {
+ super(root, [BeltComponent]);
+ /**
+ * @type {Object.>}
+ */
+ this.beltSprites = {
+ [enumDirection.top]: Loader.getSprite("sprites/belt/built/forward_0.png"),
+ [enumDirection.left]: Loader.getSprite("sprites/belt/built/left_0.png"),
+ [enumDirection.right]: Loader.getSprite("sprites/belt/built/right_0.png"),
+ };
+
+ /**
+ * @type {Object.>}
+ */
+ this.beltAnimations = {
+ [enumDirection.top]: [],
+ [enumDirection.left]: [],
+ [enumDirection.right]: [],
+ };
+
+ for (let i = 0; i < BELT_ANIM_COUNT; ++i) {
+ this.beltAnimations[enumDirection.top].push(
+ Loader.getSprite("sprites/belt/built/forward_" + i + ".png")
+ );
+ this.beltAnimations[enumDirection.left].push(
+ Loader.getSprite("sprites/belt/built/left_" + i + ".png")
+ );
+ this.beltAnimations[enumDirection.right].push(
+ Loader.getSprite("sprites/belt/built/right_" + i + ".png")
+ );
+ }
+
+ this.root.signals.entityDestroyed.add(this.onEntityDestroyed, this);
+ this.root.signals.entityDestroyed.add(this.updateSurroundingBeltPlacement, this);
+
+ // Notice: These must come *after* the entity destroyed signals
+ this.root.signals.entityAdded.add(this.onEntityAdded, this);
+ this.root.signals.entityAdded.add(this.updateSurroundingBeltPlacement, this);
+
+ /** @type {Array} */
+ this.beltPaths = [];
+ }
+
+ /**
+ * Serializes all belt paths
+ * @returns {Array}
+ */
+ serializePaths() {
+ let data = [];
+ for (let i = 0; i < this.beltPaths.length; ++i) {
+ data.push(this.beltPaths[i].serialize());
+ }
+ return data;
+ }
+
+ /**
+ * Deserializes all belt paths
+ * @param {Array} data
+ */
+ deserializePaths(data) {
+ if (!Array.isArray(data)) {
+ return "Belt paths are not an array: " + typeof data;
+ }
+
+ for (let i = 0; i < data.length; ++i) {
+ const path = BeltPath.fromSerialized(this.root, data[i]);
+ // If path is a string, that means its an error
+ if (!(path instanceof BeltPath)) {
+ return "Failed to create path from belt data: " + path;
+ }
+ this.beltPaths.push(path);
+ }
+
+ if (this.beltPaths.length === 0) {
+ // Old savegames might not have paths yet
+ logger.warn("Recomputing belt paths (most likely the savegame is old or empty)");
+ this.recomputeAllBeltPaths();
+ } else {
+ logger.warn("Restored", this.beltPaths.length, "belt paths");
+ }
+
+ if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
+ this.debug_verifyBeltPaths();
+ }
+ }
+
+ /**
+ * Updates the belt placement after an entity has been added / deleted
+ * @param {Entity} entity
+ */
+ updateSurroundingBeltPlacement(entity) {
+ if (!this.root.gameInitialized) {
+ return;
+ }
+
+ const staticComp = entity.components.StaticMapEntity;
+ if (!staticComp) {
+ return;
+ }
+
+ const metaBelt = gMetaBuildingRegistry.findByClass(MetaBeltBuilding);
+ // Compute affected area
+ const originalRect = staticComp.getTileSpaceBounds();
+ const affectedArea = originalRect.expandedInAllDirections(1);
+
+ /** @type {Set} */
+ const changedPaths = new Set();
+
+ for (let x = affectedArea.x; x < affectedArea.right(); ++x) {
+ for (let y = affectedArea.y; y < affectedArea.bottom(); ++y) {
+ if (originalRect.containsPoint(x, y)) {
+ // Make sure we don't update the original entity
+ continue;
+ }
+
+ const targetEntities = this.root.map.getLayersContentsMultipleXY(x, y);
+ for (let i = 0; i < targetEntities.length; ++i) {
+ const targetEntity = targetEntities[i];
+
+ const targetBeltComp = targetEntity.components.Belt;
+ const targetStaticComp = targetEntity.components.StaticMapEntity;
+
+ if (!targetBeltComp) {
+ // Not a belt
+ continue;
+ }
+
+ const {
+ rotation,
+ rotationVariant,
+ } = metaBelt.computeOptimalDirectionAndRotationVariantAtTile({
+ root: this.root,
+ tile: new Vector(x, y),
+ rotation: targetStaticComp.originalRotation,
+ variant: defaultBuildingVariant,
+ layer: targetEntity.layer,
+ });
+
+ // Compute delta to see if anything changed
+ const newDirection = arrayBeltVariantToRotation[rotationVariant];
+
+ if (targetStaticComp.rotation !== rotation || newDirection !== targetBeltComp.direction) {
+ const originalPath = targetBeltComp.assignedPath;
+
+ // Ok, first remove it from its current path
+ this.deleteEntityFromPath(targetBeltComp.assignedPath, targetEntity);
+
+ // Change stuff
+ targetStaticComp.rotation = rotation;
+ metaBelt.updateVariants(targetEntity, rotationVariant, defaultBuildingVariant);
+
+ // Update code as well
+ targetStaticComp.code = getCodeFromBuildingData(
+ metaBelt,
+ defaultBuildingVariant,
+ rotationVariant
+ );
+
+ // Update the original path since it might have picked up the entit1y
+ originalPath.onPathChanged();
+
+ // Now add it again
+ this.addEntityToPaths(targetEntity);
+
+ // Sanity
+ if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
+ this.debug_verifyBeltPaths();
+ }
+
+ // Make sure the chunks know about the update
+ this.root.signals.entityChanged.dispatch(targetEntity);
+ }
+
+ if (targetBeltComp.assignedPath) {
+ changedPaths.add(targetBeltComp.assignedPath);
+ }
+ }
+ }
+ }
+
+ // notify all paths *afterwards* to avoid multi-updates
+ changedPaths.forEach(path => path.onSurroundingsChanged());
+
+ if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
+ this.debug_verifyBeltPaths();
+ }
+ }
+
+ /**
+ * Called when an entity got destroyed
+ * @param {Entity} entity
+ */
+ onEntityDestroyed(entity) {
+ if (!this.root.gameInitialized) {
+ return;
+ }
+
+ if (!entity.components.Belt) {
+ return;
+ }
+
+ const assignedPath = entity.components.Belt.assignedPath;
+ assert(assignedPath, "Entity has no belt path assigned");
+ this.deleteEntityFromPath(assignedPath, entity);
+ if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
+ this.debug_verifyBeltPaths();
+ }
+ }
+
+ /**
+ * Attempts to delete the belt from its current path
+ * @param {BeltPath} path
+ * @param {Entity} entity
+ */
+ deleteEntityFromPath(path, entity) {
+ if (path.entityPath.length === 1) {
+ // This is a single entity path, easy to do, simply erase whole path
+ fastArrayDeleteValue(this.beltPaths, path);
+ return;
+ }
+
+ // Notice: Since there might be circular references, it is important to check
+ // which role the entity has
+ if (path.isStartEntity(entity)) {
+ // We tried to delete the start
+ path.deleteEntityOnStart(entity);
+ } else if (path.isEndEntity(entity)) {
+ // We tried to delete the end
+ path.deleteEntityOnEnd(entity);
+ } else {
+ // We tried to delete something inbetween
+ const newPath = path.deleteEntityOnPathSplitIntoTwo(entity);
+ this.beltPaths.push(newPath);
+ }
+
+ // Sanity
+ entity.components.Belt.assignedPath = null;
+ }
+
+ /**
+ * Adds the given entity to the appropriate paths
+ * @param {Entity} entity
+ */
+ addEntityToPaths(entity) {
+ const fromEntity = this.findSupplyingEntity(entity);
+ const toEntity = this.findFollowUpEntity(entity);
+
+ // Check if we can add the entity to the previous path
+ if (fromEntity) {
+ const fromPath = fromEntity.components.Belt.assignedPath;
+ fromPath.extendOnEnd(entity);
+
+ // Check if we now can extend the current path by the next path
+ if (toEntity) {
+ const toPath = toEntity.components.Belt.assignedPath;
+
+ if (fromPath === toPath) {
+ // This is a circular dependency -> Ignore
+ } else {
+ fromPath.extendByPath(toPath);
+
+ // Delete now obsolete path
+ fastArrayDeleteValue(this.beltPaths, toPath);
+ }
+ }
+ } else {
+ if (toEntity) {
+ // Prepend it to the other path
+ const toPath = toEntity.components.Belt.assignedPath;
+ toPath.extendOnBeginning(entity);
+ } else {
+ // This is an empty belt path
+ const path = new BeltPath(this.root, [entity]);
+ this.beltPaths.push(path);
+ }
+ }
+ }
+
+ /**
+ * Called when an entity got added
+ * @param {Entity} entity
+ */
+ onEntityAdded(entity) {
+ if (!this.root.gameInitialized) {
+ return;
+ }
+
+ if (!entity.components.Belt) {
+ return;
+ }
+
+ this.addEntityToPaths(entity);
+ if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
+ this.debug_verifyBeltPaths();
+ }
+ }
+
+ /**
+ * Draws all belt paths
+ * @param {DrawParameters} parameters
+ */
+ drawBeltItems(parameters) {
+ for (let i = 0; i < this.beltPaths.length; ++i) {
+ this.beltPaths[i].draw(parameters);
+ }
+ }
+
+ /**
+ * Verifies all belt paths
+ */
+ debug_verifyBeltPaths() {
+ for (let i = 0; i < this.beltPaths.length; ++i) {
+ this.beltPaths[i].debug_checkIntegrity("general-verify");
+ }
+
+ const belts = this.root.entityMgr.getAllWithComponent(BeltComponent);
+ for (let i = 0; i < belts.length; ++i) {
+ const path = belts[i].components.Belt.assignedPath;
+ if (!path) {
+ throw new Error("Belt has no path: " + belts[i].uid);
+ }
+ if (this.beltPaths.indexOf(path) < 0) {
+ throw new Error("Path of entity not contained: " + belts[i].uid);
+ }
+ }
+ }
+
+ /**
+ * Finds the follow up entity for a given belt. Used for building the dependencies
+ * @param {Entity} entity
+ * @returns {Entity|null}
+ */
+ findFollowUpEntity(entity) {
+ const staticComp = entity.components.StaticMapEntity;
+ const beltComp = entity.components.Belt;
+
+ const followUpDirection = staticComp.localDirectionToWorld(beltComp.direction);
+ const followUpVector = enumDirectionToVector[followUpDirection];
+
+ const followUpTile = staticComp.origin.add(followUpVector);
+ const followUpEntity = this.root.map.getLayerContentXY(followUpTile.x, followUpTile.y, entity.layer);
+
+ // Check if there's a belt at the tile we point to
+ if (followUpEntity) {
+ const followUpBeltComp = followUpEntity.components.Belt;
+ if (followUpBeltComp) {
+ const followUpStatic = followUpEntity.components.StaticMapEntity;
+
+ const acceptedDirection = followUpStatic.localDirectionToWorld(enumDirection.top);
+ if (acceptedDirection === followUpDirection) {
+ return followUpEntity;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Finds the supplying belt for a given belt. Used for building the dependencies
+ * @param {Entity} entity
+ * @returns {Entity|null}
+ */
+ findSupplyingEntity(entity) {
+ const staticComp = entity.components.StaticMapEntity;
+
+ const supplyDirection = staticComp.localDirectionToWorld(enumDirection.bottom);
+ const supplyVector = enumDirectionToVector[supplyDirection];
+
+ const supplyTile = staticComp.origin.add(supplyVector);
+ const supplyEntity = this.root.map.getLayerContentXY(supplyTile.x, supplyTile.y, entity.layer);
+
+ // Check if there's a belt at the tile we point to
+ if (supplyEntity) {
+ const supplyBeltComp = supplyEntity.components.Belt;
+ if (supplyBeltComp) {
+ const supplyStatic = supplyEntity.components.StaticMapEntity;
+ const otherDirection = supplyStatic.localDirectionToWorld(
+ enumInvertedDirections[supplyBeltComp.direction]
+ );
+
+ if (otherDirection === supplyDirection) {
+ return supplyEntity;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Recomputes the belt path network. Only required for old savegames
+ */
+ recomputeAllBeltPaths() {
+ logger.warn("Recomputing all belt paths");
+ const visitedUids = new Set();
+
+ const result = [];
+
+ for (let i = 0; i < this.allEntities.length; ++i) {
+ const entity = this.allEntities[i];
+ if (visitedUids.has(entity.uid)) {
+ continue;
+ }
+
+ // Mark entity as visited
+ visitedUids.add(entity.uid);
+
+ // Compute path, start with entity and find precedors / successors
+ const path = [entity];
+
+ // Prevent infinite loops
+ let maxIter = 99999;
+
+ // Find precedors
+ let prevEntity = this.findSupplyingEntity(entity);
+ while (prevEntity && --maxIter > 0) {
+ if (visitedUids.has(prevEntity.uid)) {
+ break;
+ }
+ path.unshift(prevEntity);
+ visitedUids.add(prevEntity.uid);
+ prevEntity = this.findSupplyingEntity(prevEntity);
+ }
+
+ // Find succedors
+ let nextEntity = this.findFollowUpEntity(entity);
+ while (nextEntity && --maxIter > 0) {
+ if (visitedUids.has(nextEntity.uid)) {
+ break;
+ }
+
+ path.push(nextEntity);
+ visitedUids.add(nextEntity.uid);
+ nextEntity = this.findFollowUpEntity(nextEntity);
+ }
+
+ assert(maxIter > 1, "Ran out of iterations");
+ result.push(new BeltPath(this.root, path));
+ }
+
+ logger.log("Found", this.beltPaths.length, "belt paths");
+ this.beltPaths = result;
+ }
+
+ /**
+ * Updates all belts
+ */
+ update() {
+ if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
+ this.debug_verifyBeltPaths();
+ }
+
+ for (let i = 0; i < this.beltPaths.length; ++i) {
+ this.beltPaths[i].update();
+ }
+
+ if (G_IS_DEV && globalConfig.debug.checkBeltPaths) {
+ this.debug_verifyBeltPaths();
+ }
+ }
+
+ /**
+ * Draws a given chunk
+ * @param {DrawParameters} parameters
+ * @param {MapChunkView} chunk
+ */
+ drawChunk(parameters, chunk) {
+ // Limit speed to avoid belts going backwards
+ const speedMultiplier = Math.min(this.root.hubGoals.getBeltBaseSpeed(), 10);
+
+ // SYNC with systems/item_acceptor.js:drawEntityUnderlays!
+ // 126 / 42 is the exact animation speed of the png animation
+ const animationIndex = Math.floor(
+ ((this.root.time.realtimeNow() * speedMultiplier * BELT_ANIM_COUNT * 126) / 42) *
+ globalConfig.itemSpacingOnBelts
+ );
+ const contents = chunk.containedEntitiesByLayer.regular;
+
+ if (this.root.app.settings.getAllSettings().simplifiedBelts) {
+ // POTATO Mode: Only show items when belt is hovered
+ let hoveredBeltPath = null;
+ const mousePos = this.root.app.mousePosition;
+ if (mousePos && this.root.currentLayer === "regular") {
+ const tile = this.root.camera.screenToWorld(mousePos).toTileSpace();
+ const contents = this.root.map.getLayerContentXY(tile.x, tile.y, "regular");
+ if (contents && contents.components.Belt) {
+ hoveredBeltPath = contents.components.Belt.assignedPath;
+ }
+ }
+
+ for (let i = 0; i < contents.length; ++i) {
+ const entity = contents[i];
+ if (entity.components.Belt) {
+ const direction = entity.components.Belt.direction;
+ let sprite = this.beltAnimations[direction][0];
+
+ if (entity.components.Belt.assignedPath === hoveredBeltPath) {
+ sprite = this.beltAnimations[direction][animationIndex % BELT_ANIM_COUNT];
+ }
+
+ // Culling happens within the static map entity component
+ entity.components.StaticMapEntity.drawSpriteOnBoundsClipped(parameters, sprite, 0);
+ }
+ }
+ } else {
+ for (let i = 0; i < contents.length; ++i) {
+ const entity = contents[i];
+ if (entity.components.Belt) {
+ const direction = entity.components.Belt.direction;
+ const sprite = this.beltAnimations[direction][animationIndex % BELT_ANIM_COUNT];
+
+ // Culling happens within the static map entity component
+ entity.components.StaticMapEntity.drawSpriteOnBoundsClipped(parameters, sprite, 0);
+ }
+ }
+ }
+ }
+
+ /**
+ * Draws the belt path debug overlays
+ * @param {DrawParameters} parameters
+ */
+ drawBeltPathDebug(parameters) {
+ for (let i = 0; i < this.beltPaths.length; ++i) {
+ this.beltPaths[i].drawDebug(parameters);
+ }
+ }
+}
diff --git a/src/js/game/systems/belt_reader.js b/src/js/game/systems/belt_reader.js
index abddd999..4ce75af4 100644
--- a/src/js/game/systems/belt_reader.js
+++ b/src/js/game/systems/belt_reader.js
@@ -48,7 +48,7 @@ export class BeltReaderSystem extends GameSystemWithFilter {
throughput = 1 / (averageSpacing / averageSpacingNum);
}
- readerComp.lastThroughput = throughput;
+ readerComp.lastThroughput = Math.min(30, throughput);
}
}
}
diff --git a/src/js/game/systems/belt_underlays.js b/src/js/game/systems/belt_underlays.js
index 5bdf2331..c5c69d26 100644
--- a/src/js/game/systems/belt_underlays.js
+++ b/src/js/game/systems/belt_underlays.js
@@ -1,84 +1,300 @@
-import { globalConfig } from "../../core/config";
-import { drawRotatedSprite } from "../../core/draw_utils";
-import { Loader } from "../../core/loader";
-import { enumDirectionToAngle } from "../../core/vector";
-import { BeltUnderlaysComponent } from "../components/belt_underlays";
-import { GameSystemWithFilter } from "../game_system_with_filter";
-import { BELT_ANIM_COUNT } from "./belt";
-import { MapChunkView } from "../map_chunk_view";
-import { DrawParameters } from "../../core/draw_parameters";
-
-export class BeltUnderlaysSystem extends GameSystemWithFilter {
- constructor(root) {
- super(root, [BeltUnderlaysComponent]);
-
- this.underlayBeltSprites = [];
-
- for (let i = 0; i < BELT_ANIM_COUNT; ++i) {
- this.underlayBeltSprites.push(Loader.getSprite("sprites/belt/built/forward_" + i + ".png"));
- }
- }
-
- /**
- * Draws a given chunk
- * @param {DrawParameters} parameters
- * @param {MapChunkView} chunk
- */
- drawChunk(parameters, chunk) {
- // Limit speed to avoid belts going backwards
- const speedMultiplier = Math.min(this.root.hubGoals.getBeltBaseSpeed(), 10);
-
- const contents = chunk.containedEntitiesByLayer.regular;
- for (let i = 0; i < contents.length; ++i) {
- const entity = contents[i];
- const underlayComp = entity.components.BeltUnderlays;
- if (!underlayComp) {
- continue;
- }
-
- const staticComp = entity.components.StaticMapEntity;
- const underlays = underlayComp.underlays;
- for (let i = 0; i < underlays.length; ++i) {
- const { pos, direction } = underlays[i];
- const transformedPos = staticComp.localTileToWorld(pos);
-
- // Culling
- if (!chunk.tileSpaceRectangle.containsPoint(transformedPos.x, transformedPos.y)) {
- continue;
- }
-
- const destX = transformedPos.x * globalConfig.tileSize;
- const destY = transformedPos.y * globalConfig.tileSize;
-
- // Culling, #2
- if (
- !parameters.visibleRect.containsRect4Params(
- destX,
- destY,
- globalConfig.tileSize,
- globalConfig.tileSize
- )
- ) {
- continue;
- }
-
- const angle = enumDirectionToAngle[staticComp.localDirectionToWorld(direction)];
-
- // SYNC with systems/belt.js:drawSingleEntity!
- const animationIndex = Math.floor(
- ((this.root.time.realtimeNow() * speedMultiplier * BELT_ANIM_COUNT * 126) / 42) *
- globalConfig.itemSpacingOnBelts
- );
-
- drawRotatedSprite({
- parameters,
- sprite: this.underlayBeltSprites[animationIndex % this.underlayBeltSprites.length],
- x: destX + globalConfig.halfTileSize,
- y: destY + globalConfig.halfTileSize,
- angle: Math.radians(angle),
- size: globalConfig.tileSize,
- });
- }
- }
- }
-}
+import { globalConfig } from "../../core/config";
+import { DrawParameters } from "../../core/draw_parameters";
+import { Loader } from "../../core/loader";
+import { Rectangle } from "../../core/rectangle";
+import { FULL_CLIP_RECT } from "../../core/sprites";
+import { StaleAreaDetector } from "../../core/stale_area_detector";
+import {
+ enumDirection,
+ enumDirectionToAngle,
+ enumDirectionToVector,
+ enumInvertedDirections,
+ Vector,
+} from "../../core/vector";
+import { BeltComponent } from "../components/belt";
+import { BeltUnderlaysComponent, enumClippedBeltUnderlayType } from "../components/belt_underlays";
+import { ItemAcceptorComponent } from "../components/item_acceptor";
+import { ItemEjectorComponent } from "../components/item_ejector";
+import { Entity } from "../entity";
+import { GameSystemWithFilter } from "../game_system_with_filter";
+import { MapChunkView } from "../map_chunk_view";
+import { BELT_ANIM_COUNT } from "./belt";
+
+/**
+ * Mapping from underlay type to clip rect
+ * @type {Object}
+ */
+const enumUnderlayTypeToClipRect = {
+ [enumClippedBeltUnderlayType.none]: null,
+ [enumClippedBeltUnderlayType.full]: FULL_CLIP_RECT,
+ [enumClippedBeltUnderlayType.topOnly]: new Rectangle(0, 0, 1, 0.5),
+ [enumClippedBeltUnderlayType.bottomOnly]: new Rectangle(0, 0.5, 1, 0.5),
+};
+
+export class BeltUnderlaysSystem extends GameSystemWithFilter {
+ constructor(root) {
+ super(root, [BeltUnderlaysComponent]);
+
+ this.underlayBeltSprites = [];
+
+ for (let i = 0; i < BELT_ANIM_COUNT; ++i) {
+ this.underlayBeltSprites.push(Loader.getSprite("sprites/belt/built/forward_" + i + ".png"));
+ }
+
+ // Automatically recompute areas
+ this.staleArea = new StaleAreaDetector({
+ root,
+ name: "belt-underlay",
+ recomputeMethod: this.recomputeStaleArea.bind(this),
+ });
+
+ this.staleArea.recomputeOnComponentsChanged(
+ [BeltUnderlaysComponent, BeltComponent, ItemAcceptorComponent, ItemEjectorComponent],
+ 1
+ );
+ }
+
+ update() {
+ this.staleArea.update();
+ }
+
+ /**
+ * Called when an area changed - Resets all caches in the given area
+ * @param {Rectangle} area
+ */
+ recomputeStaleArea(area) {
+ for (let x = 0; x < area.w; ++x) {
+ for (let y = 0; y < area.h; ++y) {
+ const tileX = area.x + x;
+ const tileY = area.y + y;
+ const entity = this.root.map.getLayerContentXY(tileX, tileY, "regular");
+ if (entity) {
+ const underlayComp = entity.components.BeltUnderlays;
+ if (underlayComp) {
+ for (let i = 0; i < underlayComp.underlays.length; ++i) {
+ underlayComp.underlays[i].cachedType = null;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks if a given tile is connected and has an acceptor
+ * @param {Vector} tile
+ * @param {enumDirection} fromDirection
+ * @returns {boolean}
+ */
+ checkIsAcceptorConnected(tile, fromDirection) {
+ const contents = this.root.map.getLayerContentXY(tile.x, tile.y, "regular");
+ if (!contents) {
+ return false;
+ }
+
+ const staticComp = contents.components.StaticMapEntity;
+
+ // Check if its a belt, since then its simple
+ const beltComp = contents.components.Belt;
+ if (beltComp) {
+ return staticComp.localDirectionToWorld(enumDirection.bottom) === fromDirection;
+ }
+
+ // Check if there's an item acceptor
+ const acceptorComp = contents.components.ItemAcceptor;
+ if (acceptorComp) {
+ // Check each slot to see if its connected
+ for (let i = 0; i < acceptorComp.slots.length; ++i) {
+ const slot = acceptorComp.slots[i];
+ const slotTile = staticComp.localTileToWorld(slot.pos);
+
+ // Step 1: Check if the tile matches
+ if (!slotTile.equals(tile)) {
+ continue;
+ }
+
+ // Step 2: Check if any of the directions matches
+ for (let j = 0; j < slot.directions.length; ++j) {
+ const slotDirection = staticComp.localDirectionToWorld(slot.directions[j]);
+ if (slotDirection === fromDirection) {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Checks if a given tile is connected and has an ejector
+ * @param {Vector} tile
+ * @param {enumDirection} toDirection
+ * @returns {boolean}
+ */
+ checkIsEjectorConnected(tile, toDirection) {
+ const contents = this.root.map.getLayerContentXY(tile.x, tile.y, "regular");
+ if (!contents) {
+ return false;
+ }
+
+ const staticComp = contents.components.StaticMapEntity;
+
+ // Check if its a belt, since then its simple
+ const beltComp = contents.components.Belt;
+ if (beltComp) {
+ return staticComp.localDirectionToWorld(beltComp.direction) === toDirection;
+ }
+
+ // Check for an ejector
+ const ejectorComp = contents.components.ItemEjector;
+ if (ejectorComp) {
+ // Check each slot to see if its connected
+ for (let i = 0; i < ejectorComp.slots.length; ++i) {
+ const slot = ejectorComp.slots[i];
+ const slotTile = staticComp.localTileToWorld(slot.pos);
+
+ // Step 1: Check if the tile matches
+ if (!slotTile.equals(tile)) {
+ continue;
+ }
+
+ // Step 2: Check if the direction matches
+ const slotDirection = staticComp.localDirectionToWorld(slot.direction);
+ if (slotDirection === toDirection) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Computes the flag for a given tile
+ * @param {Entity} entity
+ * @param {import("../components/belt_underlays").BeltUnderlayTile} underlayTile
+ * @returns {enumClippedBeltUnderlayType} The type of the underlay
+ */
+ computeBeltUnderlayType(entity, underlayTile) {
+ if (underlayTile.cachedType) {
+ return underlayTile.cachedType;
+ }
+
+ const staticComp = entity.components.StaticMapEntity;
+
+ const transformedPos = staticComp.localTileToWorld(underlayTile.pos);
+ const destX = transformedPos.x * globalConfig.tileSize;
+ const destY = transformedPos.y * globalConfig.tileSize;
+
+ // Extract direction and angle
+ const worldDirection = staticComp.localDirectionToWorld(underlayTile.direction);
+ const worldDirectionVector = enumDirectionToVector[worldDirection];
+
+ // Figure out if there is anything connected at the top
+ const connectedTop = this.checkIsAcceptorConnected(
+ transformedPos.add(worldDirectionVector),
+ enumInvertedDirections[worldDirection]
+ );
+
+ // Figure out if there is anything connected at the bottom
+ const connectedBottom = this.checkIsEjectorConnected(
+ transformedPos.sub(worldDirectionVector),
+ worldDirection
+ );
+
+ let flag = enumClippedBeltUnderlayType.none;
+
+ if (connectedTop && connectedBottom) {
+ flag = enumClippedBeltUnderlayType.full;
+ } else if (connectedTop) {
+ flag = enumClippedBeltUnderlayType.topOnly;
+ } else if (connectedBottom) {
+ flag = enumClippedBeltUnderlayType.bottomOnly;
+ }
+
+ return (underlayTile.cachedType = flag);
+ }
+
+ /**
+ * Draws a given chunk
+ * @param {DrawParameters} parameters
+ * @param {MapChunkView} chunk
+ */
+ drawChunk(parameters, chunk) {
+ // Limit speed to avoid belts going backwards
+ const speedMultiplier = Math.min(this.root.hubGoals.getBeltBaseSpeed(), 10);
+
+ const contents = chunk.containedEntitiesByLayer.regular;
+ for (let i = 0; i < contents.length; ++i) {
+ const entity = contents[i];
+ const underlayComp = entity.components.BeltUnderlays;
+ if (!underlayComp) {
+ continue;
+ }
+
+ const staticComp = entity.components.StaticMapEntity;
+ const underlays = underlayComp.underlays;
+ for (let i = 0; i < underlays.length; ++i) {
+ // Extract underlay parameters
+ const { pos, direction } = underlays[i];
+ const transformedPos = staticComp.localTileToWorld(pos);
+ const destX = transformedPos.x * globalConfig.tileSize;
+ const destY = transformedPos.y * globalConfig.tileSize;
+
+ // Culling, Part 1: Check if the chunk contains the tile
+ if (!chunk.tileSpaceRectangle.containsPoint(transformedPos.x, transformedPos.y)) {
+ continue;
+ }
+
+ // Culling, Part 2: Check if the overlay is visible
+ if (
+ !parameters.visibleRect.containsRect4Params(
+ destX,
+ destY,
+ globalConfig.tileSize,
+ globalConfig.tileSize
+ )
+ ) {
+ continue;
+ }
+
+ // Extract direction and angle
+ const worldDirection = staticComp.localDirectionToWorld(direction);
+ const angle = enumDirectionToAngle[worldDirection];
+
+ const underlayType = this.computeBeltUnderlayType(entity, underlays[i]);
+ const clipRect = enumUnderlayTypeToClipRect[underlayType];
+ if (!clipRect) {
+ // Empty
+ continue;
+ }
+
+ // Actually draw the sprite
+ const x = destX + globalConfig.halfTileSize;
+ const y = destY + globalConfig.halfTileSize;
+ const angleRadians = Math.radians(angle);
+
+ // SYNC with systems/belt.js:drawSingleEntity!
+ const animationIndex = Math.floor(
+ ((this.root.time.realtimeNow() * speedMultiplier * BELT_ANIM_COUNT * 126) / 42) *
+ globalConfig.itemSpacingOnBelts
+ );
+ parameters.context.translate(x, y);
+ parameters.context.rotate(angleRadians);
+ this.underlayBeltSprites[
+ animationIndex % this.underlayBeltSprites.length
+ ].drawCachedWithClipRect(
+ parameters,
+ -globalConfig.halfTileSize,
+ -globalConfig.halfTileSize,
+ globalConfig.tileSize,
+ globalConfig.tileSize,
+ clipRect
+ );
+ parameters.context.rotate(-angleRadians);
+ parameters.context.translate(-x, -y);
+ }
+ }
+ }
+}
diff --git a/src/js/game/systems/display.js b/src/js/game/systems/display.js
index 2ad551f0..f11091b9 100644
--- a/src/js/game/systems/display.js
+++ b/src/js/game/systems/display.js
@@ -65,7 +65,7 @@ export class DisplaySystem extends GameSystemWithFilter {
const pinsComp = entity.components.WiredPins;
const network = pinsComp.slots[0].linkedNetwork;
- if (!network || !network.currentValue) {
+ if (!network || !network.hasValue()) {
continue;
}
diff --git a/src/js/game/systems/filter.js b/src/js/game/systems/filter.js
new file mode 100644
index 00000000..a6442b41
--- /dev/null
+++ b/src/js/game/systems/filter.js
@@ -0,0 +1,85 @@
+import { globalConfig } from "../../core/config";
+import { BaseItem } from "../base_item";
+import { FilterComponent } from "../components/filter";
+import { Entity } from "../entity";
+import { GameSystemWithFilter } from "../game_system_with_filter";
+import { BOOL_TRUE_SINGLETON } from "../items/boolean_item";
+
+const MAX_ITEMS_IN_QUEUE = 2;
+
+export class FilterSystem extends GameSystemWithFilter {
+ constructor(root) {
+ super(root, [FilterComponent]);
+ }
+
+ update() {
+ const progress =
+ this.root.dynamicTickrate.deltaSeconds *
+ this.root.hubGoals.getBeltBaseSpeed() *
+ globalConfig.itemSpacingOnBelts;
+
+ const requiredProgress = 1 - progress;
+
+ for (let i = 0; i < this.allEntities.length; ++i) {
+ const entity = this.allEntities[i];
+ const filterComp = entity.components.Filter;
+ const ejectorComp = entity.components.ItemEjector;
+
+ // Process payloads
+ const slotsAndLists = [filterComp.pendingItemsToLeaveThrough, filterComp.pendingItemsToReject];
+ for (let slotIndex = 0; slotIndex < slotsAndLists.length; ++slotIndex) {
+ const pendingItems = slotsAndLists[slotIndex];
+
+ for (let j = 0; j < pendingItems.length; ++j) {
+ const nextItem = pendingItems[j];
+ // Advance next item
+ nextItem.progress = Math.min(requiredProgress, nextItem.progress + progress);
+ // Check if it's ready to eject
+ if (nextItem.progress >= requiredProgress - 1e-5) {
+ if (ejectorComp.tryEject(slotIndex, nextItem.item)) {
+ pendingItems.shift();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ *
+ * @param {Entity} entity
+ * @param {number} slot
+ * @param {BaseItem} item
+ */
+ tryAcceptItem(entity, slot, item) {
+ const network = entity.components.WiredPins.slots[0].linkedNetwork;
+ if (!network || !network.hasValue()) {
+ // Filter is not connected
+ return false;
+ }
+
+ const value = network.currentValue;
+ const filterComp = entity.components.Filter;
+ assert(filterComp, "entity is no filter");
+
+ // Figure out which list we have to check
+ let listToCheck;
+ if (value.equals(BOOL_TRUE_SINGLETON) || value.equals(item)) {
+ listToCheck = filterComp.pendingItemsToLeaveThrough;
+ } else {
+ listToCheck = filterComp.pendingItemsToReject;
+ }
+
+ if (listToCheck.length >= MAX_ITEMS_IN_QUEUE) {
+ // Busy
+ return false;
+ }
+
+ // Actually accept item
+ listToCheck.push({
+ item,
+ progress: 0.0,
+ });
+ return true;
+ }
+}
diff --git a/src/js/game/systems/item_acceptor.js b/src/js/game/systems/item_acceptor.js
index 6d6fec77..780b4abd 100644
--- a/src/js/game/systems/item_acceptor.js
+++ b/src/js/game/systems/item_acceptor.js
@@ -9,14 +9,35 @@ import { MapChunkView } from "../map_chunk_view";
export class ItemAcceptorSystem extends GameSystemWithFilter {
constructor(root) {
super(root, [ItemAcceptorComponent]);
+
+ // Well ... it's better to be verbose I guess?
+ this.accumulatedTicksWhileInMapOverview = 0;
}
update() {
+ if (this.root.app.settings.getAllSettings().simplifiedBelts) {
+ // Disabled in potato mode
+ return;
+ }
+
+ // This system doesn't render anything while in map overview,
+ // so simply accumulate ticks
+ if (this.root.camera.getIsMapOverlayActive()) {
+ ++this.accumulatedTicksWhileInMapOverview;
+ return;
+ }
+
+ // Compute how much ticks we missed
+ const numTicks = 1 + this.accumulatedTicksWhileInMapOverview;
const progress =
this.root.dynamicTickrate.deltaSeconds *
2 *
this.root.hubGoals.getBeltBaseSpeed() *
- globalConfig.itemSpacingOnBelts; // * 2 because its only a half tile
+ globalConfig.itemSpacingOnBelts * // * 2 because its only a half tile
+ numTicks;
+
+ // Reset accumulated ticks
+ this.accumulatedTicksWhileInMapOverview = 0;
for (let i = 0; i < this.allEntities.length; ++i) {
const entity = this.allEntities[i];
@@ -40,6 +61,11 @@ export class ItemAcceptorSystem extends GameSystemWithFilter {
* @param {MapChunkView} chunk
*/
drawChunk(parameters, chunk) {
+ if (this.root.app.settings.getAllSettings().simplifiedBelts) {
+ // Disabled in potato mode
+ return;
+ }
+
const contents = chunk.containedEntitiesByLayer.regular;
for (let i = 0; i < contents.length; ++i) {
const entity = contents[i];
diff --git a/src/js/game/systems/item_ejector.js b/src/js/game/systems/item_ejector.js
index 925dcc2e..4f7d29be 100644
--- a/src/js/game/systems/item_ejector.js
+++ b/src/js/game/systems/item_ejector.js
@@ -2,8 +2,11 @@ import { globalConfig } from "../../core/config";
import { DrawParameters } from "../../core/draw_parameters";
import { createLogger } from "../../core/logging";
import { Rectangle } from "../../core/rectangle";
+import { StaleAreaDetector } from "../../core/stale_area_detector";
import { enumDirection, enumDirectionToVector } from "../../core/vector";
import { BaseItem } from "../base_item";
+import { BeltComponent } from "../components/belt";
+import { ItemAcceptorComponent } from "../components/item_acceptor";
import { ItemEjectorComponent } from "../components/item_ejector";
import { Entity } from "../entity";
import { GameSystemWithFilter } from "../game_system_with_filter";
@@ -15,102 +18,52 @@ export class ItemEjectorSystem extends GameSystemWithFilter {
constructor(root) {
super(root, [ItemEjectorComponent]);
- this.root.signals.entityAdded.add(this.checkForCacheInvalidation, this);
- this.root.signals.entityDestroyed.add(this.checkForCacheInvalidation, this);
- this.root.signals.postLoadHook.add(this.recomputeCache, this);
+ this.staleAreaDetector = new StaleAreaDetector({
+ root: this.root,
+ name: "item-ejector",
+ recomputeMethod: this.recomputeArea.bind(this),
+ });
- /**
- * @type {Rectangle}
- */
- this.areaToRecompute = null;
+ this.staleAreaDetector.recomputeOnComponentsChanged(
+ [ItemEjectorComponent, ItemAcceptorComponent, BeltComponent],
+ 1
+ );
+
+ this.root.signals.postLoadHook.add(this.recomputeCacheFull, this);
}
/**
- *
- * @param {Entity} entity
+ * Recomputes an area after it changed
+ * @param {Rectangle} area
*/
- checkForCacheInvalidation(entity) {
- if (!this.root.gameInitialized) {
- return;
- }
- if (!entity.components.StaticMapEntity) {
- return;
- }
-
- // Optimize for the common case: adding or removing one building at a time. Clicking
- // and dragging can cause up to 4 add/remove signals.
- const staticComp = entity.components.StaticMapEntity;
- const bounds = staticComp.getTileSpaceBounds();
- const expandedBounds = bounds.expandedInAllDirections(2);
-
- if (this.areaToRecompute) {
- this.areaToRecompute = this.areaToRecompute.getUnion(expandedBounds);
- } else {
- this.areaToRecompute = expandedBounds;
- }
- }
-
- /**
- * Precomputes the cache, which makes up for a huge performance improvement
- */
- recomputeCache() {
- if (this.areaToRecompute) {
- logger.log("Recomputing cache using rectangle");
- if (G_IS_DEV && globalConfig.debug.renderChanges) {
- this.root.hud.parts.changesDebugger.renderChange(
- "ejector-area",
- this.areaToRecompute,
- "#fe50a6"
- );
- }
- this.recomputeAreaCache();
- this.areaToRecompute = null;
- } else {
- logger.log("Full cache recompute");
- if (G_IS_DEV && globalConfig.debug.renderChanges) {
- this.root.hud.parts.changesDebugger.renderChange(
- "ejector-full",
- new Rectangle(-1000, -1000, 2000, 2000),
- "#fe50a6"
- );
- }
-
- // Try to find acceptors for every ejector
- for (let i = 0; i < this.allEntities.length; ++i) {
- const entity = this.allEntities[i];
- this.recomputeSingleEntityCache(entity);
- }
- }
- }
-
- /**
- * Recomputes the cache in the given area
- */
- recomputeAreaCache() {
- const area = this.areaToRecompute;
- let entryCount = 0;
-
- logger.log("Recomputing area:", area.x, area.y, "/", area.w, area.h);
-
- // Store the entities we already recomputed, so we don't do work twice
- const recomputedEntities = new Set();
-
- for (let x = area.x; x < area.right(); ++x) {
- for (let y = area.y; y < area.bottom(); ++y) {
- const entities = this.root.map.getLayersContentsMultipleXY(x, y);
- for (let i = 0; i < entities.length; ++i) {
- const entity = entities[i];
-
- // Recompute the entity in case its relevant for this system and it
- // hasn't already been computed
- if (!recomputedEntities.has(entity.uid) && entity.components.ItemEjector) {
- recomputedEntities.add(entity.uid);
- this.recomputeSingleEntityCache(entity);
+ recomputeArea(area) {
+ /** @type {Set} */
+ const seenUids = new Set();
+ for (let x = 0; x < area.w; ++x) {
+ for (let y = 0; y < area.h; ++y) {
+ const tileX = area.x + x;
+ const tileY = area.y + y;
+ // @NOTICE: Item ejector currently only supports regular layer
+ const contents = this.root.map.getLayerContentXY(tileX, tileY, "regular");
+ if (contents && contents.components.ItemEjector) {
+ if (!seenUids.has(contents.uid)) {
+ seenUids.add(contents.uid);
+ this.recomputeSingleEntityCache(contents);
}
}
}
}
- return entryCount;
+ }
+
+ /**
+ * Recomputes the whole cache after the game has loaded
+ */
+ recomputeCacheFull() {
+ logger.log("Full cache recompute in post load hook");
+ for (let i = 0; i < this.allEntities.length; ++i) {
+ const entity = this.allEntities[i];
+ this.recomputeSingleEntityCache(entity);
+ }
}
/**
@@ -183,9 +136,7 @@ export class ItemEjectorSystem extends GameSystemWithFilter {
}
update() {
- if (this.areaToRecompute) {
- this.recomputeCache();
- }
+ this.staleAreaDetector.update();
// Precompute effective belt speed
let progressGrowth = 2 * this.root.dynamicTickrate.deltaSeconds;
@@ -198,9 +149,6 @@ export class ItemEjectorSystem extends GameSystemWithFilter {
for (let i = 0; i < this.allEntities.length; ++i) {
const sourceEntity = this.allEntities[i];
const sourceEjectorComp = sourceEntity.components.ItemEjector;
- if (!sourceEjectorComp.enabled) {
- continue;
- }
const slots = sourceEjectorComp.slots;
for (let j = 0; j < slots.length; ++j) {
@@ -211,8 +159,6 @@ export class ItemEjectorSystem extends GameSystemWithFilter {
continue;
}
- const targetEntity = sourceSlot.cachedTargetEntity;
-
// Advance items on the slot
sourceSlot.progress = Math.min(
1,
@@ -245,17 +191,24 @@ export class ItemEjectorSystem extends GameSystemWithFilter {
}
// Check if the target acceptor can actually accept this item
+ const destEntity = sourceSlot.cachedTargetEntity;
const destSlot = sourceSlot.cachedDestSlot;
if (destSlot) {
- const targetAcceptorComp = targetEntity.components.ItemAcceptor;
+ const targetAcceptorComp = destEntity.components.ItemAcceptor;
if (!targetAcceptorComp.canAcceptItem(destSlot.index, item)) {
continue;
}
// Try to hand over the item
- if (this.tryPassOverItem(item, targetEntity, destSlot.index)) {
+ if (this.tryPassOverItem(item, destEntity, destSlot.index)) {
// Handover successful, clear slot
- targetAcceptorComp.onItemAccepted(destSlot.index, destSlot.acceptedDirection, item);
+ if (!this.root.app.settings.getAllSettings().simplifiedBelts) {
+ targetAcceptorComp.onItemAccepted(
+ destSlot.index,
+ destSlot.acceptedDirection,
+ item
+ );
+ }
sourceSlot.item = null;
continue;
}
@@ -329,6 +282,15 @@ export class ItemEjectorSystem extends GameSystemWithFilter {
return false;
}
+ const filterComp = receiver.components.Filter;
+ if (filterComp) {
+ // It's a filter! Unfortunately the filter has to know a lot about it's
+ // surrounding state and components, so it can't be within the component itself.
+ if (this.root.systemMgr.systems.filter.tryAcceptItem(receiver, slotIndex, item)) {
+ return true;
+ }
+ }
+
return false;
}
@@ -337,6 +299,11 @@ export class ItemEjectorSystem extends GameSystemWithFilter {
* @param {MapChunkView} chunk
*/
drawChunk(parameters, chunk) {
+ if (this.root.app.settings.getAllSettings().simplifiedBelts) {
+ // Disabled in potato mode
+ return;
+ }
+
const contents = chunk.containedEntitiesByLayer.regular;
for (let i = 0; i < contents.length; ++i) {
@@ -357,6 +324,11 @@ export class ItemEjectorSystem extends GameSystemWithFilter {
continue;
}
+ if (!ejectorComp.renderFloatingItems && !slot.cachedTargetEntity) {
+ // Not connected to any building
+ continue;
+ }
+
const realPosition = staticComp.localTileToWorld(slot.pos);
if (!chunk.tileSpaceRectangle.containsPoint(realPosition.x, realPosition.y)) {
// Not within this chunk
diff --git a/src/js/game/systems/item_processor.js b/src/js/game/systems/item_processor.js
index d58aa697..7fc2819b 100644
--- a/src/js/game/systems/item_processor.js
+++ b/src/js/game/systems/item_processor.js
@@ -16,9 +16,55 @@ import { ShapeItem } from "../items/shape_item";
*/
const MAX_QUEUED_CHARGES = 2;
+/**
+ * Whole data for a produced item
+ *
+ * @typedef {{
+ * item: BaseItem,
+ * preferredSlot?: number,
+ * requiredSlot?: number,
+ * doNotTrack?: boolean
+ * }} ProducedItem
+ */
+
+/**
+ * Type of a processor implementation
+ * @typedef {{
+ * entity: Entity,
+ * items: Array<{ item: BaseItem, sourceSlot: number }>,
+ * itemsBySlot: Object,
+ * outItems: Array
+ * }} ProcessorImplementationPayload
+ */
+
export class ItemProcessorSystem extends GameSystemWithFilter {
constructor(root) {
super(root, [ItemProcessorComponent]);
+
+ /**
+ * @type {Object}
+ */
+ this.handlers = {
+ [enumItemProcessorTypes.balancer]: this.process_BALANCER,
+ [enumItemProcessorTypes.cutter]: this.process_CUTTER,
+ [enumItemProcessorTypes.cutterQuad]: this.process_CUTTER_QUAD,
+ [enumItemProcessorTypes.rotater]: this.process_ROTATER,
+ [enumItemProcessorTypes.rotaterCCW]: this.process_ROTATER_CCW,
+ [enumItemProcessorTypes.rotater180]: this.process_ROTATER_180,
+ [enumItemProcessorTypes.stacker]: this.process_STACKER,
+ [enumItemProcessorTypes.trash]: this.process_TRASH,
+ [enumItemProcessorTypes.mixer]: this.process_MIXER,
+ [enumItemProcessorTypes.painter]: this.process_PAINTER,
+ [enumItemProcessorTypes.painterDouble]: this.process_PAINTER_DOUBLE,
+ [enumItemProcessorTypes.painterQuad]: this.process_PAINTER_QUAD,
+ [enumItemProcessorTypes.hub]: this.process_HUB,
+ [enumItemProcessorTypes.reader]: this.process_READER,
+ };
+
+ // Bind all handlers
+ for (const key in this.handlers) {
+ this.handlers[key] = this.handlers[key].bind(this);
+ }
}
update() {
@@ -115,24 +161,13 @@ export class ItemProcessorSystem extends GameSystemWithFilter {
// Check the network value at the given slot
const network = pinsComp.slots[slotIndex - 1].linkedNetwork;
- const slotIsEnabled = network && isTruthyItem(network.currentValue);
+ const slotIsEnabled = network && network.hasValue() && isTruthyItem(network.currentValue);
if (!slotIsEnabled) {
return false;
}
return true;
}
- case enumItemProcessorRequirements.filter: {
- const network = pinsComp.slots[0].linkedNetwork;
- if (!network || !network.currentValue) {
- // Item filter is not connected
- return false;
- }
-
- // Otherwise, all good
- return true;
- }
-
// By default, everything is accepted
default:
return true;
@@ -175,9 +210,8 @@ export class ItemProcessorSystem extends GameSystemWithFilter {
// Check which slots are enabled
for (let i = 0; i < 4; ++i) {
// Extract the network value on the Nth pin
- const networkValue = pinsComp.slots[i].linkedNetwork
- ? pinsComp.slots[i].linkedNetwork.currentValue
- : null;
+ const network = pinsComp.slots[i].linkedNetwork;
+ const networkValue = network && network.hasValue() ? network.currentValue : null;
// If there is no "1" on that slot, don't paint there
if (!isTruthyItem(networkValue)) {
@@ -210,18 +244,6 @@ export class ItemProcessorSystem extends GameSystemWithFilter {
return true;
}
- // FILTER
- // Double check with linked network
- case enumItemProcessorRequirements.filter: {
- const network = entity.components.WiredPins.slots[0].linkedNetwork;
- if (!network || !network.currentValue) {
- // Item filter is not connected
- return false;
- }
-
- return processorComp.inputSlots.length >= processorComp.inputsPerCharge;
- }
-
default:
assertAlways(false, "Unknown requirement for " + processorComp.processingRequirement);
}
@@ -238,310 +260,30 @@ export class ItemProcessorSystem extends GameSystemWithFilter {
const items = processorComp.inputSlots;
processorComp.inputSlots = [];
- /** @type {Object.} */
+ /** @type {Object} */
const itemsBySlot = {};
for (let i = 0; i < items.length; ++i) {
- itemsBySlot[items[i].sourceSlot] = items[i];
+ itemsBySlot[items[i].sourceSlot] = items[i].item;
}
- /** @type {Array<{item: BaseItem, requiredSlot?: number, preferredSlot?: number}>} */
+ /** @type {Array} */
const outItems = [];
- // Whether to track the production towards the analytics
- let trackProduction = true;
+ /** @type {function(ProcessorImplementationPayload) : void} */
+ const handler = this.handlers[processorComp.type];
+ assert(handler, "No handler for processor type defined: " + processorComp.type);
- // DO SOME MAGIC
-
- switch (processorComp.type) {
- // SPLITTER
- case enumItemProcessorTypes.splitterWires:
- case enumItemProcessorTypes.splitter: {
- trackProduction = false;
- const availableSlots = entity.components.ItemEjector.slots.length;
-
- let nextSlot = processorComp.nextOutputSlot++ % availableSlots;
- for (let i = 0; i < items.length; ++i) {
- outItems.push({
- item: items[i].item,
- preferredSlot: (nextSlot + i) % availableSlots,
- });
- }
- break;
- }
-
- // CUTTER
- case enumItemProcessorTypes.cutter: {
- const inputItem = /** @type {ShapeItem} */ (items[0].item);
- assert(inputItem instanceof ShapeItem, "Input for cut is not a shape");
- const inputDefinition = inputItem.definition;
-
- const cutDefinitions = this.root.shapeDefinitionMgr.shapeActionCutHalf(inputDefinition);
-
- for (let i = 0; i < cutDefinitions.length; ++i) {
- const definition = cutDefinitions[i];
- if (!definition.isEntirelyEmpty()) {
- outItems.push({
- item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(definition),
- requiredSlot: i,
- });
- }
- }
-
- break;
- }
-
- // CUTTER (Quad)
- case enumItemProcessorTypes.cutterQuad: {
- const inputItem = /** @type {ShapeItem} */ (items[0].item);
- assert(inputItem instanceof ShapeItem, "Input for cut is not a shape");
- const inputDefinition = inputItem.definition;
-
- const cutDefinitions = this.root.shapeDefinitionMgr.shapeActionCutQuad(inputDefinition);
-
- for (let i = 0; i < cutDefinitions.length; ++i) {
- const definition = cutDefinitions[i];
- if (!definition.isEntirelyEmpty()) {
- outItems.push({
- item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(definition),
- requiredSlot: i,
- });
- }
- }
-
- break;
- }
-
- // ROTATER
- case enumItemProcessorTypes.rotater: {
- const inputItem = /** @type {ShapeItem} */ (items[0].item);
- assert(inputItem instanceof ShapeItem, "Input for rotation is not a shape");
- const inputDefinition = inputItem.definition;
-
- const rotatedDefinition = this.root.shapeDefinitionMgr.shapeActionRotateCW(inputDefinition);
- outItems.push({
- item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(rotatedDefinition),
- });
- break;
- }
-
- // ROTATER (CCW)
- case enumItemProcessorTypes.rotaterCCW: {
- const inputItem = /** @type {ShapeItem} */ (items[0].item);
- assert(inputItem instanceof ShapeItem, "Input for rotation is not a shape");
- const inputDefinition = inputItem.definition;
-
- const rotatedDefinition = this.root.shapeDefinitionMgr.shapeActionRotateCCW(inputDefinition);
- outItems.push({
- item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(rotatedDefinition),
- });
- break;
- }
-
- // ROTATER (FL)
- case enumItemProcessorTypes.rotaterFL: {
- const inputItem = /** @type {ShapeItem} */ (items[0].item);
- assert(inputItem instanceof ShapeItem, "Input for rotation is not a shape");
- const inputDefinition = inputItem.definition;
-
- const rotatedDefinition = this.root.shapeDefinitionMgr.shapeActionRotateFL(inputDefinition);
- outItems.push({
- item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(rotatedDefinition),
- });
- break;
- }
-
- // STACKER
-
- case enumItemProcessorTypes.stacker: {
- const lowerItem = /** @type {ShapeItem} */ (itemsBySlot[0].item);
- const upperItem = /** @type {ShapeItem} */ (itemsBySlot[1].item);
-
- assert(lowerItem instanceof ShapeItem, "Input for lower stack is not a shape");
- assert(upperItem instanceof ShapeItem, "Input for upper stack is not a shape");
-
- const stackedDefinition = this.root.shapeDefinitionMgr.shapeActionStack(
- lowerItem.definition,
- upperItem.definition
- );
- outItems.push({
- item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(stackedDefinition),
- });
- break;
- }
-
- // TRASH
-
- case enumItemProcessorTypes.trash: {
- // Well this one is easy .. simply do nothing with the item
- break;
- }
-
- // MIXER
-
- case enumItemProcessorTypes.mixer: {
- // Find both colors and combine them
- const item1 = /** @type {ColorItem} */ (items[0].item);
- const item2 = /** @type {ColorItem} */ (items[1].item);
- assert(item1 instanceof ColorItem, "Input for color mixer is not a color");
- assert(item2 instanceof ColorItem, "Input for color mixer is not a color");
-
- const color1 = item1.color;
- const color2 = item2.color;
-
- // Try finding mixer color, and if we can't mix it we simply return the same color
- const mixedColor = enumColorMixingResults[color1][color2];
- let resultColor = color1;
- if (mixedColor) {
- resultColor = mixedColor;
- }
- outItems.push({
- item: COLOR_ITEM_SINGLETONS[resultColor],
- });
-
- break;
- }
-
- // PAINTER
-
- case enumItemProcessorTypes.painter: {
- const shapeItem = /** @type {ShapeItem} */ (itemsBySlot[0].item);
- const colorItem = /** @type {ColorItem} */ (itemsBySlot[1].item);
-
- const colorizedDefinition = this.root.shapeDefinitionMgr.shapeActionPaintWith(
- shapeItem.definition,
- colorItem.color
- );
-
- outItems.push({
- item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition),
- });
-
- break;
- }
-
- // PAINTER (DOUBLE)
-
- case enumItemProcessorTypes.painterDouble: {
- const shapeItem1 = /** @type {ShapeItem} */ (itemsBySlot[0].item);
- const shapeItem2 = /** @type {ShapeItem} */ (itemsBySlot[1].item);
- const colorItem = /** @type {ColorItem} */ (itemsBySlot[2].item);
-
- assert(shapeItem1 instanceof ShapeItem, "Input for painter is not a shape");
- assert(shapeItem2 instanceof ShapeItem, "Input for painter is not a shape");
- assert(colorItem instanceof ColorItem, "Input for painter is not a color");
-
- const colorizedDefinition1 = this.root.shapeDefinitionMgr.shapeActionPaintWith(
- shapeItem1.definition,
- colorItem.color
- );
-
- const colorizedDefinition2 = this.root.shapeDefinitionMgr.shapeActionPaintWith(
- shapeItem2.definition,
- colorItem.color
- );
- outItems.push({
- item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition1),
- });
-
- outItems.push({
- item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition2),
- });
-
- break;
- }
-
- // PAINTER (QUAD)
-
- case enumItemProcessorTypes.painterQuad: {
- const shapeItem = /** @type {ShapeItem} */ (itemsBySlot[0].item);
- assert(shapeItem instanceof ShapeItem, "Input for painter is not a shape");
-
- /** @type {Array} */
- const colors = [null, null, null, null];
- for (let i = 0; i < 4; ++i) {
- if (itemsBySlot[i + 1]) {
- colors[i] = /** @type {ColorItem} */ (itemsBySlot[i + 1].item).color;
- }
- }
-
- const colorizedDefinition = this.root.shapeDefinitionMgr.shapeActionPaintWith4Colors(
- shapeItem.definition,
- /** @type {[string, string, string, string]} */ (colors)
- );
-
- outItems.push({
- item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition),
- });
- break;
- }
-
- // FILTER
- case enumItemProcessorTypes.filter: {
- // TODO
- trackProduction = false;
-
- const item = itemsBySlot[0].item;
-
- const network = entity.components.WiredPins.slots[0].linkedNetwork;
- if (!network || !network.currentValue) {
- outItems.push({
- item,
- requiredSlot: 1,
- });
- break;
- }
-
- const value = network.currentValue;
- if (value.equals(BOOL_TRUE_SINGLETON) || value.equals(item)) {
- outItems.push({
- item,
- requiredSlot: 0,
- });
- } else {
- outItems.push({
- item,
- requiredSlot: 1,
- });
- }
-
- break;
- }
-
- // READER
- case enumItemProcessorTypes.reader: {
- // Pass through the item
- const item = itemsBySlot[0].item;
- outItems.push({ item });
-
- // Track the item
- const readerComp = entity.components.BeltReader;
- readerComp.lastItemTimes.push(this.root.time.now());
- readerComp.lastItem = item;
- break;
- }
-
- // HUB
- case enumItemProcessorTypes.hub: {
- trackProduction = false;
-
- const hubComponent = entity.components.Hub;
- assert(hubComponent, "Hub item processor has no hub component");
-
- for (let i = 0; i < items.length; ++i) {
- const item = /** @type {ShapeItem} */ (items[i].item);
- this.root.hubGoals.handleDefinitionDelivered(item.definition);
- }
-
- break;
- }
-
- default:
- assertAlways(false, "Unkown item processor type: " + processorComp.type);
- }
+ // Call implementation
+ handler({
+ entity,
+ items,
+ itemsBySlot,
+ outItems,
+ });
// Track produced items
- if (trackProduction) {
- for (let i = 0; i < outItems.length; ++i) {
+ for (let i = 0; i < outItems.length; ++i) {
+ if (!outItems[i].doNotTrack) {
this.root.signals.itemProduced.dispatch(outItems[i].item);
}
}
@@ -553,28 +295,265 @@ export class ItemProcessorSystem extends GameSystemWithFilter {
const bonusTimeToApply = Math.min(originalTime, processorComp.bonusTime);
const timeToProcess = originalTime - bonusTimeToApply;
- // Substract one tick because we already process it this frame
- // if (processorComp.bonusTime > originalTime) {
- // if (processorComp.type === enumItemProcessorTypes.reader) {
- // console.log(
- // "Bonus time",
- // round4Digits(processorComp.bonusTime),
- // "Original time",
- // round4Digits(originalTime),
- // "Overcomit by",
- // round4Digits(processorComp.bonusTime - originalTime),
- // "->",
- // round4Digits(timeToProcess),
- // "reduced by",
- // round4Digits(bonusTimeToApply)
- // );
- // }
- // }
processorComp.bonusTime -= bonusTimeToApply;
-
processorComp.ongoingCharges.push({
items: outItems,
remainingTime: timeToProcess,
});
}
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_BALANCER(payload) {
+ const availableSlots = payload.entity.components.ItemEjector.slots.length;
+ const processorComp = payload.entity.components.ItemProcessor;
+
+ const nextSlot = processorComp.nextOutputSlot++ % availableSlots;
+
+ for (let i = 0; i < payload.items.length; ++i) {
+ payload.outItems.push({
+ item: payload.items[i].item,
+ preferredSlot: (nextSlot + i) % availableSlots,
+ doNotTrack: true,
+ });
+ }
+ return true;
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_CUTTER(payload) {
+ const inputItem = /** @type {ShapeItem} */ (payload.items[0].item);
+ assert(inputItem instanceof ShapeItem, "Input for cut is not a shape");
+ const inputDefinition = inputItem.definition;
+
+ const cutDefinitions = this.root.shapeDefinitionMgr.shapeActionCutHalf(inputDefinition);
+
+ for (let i = 0; i < cutDefinitions.length; ++i) {
+ const definition = cutDefinitions[i];
+ if (!definition.isEntirelyEmpty()) {
+ payload.outItems.push({
+ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(definition),
+ requiredSlot: i,
+ });
+ }
+ }
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_CUTTER_QUAD(payload) {
+ const inputItem = /** @type {ShapeItem} */ (payload.items[0].item);
+ assert(inputItem instanceof ShapeItem, "Input for cut is not a shape");
+ const inputDefinition = inputItem.definition;
+
+ const cutDefinitions = this.root.shapeDefinitionMgr.shapeActionCutQuad(inputDefinition);
+
+ for (let i = 0; i < cutDefinitions.length; ++i) {
+ const definition = cutDefinitions[i];
+ if (!definition.isEntirelyEmpty()) {
+ payload.outItems.push({
+ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(definition),
+ requiredSlot: i,
+ });
+ }
+ }
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_ROTATER(payload) {
+ const inputItem = /** @type {ShapeItem} */ (payload.items[0].item);
+ assert(inputItem instanceof ShapeItem, "Input for rotation is not a shape");
+ const inputDefinition = inputItem.definition;
+
+ const rotatedDefinition = this.root.shapeDefinitionMgr.shapeActionRotateCW(inputDefinition);
+ payload.outItems.push({
+ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(rotatedDefinition),
+ });
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_ROTATER_CCW(payload) {
+ const inputItem = /** @type {ShapeItem} */ (payload.items[0].item);
+ assert(inputItem instanceof ShapeItem, "Input for rotation is not a shape");
+ const inputDefinition = inputItem.definition;
+
+ const rotatedDefinition = this.root.shapeDefinitionMgr.shapeActionRotateCCW(inputDefinition);
+ payload.outItems.push({
+ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(rotatedDefinition),
+ });
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_ROTATER_180(payload) {
+ const inputItem = /** @type {ShapeItem} */ (payload.items[0].item);
+ assert(inputItem instanceof ShapeItem, "Input for rotation is not a shape");
+ const inputDefinition = inputItem.definition;
+
+ const rotatedDefinition = this.root.shapeDefinitionMgr.shapeActionRotate180(inputDefinition);
+ payload.outItems.push({
+ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(rotatedDefinition),
+ });
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_STACKER(payload) {
+ const lowerItem = /** @type {ShapeItem} */ (payload.itemsBySlot[0]);
+ const upperItem = /** @type {ShapeItem} */ (payload.itemsBySlot[1]);
+
+ assert(lowerItem instanceof ShapeItem, "Input for lower stack is not a shape");
+ assert(upperItem instanceof ShapeItem, "Input for upper stack is not a shape");
+
+ const stackedDefinition = this.root.shapeDefinitionMgr.shapeActionStack(
+ lowerItem.definition,
+ upperItem.definition
+ );
+ payload.outItems.push({
+ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(stackedDefinition),
+ });
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_TRASH(payload) {
+ // Do nothing ..
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_MIXER(payload) {
+ // Find both colors and combine them
+ const item1 = /** @type {ColorItem} */ (payload.items[0].item);
+ const item2 = /** @type {ColorItem} */ (payload.items[1].item);
+ assert(item1 instanceof ColorItem, "Input for color mixer is not a color");
+ assert(item2 instanceof ColorItem, "Input for color mixer is not a color");
+
+ const color1 = item1.color;
+ const color2 = item2.color;
+
+ // Try finding mixer color, and if we can't mix it we simply return the same color
+ const mixedColor = enumColorMixingResults[color1][color2];
+ let resultColor = color1;
+ if (mixedColor) {
+ resultColor = mixedColor;
+ }
+ payload.outItems.push({
+ item: COLOR_ITEM_SINGLETONS[resultColor],
+ });
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_PAINTER(payload) {
+ const shapeItem = /** @type {ShapeItem} */ (payload.itemsBySlot[0]);
+ const colorItem = /** @type {ColorItem} */ (payload.itemsBySlot[1]);
+
+ const colorizedDefinition = this.root.shapeDefinitionMgr.shapeActionPaintWith(
+ shapeItem.definition,
+ colorItem.color
+ );
+
+ payload.outItems.push({
+ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition),
+ });
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_PAINTER_DOUBLE(payload) {
+ const shapeItem1 = /** @type {ShapeItem} */ (payload.itemsBySlot[0]);
+ const shapeItem2 = /** @type {ShapeItem} */ (payload.itemsBySlot[1]);
+ const colorItem = /** @type {ColorItem} */ (payload.itemsBySlot[2]);
+
+ assert(shapeItem1 instanceof ShapeItem, "Input for painter is not a shape");
+ assert(shapeItem2 instanceof ShapeItem, "Input for painter is not a shape");
+ assert(colorItem instanceof ColorItem, "Input for painter is not a color");
+
+ const colorizedDefinition1 = this.root.shapeDefinitionMgr.shapeActionPaintWith(
+ shapeItem1.definition,
+ colorItem.color
+ );
+
+ const colorizedDefinition2 = this.root.shapeDefinitionMgr.shapeActionPaintWith(
+ shapeItem2.definition,
+ colorItem.color
+ );
+ payload.outItems.push({
+ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition1),
+ });
+
+ payload.outItems.push({
+ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition2),
+ });
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_PAINTER_QUAD(payload) {
+ const shapeItem = /** @type {ShapeItem} */ (payload.itemsBySlot[0]);
+ assert(shapeItem instanceof ShapeItem, "Input for painter is not a shape");
+
+ /** @type {Array} */
+ const colors = [null, null, null, null];
+ for (let i = 0; i < 4; ++i) {
+ if (payload.itemsBySlot[i + 1]) {
+ colors[i] = /** @type {ColorItem} */ (payload.itemsBySlot[i + 1]).color;
+ }
+ }
+
+ const colorizedDefinition = this.root.shapeDefinitionMgr.shapeActionPaintWith4Colors(
+ shapeItem.definition,
+ /** @type {[string, string, string, string]} */ (colors)
+ );
+
+ payload.outItems.push({
+ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition),
+ });
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_READER(payload) {
+ // Pass through the item
+ const item = payload.itemsBySlot[0];
+ payload.outItems.push({
+ item,
+ doNotTrack: true,
+ });
+
+ // Track the item
+ const readerComp = payload.entity.components.BeltReader;
+ readerComp.lastItemTimes.push(this.root.time.now());
+ readerComp.lastItem = item;
+ }
+
+ /**
+ * @param {ProcessorImplementationPayload} payload
+ */
+ process_HUB(payload) {
+ const hubComponent = payload.entity.components.Hub;
+ assert(hubComponent, "Hub item processor has no hub component");
+
+ for (let i = 0; i < payload.items.length; ++i) {
+ const item = /** @type {ShapeItem} */ (payload.items[i].item);
+ this.root.hubGoals.handleDefinitionDelivered(item.definition);
+ }
+ }
}
diff --git a/src/js/game/systems/item_processor_overlays.js b/src/js/game/systems/item_processor_overlays.js
index 2ec91b88..3ba44c7b 100644
--- a/src/js/game/systems/item_processor_overlays.js
+++ b/src/js/game/systems/item_processor_overlays.js
@@ -1,6 +1,6 @@
import { globalConfig } from "../../core/config";
import { Loader } from "../../core/loader";
-import { smoothPulse, round4Digits } from "../../core/utils";
+import { smoothPulse } from "../../core/utils";
import { enumItemProcessorRequirements, enumItemProcessorTypes } from "../components/item_processor";
import { Entity } from "../entity";
import { GameSystem } from "../game_system";
@@ -17,7 +17,6 @@ export class ItemProcessorOverlaysSystem extends GameSystem {
this.readerOverlaySprite = Loader.getSprite("sprites/misc/reader_overlay.png");
this.drawnUids = new Set();
-
this.root.signals.gameFrameStarted.add(this.clearDrawnUids, this);
}
@@ -35,35 +34,40 @@ export class ItemProcessorOverlaysSystem extends GameSystem {
for (let i = 0; i < contents.length; ++i) {
const entity = contents[i];
const processorComp = entity.components.ItemProcessor;
- if (!processorComp) {
- continue;
- }
+ const filterComp = entity.components.Filter;
- const requirement = processorComp.processingRequirement;
-
- if (!requirement && processorComp.type !== enumItemProcessorTypes.reader) {
- continue;
- }
-
- if (this.drawnUids.has(entity.uid)) {
- continue;
- }
-
- this.drawnUids.add(entity.uid);
-
- switch (requirement) {
- case enumItemProcessorRequirements.painterQuad: {
- this.drawConnectedSlotRequirement(parameters, entity, { drawIfFalse: true });
- break;
+ // Draw processor overlays
+ if (processorComp) {
+ const requirement = processorComp.processingRequirement;
+ if (!requirement && processorComp.type !== enumItemProcessorTypes.reader) {
+ continue;
}
- case enumItemProcessorRequirements.filter: {
- this.drawConnectedSlotRequirement(parameters, entity, { drawIfFalse: false });
- break;
+
+ if (this.drawnUids.has(entity.uid)) {
+ continue;
+ }
+ this.drawnUids.add(entity.uid);
+
+ switch (requirement) {
+ case enumItemProcessorRequirements.painterQuad: {
+ this.drawConnectedSlotRequirement(parameters, entity, { drawIfFalse: true });
+ break;
+ }
+ }
+
+ if (processorComp.type === enumItemProcessorTypes.reader) {
+ this.drawReaderOverlays(parameters, entity);
}
}
- if (processorComp.type === enumItemProcessorTypes.reader) {
- this.drawReaderOverlays(parameters, entity);
+ // Draw filter overlays
+ else if (filterComp) {
+ if (this.drawnUids.has(entity.uid)) {
+ continue;
+ }
+ this.drawnUids.add(entity.uid);
+
+ this.drawConnectedSlotRequirement(parameters, entity, { drawIfFalse: false });
}
}
}
@@ -113,7 +117,7 @@ export class ItemProcessorOverlaysSystem extends GameSystem {
for (let i = 0; i < pinsComp.slots.length; ++i) {
const slot = pinsComp.slots[i];
const network = slot.linkedNetwork;
- if (network && network.currentValue) {
+ if (network && network.hasValue()) {
anySlotConnected = true;
if (isTruthyItem(network.currentValue) || !drawIfFalse) {
diff --git a/src/js/game/systems/logic_gate.js b/src/js/game/systems/logic_gate.js
index 3bfc20cd..cd2d7dfb 100644
--- a/src/js/game/systems/logic_gate.js
+++ b/src/js/game/systems/logic_gate.js
@@ -7,6 +7,7 @@ import { BOOL_FALSE_SINGLETON, BOOL_TRUE_SINGLETON, isTruthyItem, BooleanItem }
import { COLOR_ITEM_SINGLETONS, ColorItem } from "../items/color_item";
import { ShapeDefinition } from "../shape_definition";
import { ShapeItem } from "../items/shape_item";
+import { enumInvertedDirections } from "../../core/vector";
export class LogicGateSystem extends GameSystemWithFilter {
constructor(root) {
@@ -24,6 +25,8 @@ export class LogicGateSystem extends GameSystemWithFilter {
[enumLogicGateType.cutter]: this.compute_CUT.bind(this),
[enumLogicGateType.unstacker]: this.compute_UNSTACK.bind(this),
[enumLogicGateType.shapecompare]: this.compute_SHAPECOMPARE.bind(this),
+ [enumLogicGateType.stacker]: this.compute_STACKER.bind(this),
+ [enumLogicGateType.painter]: this.compute_PAINTER.bind(this),
};
}
@@ -44,13 +47,13 @@ export class LogicGateSystem extends GameSystemWithFilter {
if (slot.type !== enumPinSlotType.logicalAcceptor) {
continue;
}
- if (slot.linkedNetwork) {
- if (slot.linkedNetwork.valueConflict) {
+ const network = slot.linkedNetwork;
+ if (network) {
+ if (network.valueConflict) {
anyConflict = true;
break;
}
-
- slotValues.push(slot.linkedNetwork.currentValue);
+ slotValues.push(network.currentValue);
} else {
slotValues.push(null);
}
@@ -259,6 +262,58 @@ export class LogicGateSystem extends GameSystemWithFilter {
];
}
+ /**
+ * @param {Array} parameters
+ * @returns {BaseItem}
+ */
+ compute_STACKER(parameters) {
+ const lowerItem = parameters[0];
+ const upperItem = parameters[1];
+
+ if (!lowerItem || !upperItem) {
+ // Empty
+ return null;
+ }
+
+ if (lowerItem.getItemType() !== "shape" || upperItem.getItemType() !== "shape") {
+ // Bad type
+ return null;
+ }
+
+ const stackedShape = this.root.shapeDefinitionMgr.shapeActionStack(
+ /** @type {ShapeItem} */ (lowerItem).definition,
+ /** @type {ShapeItem} */ (upperItem).definition
+ );
+
+ return this.root.shapeDefinitionMgr.getShapeItemFromDefinition(stackedShape);
+ }
+
+ /**
+ * @param {Array} parameters
+ * @returns {BaseItem}
+ */
+ compute_PAINTER(parameters) {
+ const shape = parameters[0];
+ const color = parameters[1];
+
+ if (!shape || !color) {
+ // Empty
+ return null;
+ }
+
+ if (shape.getItemType() !== "shape" || color.getItemType() !== "color") {
+ // Bad type
+ return null;
+ }
+
+ const coloredShape = this.root.shapeDefinitionMgr.shapeActionPaintWith(
+ /** @type {ShapeItem} */ (shape).definition,
+ /** @type {ColorItem} */ (color).color
+ );
+
+ return this.root.shapeDefinitionMgr.getShapeItemFromDefinition(coloredShape);
+ }
+
/**
* @param {Array} parameters
* @returns {BaseItem}
@@ -269,7 +324,7 @@ export class LogicGateSystem extends GameSystemWithFilter {
if (!itemA || !itemB) {
// Empty
- return BOOL_FALSE_SINGLETON;
+ return null;
}
if (itemA.getItemType() !== itemB.getItemType()) {
diff --git a/src/js/game/systems/map_resources.js b/src/js/game/systems/map_resources.js
index c368e684..807afb36 100644
--- a/src/js/game/systems/map_resources.js
+++ b/src/js/game/systems/map_resources.js
@@ -49,11 +49,20 @@ export class MapResourcesSystem extends GameSystem {
} else {
// HIGH QUALITY: Draw all items
const layer = chunk.lowerLayer;
+ const layerEntities = chunk.contents;
for (let x = 0; x < globalConfig.mapChunkSize; ++x) {
const row = layer[x];
+ const rowEntities = layerEntities[x];
const worldX = (chunk.tileX + x) * globalConfig.tileSize;
for (let y = 0; y < globalConfig.mapChunkSize; ++y) {
const lowerItem = row[y];
+
+ const entity = rowEntities[y];
+ if (entity) {
+ // Don't draw if there is an entity above
+ continue;
+ }
+
if (lowerItem) {
const worldY = (chunk.tileY + y) * globalConfig.tileSize;
diff --git a/src/js/game/systems/miner.js b/src/js/game/systems/miner.js
index 94f2791e..4ebc6f7b 100644
--- a/src/js/game/systems/miner.js
+++ b/src/js/game/systems/miner.js
@@ -5,6 +5,7 @@ import { BaseItem } from "../base_item";
import { MinerComponent } from "../components/miner";
import { Entity } from "../entity";
import { GameSystemWithFilter } from "../game_system_with_filter";
+import { statisticsUnitsSeconds } from "../hud/parts/statistics_handle";
import { MapChunkView } from "../map_chunk_view";
export class MinerSystem extends GameSystemWithFilter {
@@ -46,7 +47,6 @@ export class MinerSystem extends GameSystemWithFilter {
}
// Check if miner is above an actual tile
-
if (!minerComp.cachedMinedItem) {
const staticComp = entity.components.StaticMapEntity;
const tileBelow = this.root.map.getLowerLayerContentXY(
@@ -94,6 +94,11 @@ export class MinerSystem extends GameSystemWithFilter {
findChainedMiner(entity) {
const ejectComp = entity.components.ItemEjector;
const staticComp = entity.components.StaticMapEntity;
+ const contentsBelow = this.root.map.getLowerLayerContentXY(staticComp.origin.x, staticComp.origin.y);
+ if (!contentsBelow) {
+ // This miner has no contents
+ return null;
+ }
const ejectingSlot = ejectComp.slots[0];
const ejectingPos = staticComp.localTileToWorld(ejectingSlot.pos);
@@ -106,7 +111,10 @@ export class MinerSystem extends GameSystemWithFilter {
if (targetContents) {
const targetMinerComp = targetContents.components.Miner;
if (targetMinerComp && targetMinerComp.chainable) {
- return targetContents;
+ const targetLowerLayer = this.root.map.getLowerLayerContentXY(targetTile.x, targetTile.y);
+ if (targetLowerLayer) {
+ return targetContents;
+ }
}
}
@@ -171,7 +179,7 @@ export class MinerSystem extends GameSystemWithFilter {
}
// Draw the item background - this is to hide the ejected item animation from
- // the item ejecto
+ // the item ejector
const padding = 3;
const destX = staticComp.origin.x * globalConfig.tileSize + padding;
diff --git a/src/js/game/systems/storage.js b/src/js/game/systems/storage.js
index 5a2b57bb..80affac9 100644
--- a/src/js/game/systems/storage.js
+++ b/src/js/game/systems/storage.js
@@ -1,101 +1,101 @@
-import { GameSystemWithFilter } from "../game_system_with_filter";
-import { StorageComponent } from "../components/storage";
-import { DrawParameters } from "../../core/draw_parameters";
-import { formatBigNumber, lerp } from "../../core/utils";
-import { Loader } from "../../core/loader";
-import { BOOL_TRUE_SINGLETON, BOOL_FALSE_SINGLETON } from "../items/boolean_item";
-import { MapChunkView } from "../map_chunk_view";
-
-export class StorageSystem extends GameSystemWithFilter {
- constructor(root) {
- super(root, [StorageComponent]);
-
- this.storageOverlaySprite = Loader.getSprite("sprites/misc/storage_overlay.png");
-
- /**
- * Stores which uids were already drawn to avoid drawing entities twice
- * @type {Set}
- */
- this.drawnUids = new Set();
-
- this.root.signals.gameFrameStarted.add(this.clearDrawnUids, this);
- }
-
- clearDrawnUids() {
- this.drawnUids.clear();
- }
-
- update() {
- for (let i = 0; i < this.allEntities.length; ++i) {
- const entity = this.allEntities[i];
- const storageComp = entity.components.Storage;
- const pinsComp = entity.components.WiredPins;
-
- // Eject from storage
- if (storageComp.storedItem && storageComp.storedCount > 0) {
- const ejectorComp = entity.components.ItemEjector;
-
- const nextSlot = ejectorComp.getFirstFreeSlot();
- if (nextSlot !== null) {
- if (ejectorComp.tryEject(nextSlot, storageComp.storedItem)) {
- storageComp.storedCount--;
-
- if (storageComp.storedCount === 0) {
- storageComp.storedItem = null;
- }
- }
- }
- }
-
- let targetAlpha = storageComp.storedCount > 0 ? 1 : 0;
- storageComp.overlayOpacity = lerp(storageComp.overlayOpacity, targetAlpha, 0.05);
-
- pinsComp.slots[0].value = storageComp.storedItem;
- pinsComp.slots[1].value = storageComp.getIsFull() ? BOOL_TRUE_SINGLETON : BOOL_FALSE_SINGLETON;
- }
- }
-
- /**
- * @param {DrawParameters} parameters
- * @param {MapChunkView} chunk
- */
- drawChunk(parameters, chunk) {
- const contents = chunk.containedEntitiesByLayer.regular;
- for (let i = 0; i < contents.length; ++i) {
- const entity = contents[i];
- const storageComp = entity.components.Storage;
- if (!storageComp) {
- continue;
- }
-
- const storedItem = storageComp.storedItem;
- if (!storedItem) {
- continue;
- }
-
- if (this.drawnUids.has(entity.uid)) {
- continue;
- }
-
- this.drawnUids.add(entity.uid);
-
- const staticComp = entity.components.StaticMapEntity;
-
- const context = parameters.context;
- context.globalAlpha = storageComp.overlayOpacity;
- const center = staticComp.getTileSpaceBounds().getCenter().toWorldSpace();
- storedItem.drawItemCenteredClipped(center.x, center.y, parameters, 30);
-
- this.storageOverlaySprite.drawCached(parameters, center.x - 15, center.y + 15, 30, 15);
-
- if (parameters.visibleRect.containsCircle(center.x, center.y + 25, 20)) {
- context.font = "bold 10px GameFont";
- context.textAlign = "center";
- context.fillStyle = "#64666e";
- context.fillText(formatBigNumber(storageComp.storedCount), center.x, center.y + 25.5);
- context.textAlign = "left";
- }
- context.globalAlpha = 1;
- }
- }
-}
+import { GameSystemWithFilter } from "../game_system_with_filter";
+import { StorageComponent } from "../components/storage";
+import { DrawParameters } from "../../core/draw_parameters";
+import { formatBigNumber, lerp } from "../../core/utils";
+import { Loader } from "../../core/loader";
+import { BOOL_TRUE_SINGLETON, BOOL_FALSE_SINGLETON } from "../items/boolean_item";
+import { MapChunkView } from "../map_chunk_view";
+
+export class StorageSystem extends GameSystemWithFilter {
+ constructor(root) {
+ super(root, [StorageComponent]);
+
+ this.storageOverlaySprite = Loader.getSprite("sprites/misc/storage_overlay.png");
+
+ /**
+ * Stores which uids were already drawn to avoid drawing entities twice
+ * @type {Set}
+ */
+ this.drawnUids = new Set();
+
+ this.root.signals.gameFrameStarted.add(this.clearDrawnUids, this);
+ }
+
+ clearDrawnUids() {
+ this.drawnUids.clear();
+ }
+
+ update() {
+ for (let i = 0; i < this.allEntities.length; ++i) {
+ const entity = this.allEntities[i];
+ const storageComp = entity.components.Storage;
+ const pinsComp = entity.components.WiredPins;
+
+ // Eject from storage
+ if (storageComp.storedItem && storageComp.storedCount > 0) {
+ const ejectorComp = entity.components.ItemEjector;
+
+ const nextSlot = ejectorComp.getFirstFreeSlot();
+ if (nextSlot !== null) {
+ if (ejectorComp.tryEject(nextSlot, storageComp.storedItem)) {
+ storageComp.storedCount--;
+
+ if (storageComp.storedCount === 0) {
+ storageComp.storedItem = null;
+ }
+ }
+ }
+ }
+
+ let targetAlpha = storageComp.storedCount > 0 ? 1 : 0;
+ storageComp.overlayOpacity = lerp(storageComp.overlayOpacity, targetAlpha, 0.05);
+
+ pinsComp.slots[0].value = storageComp.storedItem;
+ pinsComp.slots[1].value = storageComp.getIsFull() ? BOOL_TRUE_SINGLETON : BOOL_FALSE_SINGLETON;
+ }
+ }
+
+ /**
+ * @param {DrawParameters} parameters
+ * @param {MapChunkView} chunk
+ */
+ drawChunk(parameters, chunk) {
+ const contents = chunk.containedEntitiesByLayer.regular;
+ for (let i = 0; i < contents.length; ++i) {
+ const entity = contents[i];
+ const storageComp = entity.components.Storage;
+ if (!storageComp) {
+ continue;
+ }
+
+ const storedItem = storageComp.storedItem;
+ if (!storedItem) {
+ continue;
+ }
+
+ if (this.drawnUids.has(entity.uid)) {
+ continue;
+ }
+
+ this.drawnUids.add(entity.uid);
+
+ const staticComp = entity.components.StaticMapEntity;
+
+ const context = parameters.context;
+ context.globalAlpha = storageComp.overlayOpacity;
+ const center = staticComp.getTileSpaceBounds().getCenter().toWorldSpace();
+ storedItem.drawItemCenteredClipped(center.x, center.y, parameters, 30);
+
+ this.storageOverlaySprite.drawCached(parameters, center.x - 15, center.y + 15, 30, 15);
+
+ if (parameters.visibleRect.containsCircle(center.x, center.y + 25, 20)) {
+ context.font = "bold 10px GameFont";
+ context.textAlign = "center";
+ context.fillStyle = "#64666e";
+ context.fillText(formatBigNumber(storageComp.storedCount), center.x, center.y + 25.5);
+ context.textAlign = "left";
+ }
+ context.globalAlpha = 1;
+ }
+ }
+}
diff --git a/src/js/game/systems/underground_belt.js b/src/js/game/systems/underground_belt.js
index 90d29e50..7a7609f8 100644
--- a/src/js/game/systems/underground_belt.js
+++ b/src/js/game/systems/underground_belt.js
@@ -1,406 +1,349 @@
-import { globalConfig } from "../../core/config";
-import { Loader } from "../../core/loader";
-import { createLogger } from "../../core/logging";
-import { Rectangle } from "../../core/rectangle";
-import {
- enumAngleToDirection,
- enumDirection,
- enumDirectionToAngle,
- enumDirectionToVector,
- enumInvertedDirections,
-} from "../../core/vector";
-import { enumUndergroundBeltMode, UndergroundBeltComponent } from "../components/underground_belt";
-import { Entity } from "../entity";
-import { GameSystemWithFilter } from "../game_system_with_filter";
-import { fastArrayDelete } from "../../core/utils";
-
-const logger = createLogger("tunnels");
-
-export class UndergroundBeltSystem extends GameSystemWithFilter {
- constructor(root) {
- super(root, [UndergroundBeltComponent]);
-
- this.beltSprites = {
- [enumUndergroundBeltMode.sender]: Loader.getSprite(
- "sprites/buildings/underground_belt_entry.png"
- ),
- [enumUndergroundBeltMode.receiver]: Loader.getSprite(
- "sprites/buildings/underground_belt_exit.png"
- ),
- };
-
- this.root.signals.entityManuallyPlaced.add(this.onEntityManuallyPlaced, this);
-
- /**
- * @type {Rectangle}
- */
- this.areaToRecompute = null;
-
- this.root.signals.entityAdded.add(this.onEntityChanged, this);
- this.root.signals.entityDestroyed.add(this.onEntityChanged, this);
- }
-
- /**
- * Called when an entity got added or removed
- * @param {Entity} entity
- */
- onEntityChanged(entity) {
- if (!this.root.gameInitialized) {
- return;
- }
- const undergroundComp = entity.components.UndergroundBelt;
- if (!undergroundComp) {
- return;
- }
-
- const affectedArea = entity.components.StaticMapEntity.getTileSpaceBounds().expandedInAllDirections(
- globalConfig.undergroundBeltMaxTilesByTier[
- globalConfig.undergroundBeltMaxTilesByTier.length - 1
- ] + 1
- );
-
- if (this.areaToRecompute) {
- this.areaToRecompute = this.areaToRecompute.getUnion(affectedArea);
- } else {
- this.areaToRecompute = affectedArea;
- }
- }
-
- /**
- * Callback when an entity got placed, used to remove belts between underground belts
- * @param {Entity} entity
- */
- onEntityManuallyPlaced(entity) {
- if (!this.root.app.settings.getAllSettings().enableTunnelSmartplace) {
- // Smart-place disabled
- return;
- }
-
- const undergroundComp = entity.components.UndergroundBelt;
- if (undergroundComp && undergroundComp.mode === enumUndergroundBeltMode.receiver) {
- const staticComp = entity.components.StaticMapEntity;
- const tile = staticComp.origin;
-
- const direction = enumAngleToDirection[staticComp.rotation];
- const inverseDirection = enumInvertedDirections[direction];
- const offset = enumDirectionToVector[inverseDirection];
-
- let currentPos = tile.copy();
-
- const tier = undergroundComp.tier;
- const range = globalConfig.undergroundBeltMaxTilesByTier[tier];
-
- // FIND ENTRANCE
- // Search for the entrance which is furthes apart (this is why we can't reuse logic here)
- let matchingEntrance = null;
- for (let i = 0; i < range; ++i) {
- currentPos.addInplace(offset);
- const contents = this.root.map.getTileContent(currentPos, entity.layer);
- if (!contents) {
- continue;
- }
-
- const contentsUndergroundComp = contents.components.UndergroundBelt;
- const contentsStaticComp = contents.components.StaticMapEntity;
- if (
- contentsUndergroundComp &&
- contentsUndergroundComp.tier === undergroundComp.tier &&
- contentsUndergroundComp.mode === enumUndergroundBeltMode.sender &&
- enumAngleToDirection[contentsStaticComp.rotation] === direction
- ) {
- matchingEntrance = {
- entity: contents,
- range: i,
- };
- }
- }
-
- if (!matchingEntrance) {
- // Nothing found
- return;
- }
-
- // DETECT OBSOLETE BELTS BETWEEN
- // Remove any belts between entrance and exit which have the same direction,
- // but only if they *all* have the right direction
- currentPos = tile.copy();
- let allBeltsMatch = true;
- for (let i = 0; i < matchingEntrance.range; ++i) {
- currentPos.addInplace(offset);
-
- const contents = this.root.map.getTileContent(currentPos, entity.layer);
- if (!contents) {
- allBeltsMatch = false;
- break;
- }
-
- const contentsStaticComp = contents.components.StaticMapEntity;
- const contentsBeltComp = contents.components.Belt;
- if (!contentsBeltComp) {
- allBeltsMatch = false;
- break;
- }
-
- // It's a belt
- if (
- contentsBeltComp.direction !== enumDirection.top ||
- enumAngleToDirection[contentsStaticComp.rotation] !== direction
- ) {
- allBeltsMatch = false;
- break;
- }
- }
-
- currentPos = tile.copy();
- if (allBeltsMatch) {
- // All belts between this are obsolete, so drop them
- for (let i = 0; i < matchingEntrance.range; ++i) {
- currentPos.addInplace(offset);
- const contents = this.root.map.getTileContent(currentPos, entity.layer);
- assert(contents, "Invalid smart underground belt logic");
- this.root.logic.tryDeleteBuilding(contents);
- }
- }
-
- // REMOVE OBSOLETE TUNNELS
- // Remove any double tunnels, by checking the tile plus the tile above
- currentPos = tile.copy().add(offset);
- for (let i = 0; i < matchingEntrance.range - 1; ++i) {
- const posBefore = currentPos.copy();
- currentPos.addInplace(offset);
-
- const entityBefore = this.root.map.getTileContent(posBefore, entity.layer);
- const entityAfter = this.root.map.getTileContent(currentPos, entity.layer);
-
- if (!entityBefore || !entityAfter) {
- continue;
- }
-
- const undergroundBefore = entityBefore.components.UndergroundBelt;
- const undergroundAfter = entityAfter.components.UndergroundBelt;
-
- if (!undergroundBefore || !undergroundAfter) {
- // Not an underground belt
- continue;
- }
-
- if (
- // Both same tier
- undergroundBefore.tier !== undergroundAfter.tier ||
- // And same tier as our original entity
- undergroundBefore.tier !== undergroundComp.tier
- ) {
- // Mismatching tier
- continue;
- }
-
- if (
- undergroundBefore.mode !== enumUndergroundBeltMode.sender ||
- undergroundAfter.mode !== enumUndergroundBeltMode.receiver
- ) {
- // Not the right mode
- continue;
- }
-
- // Check rotations
- const staticBefore = entityBefore.components.StaticMapEntity;
- const staticAfter = entityAfter.components.StaticMapEntity;
-
- if (
- enumAngleToDirection[staticBefore.rotation] !== direction ||
- enumAngleToDirection[staticAfter.rotation] !== direction
- ) {
- // Wrong rotation
- continue;
- }
-
- // All good, can remove
- this.root.logic.tryDeleteBuilding(entityBefore);
- this.root.logic.tryDeleteBuilding(entityAfter);
- }
- }
- }
-
- /**
- * Recomputes the cache in the given area, invalidating all entries there
- */
- recomputeArea() {
- const area = this.areaToRecompute;
- logger.log("Recomputing area:", area.x, area.y, "/", area.w, area.h);
- if (G_IS_DEV && globalConfig.debug.renderChanges) {
- this.root.hud.parts.changesDebugger.renderChange("tunnels", this.areaToRecompute, "#fc03be");
- }
-
- for (let x = area.x; x < area.right(); ++x) {
- for (let y = area.y; y < area.bottom(); ++y) {
- const entities = this.root.map.getLayersContentsMultipleXY(x, y);
- for (let i = 0; i < entities.length; ++i) {
- const entity = entities[i];
- const undergroundComp = entity.components.UndergroundBelt;
- if (!undergroundComp) {
- continue;
- }
-
- undergroundComp.cachedLinkedEntity = null;
- }
- }
- }
- }
-
- update() {
- if (this.areaToRecompute) {
- this.recomputeArea();
- this.areaToRecompute = null;
- }
-
- const delta = this.root.dynamicTickrate.deltaSeconds;
-
- for (let i = 0; i < this.allEntities.length; ++i) {
- const entity = this.allEntities[i];
- const undergroundComp = entity.components.UndergroundBelt;
- const pendingItems = undergroundComp.pendingItems;
-
- // Decrease remaining time of all items in belt
- for (let k = 0; k < pendingItems.length; ++k) {
- const item = pendingItems[k];
- item[1] = Math.max(0, item[1] - delta);
- if (G_IS_DEV && globalConfig.debug.instantBelts) {
- item[1] = 0;
- }
- }
- if (undergroundComp.mode === enumUndergroundBeltMode.sender) {
- this.handleSender(entity);
- } else {
- this.handleReceiver(entity);
- }
- }
- }
-
- /**
- * Finds the receiver for a given sender
- * @param {Entity} entity
- * @returns {import("../components/underground_belt").LinkedUndergroundBelt}
- */
- findRecieverForSender(entity) {
- const staticComp = entity.components.StaticMapEntity;
- const undergroundComp = entity.components.UndergroundBelt;
- const searchDirection = staticComp.localDirectionToWorld(enumDirection.top);
- const searchVector = enumDirectionToVector[searchDirection];
- const targetRotation = enumDirectionToAngle[searchDirection];
- let currentTile = staticComp.origin;
-
- // Search in the direction of the tunnel
- for (
- let searchOffset = 0;
- searchOffset < globalConfig.undergroundBeltMaxTilesByTier[undergroundComp.tier];
- ++searchOffset
- ) {
- currentTile = currentTile.add(searchVector);
-
- const potentialReceiver = this.root.map.getTileContent(currentTile, "regular");
- if (!potentialReceiver) {
- // Empty tile
- continue;
- }
- const receiverUndergroundComp = potentialReceiver.components.UndergroundBelt;
- if (!receiverUndergroundComp || receiverUndergroundComp.tier !== undergroundComp.tier) {
- // Not a tunnel, or not on the same tier
- continue;
- }
-
- const receiverStaticComp = potentialReceiver.components.StaticMapEntity;
- if (receiverStaticComp.rotation !== targetRotation) {
- // Wrong rotation
- continue;
- }
-
- if (receiverUndergroundComp.mode !== enumUndergroundBeltMode.receiver) {
- // Not a receiver, but a sender -> Abort to make sure we don't deliver double
- break;
- }
-
- return { entity: potentialReceiver, distance: searchOffset };
- }
-
- // None found
- return { entity: null, distance: 0 };
- }
-
- /**
- *
- * @param {Entity} entity
- */
- handleSender(entity) {
- const undergroundComp = entity.components.UndergroundBelt;
-
- // Find the current receiver
- let receiver = undergroundComp.cachedLinkedEntity;
- if (!receiver) {
- // We don't have a receiver, compute it
- receiver = undergroundComp.cachedLinkedEntity = this.findRecieverForSender(entity);
-
- if (G_IS_DEV && globalConfig.debug.renderChanges) {
- this.root.hud.parts.changesDebugger.renderChange(
- "sender",
- entity.components.StaticMapEntity.getTileSpaceBounds(),
- "#fc03be"
- );
- }
- }
-
- if (!receiver.entity) {
- // If there is no connection to a receiver, ignore this one
- return;
- }
-
- // Check if we have any item
- if (undergroundComp.pendingItems.length > 0) {
- assert(undergroundComp.pendingItems.length === 1, "more than 1 pending");
- const nextItemAndDuration = undergroundComp.pendingItems[0];
- const remainingTime = nextItemAndDuration[1];
- const nextItem = nextItemAndDuration[0];
-
- // Check if the item is ready to be emitted
- if (remainingTime === 0) {
- // Check if the receiver can accept it
- if (
- receiver.entity.components.UndergroundBelt.tryAcceptTunneledItem(
- nextItem,
- receiver.distance,
- this.root.hubGoals.getUndergroundBeltBaseSpeed()
- )
- ) {
- // Drop this item
- fastArrayDelete(undergroundComp.pendingItems, 0);
- }
- }
- }
- }
-
- /**
- *
- * @param {Entity} entity
- */
- handleReceiver(entity) {
- const undergroundComp = entity.components.UndergroundBelt;
-
- // Try to eject items, we only check the first one because it is sorted by remaining time
- const items = undergroundComp.pendingItems;
- if (items.length > 0) {
- const nextItemAndDuration = undergroundComp.pendingItems[0];
- const remainingTime = nextItemAndDuration[1];
- const nextItem = nextItemAndDuration[0];
-
- if (remainingTime <= 0) {
- const ejectorComp = entity.components.ItemEjector;
-
- const nextSlotIndex = ejectorComp.getFirstFreeSlot();
- if (nextSlotIndex !== null) {
- if (ejectorComp.tryEject(nextSlotIndex, nextItem)) {
- items.shift();
- }
- }
- }
- }
- }
-}
+import { globalConfig } from "../../core/config";
+import { Loader } from "../../core/loader";
+import { createLogger } from "../../core/logging";
+import { Rectangle } from "../../core/rectangle";
+import { StaleAreaDetector } from "../../core/stale_area_detector";
+import { fastArrayDelete } from "../../core/utils";
+import {
+ enumAngleToDirection,
+ enumDirection,
+ enumDirectionToAngle,
+ enumDirectionToVector,
+ enumInvertedDirections,
+} from "../../core/vector";
+import { enumUndergroundBeltMode, UndergroundBeltComponent } from "../components/underground_belt";
+import { Entity } from "../entity";
+import { GameSystemWithFilter } from "../game_system_with_filter";
+
+const logger = createLogger("tunnels");
+
+export class UndergroundBeltSystem extends GameSystemWithFilter {
+ constructor(root) {
+ super(root, [UndergroundBeltComponent]);
+
+ this.beltSprites = {
+ [enumUndergroundBeltMode.sender]: Loader.getSprite(
+ "sprites/buildings/underground_belt_entry.png"
+ ),
+ [enumUndergroundBeltMode.receiver]: Loader.getSprite(
+ "sprites/buildings/underground_belt_exit.png"
+ ),
+ };
+
+ this.staleAreaWatcher = new StaleAreaDetector({
+ root: this.root,
+ name: "underground-belt",
+ recomputeMethod: this.recomputeArea.bind(this),
+ });
+
+ this.root.signals.entityManuallyPlaced.add(this.onEntityManuallyPlaced, this);
+
+ // NOTICE: Once we remove a tunnel, we need to update the whole area to
+ // clear outdated handles
+ this.staleAreaWatcher.recomputeOnComponentsChanged(
+ [UndergroundBeltComponent],
+ globalConfig.undergroundBeltMaxTilesByTier[globalConfig.undergroundBeltMaxTilesByTier.length - 1]
+ );
+ }
+
+ /**
+ * Callback when an entity got placed, used to remove belts between underground belts
+ * @param {Entity} entity
+ */
+ onEntityManuallyPlaced(entity) {
+ if (!this.root.app.settings.getAllSettings().enableTunnelSmartplace) {
+ // Smart-place disabled
+ return;
+ }
+
+ const undergroundComp = entity.components.UndergroundBelt;
+ if (undergroundComp && undergroundComp.mode === enumUndergroundBeltMode.receiver) {
+ const staticComp = entity.components.StaticMapEntity;
+ const tile = staticComp.origin;
+
+ const direction = enumAngleToDirection[staticComp.rotation];
+ const inverseDirection = enumInvertedDirections[direction];
+ const offset = enumDirectionToVector[inverseDirection];
+
+ let currentPos = tile.copy();
+
+ const tier = undergroundComp.tier;
+ const range = globalConfig.undergroundBeltMaxTilesByTier[tier];
+
+ // FIND ENTRANCE
+ // Search for the entrance which is farthest apart (this is why we can't reuse logic here)
+ let matchingEntrance = null;
+ for (let i = 0; i < range; ++i) {
+ currentPos.addInplace(offset);
+ const contents = this.root.map.getTileContent(currentPos, entity.layer);
+ if (!contents) {
+ continue;
+ }
+
+ const contentsUndergroundComp = contents.components.UndergroundBelt;
+ const contentsStaticComp = contents.components.StaticMapEntity;
+ if (
+ contentsUndergroundComp &&
+ contentsUndergroundComp.tier === undergroundComp.tier &&
+ contentsUndergroundComp.mode === enumUndergroundBeltMode.sender &&
+ enumAngleToDirection[contentsStaticComp.rotation] === direction
+ ) {
+ matchingEntrance = {
+ entity: contents,
+ range: i,
+ };
+ }
+ }
+
+ if (!matchingEntrance) {
+ // Nothing found
+ return;
+ }
+
+ // DETECT OBSOLETE BELTS BETWEEN
+ // Remove any belts between entrance and exit which have the same direction,
+ // but only if they *all* have the right direction
+ currentPos = tile.copy();
+ let allBeltsMatch = true;
+ for (let i = 0; i < matchingEntrance.range; ++i) {
+ currentPos.addInplace(offset);
+
+ const contents = this.root.map.getTileContent(currentPos, entity.layer);
+ if (!contents) {
+ allBeltsMatch = false;
+ break;
+ }
+
+ const contentsStaticComp = contents.components.StaticMapEntity;
+ const contentsBeltComp = contents.components.Belt;
+ if (!contentsBeltComp) {
+ allBeltsMatch = false;
+ break;
+ }
+
+ // It's a belt
+ if (
+ contentsBeltComp.direction !== enumDirection.top ||
+ enumAngleToDirection[contentsStaticComp.rotation] !== direction
+ ) {
+ allBeltsMatch = false;
+ break;
+ }
+ }
+
+ currentPos = tile.copy();
+ if (allBeltsMatch) {
+ // All belts between this are obsolete, so drop them
+ for (let i = 0; i < matchingEntrance.range; ++i) {
+ currentPos.addInplace(offset);
+ const contents = this.root.map.getTileContent(currentPos, entity.layer);
+ assert(contents, "Invalid smart underground belt logic");
+ this.root.logic.tryDeleteBuilding(contents);
+ }
+ }
+
+ // REMOVE OBSOLETE TUNNELS
+ // Remove any double tunnels, by checking the tile plus the tile above
+ currentPos = tile.copy().add(offset);
+ for (let i = 0; i < matchingEntrance.range - 1; ++i) {
+ const posBefore = currentPos.copy();
+ currentPos.addInplace(offset);
+
+ const entityBefore = this.root.map.getTileContent(posBefore, entity.layer);
+ const entityAfter = this.root.map.getTileContent(currentPos, entity.layer);
+
+ if (!entityBefore || !entityAfter) {
+ continue;
+ }
+
+ const undergroundBefore = entityBefore.components.UndergroundBelt;
+ const undergroundAfter = entityAfter.components.UndergroundBelt;
+
+ if (!undergroundBefore || !undergroundAfter) {
+ // Not an underground belt
+ continue;
+ }
+
+ if (
+ // Both same tier
+ undergroundBefore.tier !== undergroundAfter.tier ||
+ // And same tier as our original entity
+ undergroundBefore.tier !== undergroundComp.tier
+ ) {
+ // Mismatching tier
+ continue;
+ }
+
+ if (
+ undergroundBefore.mode !== enumUndergroundBeltMode.sender ||
+ undergroundAfter.mode !== enumUndergroundBeltMode.receiver
+ ) {
+ // Not the right mode
+ continue;
+ }
+
+ // Check rotations
+ const staticBefore = entityBefore.components.StaticMapEntity;
+ const staticAfter = entityAfter.components.StaticMapEntity;
+
+ if (
+ enumAngleToDirection[staticBefore.rotation] !== direction ||
+ enumAngleToDirection[staticAfter.rotation] !== direction
+ ) {
+ // Wrong rotation
+ continue;
+ }
+
+ // All good, can remove
+ this.root.logic.tryDeleteBuilding(entityBefore);
+ this.root.logic.tryDeleteBuilding(entityAfter);
+ }
+ }
+ }
+
+ /**
+ * Recomputes the cache in the given area, invalidating all entries there
+ * @param {Rectangle} area
+ */
+ recomputeArea(area) {
+ for (let x = area.x; x < area.right(); ++x) {
+ for (let y = area.y; y < area.bottom(); ++y) {
+ const entities = this.root.map.getLayersContentsMultipleXY(x, y);
+ for (let i = 0; i < entities.length; ++i) {
+ const entity = entities[i];
+ const undergroundComp = entity.components.UndergroundBelt;
+ if (!undergroundComp) {
+ continue;
+ }
+ undergroundComp.cachedLinkedEntity = null;
+ }
+ }
+ }
+ }
+
+ update() {
+ this.staleAreaWatcher.update();
+
+ for (let i = 0; i < this.allEntities.length; ++i) {
+ const entity = this.allEntities[i];
+ const undergroundComp = entity.components.UndergroundBelt;
+ if (undergroundComp.mode === enumUndergroundBeltMode.sender) {
+ this.handleSender(entity);
+ } else {
+ this.handleReceiver(entity);
+ }
+ }
+ }
+
+ /**
+ * Finds the receiver for a given sender
+ * @param {Entity} entity
+ * @returns {import("../components/underground_belt").LinkedUndergroundBelt}
+ */
+ findRecieverForSender(entity) {
+ const staticComp = entity.components.StaticMapEntity;
+ const undergroundComp = entity.components.UndergroundBelt;
+ const searchDirection = staticComp.localDirectionToWorld(enumDirection.top);
+ const searchVector = enumDirectionToVector[searchDirection];
+ const targetRotation = enumDirectionToAngle[searchDirection];
+ let currentTile = staticComp.origin;
+
+ // Search in the direction of the tunnel
+ for (
+ let searchOffset = 0;
+ searchOffset < globalConfig.undergroundBeltMaxTilesByTier[undergroundComp.tier];
+ ++searchOffset
+ ) {
+ currentTile = currentTile.add(searchVector);
+
+ const potentialReceiver = this.root.map.getTileContent(currentTile, "regular");
+ if (!potentialReceiver) {
+ // Empty tile
+ continue;
+ }
+ const receiverUndergroundComp = potentialReceiver.components.UndergroundBelt;
+ if (!receiverUndergroundComp || receiverUndergroundComp.tier !== undergroundComp.tier) {
+ // Not a tunnel, or not on the same tier
+ continue;
+ }
+
+ const receiverStaticComp = potentialReceiver.components.StaticMapEntity;
+ if (receiverStaticComp.rotation !== targetRotation) {
+ // Wrong rotation
+ continue;
+ }
+
+ if (receiverUndergroundComp.mode !== enumUndergroundBeltMode.receiver) {
+ // Not a receiver, but a sender -> Abort to make sure we don't deliver double
+ break;
+ }
+
+ return { entity: potentialReceiver, distance: searchOffset };
+ }
+
+ // None found
+ return { entity: null, distance: 0 };
+ }
+
+ /**
+ *
+ * @param {Entity} entity
+ */
+ handleSender(entity) {
+ const undergroundComp = entity.components.UndergroundBelt;
+
+ // Find the current receiver
+ let cacheEntry = undergroundComp.cachedLinkedEntity;
+ if (!cacheEntry) {
+ // Need to recompute cache
+ cacheEntry = undergroundComp.cachedLinkedEntity = this.findRecieverForSender(entity);
+ }
+
+ if (!cacheEntry.entity) {
+ // If there is no connection to a receiver, ignore this one
+ return;
+ }
+
+ // Check if we have any items to eject
+ const nextItemAndDuration = undergroundComp.pendingItems[0];
+ if (nextItemAndDuration) {
+ assert(undergroundComp.pendingItems.length === 1, "more than 1 pending");
+
+ // Check if the receiver can accept it
+ if (
+ cacheEntry.entity.components.UndergroundBelt.tryAcceptTunneledItem(
+ nextItemAndDuration[0],
+ cacheEntry.distance,
+ this.root.hubGoals.getUndergroundBeltBaseSpeed(),
+ this.root.time.now()
+ )
+ ) {
+ // Drop this item
+ fastArrayDelete(undergroundComp.pendingItems, 0);
+ }
+ }
+ }
+
+ /**
+ *
+ * @param {Entity} entity
+ */
+ handleReceiver(entity) {
+ const undergroundComp = entity.components.UndergroundBelt;
+
+ // Try to eject items, we only check the first one because it is sorted by remaining time
+ const nextItemAndDuration = undergroundComp.pendingItems[0];
+ if (nextItemAndDuration) {
+ if (this.root.time.now() > nextItemAndDuration[1]) {
+ const ejectorComp = entity.components.ItemEjector;
+
+ const nextSlotIndex = ejectorComp.getFirstFreeSlot();
+ if (nextSlotIndex !== null) {
+ if (ejectorComp.tryEject(nextSlotIndex, nextItemAndDuration[0])) {
+ undergroundComp.pendingItems.shift();
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/js/game/systems/wire.js b/src/js/game/systems/wire.js
index fa9287e1..4168edc4 100644
--- a/src/js/game/systems/wire.js
+++ b/src/js/game/systems/wire.js
@@ -79,6 +79,14 @@ export class WireNetwork {
*/
this.uid = ++networkUidCounter;
}
+
+ /**
+ * Returns whether this network currently has a value
+ * @returns {boolean}
+ */
+ hasValue() {
+ return !!this.currentValue && !this.valueConflict;
+ }
}
export class WireSystem extends GameSystemWithFilter {
@@ -162,7 +170,7 @@ export class WireSystem extends GameSystemWithFilter {
const tunnelEntities = this.root.entityMgr.getAllWithComponent(WireTunnelComponent);
const pinEntities = this.root.entityMgr.getAllWithComponent(WiredPinsComponent);
- // Clear all network references, but not on the first update since thats the deserializing one
+ // Clear all network references, but not on the first update since that's the deserializing one
if (!this.isFirstRecompute) {
for (let i = 0; i < wireEntities.length; ++i) {
wireEntities[i].components.Wire.linkedNetwork = null;
@@ -432,7 +440,7 @@ export class WireSystem extends GameSystemWithFilter {
continue;
}
- // Check if its a tunnel, if so, go to the forwarded item
+ // Check if it's a tunnel, if so, go to the forwarded item
const tunnelComp = entity.components.WireTunnel;
if (tunnelComp) {
if (visitedTunnels.has(entity.uid)) {
diff --git a/src/js/game/systems/wired_pins.js b/src/js/game/systems/wired_pins.js
index 202691b8..e8bc1882 100644
--- a/src/js/game/systems/wired_pins.js
+++ b/src/js/game/systems/wired_pins.js
@@ -149,8 +149,6 @@ export class WiredPinsSystem extends GameSystemWithFilter {
}
}
- update() {}
-
/**
* Draws a given entity
* @param {DrawParameters} parameters
diff --git a/src/js/game/themes/dark.json b/src/js/game/themes/dark.json
index 7466201f..2f03b767 100644
--- a/src/js/game/themes/dark.json
+++ b/src/js/game/themes/dark.json
@@ -1,7 +1,7 @@
{
"uiStyle": "dark",
"map": {
- "background": "#2e2f37",
+ "background": "#3e3f47",
"grid": "rgba(255, 255, 255, 0.02)",
"gridLineWidth": 0.5,
@@ -25,10 +25,10 @@
"colorBlindPickerTile": "rgba(255, 255, 255, 0.5)",
"resources": {
- "shape": "#3d3f4a",
- "red": "#4a3d3f",
- "green": "#3e4a3d",
- "blue": "#35384a"
+ "shape": "#5d5f6a",
+ "red": "#854f56",
+ "green": "#667964",
+ "blue": "#5e7ca4"
},
"chunkOverview": {
"empty": "#444856",
diff --git a/src/js/game/tutorial_goals.js b/src/js/game/tutorial_goals.js
index 9084f508..3a5cf807 100644
--- a/src/js/game/tutorial_goals.js
+++ b/src/js/game/tutorial_goals.js
@@ -11,21 +11,19 @@ export const enumHubGoalRewards = {
reward_painter: "reward_painter",
reward_mixer: "reward_mixer",
reward_stacker: "reward_stacker",
- reward_splitter: "reward_splitter",
+ reward_balancer: "reward_balancer",
reward_tunnel: "reward_tunnel",
reward_rotater_ccw: "reward_rotater_ccw",
- reward_rotater_fl: "reward_rotater_fl",
+ reward_rotater_180: "reward_rotater_180",
reward_miner_chainable: "reward_miner_chainable",
reward_underground_belt_tier_2: "reward_underground_belt_tier_2",
- reward_splitter_compact: "reward_splitter_compact",
+ reward_splitter: "reward_splitter",
reward_cutter_quad: "reward_cutter_quad",
reward_painter_double: "reward_painter_double",
reward_painter_quad: "reward_painter_quad",
reward_storage: "reward_storage",
-
- // @todo: unlock
- reward_merger_compact: "reward_compact_merger",
+ reward_merger: "reward_merger",
reward_blueprints: "reward_blueprints",
reward_freeplay: "reward_freeplay",
@@ -55,14 +53,14 @@ export const tutorialGoals = [
// Rectangle
{
shape: "RuRuRuRu", // miners t1
- required: 100,
- reward: enumHubGoalRewards.reward_splitter,
+ required: 85,
+ reward: enumHubGoalRewards.reward_balancer,
},
// 4
{
shape: "RuRu----", // processors t2
- required: 120,
+ required: 100,
reward: enumHubGoalRewards.reward_rotater,
},
@@ -70,14 +68,14 @@ export const tutorialGoals = [
// Rotater
{
shape: "Cu----Cu", // belts t2
- required: 200,
+ required: 175,
reward: enumHubGoalRewards.reward_tunnel,
},
// 6
{
shape: "Cu------", // miners t2
- required: 400,
+ required: 250,
reward: enumHubGoalRewards.reward_painter,
},
@@ -85,14 +83,14 @@ export const tutorialGoals = [
// Painter
{
shape: "CrCrCrCr", // unused
- required: 800,
+ required: 500,
reward: enumHubGoalRewards.reward_rotater_ccw,
},
// 8
{
shape: "RbRb----", // painter t2
- required: 1000,
+ required: 700,
reward: enumHubGoalRewards.reward_mixer,
},
@@ -100,15 +98,15 @@ export const tutorialGoals = [
// Mixing (purple)
{
shape: "CpCpCpCp", // belts t3
- required: 1400,
- reward: enumHubGoalRewards.reward_splitter_compact,
+ required: 800,
+ reward: enumHubGoalRewards.reward_splitter,
},
// 10
// Star shape + cyan
{
shape: "ScScScSc", // miners t3
- required: 1600,
+ required: 900,
reward: enumHubGoalRewards.reward_stacker,
},
@@ -116,7 +114,7 @@ export const tutorialGoals = [
// Stacker
{
shape: "CgScScCg", // processors t3
- required: 1800,
+ required: 1000,
reward: enumHubGoalRewards.reward_miner_chainable,
},
@@ -124,49 +122,56 @@ export const tutorialGoals = [
// Blueprints
{
shape: "CbCbCbRb:CwCwCwCw",
- required: 2000,
+ required: 1250,
reward: enumHubGoalRewards.reward_blueprints,
},
// 13
{
shape: "RpRpRpRp:CwCwCwCw", // painting t3
- required: 12000,
+ required: 5000,
reward: enumHubGoalRewards.reward_underground_belt_tier_2,
},
// 14
{
shape: "SrSrSrSr:CyCyCyCy", // unused
- required: 16000,
+ required: 7500,
reward: enumHubGoalRewards.reward_storage,
},
// 15
{
shape: "SrSrSrSr:CyCyCyCy:SwSwSwSw", // belts t4 (two variants)
- required: 25000,
+ required: 15000,
reward: enumHubGoalRewards.reward_cutter_quad,
},
// 16
{
shape: "CbRbRbCb:CwCwCwCw:WbWbWbWb", // miner t4 (two variants)
- required: 50000,
+ required: 20000,
reward: enumHubGoalRewards.reward_painter_double,
},
// 17
{
- shape: "WrRgWrRg:CwCrCwCr:SgSgSgSg", // processors t4 (two variants)
- required: 120000,
- reward: enumHubGoalRewards.reward_painter_quad,
+ shape: "CbRbRbCb:CwCwCwCw:WbWbWbWb", // rotater 180
+ required: 25000,
+ reward: enumHubGoalRewards.reward_rotater_180,
},
// 18
+ {
+ shape: "WrRgWrRg:CwCrCwCr:SgSgSgSg", // processors t4 (two variants)
+ required: 30000,
+ reward: enumHubGoalRewards.reward_painter_quad,
+ },
+
+ // 19
{
shape: finalGameShape,
- required: 250000,
+ required: 50000,
reward: enumHubGoalRewards.reward_freeplay,
},
];
diff --git a/src/js/game/tutorial_goals_mappings.js b/src/js/game/tutorial_goals_mappings.js
index 923c2814..1257cad9 100644
--- a/src/js/game/tutorial_goals_mappings.js
+++ b/src/js/game/tutorial_goals_mappings.js
@@ -1,52 +1,51 @@
-import { MetaBuilding, defaultBuildingVariant } from "./meta_building";
-import { MetaCutterBuilding, enumCutterVariants } from "./buildings/cutter";
-import { MetaRotaterBuilding, enumRotaterVariants } from "./buildings/rotater";
-import { MetaPainterBuilding, enumPainterVariants } from "./buildings/painter";
-import { MetaMixerBuilding } from "./buildings/mixer";
-import { MetaStackerBuilding } from "./buildings/stacker";
-import { MetaSplitterBuilding, enumSplitterVariants } from "./buildings/splitter";
-import { MetaUndergroundBeltBuilding, enumUndergroundBeltVariants } from "./buildings/underground_belt";
-import { MetaMinerBuilding, enumMinerVariants } from "./buildings/miner";
-import { MetaTrashBuilding, enumTrashVariants } from "./buildings/trash";
-
-/** @typedef {Array<[typeof MetaBuilding, string]>} TutorialGoalReward */
-
-import { enumHubGoalRewards } from "./tutorial_goals";
-
-/**
- * Helper method for proper types
- * @returns {TutorialGoalReward}
- */
-const typed = x => x;
-
-/**
- * Stores which reward unlocks what
- * @enum {TutorialGoalReward?}
- */
-export const enumHubGoalRewardsToContentUnlocked = {
- [enumHubGoalRewards.reward_cutter_and_trash]: typed([[MetaCutterBuilding, defaultBuildingVariant]]),
- [enumHubGoalRewards.reward_rotater]: typed([[MetaRotaterBuilding, defaultBuildingVariant]]),
- [enumHubGoalRewards.reward_painter]: typed([[MetaPainterBuilding, defaultBuildingVariant]]),
- [enumHubGoalRewards.reward_mixer]: typed([[MetaMixerBuilding, defaultBuildingVariant]]),
- [enumHubGoalRewards.reward_stacker]: typed([[MetaStackerBuilding, defaultBuildingVariant]]),
- [enumHubGoalRewards.reward_splitter]: typed([[MetaSplitterBuilding, defaultBuildingVariant]]),
- [enumHubGoalRewards.reward_tunnel]: typed([[MetaUndergroundBeltBuilding, defaultBuildingVariant]]),
-
- [enumHubGoalRewards.reward_rotater_ccw]: typed([[MetaRotaterBuilding, enumRotaterVariants.ccw]]),
- [enumHubGoalRewards.reward_rotater_fl]: typed([[MetaRotaterBuilding, enumRotaterVariants.fl]]),
- [enumHubGoalRewards.reward_miner_chainable]: typed([[MetaMinerBuilding, enumMinerVariants.chainable]]),
- [enumHubGoalRewards.reward_underground_belt_tier_2]: typed([
- [MetaUndergroundBeltBuilding, enumUndergroundBeltVariants.tier2],
- ]),
- [enumHubGoalRewards.reward_splitter_compact]: typed([
- [MetaSplitterBuilding, enumSplitterVariants.compact],
- ]),
- [enumHubGoalRewards.reward_cutter_quad]: typed([[MetaCutterBuilding, enumCutterVariants.quad]]),
- [enumHubGoalRewards.reward_painter_double]: typed([[MetaPainterBuilding, enumPainterVariants.double]]),
- [enumHubGoalRewards.reward_painter_quad]: typed([[MetaPainterBuilding, enumPainterVariants.quad]]),
- [enumHubGoalRewards.reward_storage]: typed([[MetaTrashBuilding, enumTrashVariants.storage]]),
-
- [enumHubGoalRewards.reward_freeplay]: null,
- [enumHubGoalRewards.no_reward]: null,
- [enumHubGoalRewards.no_reward_freeplay]: null,
-};
+import { MetaBuilding, defaultBuildingVariant } from "./meta_building";
+import { MetaCutterBuilding, enumCutterVariants } from "./buildings/cutter";
+import { MetaRotaterBuilding, enumRotaterVariants } from "./buildings/rotater";
+import { MetaPainterBuilding, enumPainterVariants } from "./buildings/painter";
+import { MetaMixerBuilding } from "./buildings/mixer";
+import { MetaStackerBuilding } from "./buildings/stacker";
+import { MetaBalancerBuilding, enumBalancerVariants } from "./buildings/balancer";
+import { MetaUndergroundBeltBuilding, enumUndergroundBeltVariants } from "./buildings/underground_belt";
+import { MetaMinerBuilding, enumMinerVariants } from "./buildings/miner";
+import { MetaTrashBuilding, enumTrashVariants } from "./buildings/trash";
+
+/** @typedef {Array<[typeof MetaBuilding, string]>} TutorialGoalReward */
+
+import { enumHubGoalRewards } from "./tutorial_goals";
+
+/**
+ * Helper method for proper types
+ * @returns {TutorialGoalReward}
+ */
+const typed = x => x;
+
+/**
+ * Stores which reward unlocks what
+ * @enum {TutorialGoalReward?}
+ */
+export const enumHubGoalRewardsToContentUnlocked = {
+ [enumHubGoalRewards.reward_cutter_and_trash]: typed([[MetaCutterBuilding, defaultBuildingVariant]]),
+ [enumHubGoalRewards.reward_rotater]: typed([[MetaRotaterBuilding, defaultBuildingVariant]]),
+ [enumHubGoalRewards.reward_painter]: typed([[MetaPainterBuilding, defaultBuildingVariant]]),
+ [enumHubGoalRewards.reward_mixer]: typed([[MetaMixerBuilding, defaultBuildingVariant]]),
+ [enumHubGoalRewards.reward_stacker]: typed([[MetaStackerBuilding, defaultBuildingVariant]]),
+ [enumHubGoalRewards.reward_balancer]: typed([[MetaBalancerBuilding, defaultBuildingVariant]]),
+ [enumHubGoalRewards.reward_tunnel]: typed([[MetaUndergroundBeltBuilding, defaultBuildingVariant]]),
+
+ [enumHubGoalRewards.reward_rotater_ccw]: typed([[MetaRotaterBuilding, enumRotaterVariants.ccw]]),
+ [enumHubGoalRewards.reward_rotater_180]: typed([[MetaRotaterBuilding, enumRotaterVariants.rotate180]]),
+ [enumHubGoalRewards.reward_miner_chainable]: typed([[MetaMinerBuilding, enumMinerVariants.chainable]]),
+ [enumHubGoalRewards.reward_underground_belt_tier_2]: typed([
+ [MetaUndergroundBeltBuilding, enumUndergroundBeltVariants.tier2],
+ ]),
+ [enumHubGoalRewards.reward_splitter]: typed([[MetaBalancerBuilding, enumBalancerVariants.splitter]]),
+ [enumHubGoalRewards.reward_merger]: typed([[MetaBalancerBuilding, enumBalancerVariants.merger]]),
+ [enumHubGoalRewards.reward_cutter_quad]: typed([[MetaCutterBuilding, enumCutterVariants.quad]]),
+ [enumHubGoalRewards.reward_painter_double]: typed([[MetaPainterBuilding, enumPainterVariants.double]]),
+ [enumHubGoalRewards.reward_painter_quad]: typed([[MetaPainterBuilding, enumPainterVariants.quad]]),
+ [enumHubGoalRewards.reward_storage]: typed([[MetaTrashBuilding, enumTrashVariants.storage]]),
+
+ [enumHubGoalRewards.reward_freeplay]: null,
+ [enumHubGoalRewards.no_reward]: null,
+ [enumHubGoalRewards.no_reward_freeplay]: null,
+};
diff --git a/src/js/game/upgrades.js b/src/js/game/upgrades.js
index 6e0c7c64..4735592b 100644
--- a/src/js/game/upgrades.js
+++ b/src/js/game/upgrades.js
@@ -1,175 +1,160 @@
-import { findNiceIntegerValue } from "../core/utils";
-import { ShapeDefinition } from "./shape_definition";
-
-export const finalGameShape = "RuCw--Cw:----Ru--";
-export const blueprintShape = "CbCbCbRb:CwCwCwCw";
-
-export const UPGRADES = {
- belt: {
- tiers: [
- {
- required: [{ shape: "CuCuCuCu", amount: 150 }],
- improvement: 1,
- },
- {
- required: [{ shape: "--CuCu--", amount: 1200 }],
- improvement: 2,
- },
- {
- required: [{ shape: "CpCpCpCp", amount: 15000 }],
- improvement: 2,
- },
- {
- required: [{ shape: "SrSrSrSr:CyCyCyCy", amount: 40000 }],
- improvement: 2,
- },
- {
- required: [{ shape: "SrSrSrSr:CyCyCyCy:SwSwSwSw", amount: 40000 }],
- improvement: 2,
- },
- {
- required: [{ shape: finalGameShape, amount: 150000 }],
- improvement: 5,
- excludePrevious: true,
- },
- ],
- },
-
- miner: {
- tiers: [
- {
- required: [{ shape: "RuRuRuRu", amount: 400 }],
- improvement: 1,
- },
- {
- required: [{ shape: "Cu------", amount: 4000 }],
- improvement: 2,
- },
- {
- required: [{ shape: "ScScScSc", amount: 20000 }],
- improvement: 2,
- },
- {
- required: [{ shape: "CwCwCwCw:WbWbWbWb", amount: 40000 }],
- improvement: 2,
- },
- {
- required: [{ shape: "CbRbRbCb:CwCwCwCw:WbWbWbWb", amount: 40000 }],
- improvement: 2,
- },
- {
- required: [{ shape: finalGameShape, amount: 150000 }],
- improvement: 5,
- excludePrevious: true,
- },
- ],
- },
-
- processors: {
- tiers: [
- {
- required: [{ shape: "SuSuSuSu", amount: 1000 }],
- improvement: 1,
- },
- {
- required: [{ shape: "RuRu----", amount: 2000 }],
- improvement: 2,
- },
- {
- required: [{ shape: "CgScScCg", amount: 25000 }],
- improvement: 2,
- },
- {
- required: [{ shape: "CwCrCwCr:SgSgSgSg", amount: 40000 }],
- improvement: 2,
- },
- {
- required: [{ shape: "WrRgWrRg:CwCrCwCr:SgSgSgSg", amount: 40000 }],
- improvement: 2,
- },
- {
- required: [{ shape: finalGameShape, amount: 150000 }],
- improvement: 5,
- excludePrevious: true,
- },
- ],
- },
-
- painting: {
- tiers: [
- {
- required: [{ shape: "RbRb----", amount: 1500 }],
- improvement: 2,
- },
- {
- required: [{ shape: "WrWrWrWr", amount: 4000 }],
- improvement: 1,
- },
- {
- required: [{ shape: "RpRpRpRp:CwCwCwCw", amount: 30000 }],
- improvement: 2,
- },
- {
- required: [{ shape: "WpWpWpWp:CwCwCwCw:WpWpWpWp", amount: 40000 }],
- improvement: 2,
- },
- {
- required: [{ shape: "WpWpWpWp:CwCwCwCw:WpWpWpWp:CwCwCwCw", amount: 40000 }],
- improvement: 2,
- },
- {
- required: [{ shape: finalGameShape, amount: 150000 }],
- improvement: 5,
- excludePrevious: true,
- },
- ],
- },
-};
-
-// Tiers need % of the previous tier as requirement too
-const tierGrowth = 2.5;
-
-// Automatically generate tier levels
-for (const upgradeId in UPGRADES) {
- const upgrade = UPGRADES[upgradeId];
-
- let currentTierRequirements = [];
- for (let i = 0; i < upgrade.tiers.length; ++i) {
- const tierHandle = upgrade.tiers[i];
- const originalRequired = tierHandle.required.slice();
-
- for (let k = currentTierRequirements.length - 1; k >= 0; --k) {
- const oldTierRequirement = currentTierRequirements[k];
- if (!tierHandle.excludePrevious) {
- tierHandle.required.unshift({
- shape: oldTierRequirement.shape,
- amount: oldTierRequirement.amount,
- });
- }
- }
- currentTierRequirements.push(
- ...originalRequired.map(req => ({
- amount: req.amount,
- shape: req.shape,
- }))
- );
- currentTierRequirements.forEach(tier => {
- tier.amount = findNiceIntegerValue(tier.amount * tierGrowth);
- });
- }
-}
-
-if (G_IS_DEV) {
- for (const upgradeId in UPGRADES) {
- const upgrade = UPGRADES[upgradeId];
- upgrade.tiers.forEach(tier => {
- tier.required.forEach(({ shape }) => {
- try {
- ShapeDefinition.fromShortKey(shape);
- } catch (ex) {
- throw new Error("Invalid upgrade goal: '" + ex + "' for shape" + shape);
- }
- });
- });
- }
-}
+import { findNiceIntegerValue } from "../core/utils";
+import { ShapeDefinition } from "./shape_definition";
+
+export const finalGameShape = "RuCw--Cw:----Ru--";
+export const blueprintShape = "CbCbCbRb:CwCwCwCw";
+
+const fixedImprovements = [0.5, 0.5, 1, 1, 2, 2];
+
+/** @typedef {{
+ * shape: string,
+ * amount: number
+ * }} UpgradeRequirement */
+
+/** @typedef {{
+ * required: Array
+ * improvement?: number,
+ * excludePrevious?: boolean
+ * }} TierRequirement */
+
+/** @typedef {Array} UpgradeTiers */
+
+/** @type {Object} */
+export const UPGRADES = {
+ belt: [
+ {
+ required: [{ shape: "CuCuCuCu", amount: 150 }],
+ },
+ {
+ required: [{ shape: "--CuCu--", amount: 1000 }],
+ },
+ {
+ required: [{ shape: "CpCpCpCp", amount: 5000 }],
+ },
+ {
+ required: [{ shape: "SrSrSrSr:CyCyCyCy", amount: 12000 }],
+ },
+ {
+ required: [{ shape: "SrSrSrSr:CyCyCyCy:SwSwSwSw", amount: 20000 }],
+ },
+ {
+ required: [{ shape: finalGameShape, amount: 75000 }],
+ excludePrevious: true,
+ },
+ ],
+
+ miner: [
+ {
+ required: [{ shape: "RuRuRuRu", amount: 400 }],
+ },
+ {
+ required: [{ shape: "Cu------", amount: 3000 }],
+ },
+ {
+ required: [{ shape: "ScScScSc", amount: 7000 }],
+ },
+ {
+ required: [{ shape: "CwCwCwCw:WbWbWbWb", amount: 15000 }],
+ },
+ {
+ required: [{ shape: "CbRbRbCb:CwCwCwCw:WbWbWbWb", amount: 30000 }],
+ },
+ {
+ required: [{ shape: finalGameShape, amount: 85000 }],
+ excludePrevious: true,
+ },
+ ],
+
+ processors: [
+ {
+ required: [{ shape: "SuSuSuSu", amount: 600 }],
+ },
+ {
+ required: [{ shape: "RuRu----", amount: 2000 }],
+ },
+ {
+ required: [{ shape: "CgScScCg", amount: 15000 }],
+ },
+ {
+ required: [{ shape: "CwCrCwCr:SgSgSgSg", amount: 20000 }],
+ },
+ {
+ required: [{ shape: "WrRgWrRg:CwCrCwCr:SgSgSgSg", amount: 30000 }],
+ },
+ {
+ required: [{ shape: finalGameShape, amount: 100000 }],
+ excludePrevious: true,
+ },
+ ],
+
+ painting: [
+ {
+ required: [{ shape: "RbRb----", amount: 1000 }],
+ },
+ {
+ required: [{ shape: "WrWrWrWr", amount: 3000 }],
+ },
+ {
+ required: [{ shape: "RpRpRpRp:CwCwCwCw", amount: 15000 }],
+ },
+ {
+ required: [{ shape: "WpWpWpWp:CwCwCwCw:WpWpWpWp", amount: 20000 }],
+ },
+ {
+ required: [{ shape: "WpWpWpWp:CwCwCwCw:WpWpWpWp:CwCwCwCw", amount: 30000 }],
+ },
+ {
+ required: [{ shape: finalGameShape, amount: 125000 }],
+ excludePrevious: true,
+ },
+ ],
+};
+
+// Tiers need % of the previous tier as requirement too
+const tierGrowth = 1.8;
+
+// Automatically generate tier levels
+for (const upgradeId in UPGRADES) {
+ const upgradeTiers = UPGRADES[upgradeId];
+
+ let currentTierRequirements = [];
+ for (let i = 0; i < upgradeTiers.length; ++i) {
+ const tierHandle = upgradeTiers[i];
+ tierHandle.improvement = fixedImprovements[i];
+ const originalRequired = tierHandle.required.slice();
+
+ for (let k = currentTierRequirements.length - 1; k >= 0; --k) {
+ const oldTierRequirement = currentTierRequirements[k];
+ if (!tierHandle.excludePrevious) {
+ tierHandle.required.unshift({
+ shape: oldTierRequirement.shape,
+ amount: oldTierRequirement.amount,
+ });
+ }
+ }
+ currentTierRequirements.push(
+ ...originalRequired.map(req => ({
+ amount: req.amount,
+ shape: req.shape,
+ }))
+ );
+ currentTierRequirements.forEach(tier => {
+ tier.amount = findNiceIntegerValue(tier.amount * tierGrowth);
+ });
+ }
+}
+
+// VALIDATE
+if (G_IS_DEV) {
+ for (const upgradeId in UPGRADES) {
+ UPGRADES[upgradeId].forEach(tier => {
+ tier.required.forEach(({ shape }) => {
+ try {
+ ShapeDefinition.fromShortKey(shape);
+ } catch (ex) {
+ throw new Error("Invalid upgrade goal: '" + ex + "' for shape" + shape);
+ }
+ });
+ });
+ }
+}
diff --git a/src/js/jsconfig.json b/src/js/jsconfig.json
index e28a1c04..99d65145 100644
--- a/src/js/jsconfig.json
+++ b/src/js/jsconfig.json
@@ -2,5 +2,6 @@
"compilerOptions": {
"target": "es6",
"checkJs": true
- }
+ },
+ "include": ["./**/*.js"]
}
diff --git a/src/js/platform/browser/game_analytics.js b/src/js/platform/browser/game_analytics.js
index 7336ffd9..52497ef7 100644
--- a/src/js/platform/browser/game_analytics.js
+++ b/src/js/platform/browser/game_analytics.js
@@ -1,261 +1,260 @@
-import { globalConfig } from "../../core/config";
-import { createLogger } from "../../core/logging";
-import { GameRoot } from "../../game/root";
-import { InGameState } from "../../states/ingame";
-import { GameAnalyticsInterface } from "../game_analytics";
-import { FILE_NOT_FOUND } from "../storage";
-import { blueprintShape, UPGRADES } from "../../game/upgrades";
-import { tutorialGoals } from "../../game/tutorial_goals";
-import { BeltComponent } from "../../game/components/belt";
-import { StaticMapEntityComponent } from "../../game/components/static_map_entity";
-
-const logger = createLogger("game_analytics");
-
-const analyticsUrl = G_IS_DEV ? "http://localhost:8001" : "https://analytics.shapez.io";
-
-// Be sure to increment the ID whenever it changes to make sure all
-// users are tracked
-const analyticsLocalFile = "shapez_token_123.bin";
-
-export class ShapezGameAnalytics extends GameAnalyticsInterface {
- get environment() {
- if (G_IS_DEV) {
- return "dev";
- }
-
- if (G_IS_STANDALONE) {
- return "steam";
- }
-
- if (G_IS_RELEASE) {
- return "prod";
- }
-
- return "beta";
- }
-
- /**
- * @returns {Promise}
- */
- initialize() {
- this.syncKey = null;
-
- setInterval(() => this.sendTimePoints(), 60 * 1000);
-
- // Retrieve sync key from player
- return this.app.storage.readFileAsync(analyticsLocalFile).then(
- syncKey => {
- this.syncKey = syncKey;
- logger.log("Player sync key read:", this.syncKey);
- },
- error => {
- // File was not found, retrieve new key
- if (error === FILE_NOT_FOUND) {
- logger.log("Retrieving new player key");
-
- // Perform call to get a new key from the API
- this.sendToApi("/v1/register", {
- environment: this.environment,
- })
- .then(res => {
- // Try to read and parse the key from the api
- if (res.key && typeof res.key === "string" && res.key.length === 40) {
- this.syncKey = res.key;
- logger.log("Key retrieved:", this.syncKey);
- this.app.storage.writeFileAsync(analyticsLocalFile, res.key);
- } else {
- throw new Error("Bad response from analytics server: " + res);
- }
- })
- .catch(err => {
- logger.error("Failed to register on analytics api:", err);
- });
- } else {
- logger.error("Failed to read ga key:", error);
- }
- return;
- }
- );
- }
-
- /**
- * Sends a request to the api
- * @param {string} endpoint Endpoint without base url
- * @param {object} data payload
- * @returns {Promise}
- */
- sendToApi(endpoint, data) {
- return new Promise((resolve, reject) => {
- const timeout = setTimeout(() => reject("Request to " + endpoint + " timed out"), 20000);
-
- fetch(analyticsUrl + endpoint, {
- method: "POST",
- mode: "cors",
- cache: "no-cache",
- referrer: "no-referrer",
- credentials: "omit",
- headers: {
- "Content-Type": "application/json",
- "Accept": "application/json",
- "x-api-key": globalConfig.info.analyticsApiKey,
- },
- body: JSON.stringify(data),
- })
- .then(res => {
- clearTimeout(timeout);
- if (!res.ok || res.status !== 200) {
- reject("Fetch error: Bad status " + res.status);
- } else {
- return res.json();
- }
- })
- .then(resolve)
- .catch(reason => {
- clearTimeout(timeout);
- reject(reason);
- });
- });
- }
-
- /**
- * Sends a game event to the analytics
- * @param {string} category
- * @param {string} value
- */
- sendGameEvent(category, value) {
- if (!this.syncKey) {
- logger.warn("Can not send event due to missing sync key");
- return;
- }
-
- const gameState = this.app.stateMgr.currentState;
- if (!(gameState instanceof InGameState)) {
- logger.warn("Trying to send analytics event outside of ingame state");
- return;
- }
-
- const savegame = gameState.savegame;
- if (!savegame) {
- logger.warn("Ingame state has empty savegame");
- return;
- }
-
- const savegameId = savegame.internalId;
- if (!gameState.core) {
- logger.warn("Game state has no core");
- return;
- }
- const root = gameState.core.root;
- if (!root) {
- logger.warn("Root is not initialized");
- return;
- }
-
- logger.log("Sending event", category, value);
-
- this.sendToApi("/v1/game-event", {
- playerKey: this.syncKey,
- gameKey: savegameId,
- ingameTime: root.time.now(),
- environment: this.environment,
- category,
- value,
- version: G_BUILD_VERSION,
- level: root.hubGoals.level,
- gameDump: this.generateGameDump(root),
- });
- }
-
- sendTimePoints() {
- const gameState = this.app.stateMgr.currentState;
- if (gameState instanceof InGameState) {
- logger.log("Syncing analytics");
- this.sendGameEvent("sync", "");
- }
- }
-
- /**
- * Returns true if the shape is interesting
- * @param {string} key
- */
- isInterestingShape(key) {
- if (key === blueprintShape) {
- return true;
- }
-
- // Check if its a story goal
- for (let i = 0; i < tutorialGoals.length; ++i) {
- if (key === tutorialGoals[i].shape) {
- return true;
- }
- }
-
- // Check if its required to unlock an upgrade
- for (const upgradeKey in UPGRADES) {
- const handle = UPGRADES[upgradeKey];
- const tiers = handle.tiers;
- for (let i = 0; i < tiers.length; ++i) {
- const tier = tiers[i];
- const required = tier.required;
- for (let k = 0; k < required.length; ++k) {
- if (required[k].shape === key) {
- return true;
- }
- }
- }
- }
-
- return false;
- }
-
- /**
- * Generates a game dump
- * @param {GameRoot} root
- */
- generateGameDump(root) {
- const shapeIds = Object.keys(root.hubGoals.storedShapes).filter(this.isInterestingShape.bind(this));
- let shapes = {};
- for (let i = 0; i < shapeIds.length; ++i) {
- shapes[shapeIds[i]] = root.hubGoals.storedShapes[shapeIds[i]];
- }
- return {
- shapes,
- upgrades: root.hubGoals.upgradeLevels,
- belts: root.entityMgr.getAllWithComponent(BeltComponent).length,
- buildings:
- root.entityMgr.getAllWithComponent(StaticMapEntityComponent).length -
- root.entityMgr.getAllWithComponent(BeltComponent).length,
- };
- }
-
- /**
- */
- handleGameStarted() {
- this.sendGameEvent("game_start", "");
- }
-
- /**
- */
- handleGameResumed() {
- this.sendTimePoints();
- }
-
- /**
- * Handles the given level completed
- * @param {number} level
- */
- handleLevelCompleted(level) {
- logger.log("Complete level", level);
- this.sendGameEvent("level_complete", "" + level);
- }
-
- /**
- * Handles the given upgrade completed
- * @param {string} id
- * @param {number} level
- */
- handleUpgradeUnlocked(id, level) {
- logger.log("Unlock upgrade", id, level);
- this.sendGameEvent("upgrade_unlock", id + "@" + level);
- }
-}
+import { globalConfig } from "../../core/config";
+import { createLogger } from "../../core/logging";
+import { GameRoot } from "../../game/root";
+import { InGameState } from "../../states/ingame";
+import { GameAnalyticsInterface } from "../game_analytics";
+import { FILE_NOT_FOUND } from "../storage";
+import { blueprintShape, UPGRADES } from "../../game/upgrades";
+import { tutorialGoals } from "../../game/tutorial_goals";
+import { BeltComponent } from "../../game/components/belt";
+import { StaticMapEntityComponent } from "../../game/components/static_map_entity";
+
+const logger = createLogger("game_analytics");
+
+const analyticsUrl = G_IS_DEV ? "http://localhost:8001" : "https://analytics.shapez.io";
+
+// Be sure to increment the ID whenever it changes to make sure all
+// users are tracked
+const analyticsLocalFile = "shapez_token_123.bin";
+
+export class ShapezGameAnalytics extends GameAnalyticsInterface {
+ get environment() {
+ if (G_IS_DEV) {
+ return "dev";
+ }
+
+ if (G_IS_STANDALONE) {
+ return "steam";
+ }
+
+ if (G_IS_RELEASE) {
+ return "prod";
+ }
+
+ return "beta";
+ }
+
+ /**
+ * @returns {Promise}
+ */
+ initialize() {
+ this.syncKey = null;
+
+ setInterval(() => this.sendTimePoints(), 60 * 1000);
+
+ // Retrieve sync key from player
+ return this.app.storage.readFileAsync(analyticsLocalFile).then(
+ syncKey => {
+ this.syncKey = syncKey;
+ logger.log("Player sync key read:", this.syncKey);
+ },
+ error => {
+ // File was not found, retrieve new key
+ if (error === FILE_NOT_FOUND) {
+ logger.log("Retrieving new player key");
+
+ // Perform call to get a new key from the API
+ this.sendToApi("/v1/register", {
+ environment: this.environment,
+ })
+ .then(res => {
+ // Try to read and parse the key from the api
+ if (res.key && typeof res.key === "string" && res.key.length === 40) {
+ this.syncKey = res.key;
+ logger.log("Key retrieved:", this.syncKey);
+ this.app.storage.writeFileAsync(analyticsLocalFile, res.key);
+ } else {
+ throw new Error("Bad response from analytics server: " + res);
+ }
+ })
+ .catch(err => {
+ logger.error("Failed to register on analytics api:", err);
+ });
+ } else {
+ logger.error("Failed to read ga key:", error);
+ }
+ return;
+ }
+ );
+ }
+
+ /**
+ * Sends a request to the api
+ * @param {string} endpoint Endpoint without base url
+ * @param {object} data payload
+ * @returns {Promise}
+ */
+ sendToApi(endpoint, data) {
+ return new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => reject("Request to " + endpoint + " timed out"), 20000);
+
+ fetch(analyticsUrl + endpoint, {
+ method: "POST",
+ mode: "cors",
+ cache: "no-cache",
+ referrer: "no-referrer",
+ credentials: "omit",
+ headers: {
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ "x-api-key": globalConfig.info.analyticsApiKey,
+ },
+ body: JSON.stringify(data),
+ })
+ .then(res => {
+ clearTimeout(timeout);
+ if (!res.ok || res.status !== 200) {
+ reject("Fetch error: Bad status " + res.status);
+ } else {
+ return res.json();
+ }
+ })
+ .then(resolve)
+ .catch(reason => {
+ clearTimeout(timeout);
+ reject(reason);
+ });
+ });
+ }
+
+ /**
+ * Sends a game event to the analytics
+ * @param {string} category
+ * @param {string} value
+ */
+ sendGameEvent(category, value) {
+ if (!this.syncKey) {
+ logger.warn("Can not send event due to missing sync key");
+ return;
+ }
+
+ const gameState = this.app.stateMgr.currentState;
+ if (!(gameState instanceof InGameState)) {
+ logger.warn("Trying to send analytics event outside of ingame state");
+ return;
+ }
+
+ const savegame = gameState.savegame;
+ if (!savegame) {
+ logger.warn("Ingame state has empty savegame");
+ return;
+ }
+
+ const savegameId = savegame.internalId;
+ if (!gameState.core) {
+ logger.warn("Game state has no core");
+ return;
+ }
+ const root = gameState.core.root;
+ if (!root) {
+ logger.warn("Root is not initialized");
+ return;
+ }
+
+ logger.log("Sending event", category, value);
+
+ this.sendToApi("/v1/game-event", {
+ playerKey: this.syncKey,
+ gameKey: savegameId,
+ ingameTime: root.time.now(),
+ environment: this.environment,
+ category,
+ value,
+ version: G_BUILD_VERSION,
+ level: root.hubGoals.level,
+ gameDump: this.generateGameDump(root),
+ });
+ }
+
+ sendTimePoints() {
+ const gameState = this.app.stateMgr.currentState;
+ if (gameState instanceof InGameState) {
+ logger.log("Syncing analytics");
+ this.sendGameEvent("sync", "");
+ }
+ }
+
+ /**
+ * Returns true if the shape is interesting
+ * @param {string} key
+ */
+ isInterestingShape(key) {
+ if (key === blueprintShape) {
+ return true;
+ }
+
+ // Check if its a story goal
+ for (let i = 0; i < tutorialGoals.length; ++i) {
+ if (key === tutorialGoals[i].shape) {
+ return true;
+ }
+ }
+
+ // Check if its required to unlock an upgrade
+ for (const upgradeKey in UPGRADES) {
+ const upgradeTiers = UPGRADES[upgradeKey];
+ for (let i = 0; i < upgradeTiers.length; ++i) {
+ const tier = upgradeTiers[i];
+ const required = tier.required;
+ for (let k = 0; k < required.length; ++k) {
+ if (required[k].shape === key) {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Generates a game dump
+ * @param {GameRoot} root
+ */
+ generateGameDump(root) {
+ const shapeIds = Object.keys(root.hubGoals.storedShapes).filter(this.isInterestingShape.bind(this));
+ let shapes = {};
+ for (let i = 0; i < shapeIds.length; ++i) {
+ shapes[shapeIds[i]] = root.hubGoals.storedShapes[shapeIds[i]];
+ }
+ return {
+ shapes,
+ upgrades: root.hubGoals.upgradeLevels,
+ belts: root.entityMgr.getAllWithComponent(BeltComponent).length,
+ buildings:
+ root.entityMgr.getAllWithComponent(StaticMapEntityComponent).length -
+ root.entityMgr.getAllWithComponent(BeltComponent).length,
+ };
+ }
+
+ /**
+ */
+ handleGameStarted() {
+ this.sendGameEvent("game_start", "");
+ }
+
+ /**
+ */
+ handleGameResumed() {
+ this.sendTimePoints();
+ }
+
+ /**
+ * Handles the given level completed
+ * @param {number} level
+ */
+ handleLevelCompleted(level) {
+ logger.log("Complete level", level);
+ this.sendGameEvent("level_complete", "" + level);
+ }
+
+ /**
+ * Handles the given upgrade completed
+ * @param {string} id
+ * @param {number} level
+ */
+ handleUpgradeUnlocked(id, level) {
+ logger.log("Unlock upgrade", id, level);
+ this.sendGameEvent("upgrade_unlock", id + "@" + level);
+ }
+}
diff --git a/src/js/profile/application_settings.js b/src/js/profile/application_settings.js
index 084a6fe7..ace30eff 100644
--- a/src/js/profile/application_settings.js
+++ b/src/js/profile/application_settings.js
@@ -253,6 +253,7 @@ export const allApplicationSettings = [
changeCb: (app, id) => {},
}),
+ new BoolSetting("enableMousePan", enumCategories.advanced, (app, value) => {}),
new BoolSetting("alwaysMultiplace", enumCategories.advanced, (app, value) => {}),
new BoolSetting("clearCursorOnDeleteWhilePlacing", enumCategories.advanced, (app, value) => {}),
new BoolSetting("enableTunnelSmartplace", enumCategories.advanced, (app, value) => {}),
@@ -276,6 +277,7 @@ export const allApplicationSettings = [
new BoolSetting("lowQualityMapResources", enumCategories.performance, (app, value) => {}),
new BoolSetting("disableTileGrid", enumCategories.performance, (app, value) => {}),
new BoolSetting("lowQualityTextures", enumCategories.performance, (app, value) => {}),
+ new BoolSetting("simplifiedBelts", enumCategories.performance, (app, value) => {}),
];
export function getApplicationSettingById(id) {
@@ -307,12 +309,14 @@ class SettingsStorage {
this.clearCursorOnDeleteWhilePlacing = true;
this.displayChunkBorders = false;
this.pickMinerOnPatch = true;
+ this.enableMousePan = true;
this.enableColorBlindHelper = false;
this.lowQualityMapResources = false;
this.disableTileGrid = false;
this.lowQualityTextures = false;
+ this.simplifiedBelts = false;
/**
* @type {Object.}
@@ -523,7 +527,7 @@ export class ApplicationSettings extends ReadWriteProxy {
}
getCurrentVersion() {
- return 26;
+ return 28;
}
/** @param {{settings: SettingsStorage, version: number}} data */
@@ -646,6 +650,16 @@ export class ApplicationSettings extends ReadWriteProxy {
data.version = 26;
}
+ if (data.version < 27) {
+ data.settings.simplifiedBelts = false;
+ data.version = 27;
+ }
+
+ if (data.version < 28) {
+ data.settings.enableMousePan = true;
+ data.version = 28;
+ }
+
return ExplainedResult.good();
}
}
diff --git a/src/js/savegame/savegame.js b/src/js/savegame/savegame.js
index 2a7102a9..0ad630f6 100644
--- a/src/js/savegame/savegame.js
+++ b/src/js/savegame/savegame.js
@@ -1,273 +1,279 @@
-import { ReadWriteProxy } from "../core/read_write_proxy";
-import { ExplainedResult } from "../core/explained_result";
-import { SavegameSerializer } from "./savegame_serializer";
-import { BaseSavegameInterface } from "./savegame_interface";
-import { createLogger } from "../core/logging";
-import { globalConfig } from "../core/config";
-import { getSavegameInterface, savegameInterfaces } from "./savegame_interface_registry";
-import { SavegameInterface_V1001 } from "./schemas/1001";
-import { SavegameInterface_V1002 } from "./schemas/1002";
-import { SavegameInterface_V1003 } from "./schemas/1003";
-import { SavegameInterface_V1004 } from "./schemas/1004";
-import { SavegameInterface_V1005 } from "./schemas/1005";
-
-const logger = createLogger("savegame");
-
-/**
- * @typedef {import("../application").Application} Application
- * @typedef {import("../game/root").GameRoot} GameRoot
- * @typedef {import("./savegame_typedefs").SavegameData} SavegameData
- * @typedef {import("./savegame_typedefs").SavegameMetadata} SavegameMetadata
- * @typedef {import("./savegame_typedefs").SavegameStats} SavegameStats
- * @typedef {import("./savegame_typedefs").SerializedGame} SerializedGame
- */
-
-export class Savegame extends ReadWriteProxy {
- /**
- *
- * @param {Application} app
- * @param {object} param0
- * @param {string} param0.internalId
- * @param {SavegameMetadata} param0.metaDataRef Handle to the meta data
- */
- constructor(app, { internalId, metaDataRef }) {
- super(app, "savegame-" + internalId + ".bin");
- this.internalId = internalId;
- this.metaDataRef = metaDataRef;
-
- /** @type {SavegameData} */
- this.currentData = this.getDefaultData();
-
- assert(
- savegameInterfaces[Savegame.getCurrentVersion()],
- "Savegame interface not defined: " + Savegame.getCurrentVersion()
- );
- }
-
- //////// RW Proxy Impl //////////
-
- /**
- * @returns {number}
- */
- static getCurrentVersion() {
- return 1005;
- }
-
- /**
- * @returns {typeof BaseSavegameInterface}
- */
- static getReaderClass() {
- return savegameInterfaces[Savegame.getCurrentVersion()];
- }
-
- /**
- * @returns {number}
- */
- getCurrentVersion() {
- return /** @type {typeof Savegame} */ (this.constructor).getCurrentVersion();
- }
-
- /**
- * Returns the savegames default data
- * @returns {SavegameData}
- */
- getDefaultData() {
- return {
- version: this.getCurrentVersion(),
- dump: null,
- stats: {},
- lastUpdate: Date.now(),
- };
- }
-
- /**
- * Migrates the savegames data
- * @param {SavegameData} data
- */
- migrate(data) {
- if (data.version < 1000) {
- return ExplainedResult.bad("Can not migrate savegame, too old");
- }
-
- if (data.version === 1000) {
- SavegameInterface_V1001.migrate1000to1001(data);
- data.version = 1001;
- }
-
- if (data.version === 1001) {
- SavegameInterface_V1002.migrate1001to1002(data);
- data.version = 1002;
- }
-
- if (data.version === 1002) {
- SavegameInterface_V1003.migrate1002to1003(data);
- data.version = 1003;
- }
-
- if (data.version === 1003) {
- SavegameInterface_V1004.migrate1003to1004(data);
- data.version = 1004;
- }
-
- if (data.version === 1004) {
- SavegameInterface_V1005.migrate1004to1005(data);
- data.version = 1005;
- }
-
- return ExplainedResult.good();
- }
-
- /**
- * Verifies the savegames data
- * @param {SavegameData} data
- */
- verify(data) {
- if (!data.dump) {
- // Well, guess that works
- return ExplainedResult.good();
- }
-
- if (!this.getDumpReaderForExternalData(data).validate()) {
- return ExplainedResult.bad("dump-reader-failed-validation");
- }
- return ExplainedResult.good();
- }
-
- //////// Subclasses interface ////////
-
- /**
- * Returns if this game can be saved on disc
- * @returns {boolean}
- */
- isSaveable() {
- return true;
- }
- /**
- * Returns the statistics of the savegame
- * @returns {SavegameStats}
- */
- getStatistics() {
- return this.currentData.stats;
- }
-
- /**
- * Returns the *real* last update of the savegame, not the one of the metadata
- * which could also be the servers one
- */
- getRealLastUpdate() {
- return this.currentData.lastUpdate;
- }
-
- /**
- * Returns if this game has a serialized game dump
- */
- hasGameDump() {
- return !!this.currentData.dump && this.currentData.dump.entities.length > 0;
- }
-
- /**
- * Returns the current game dump
- * @returns {SerializedGame}
- */
- getCurrentDump() {
- return this.currentData.dump;
- }
-
- /**
- * Returns a reader to access the data
- * @returns {BaseSavegameInterface}
- */
- getDumpReader() {
- if (!this.currentData.dump) {
- logger.warn("Getting reader on null-savegame dump");
- }
-
- const cls = /** @type {typeof Savegame} */ (this.constructor).getReaderClass();
- return new cls(this.currentData);
- }
-
- /**
- * Returns a reader to access external data
- * @returns {BaseSavegameInterface}
- */
- getDumpReaderForExternalData(data) {
- assert(data.version, "External data contains no version");
- return getSavegameInterface(data);
- }
-
- ///////// Public Interface ///////////
-
- /**
- * Updates the last update field so we can send the savegame to the server,
- * WITHOUT Saving!
- */
- setLastUpdate(time) {
- this.currentData.lastUpdate = time;
- }
-
- /**
- *
- * @param {GameRoot} root
- */
- updateData(root) {
- // Construct a new serializer
- const serializer = new SavegameSerializer();
-
- // let timer = performance.now();
- const dump = serializer.generateDumpFromGameRoot(root);
- if (!dump) {
- return false;
- }
-
- const shadowData = Object.assign({}, this.currentData);
- shadowData.dump = dump;
- shadowData.lastUpdate = new Date().getTime();
- shadowData.version = this.getCurrentVersion();
-
- const reader = this.getDumpReaderForExternalData(shadowData);
-
- // Validate (not in prod though)
- if (!G_IS_RELEASE) {
- const validationResult = reader.validate();
- if (!validationResult) {
- return false;
- }
- }
-
- // Save data
- this.currentData = shadowData;
- }
-
- /**
- * Writes the savegame as well as its metadata
- */
- writeSavegameAndMetadata() {
- return this.writeAsync().then(() => this.saveMetadata());
- }
-
- /**
- * Updates the savegames metadata
- */
- saveMetadata() {
- this.metaDataRef.lastUpdate = new Date().getTime();
- this.metaDataRef.version = this.getCurrentVersion();
- if (!this.hasGameDump()) {
- this.metaDataRef.level = 0;
- } else {
- this.metaDataRef.level = this.currentData.dump.hubGoals.level;
- }
-
- return this.app.savegameMgr.writeAsync();
- }
-
- /**
- * @see ReadWriteProxy.writeAsync
- * @returns {Promise}
- */
- writeAsync() {
- if (G_IS_DEV && globalConfig.debug.disableSavegameWrite) {
- return Promise.resolve();
- }
- return super.writeAsync();
- }
-}
+import { ReadWriteProxy } from "../core/read_write_proxy";
+import { ExplainedResult } from "../core/explained_result";
+import { SavegameSerializer } from "./savegame_serializer";
+import { BaseSavegameInterface } from "./savegame_interface";
+import { createLogger } from "../core/logging";
+import { globalConfig } from "../core/config";
+import { getSavegameInterface, savegameInterfaces } from "./savegame_interface_registry";
+import { SavegameInterface_V1001 } from "./schemas/1001";
+import { SavegameInterface_V1002 } from "./schemas/1002";
+import { SavegameInterface_V1003 } from "./schemas/1003";
+import { SavegameInterface_V1004 } from "./schemas/1004";
+import { SavegameInterface_V1005 } from "./schemas/1005";
+import { SavegameInterface_V1006 } from "./schemas/1006";
+
+const logger = createLogger("savegame");
+
+/**
+ * @typedef {import("../application").Application} Application
+ * @typedef {import("../game/root").GameRoot} GameRoot
+ * @typedef {import("./savegame_typedefs").SavegameData} SavegameData
+ * @typedef {import("./savegame_typedefs").SavegameMetadata} SavegameMetadata
+ * @typedef {import("./savegame_typedefs").SavegameStats} SavegameStats
+ * @typedef {import("./savegame_typedefs").SerializedGame} SerializedGame
+ */
+
+export class Savegame extends ReadWriteProxy {
+ /**
+ *
+ * @param {Application} app
+ * @param {object} param0
+ * @param {string} param0.internalId
+ * @param {SavegameMetadata} param0.metaDataRef Handle to the meta data
+ */
+ constructor(app, { internalId, metaDataRef }) {
+ super(app, "savegame-" + internalId + ".bin");
+ this.internalId = internalId;
+ this.metaDataRef = metaDataRef;
+
+ /** @type {SavegameData} */
+ this.currentData = this.getDefaultData();
+
+ assert(
+ savegameInterfaces[Savegame.getCurrentVersion()],
+ "Savegame interface not defined: " + Savegame.getCurrentVersion()
+ );
+ }
+
+ //////// RW Proxy Impl //////////
+
+ /**
+ * @returns {number}
+ */
+ static getCurrentVersion() {
+ return 1006;
+ }
+
+ /**
+ * @returns {typeof BaseSavegameInterface}
+ */
+ static getReaderClass() {
+ return savegameInterfaces[Savegame.getCurrentVersion()];
+ }
+
+ /**
+ * @returns {number}
+ */
+ getCurrentVersion() {
+ return /** @type {typeof Savegame} */ (this.constructor).getCurrentVersion();
+ }
+
+ /**
+ * Returns the savegames default data
+ * @returns {SavegameData}
+ */
+ getDefaultData() {
+ return {
+ version: this.getCurrentVersion(),
+ dump: null,
+ stats: {},
+ lastUpdate: Date.now(),
+ };
+ }
+
+ /**
+ * Migrates the savegames data
+ * @param {SavegameData} data
+ */
+ migrate(data) {
+ if (data.version < 1000) {
+ return ExplainedResult.bad("Can not migrate savegame, too old");
+ }
+
+ if (data.version === 1000) {
+ SavegameInterface_V1001.migrate1000to1001(data);
+ data.version = 1001;
+ }
+
+ if (data.version === 1001) {
+ SavegameInterface_V1002.migrate1001to1002(data);
+ data.version = 1002;
+ }
+
+ if (data.version === 1002) {
+ SavegameInterface_V1003.migrate1002to1003(data);
+ data.version = 1003;
+ }
+
+ if (data.version === 1003) {
+ SavegameInterface_V1004.migrate1003to1004(data);
+ data.version = 1004;
+ }
+
+ if (data.version === 1004) {
+ SavegameInterface_V1005.migrate1004to1005(data);
+ data.version = 1005;
+ }
+
+ if (data.version === 1005) {
+ SavegameInterface_V1006.migrate1005to1006(data);
+ data.version = 1006;
+ }
+
+ return ExplainedResult.good();
+ }
+
+ /**
+ * Verifies the savegames data
+ * @param {SavegameData} data
+ */
+ verify(data) {
+ if (!data.dump) {
+ // Well, guess that works
+ return ExplainedResult.good();
+ }
+
+ if (!this.getDumpReaderForExternalData(data).validate()) {
+ return ExplainedResult.bad("dump-reader-failed-validation");
+ }
+ return ExplainedResult.good();
+ }
+
+ //////// Subclasses interface ////////
+
+ /**
+ * Returns if this game can be saved on disc
+ * @returns {boolean}
+ */
+ isSaveable() {
+ return true;
+ }
+ /**
+ * Returns the statistics of the savegame
+ * @returns {SavegameStats}
+ */
+ getStatistics() {
+ return this.currentData.stats;
+ }
+
+ /**
+ * Returns the *real* last update of the savegame, not the one of the metadata
+ * which could also be the servers one
+ */
+ getRealLastUpdate() {
+ return this.currentData.lastUpdate;
+ }
+
+ /**
+ * Returns if this game has a serialized game dump
+ */
+ hasGameDump() {
+ return !!this.currentData.dump && this.currentData.dump.entities.length > 0;
+ }
+
+ /**
+ * Returns the current game dump
+ * @returns {SerializedGame}
+ */
+ getCurrentDump() {
+ return this.currentData.dump;
+ }
+
+ /**
+ * Returns a reader to access the data
+ * @returns {BaseSavegameInterface}
+ */
+ getDumpReader() {
+ if (!this.currentData.dump) {
+ logger.warn("Getting reader on null-savegame dump");
+ }
+
+ const cls = /** @type {typeof Savegame} */ (this.constructor).getReaderClass();
+ return new cls(this.currentData);
+ }
+
+ /**
+ * Returns a reader to access external data
+ * @returns {BaseSavegameInterface}
+ */
+ getDumpReaderForExternalData(data) {
+ assert(data.version, "External data contains no version");
+ return getSavegameInterface(data);
+ }
+
+ ///////// Public Interface ///////////
+
+ /**
+ * Updates the last update field so we can send the savegame to the server,
+ * WITHOUT Saving!
+ */
+ setLastUpdate(time) {
+ this.currentData.lastUpdate = time;
+ }
+
+ /**
+ *
+ * @param {GameRoot} root
+ */
+ updateData(root) {
+ // Construct a new serializer
+ const serializer = new SavegameSerializer();
+
+ // let timer = performance.now();
+ const dump = serializer.generateDumpFromGameRoot(root);
+ if (!dump) {
+ return false;
+ }
+
+ const shadowData = Object.assign({}, this.currentData);
+ shadowData.dump = dump;
+ shadowData.lastUpdate = new Date().getTime();
+ shadowData.version = this.getCurrentVersion();
+
+ const reader = this.getDumpReaderForExternalData(shadowData);
+
+ // Validate (not in prod though)
+ if (!G_IS_RELEASE) {
+ const validationResult = reader.validate();
+ if (!validationResult) {
+ return false;
+ }
+ }
+
+ // Save data
+ this.currentData = shadowData;
+ }
+
+ /**
+ * Writes the savegame as well as its metadata
+ */
+ writeSavegameAndMetadata() {
+ return this.writeAsync().then(() => this.saveMetadata());
+ }
+
+ /**
+ * Updates the savegames metadata
+ */
+ saveMetadata() {
+ this.metaDataRef.lastUpdate = new Date().getTime();
+ this.metaDataRef.version = this.getCurrentVersion();
+ if (!this.hasGameDump()) {
+ this.metaDataRef.level = 0;
+ } else {
+ this.metaDataRef.level = this.currentData.dump.hubGoals.level;
+ }
+
+ return this.app.savegameMgr.writeAsync();
+ }
+
+ /**
+ * @see ReadWriteProxy.writeAsync
+ * @returns {Promise}
+ */
+ writeAsync() {
+ if (G_IS_DEV && globalConfig.debug.disableSavegameWrite) {
+ return Promise.resolve();
+ }
+ return super.writeAsync();
+ }
+}
diff --git a/src/js/savegame/savegame_interface_registry.js b/src/js/savegame/savegame_interface_registry.js
index fb1df52f..07b5353c 100644
--- a/src/js/savegame/savegame_interface_registry.js
+++ b/src/js/savegame/savegame_interface_registry.js
@@ -1,45 +1,47 @@
-import { BaseSavegameInterface } from "./savegame_interface";
-import { SavegameInterface_V1000 } from "./schemas/1000";
-import { createLogger } from "../core/logging";
-import { SavegameInterface_V1001 } from "./schemas/1001";
-import { SavegameInterface_V1002 } from "./schemas/1002";
-import { SavegameInterface_V1003 } from "./schemas/1003";
-import { SavegameInterface_V1004 } from "./schemas/1004";
-import { SavegameInterface_V1005 } from "./schemas/1005";
-
-/** @type {Object.} */
-export const savegameInterfaces = {
- 1000: SavegameInterface_V1000,
- 1001: SavegameInterface_V1001,
- 1002: SavegameInterface_V1002,
- 1003: SavegameInterface_V1003,
- 1004: SavegameInterface_V1004,
- 1005: SavegameInterface_V1005,
-};
-
-const logger = createLogger("savegame_interface_registry");
-
-/**
- * Returns if the given savegame has any supported interface
- * @param {any} savegame
- * @returns {BaseSavegameInterface|null}
- */
-export function getSavegameInterface(savegame) {
- if (!savegame || !savegame.version) {
- logger.warn("Savegame does not contain a valid version (undefined)");
- return null;
- }
- const version = savegame.version;
- if (!Number.isInteger(version)) {
- logger.warn("Savegame does not contain a valid version (non-integer):", version);
- return null;
- }
-
- const interfaceClass = savegameInterfaces[version];
- if (!interfaceClass) {
- logger.warn("Version", version, "has no implemented interface!");
- return null;
- }
-
- return new interfaceClass(savegame);
-}
+import { BaseSavegameInterface } from "./savegame_interface";
+import { SavegameInterface_V1000 } from "./schemas/1000";
+import { createLogger } from "../core/logging";
+import { SavegameInterface_V1001 } from "./schemas/1001";
+import { SavegameInterface_V1002 } from "./schemas/1002";
+import { SavegameInterface_V1003 } from "./schemas/1003";
+import { SavegameInterface_V1004 } from "./schemas/1004";
+import { SavegameInterface_V1005 } from "./schemas/1005";
+import { SavegameInterface_V1006 } from "./schemas/1006";
+
+/** @type {Object.} */
+export const savegameInterfaces = {
+ 1000: SavegameInterface_V1000,
+ 1001: SavegameInterface_V1001,
+ 1002: SavegameInterface_V1002,
+ 1003: SavegameInterface_V1003,
+ 1004: SavegameInterface_V1004,
+ 1005: SavegameInterface_V1005,
+ 1006: SavegameInterface_V1006,
+};
+
+const logger = createLogger("savegame_interface_registry");
+
+/**
+ * Returns if the given savegame has any supported interface
+ * @param {any} savegame
+ * @returns {BaseSavegameInterface|null}
+ */
+export function getSavegameInterface(savegame) {
+ if (!savegame || !savegame.version) {
+ logger.warn("Savegame does not contain a valid version (undefined)");
+ return null;
+ }
+ const version = savegame.version;
+ if (!Number.isInteger(version)) {
+ logger.warn("Savegame does not contain a valid version (non-integer):", version);
+ return null;
+ }
+
+ const interfaceClass = savegameInterfaces[version];
+ if (!interfaceClass) {
+ logger.warn("Version", version, "has no implemented interface!");
+ return null;
+ }
+
+ return new interfaceClass(savegame);
+}
diff --git a/src/js/savegame/savegame_serializer.js b/src/js/savegame/savegame_serializer.js
index 92db738b..552bc35c 100644
--- a/src/js/savegame/savegame_serializer.js
+++ b/src/js/savegame/savegame_serializer.js
@@ -1,146 +1,146 @@
-import { ExplainedResult } from "../core/explained_result";
-import { createLogger } from "../core/logging";
-import { gComponentRegistry } from "../core/global_registries";
-import { SerializerInternal } from "./serializer_internal";
-
-/**
- * @typedef {import("../game/component").Component} Component
- * @typedef {import("../game/component").StaticComponent} StaticComponent
- * @typedef {import("../game/entity").Entity} Entity
- * @typedef {import("../game/root").GameRoot} GameRoot
- * @typedef {import("../savegame/savegame_typedefs").SerializedGame} SerializedGame
- */
-
-const logger = createLogger("savegame_serializer");
-
-/**
- * Serializes a savegame
- */
-export class SavegameSerializer {
- constructor() {
- this.internal = new SerializerInternal();
- }
-
- /**
- * Serializes the game root into a dump
- * @param {GameRoot} root
- * @param {boolean=} sanityChecks Whether to check for validity
- * @returns {object}
- */
- generateDumpFromGameRoot(root, sanityChecks = true) {
- /** @type {SerializedGame} */
- const data = {
- camera: root.camera.serialize(),
- time: root.time.serialize(),
- map: root.map.serialize(),
- entityMgr: root.entityMgr.serialize(),
- hubGoals: root.hubGoals.serialize(),
- pinnedShapes: root.hud.parts.pinnedShapes.serialize(),
- waypoints: root.hud.parts.waypoints.serialize(),
- entities: this.internal.serializeEntityArray(root.entityMgr.entities),
- beltPaths: root.systemMgr.systems.belt.serializePaths(),
- };
-
- if (!G_IS_RELEASE) {
- if (sanityChecks) {
- // Sanity check
- const sanity = this.verifyLogicalErrors(data);
- if (!sanity.result) {
- logger.error("Created invalid savegame:", sanity.reason, "savegame:", data);
- return null;
- }
- }
- }
- return data;
- }
-
- /**
- * Verifies if there are logical errors in the savegame
- * @param {SerializedGame} savegame
- * @returns {ExplainedResult}
- */
- verifyLogicalErrors(savegame) {
- if (!savegame.entities) {
- return ExplainedResult.bad("Savegame has no entities");
- }
-
- const seenUids = [];
-
- // Check for duplicate UIDS
- for (let i = 0; i < savegame.entities.length; ++i) {
- /** @type {Entity} */
- const entity = savegame.entities[i];
-
- const uid = entity.uid;
- if (!Number.isInteger(uid)) {
- return ExplainedResult.bad("Entity has invalid uid: " + uid);
- }
- if (seenUids.indexOf(uid) >= 0) {
- return ExplainedResult.bad("Duplicate uid " + uid);
- }
- seenUids.push(uid);
-
- // Verify components
- if (!entity.components) {
- return ExplainedResult.bad("Entity is missing key 'components': " + JSON.stringify(entity));
- }
-
- const components = entity.components;
- for (const componentId in components) {
- const componentClass = gComponentRegistry.findById(componentId);
-
- // Check component id is known
- if (!componentClass) {
- return ExplainedResult.bad("Unknown component id: " + componentId);
- }
-
- // Verify component data
- const componentData = components[componentId];
- const componentVerifyError = /** @type {StaticComponent} */ (componentClass).verify(
- componentData
- );
-
- // Check component data is ok
- if (componentVerifyError) {
- return ExplainedResult.bad(
- "Component " + componentId + " has invalid data: " + componentVerifyError
- );
- }
- }
- }
-
- return ExplainedResult.good();
- }
-
- /**
- * Tries to load the savegame from a given dump
- * @param {SerializedGame} savegame
- * @param {GameRoot} root
- * @returns {ExplainedResult}
- */
- deserialize(savegame, root) {
- // Sanity
- const verifyResult = this.verifyLogicalErrors(savegame);
- if (!verifyResult.result) {
- return ExplainedResult.bad(verifyResult.reason);
- }
- let errorReason = null;
-
- errorReason = errorReason || root.entityMgr.deserialize(savegame.entityMgr);
- errorReason = errorReason || root.time.deserialize(savegame.time);
- errorReason = errorReason || root.camera.deserialize(savegame.camera);
- errorReason = errorReason || root.map.deserialize(savegame.map);
- errorReason = errorReason || root.hubGoals.deserialize(savegame.hubGoals);
- errorReason = errorReason || root.hud.parts.pinnedShapes.deserialize(savegame.pinnedShapes);
- errorReason = errorReason || root.hud.parts.waypoints.deserialize(savegame.waypoints);
- errorReason = errorReason || this.internal.deserializeEntityArray(root, savegame.entities);
- errorReason = errorReason || root.systemMgr.systems.belt.deserializePaths(savegame.beltPaths);
-
- // Check for errors
- if (errorReason) {
- return ExplainedResult.bad(errorReason);
- }
-
- return ExplainedResult.good();
- }
-}
+import { ExplainedResult } from "../core/explained_result";
+import { createLogger } from "../core/logging";
+import { gComponentRegistry } from "../core/global_registries";
+import { SerializerInternal } from "./serializer_internal";
+
+/**
+ * @typedef {import("../game/component").Component} Component
+ * @typedef {import("../game/component").StaticComponent} StaticComponent
+ * @typedef {import("../game/entity").Entity} Entity
+ * @typedef {import("../game/root").GameRoot} GameRoot
+ * @typedef {import("../savegame/savegame_typedefs").SerializedGame} SerializedGame
+ */
+
+const logger = createLogger("savegame_serializer");
+
+/**
+ * Serializes a savegame
+ */
+export class SavegameSerializer {
+ constructor() {
+ this.internal = new SerializerInternal();
+ }
+
+ /**
+ * Serializes the game root into a dump
+ * @param {GameRoot} root
+ * @param {boolean=} sanityChecks Whether to check for validity
+ * @returns {object}
+ */
+ generateDumpFromGameRoot(root, sanityChecks = true) {
+ /** @type {SerializedGame} */
+ const data = {
+ camera: root.camera.serialize(),
+ time: root.time.serialize(),
+ map: root.map.serialize(),
+ entityMgr: root.entityMgr.serialize(),
+ hubGoals: root.hubGoals.serialize(),
+ pinnedShapes: root.hud.parts.pinnedShapes.serialize(),
+ waypoints: root.hud.parts.waypoints.serialize(),
+ entities: this.internal.serializeEntityArray(root.entityMgr.entities),
+ beltPaths: root.systemMgr.systems.belt.serializePaths(),
+ };
+
+ if (G_IS_DEV) {
+ if (sanityChecks) {
+ // Sanity check
+ const sanity = this.verifyLogicalErrors(data);
+ if (!sanity.result) {
+ logger.error("Created invalid savegame:", sanity.reason, "savegame:", data);
+ return null;
+ }
+ }
+ }
+ return data;
+ }
+
+ /**
+ * Verifies if there are logical errors in the savegame
+ * @param {SerializedGame} savegame
+ * @returns {ExplainedResult}
+ */
+ verifyLogicalErrors(savegame) {
+ if (!savegame.entities) {
+ return ExplainedResult.bad("Savegame has no entities");
+ }
+
+ const seenUids = new Set();
+
+ // Check for duplicate UIDS
+ for (let i = 0; i < savegame.entities.length; ++i) {
+ /** @type {Entity} */
+ const entity = savegame.entities[i];
+
+ const uid = entity.uid;
+ if (!Number.isInteger(uid)) {
+ return ExplainedResult.bad("Entity has invalid uid: " + uid);
+ }
+ if (seenUids.has(uid)) {
+ return ExplainedResult.bad("Duplicate uid " + uid);
+ }
+ seenUids.add(uid);
+
+ // Verify components
+ if (!entity.components) {
+ return ExplainedResult.bad("Entity is missing key 'components': " + JSON.stringify(entity));
+ }
+
+ const components = entity.components;
+ for (const componentId in components) {
+ const componentClass = gComponentRegistry.findById(componentId);
+
+ // Check component id is known
+ if (!componentClass) {
+ return ExplainedResult.bad("Unknown component id: " + componentId);
+ }
+
+ // Verify component data
+ const componentData = components[componentId];
+ const componentVerifyError = /** @type {StaticComponent} */ (componentClass).verify(
+ componentData
+ );
+
+ // Check component data is ok
+ if (componentVerifyError) {
+ return ExplainedResult.bad(
+ "Component " + componentId + " has invalid data: " + componentVerifyError
+ );
+ }
+ }
+ }
+
+ return ExplainedResult.good();
+ }
+
+ /**
+ * Tries to load the savegame from a given dump
+ * @param {SerializedGame} savegame
+ * @param {GameRoot} root
+ * @returns {ExplainedResult}
+ */
+ deserialize(savegame, root) {
+ // Sanity
+ const verifyResult = this.verifyLogicalErrors(savegame);
+ if (!verifyResult.result) {
+ return ExplainedResult.bad(verifyResult.reason);
+ }
+ let errorReason = null;
+
+ errorReason = errorReason || root.entityMgr.deserialize(savegame.entityMgr);
+ errorReason = errorReason || root.time.deserialize(savegame.time);
+ errorReason = errorReason || root.camera.deserialize(savegame.camera);
+ errorReason = errorReason || root.map.deserialize(savegame.map);
+ errorReason = errorReason || root.hubGoals.deserialize(savegame.hubGoals);
+ errorReason = errorReason || root.hud.parts.pinnedShapes.deserialize(savegame.pinnedShapes);
+ errorReason = errorReason || root.hud.parts.waypoints.deserialize(savegame.waypoints);
+ errorReason = errorReason || this.internal.deserializeEntityArray(root, savegame.entities);
+ errorReason = errorReason || root.systemMgr.systems.belt.deserializePaths(savegame.beltPaths);
+
+ // Check for errors
+ if (errorReason) {
+ return ExplainedResult.bad(errorReason);
+ }
+
+ return ExplainedResult.good();
+ }
+}
diff --git a/src/js/savegame/schemas/1006.js b/src/js/savegame/schemas/1006.js
new file mode 100644
index 00000000..422814c1
--- /dev/null
+++ b/src/js/savegame/schemas/1006.js
@@ -0,0 +1,285 @@
+import { gMetaBuildingRegistry } from "../../core/global_registries.js";
+import { createLogger } from "../../core/logging.js";
+import { MetaBeltBuilding } from "../../game/buildings/belt.js";
+import { enumCutterVariants, MetaCutterBuilding } from "../../game/buildings/cutter.js";
+import { MetaHubBuilding } from "../../game/buildings/hub.js";
+import { enumMinerVariants, MetaMinerBuilding } from "../../game/buildings/miner.js";
+import { MetaMixerBuilding } from "../../game/buildings/mixer.js";
+import { enumPainterVariants, MetaPainterBuilding } from "../../game/buildings/painter.js";
+import { enumRotaterVariants, MetaRotaterBuilding } from "../../game/buildings/rotater.js";
+import { enumBalancerVariants, MetaBalancerBuilding } from "../../game/buildings/balancer.js";
+import { MetaStackerBuilding } from "../../game/buildings/stacker.js";
+import { enumTrashVariants, MetaTrashBuilding } from "../../game/buildings/trash.js";
+import {
+ enumUndergroundBeltVariants,
+ MetaUndergroundBeltBuilding,
+} from "../../game/buildings/underground_belt.js";
+import { getCodeFromBuildingData } from "../../game/building_codes.js";
+import { StaticMapEntityComponent } from "../../game/components/static_map_entity.js";
+import { Entity } from "../../game/entity.js";
+import { defaultBuildingVariant, MetaBuilding } from "../../game/meta_building.js";
+import { SavegameInterface_V1005 } from "./1005.js";
+
+const schema = require("./1006.json");
+const logger = createLogger("savegame_interface/1006");
+
+/**
+ *
+ * @param {typeof MetaBuilding} metaBuilding
+ * @param {string=} variant
+ * @param {number=} rotationVariant
+ */
+function findCode(metaBuilding, variant = defaultBuildingVariant, rotationVariant = 0) {
+ return getCodeFromBuildingData(gMetaBuildingRegistry.findByClass(metaBuilding), variant, rotationVariant);
+}
+
+/**
+ * Rebalances a value from the old balancing to the new one
+ * @param {number} value
+ * @returns {number}
+ */
+function rebalance(value) {
+ return Math.round(Math.pow(value, 0.75));
+}
+
+export class SavegameInterface_V1006 extends SavegameInterface_V1005 {
+ getVersion() {
+ return 1006;
+ }
+
+ getSchemaUncached() {
+ return schema;
+ }
+
+ static computeSpriteMapping() {
+ return {
+ // Belt
+ "sprites/blueprints/belt_top.png": findCode(MetaBeltBuilding, defaultBuildingVariant, 0),
+ "sprites/blueprints/belt_left.png": findCode(MetaBeltBuilding, defaultBuildingVariant, 1),
+ "sprites/blueprints/belt_right.png": findCode(MetaBeltBuilding, defaultBuildingVariant, 2),
+
+ // Splitter (=Balancer)
+ "sprites/blueprints/splitter.png": findCode(MetaBalancerBuilding),
+ "sprites/blueprints/splitter-compact.png": findCode(
+ MetaBalancerBuilding,
+ enumBalancerVariants.merger
+ ),
+ "sprites/blueprints/splitter-compact-inverse.png": findCode(
+ MetaBalancerBuilding,
+ enumBalancerVariants.mergerInverse
+ ),
+
+ // Underground belt
+ "sprites/blueprints/underground_belt_entry.png": findCode(
+ MetaUndergroundBeltBuilding,
+ defaultBuildingVariant,
+ 0
+ ),
+ "sprites/blueprints/underground_belt_exit.png": findCode(
+ MetaUndergroundBeltBuilding,
+ defaultBuildingVariant,
+ 1
+ ),
+
+ "sprites/blueprints/underground_belt_entry-tier2.png": findCode(
+ MetaUndergroundBeltBuilding,
+ enumUndergroundBeltVariants.tier2,
+ 0
+ ),
+ "sprites/blueprints/underground_belt_exit-tier2.png": findCode(
+ MetaUndergroundBeltBuilding,
+ enumUndergroundBeltVariants.tier2,
+ 1
+ ),
+
+ // Miner
+ "sprites/blueprints/miner.png": findCode(MetaMinerBuilding),
+ "sprites/blueprints/miner-chainable.png": findCode(
+ MetaMinerBuilding,
+ enumMinerVariants.chainable,
+ 0
+ ),
+
+ // Cutter
+ "sprites/blueprints/cutter.png": findCode(MetaCutterBuilding),
+ "sprites/blueprints/cutter-quad.png": findCode(MetaCutterBuilding, enumCutterVariants.quad),
+
+ // Rotater
+ "sprites/blueprints/rotater.png": findCode(MetaRotaterBuilding),
+ "sprites/blueprints/rotater-ccw.png": findCode(MetaRotaterBuilding, enumRotaterVariants.ccw),
+
+ // Stacker
+ "sprites/blueprints/stacker.png": findCode(MetaStackerBuilding),
+
+ // Mixer
+ "sprites/blueprints/mixer.png": findCode(MetaMixerBuilding),
+
+ // Painter
+ "sprites/blueprints/painter.png": findCode(MetaPainterBuilding),
+ "sprites/blueprints/painter-mirrored.png": findCode(
+ MetaPainterBuilding,
+ enumPainterVariants.mirrored
+ ),
+ "sprites/blueprints/painter-double.png": findCode(
+ MetaPainterBuilding,
+ enumPainterVariants.double
+ ),
+ "sprites/blueprints/painter-quad.png": findCode(MetaPainterBuilding, enumPainterVariants.quad),
+
+ // Trash / Storage
+ "sprites/blueprints/trash.png": findCode(MetaTrashBuilding),
+ "sprites/blueprints/trash-storage.png": findCode(MetaTrashBuilding, enumTrashVariants.storage),
+ };
+ }
+
+ /**
+ * @param {import("../savegame_typedefs.js").SavegameData} data
+ */
+ static migrate1005to1006(data) {
+ logger.log("Migrating 1005 to 1006");
+ const dump = data.dump;
+ if (!dump) {
+ return true;
+ }
+
+ // Reduce stored shapes
+ const stored = dump.hubGoals.storedShapes;
+ for (const shapeKey in stored) {
+ stored[shapeKey] = rebalance(stored[shapeKey]);
+ }
+
+ // Reduce goals
+ if (dump.hubGoals.currentGoal) {
+ dump.hubGoals.currentGoal.required = rebalance(dump.hubGoals.currentGoal.required);
+ }
+
+ // Update entities
+ const entities = dump.entities;
+ for (let i = 0; i < entities.length; ++i) {
+ const entity = entities[i];
+ const components = entity.components;
+ this.migrateStaticComp1005to1006(entity);
+
+ // HUB
+ if (components.Hub) {
+ // @ts-ignore
+ components.Hub = {};
+ }
+
+ // Item Processor
+ if (components.ItemProcessor) {
+ // @ts-ignore
+ components.ItemProcessor = {
+ nextOutputSlot: 0,
+ };
+ }
+
+ // OLD: Unremovable component
+ // @ts-ignore
+ if (components.Unremovable) {
+ // @ts-ignore
+ delete components.Unremovable;
+ }
+
+ // OLD: ReplaceableMapEntity
+ // @ts-ignore
+ if (components.ReplaceableMapEntity) {
+ // @ts-ignore
+ delete components.ReplaceableMapEntity;
+ }
+
+ // ItemAcceptor
+ if (components.ItemAcceptor) {
+ // @ts-ignore
+ components.ItemAcceptor = {};
+ }
+
+ // Belt
+ if (components.Belt) {
+ // @ts-ignore
+ components.Belt = {};
+ }
+
+ // Item Ejector
+ if (components.ItemEjector) {
+ // @ts-ignore
+ components.ItemEjector = {
+ slots: [],
+ };
+ }
+
+ // UndergroundBelt
+ if (components.UndergroundBelt) {
+ // @ts-ignore
+ components.UndergroundBelt = {
+ pendingItems: [],
+ };
+ }
+
+ // Miner
+ if (components.Miner) {
+ // @ts-ignore
+ delete components.Miner.chainable;
+
+ components.Miner.lastMiningTime = 0;
+ components.Miner.itemChainBuffer = [];
+ }
+
+ // Storage
+ if (components.Storage) {
+ // @ts-ignore
+ components.Storage = {
+ storedCount: 0,
+ storedItem: null,
+ };
+ }
+ }
+ }
+
+ /**
+ *
+ * @param {Entity} entity
+ */
+ static migrateStaticComp1005to1006(entity) {
+ const spriteMapping = this.computeSpriteMapping();
+ const staticComp = entity.components.StaticMapEntity;
+
+ /** @type {StaticMapEntityComponent} */
+ const newStaticComp = {};
+ newStaticComp.origin = staticComp.origin;
+ newStaticComp.originalRotation = staticComp.originalRotation;
+ newStaticComp.rotation = staticComp.rotation;
+
+ // @ts-ignore
+ newStaticComp.code = spriteMapping[staticComp.blueprintSpriteKey];
+
+ // Hub special case
+ if (entity.components.Hub) {
+ newStaticComp.code = findCode(MetaHubBuilding);
+ }
+
+ // Belt special case
+ if (entity.components.Belt) {
+ const actualCode = {
+ top: findCode(MetaBeltBuilding, defaultBuildingVariant, 0),
+ left: findCode(MetaBeltBuilding, defaultBuildingVariant, 1),
+ right: findCode(MetaBeltBuilding, defaultBuildingVariant, 2),
+ }[entity.components.Belt.direction];
+ if (actualCode !== newStaticComp.code) {
+ if (G_IS_DEV) {
+ console.warn("Belt mismatch");
+ }
+ newStaticComp.code = actualCode;
+ }
+ }
+
+ if (!newStaticComp.code) {
+ throw new Error(
+ // @ts-ignore
+ "1006 Migration: Could not reconstruct code for " + staticComp.blueprintSpriteKey
+ );
+ }
+
+ entity.components.StaticMapEntity = newStaticComp;
+ }
+}
diff --git a/src/js/savegame/schemas/1006.json b/src/js/savegame/schemas/1006.json
new file mode 100644
index 00000000..b0916986
--- /dev/null
+++ b/src/js/savegame/schemas/1006.json
@@ -0,0 +1,5 @@
+{
+ "type": "object",
+ "required": [],
+ "additionalProperties": true
+}
diff --git a/src/js/savegame/serializer_internal.js b/src/js/savegame/serializer_internal.js
index 6e5dfbc2..fa02a437 100644
--- a/src/js/savegame/serializer_internal.js
+++ b/src/js/savegame/serializer_internal.js
@@ -1,3 +1,4 @@
+import { globalConfig } from "../core/config";
import { createLogger } from "../core/logging";
import { Vector } from "../core/vector";
import { getBuildingDataFromCode } from "../game/building_codes";
@@ -78,7 +79,9 @@ export class SerializerInternal {
deserializeComponents(root, entity, data) {
for (const componentId in data) {
if (!entity.components[componentId]) {
- logger.warn("Entity no longer has component:", componentId);
+ if (G_IS_DEV && !globalConfig.debug.disableSlowAsserts) {
+ logger.warn("Entity no longer has component:", componentId);
+ }
continue;
}
diff --git a/src/js/states/ingame.js b/src/js/states/ingame.js
index 3eea38b7..2dd2db76 100644
--- a/src/js/states/ingame.js
+++ b/src/js/states/ingame.js
@@ -1,438 +1,458 @@
-import { APPLICATION_ERROR_OCCURED } from "../core/error_handler";
-import { GameState } from "../core/game_state";
-import { logSection, createLogger } from "../core/logging";
-import { waitNextFrame } from "../core/utils";
-import { globalConfig } from "../core/config";
-import { GameLoadingOverlay } from "../game/game_loading_overlay";
-import { KeyActionMapper } from "../game/key_action_mapper";
-import { Savegame } from "../savegame/savegame";
-import { GameCore } from "../game/core";
-import { MUSIC } from "../platform/sound";
-
-const logger = createLogger("state/ingame");
-
-// Different sub-states
-const stages = {
- s3_createCore: "🌈 3: Create core",
- s4_A_initEmptyGame: "🌈 4/A: Init empty game",
- s4_B_resumeGame: "🌈 4/B: Resume game",
-
- s5_firstUpdate: "🌈 5: First game update",
- s6_postLoadHook: "🌈 6: Post load hook",
- s7_warmup: "🌈 7: Warmup",
-
- s10_gameRunning: "🌈 10: Game finally running",
-
- leaving: "🌈 Saving, then leaving the game",
- destroyed: "🌈 DESTROYED: Core is empty and waits for state leave",
- initFailed: "🌈 ERROR: Initialization failed!",
-};
-
-export const gameCreationAction = {
- new: "new-game",
- resume: "resume-game",
-};
-
-// Typehints
-export class GameCreationPayload {
- constructor() {
- /** @type {boolean|undefined} */
- this.fastEnter;
-
- /** @type {Savegame} */
- this.savegame;
- }
-}
-
-export class InGameState extends GameState {
- constructor() {
- super("InGameState");
-
- /** @type {GameCreationPayload} */
- this.creationPayload = null;
-
- // Stores current stage
- this.stage = "";
-
- /** @type {GameCore} */
- this.core = null;
-
- /** @type {KeyActionMapper} */
- this.keyActionMapper = null;
-
- /** @type {GameLoadingOverlay} */
- this.loadingOverlay = null;
-
- /** @type {Savegame} */
- this.savegame;
-
- this.boundInputFilter = this.filterInput.bind(this);
- }
-
- /**
- * Switches the game into another sub-state
- * @param {string} stage
- */
- switchStage(stage) {
- assert(stage, "Got empty stage");
- if (stage !== this.stage) {
- this.stage = stage;
- logger.log(this.stage);
- return true;
- } else {
- // log(this, "Re entering", stage);
- return false;
- }
- }
-
- // GameState implementation
- getInnerHTML() {
- return "";
- }
-
- getThemeMusic() {
- return MUSIC.theme;
- }
-
- onBeforeExit() {
- // logger.log("Saving before quitting");
- // return this.doSave().then(() => {
- // logger.log(this, "Successfully saved");
- // // this.stageDestroyed();
- // });
- }
-
- onAppPause() {
- // if (this.stage === stages.s10_gameRunning) {
- // logger.log("Saving because app got paused");
- // this.doSave();
- // }
- }
-
- getHasFadeIn() {
- return false;
- }
-
- getPauseOnFocusLost() {
- return false;
- }
-
- getHasUnloadConfirmation() {
- return true;
- }
-
- onLeave() {
- if (this.core) {
- this.stageDestroyed();
- }
- this.app.inputMgr.dismountFilter(this.boundInputFilter);
- }
-
- onResized(w, h) {
- super.onResized(w, h);
- if (this.stage === stages.s10_gameRunning) {
- this.core.resize(w, h);
- }
- }
-
- // ---- End of GameState implementation
-
- /**
- * Goes back to the menu state
- */
- goBackToMenu() {
- this.saveThenGoToState("MainMenuState");
- }
-
- /**
- * Goes back to the settings state
- */
- goToSettings() {
- this.saveThenGoToState("SettingsState", {
- backToStateId: this.key,
- backToStatePayload: this.creationPayload,
- });
- }
-
- /**
- * Goes back to the settings state
- */
- goToKeybindings() {
- this.saveThenGoToState("KeybindingsState", {
- backToStateId: this.key,
- backToStatePayload: this.creationPayload,
- });
- }
-
- /**
- * Moves to a state outside of the game
- * @param {string} stateId
- * @param {any=} payload
- */
- saveThenGoToState(stateId, payload) {
- if (this.stage === stages.leaving || this.stage === stages.destroyed) {
- logger.warn(
- "Tried to leave game twice or during destroy:",
- this.stage,
- "(attempted to move to",
- stateId,
- ")"
- );
- return;
- }
- this.stageLeavingGame();
- this.doSave().then(() => {
- this.stageDestroyed();
- this.moveToState(stateId, payload);
- });
- }
-
- onBackButton() {
- // do nothing
- }
-
- /**
- * Called when the game somehow failed to initialize. Resets everything to basic state and
- * then goes to the main menu, showing the error
- * @param {string} err
- */
- onInitializationFailure(err) {
- if (this.switchStage(stages.initFailed)) {
- logger.error("Init failure:", err);
- this.stageDestroyed();
- this.moveToState("MainMenuState", { loadError: err });
- }
- }
-
- // STAGES
-
- /**
- * Creates the game core instance, and thus the root
- */
- stage3CreateCore() {
- if (this.switchStage(stages.s3_createCore)) {
- logger.log("Creating new game core");
- this.core = new GameCore(this.app);
-
- this.core.initializeRoot(this, this.savegame);
-
- if (this.savegame.hasGameDump()) {
- this.stage4bResumeGame();
- } else {
- this.app.gameAnalytics.handleGameStarted();
- this.stage4aInitEmptyGame();
- }
- }
- }
-
- /**
- * Initializes a new empty game
- */
- stage4aInitEmptyGame() {
- if (this.switchStage(stages.s4_A_initEmptyGame)) {
- this.core.initNewGame();
- this.stage5FirstUpdate();
- }
- }
-
- /**
- * Resumes an existing game
- */
- stage4bResumeGame() {
- if (this.switchStage(stages.s4_B_resumeGame)) {
- if (!this.core.initExistingGame()) {
- this.onInitializationFailure("Savegame is corrupt and can not be restored.");
- return;
- }
- this.app.gameAnalytics.handleGameResumed();
- this.stage5FirstUpdate();
- }
- }
-
- /**
- * Performs the first game update on the game which initializes most caches
- */
- stage5FirstUpdate() {
- if (this.switchStage(stages.s5_firstUpdate)) {
- this.core.root.logicInitialized = true;
- this.core.updateLogic();
- this.stage6PostLoadHook();
- }
- }
-
- /**
- * Call the post load hook, this means that we have loaded the game, and all systems
- * can operate and start to work now.
- */
- stage6PostLoadHook() {
- if (this.switchStage(stages.s6_postLoadHook)) {
- logger.log("Post load hook");
- this.core.postLoadHook();
- this.stage7Warmup();
- }
- }
-
- /**
- * This makes the game idle and draw for a while, because we run most code this way
- * the V8 engine can already start to optimize it. Also this makes sure the resources
- * are in the VRAM and we have a smooth experience once we start.
- */
- stage7Warmup() {
- if (this.switchStage(stages.s7_warmup)) {
- if (G_IS_DEV && globalConfig.debug.noArtificialDelays) {
- this.warmupTimeSeconds = 0.05;
- } else {
- if (this.creationPayload.fastEnter) {
- this.warmupTimeSeconds = globalConfig.warmupTimeSecondsFast;
- } else {
- this.warmupTimeSeconds = globalConfig.warmupTimeSecondsRegular;
- }
- }
- }
- }
-
- /**
- * The final stage where this game is running and updating regulary.
- */
- stage10GameRunning() {
- if (this.switchStage(stages.s10_gameRunning)) {
- this.core.root.signals.readyToRender.dispatch();
-
- logSection("GAME STARTED", "#26a69a");
-
- // Initial resize, might have changed during loading (this is possible)
- this.core.resize(this.app.screenWidth, this.app.screenHeight);
- }
- }
-
- /**
- * This stage destroys the whole game, used to cleanup
- */
- stageDestroyed() {
- if (this.switchStage(stages.destroyed)) {
- // Cleanup all api calls
- this.cancelAllAsyncOperations();
-
- if (this.syncer) {
- this.syncer.cancelSync();
- this.syncer = null;
- }
-
- // Cleanup core
- if (this.core) {
- this.core.destruct();
- this.core = null;
- }
- }
- }
-
- /**
- * When leaving the game
- */
- stageLeavingGame() {
- if (this.switchStage(stages.leaving)) {
- // ...
- }
- }
-
- // END STAGES
-
- /**
- * Filters the input (keybindings)
- */
- filterInput() {
- return this.stage === stages.s10_gameRunning;
- }
-
- /**
- * @param {GameCreationPayload} payload
- */
- onEnter(payload) {
- this.app.inputMgr.installFilter(this.boundInputFilter);
-
- this.creationPayload = payload;
- this.savegame = payload.savegame;
-
- this.loadingOverlay = new GameLoadingOverlay(this.app, this.getDivElement());
- this.loadingOverlay.showBasic();
-
- // Remove unneded default element
- document.body.querySelector(".modalDialogParent").remove();
-
- this.asyncChannel.watch(waitNextFrame()).then(() => this.stage3CreateCore());
- }
-
- /**
- * Render callback
- * @param {number} dt
- */
- onRender(dt) {
- if (APPLICATION_ERROR_OCCURED) {
- // Application somehow crashed, do not do anything
- return;
- }
-
- if (this.stage === stages.s7_warmup) {
- this.core.draw();
- this.warmupTimeSeconds -= dt / 1000.0;
- if (this.warmupTimeSeconds < 0) {
- logger.log("Warmup completed");
- this.stage10GameRunning();
- }
- }
-
- if (this.stage === stages.s10_gameRunning) {
- this.core.tick(dt);
- }
-
- // If the stage is still active (This might not be the case if tick() moved us to game over)
- if (this.stage === stages.s10_gameRunning) {
- // Only draw if page visible
- if (this.app.pageVisible) {
- this.core.draw();
- }
-
- this.loadingOverlay.removeIfAttached();
- } else {
- if (!this.loadingOverlay.isAttached()) {
- this.loadingOverlay.showBasic();
- }
- }
- }
-
- onBackgroundTick(dt) {
- this.onRender(dt);
- }
-
- /**
- * Saves the game
- */
-
- doSave() {
- if (!this.savegame || !this.savegame.isSaveable()) {
- return Promise.resolve();
- }
-
- if (APPLICATION_ERROR_OCCURED) {
- logger.warn("skipping save because application crashed");
- return Promise.resolve();
- }
-
- if (
- this.stage !== stages.s10_gameRunning &&
- this.stage !== stages.s7_warmup &&
- this.stage !== stages.leaving
- ) {
- logger.warn("Skipping save because game is not ready");
- return Promise.resolve();
- }
-
- // First update the game data
- logger.log("Starting to save game ...");
- this.core.root.signals.gameSaved.dispatch();
- this.savegame.updateData(this.core.root);
- return this.savegame.writeSavegameAndMetadata().catch(err => {
- logger.warn("Failed to save:", err);
- });
- }
-}
+import { APPLICATION_ERROR_OCCURED } from "../core/error_handler";
+import { GameState } from "../core/game_state";
+import { logSection, createLogger } from "../core/logging";
+import { waitNextFrame } from "../core/utils";
+import { globalConfig } from "../core/config";
+import { GameLoadingOverlay } from "../game/game_loading_overlay";
+import { KeyActionMapper } from "../game/key_action_mapper";
+import { Savegame } from "../savegame/savegame";
+import { GameCore } from "../game/core";
+import { MUSIC } from "../platform/sound";
+
+const logger = createLogger("state/ingame");
+
+// Different sub-states
+const stages = {
+ s3_createCore: "🌈 3: Create core",
+ s4_A_initEmptyGame: "🌈 4/A: Init empty game",
+ s4_B_resumeGame: "🌈 4/B: Resume game",
+
+ s5_firstUpdate: "🌈 5: First game update",
+ s6_postLoadHook: "🌈 6: Post load hook",
+ s7_warmup: "🌈 7: Warmup",
+
+ s10_gameRunning: "🌈 10: Game finally running",
+
+ leaving: "🌈 Saving, then leaving the game",
+ destroyed: "🌈 DESTROYED: Core is empty and waits for state leave",
+ initFailed: "🌈 ERROR: Initialization failed!",
+};
+
+export const gameCreationAction = {
+ new: "new-game",
+ resume: "resume-game",
+};
+
+// Typehints
+export class GameCreationPayload {
+ constructor() {
+ /** @type {boolean|undefined} */
+ this.fastEnter;
+
+ /** @type {Savegame} */
+ this.savegame;
+ }
+}
+
+export class InGameState extends GameState {
+ constructor() {
+ super("InGameState");
+
+ /** @type {GameCreationPayload} */
+ this.creationPayload = null;
+
+ // Stores current stage
+ this.stage = "";
+
+ /** @type {GameCore} */
+ this.core = null;
+
+ /** @type {KeyActionMapper} */
+ this.keyActionMapper = null;
+
+ /** @type {GameLoadingOverlay} */
+ this.loadingOverlay = null;
+
+ /** @type {Savegame} */
+ this.savegame = null;
+
+ this.boundInputFilter = this.filterInput.bind(this);
+
+ /**
+ * Whether we are currently saving the game
+ * @TODO: This doesn't realy fit here
+ */
+ this.currentSavePromise = null;
+ }
+
+ /**
+ * Switches the game into another sub-state
+ * @param {string} stage
+ */
+ switchStage(stage) {
+ assert(stage, "Got empty stage");
+ if (stage !== this.stage) {
+ this.stage = stage;
+ logger.log(this.stage);
+ return true;
+ } else {
+ // log(this, "Re entering", stage);
+ return false;
+ }
+ }
+
+ // GameState implementation
+ getInnerHTML() {
+ return "";
+ }
+
+ getThemeMusic() {
+ return MUSIC.theme;
+ }
+
+ onBeforeExit() {
+ // logger.log("Saving before quitting");
+ // return this.doSave().then(() => {
+ // logger.log(this, "Successfully saved");
+ // // this.stageDestroyed();
+ // });
+ }
+
+ onAppPause() {
+ // if (this.stage === stages.s10_gameRunning) {
+ // logger.log("Saving because app got paused");
+ // this.doSave();
+ // }
+ }
+
+ getHasFadeIn() {
+ return false;
+ }
+
+ getPauseOnFocusLost() {
+ return false;
+ }
+
+ getHasUnloadConfirmation() {
+ return true;
+ }
+
+ onLeave() {
+ if (this.core) {
+ this.stageDestroyed();
+ }
+ this.app.inputMgr.dismountFilter(this.boundInputFilter);
+ }
+
+ onResized(w, h) {
+ super.onResized(w, h);
+ if (this.stage === stages.s10_gameRunning) {
+ this.core.resize(w, h);
+ }
+ }
+
+ // ---- End of GameState implementation
+
+ /**
+ * Goes back to the menu state
+ */
+ goBackToMenu() {
+ this.saveThenGoToState("MainMenuState");
+ }
+
+ /**
+ * Goes back to the settings state
+ */
+ goToSettings() {
+ this.saveThenGoToState("SettingsState", {
+ backToStateId: this.key,
+ backToStatePayload: this.creationPayload,
+ });
+ }
+
+ /**
+ * Goes back to the settings state
+ */
+ goToKeybindings() {
+ this.saveThenGoToState("KeybindingsState", {
+ backToStateId: this.key,
+ backToStatePayload: this.creationPayload,
+ });
+ }
+
+ /**
+ * Moves to a state outside of the game
+ * @param {string} stateId
+ * @param {any=} payload
+ */
+ saveThenGoToState(stateId, payload) {
+ if (this.stage === stages.leaving || this.stage === stages.destroyed) {
+ logger.warn(
+ "Tried to leave game twice or during destroy:",
+ this.stage,
+ "(attempted to move to",
+ stateId,
+ ")"
+ );
+ return;
+ }
+ this.stageLeavingGame();
+ this.doSave().then(() => {
+ this.stageDestroyed();
+ this.moveToState(stateId, payload);
+ });
+ }
+
+ onBackButton() {
+ // do nothing
+ }
+
+ /**
+ * Called when the game somehow failed to initialize. Resets everything to basic state and
+ * then goes to the main menu, showing the error
+ * @param {string} err
+ */
+ onInitializationFailure(err) {
+ if (this.switchStage(stages.initFailed)) {
+ logger.error("Init failure:", err);
+ this.stageDestroyed();
+ this.moveToState("MainMenuState", { loadError: err });
+ }
+ }
+
+ // STAGES
+
+ /**
+ * Creates the game core instance, and thus the root
+ */
+ stage3CreateCore() {
+ if (this.switchStage(stages.s3_createCore)) {
+ logger.log("Creating new game core");
+ this.core = new GameCore(this.app);
+
+ this.core.initializeRoot(this, this.savegame);
+
+ if (this.savegame.hasGameDump()) {
+ this.stage4bResumeGame();
+ } else {
+ this.app.gameAnalytics.handleGameStarted();
+ this.stage4aInitEmptyGame();
+ }
+ }
+ }
+
+ /**
+ * Initializes a new empty game
+ */
+ stage4aInitEmptyGame() {
+ if (this.switchStage(stages.s4_A_initEmptyGame)) {
+ this.core.initNewGame();
+ this.stage5FirstUpdate();
+ }
+ }
+
+ /**
+ * Resumes an existing game
+ */
+ stage4bResumeGame() {
+ if (this.switchStage(stages.s4_B_resumeGame)) {
+ if (!this.core.initExistingGame()) {
+ this.onInitializationFailure("Savegame is corrupt and can not be restored.");
+ return;
+ }
+ this.app.gameAnalytics.handleGameResumed();
+ this.stage5FirstUpdate();
+ }
+ }
+
+ /**
+ * Performs the first game update on the game which initializes most caches
+ */
+ stage5FirstUpdate() {
+ if (this.switchStage(stages.s5_firstUpdate)) {
+ this.core.root.logicInitialized = true;
+ this.core.updateLogic();
+ this.stage6PostLoadHook();
+ }
+ }
+
+ /**
+ * Call the post load hook, this means that we have loaded the game, and all systems
+ * can operate and start to work now.
+ */
+ stage6PostLoadHook() {
+ if (this.switchStage(stages.s6_postLoadHook)) {
+ logger.log("Post load hook");
+ this.core.postLoadHook();
+ this.stage7Warmup();
+ }
+ }
+
+ /**
+ * This makes the game idle and draw for a while, because we run most code this way
+ * the V8 engine can already start to optimize it. Also this makes sure the resources
+ * are in the VRAM and we have a smooth experience once we start.
+ */
+ stage7Warmup() {
+ if (this.switchStage(stages.s7_warmup)) {
+ if (G_IS_DEV && globalConfig.debug.noArtificialDelays) {
+ this.warmupTimeSeconds = 0.05;
+ } else {
+ if (this.creationPayload.fastEnter) {
+ this.warmupTimeSeconds = globalConfig.warmupTimeSecondsFast;
+ } else {
+ this.warmupTimeSeconds = globalConfig.warmupTimeSecondsRegular;
+ }
+ }
+ }
+ }
+
+ /**
+ * The final stage where this game is running and updating regulary.
+ */
+ stage10GameRunning() {
+ if (this.switchStage(stages.s10_gameRunning)) {
+ this.core.root.signals.readyToRender.dispatch();
+
+ logSection("GAME STARTED", "#26a69a");
+
+ // Initial resize, might have changed during loading (this is possible)
+ this.core.resize(this.app.screenWidth, this.app.screenHeight);
+ }
+ }
+
+ /**
+ * This stage destroys the whole game, used to cleanup
+ */
+ stageDestroyed() {
+ if (this.switchStage(stages.destroyed)) {
+ // Cleanup all api calls
+ this.cancelAllAsyncOperations();
+
+ if (this.syncer) {
+ this.syncer.cancelSync();
+ this.syncer = null;
+ }
+
+ // Cleanup core
+ if (this.core) {
+ this.core.destruct();
+ this.core = null;
+ }
+ }
+ }
+
+ /**
+ * When leaving the game
+ */
+ stageLeavingGame() {
+ if (this.switchStage(stages.leaving)) {
+ // ...
+ }
+ }
+
+ // END STAGES
+
+ /**
+ * Filters the input (keybindings)
+ */
+ filterInput() {
+ return this.stage === stages.s10_gameRunning;
+ }
+
+ /**
+ * @param {GameCreationPayload} payload
+ */
+ onEnter(payload) {
+ this.app.inputMgr.installFilter(this.boundInputFilter);
+
+ this.creationPayload = payload;
+ this.savegame = payload.savegame;
+
+ this.loadingOverlay = new GameLoadingOverlay(this.app, this.getDivElement());
+ this.loadingOverlay.showBasic();
+
+ // Remove unneded default element
+ document.body.querySelector(".modalDialogParent").remove();
+
+ this.asyncChannel.watch(waitNextFrame()).then(() => this.stage3CreateCore());
+ }
+
+ /**
+ * Render callback
+ * @param {number} dt
+ */
+ onRender(dt) {
+ if (APPLICATION_ERROR_OCCURED) {
+ // Application somehow crashed, do not do anything
+ return;
+ }
+
+ if (this.stage === stages.s7_warmup) {
+ this.core.draw();
+ this.warmupTimeSeconds -= dt / 1000.0;
+ if (this.warmupTimeSeconds < 0) {
+ logger.log("Warmup completed");
+ this.stage10GameRunning();
+ }
+ }
+
+ if (this.stage === stages.s10_gameRunning) {
+ this.core.tick(dt);
+ }
+
+ // If the stage is still active (This might not be the case if tick() moved us to game over)
+ if (this.stage === stages.s10_gameRunning) {
+ // Only draw if page visible
+ if (this.app.pageVisible) {
+ this.core.draw();
+ }
+
+ this.loadingOverlay.removeIfAttached();
+ } else {
+ if (!this.loadingOverlay.isAttached()) {
+ this.loadingOverlay.showBasic();
+ }
+ }
+ }
+
+ onBackgroundTick(dt) {
+ this.onRender(dt);
+ }
+
+ /**
+ * Saves the game
+ */
+
+ doSave() {
+ if (!this.savegame || !this.savegame.isSaveable()) {
+ return Promise.resolve();
+ }
+
+ if (APPLICATION_ERROR_OCCURED) {
+ logger.warn("skipping save because application crashed");
+ return Promise.resolve();
+ }
+
+ if (
+ this.stage !== stages.s10_gameRunning &&
+ this.stage !== stages.s7_warmup &&
+ this.stage !== stages.leaving
+ ) {
+ logger.warn("Skipping save because game is not ready");
+ return Promise.resolve();
+ }
+
+ if (this.currentSavePromise) {
+ logger.warn("Skipping double save and returning same promise");
+ return this.currentSavePromise;
+ }
+ logger.log("Starting to save game ...");
+ this.savegame.updateData(this.core.root);
+
+ this.currentSavePromise = this.savegame
+ .writeSavegameAndMetadata()
+ .catch(err => {
+ // Catch errors
+ logger.warn("Failed to save:", err);
+ })
+ .then(() => {
+ // Clear promise
+ logger.log("Saved!");
+ this.core.root.signals.gameSaved.dispatch();
+ this.currentSavePromise = null;
+ });
+
+ return this.currentSavePromise;
+ }
+}
diff --git a/src/js/states/main_menu.js b/src/js/states/main_menu.js
index bea209a8..02c1e690 100644
--- a/src/js/states/main_menu.js
+++ b/src/js/states/main_menu.js
@@ -17,6 +17,8 @@ import { getApplicationSettingById } from "../profile/application_settings";
import { FormElementInput } from "../core/modal_dialog_forms";
import { DialogWithForm } from "../core/modal_dialog_elements";
+const trim = require("trim");
+
/**
* @typedef {import("../savegame/savegame_typedefs").SavegameMetadata} SavegameMetadata
* @typedef {import("../profile/setting_types").EnumSetting} EnumSetting
@@ -133,7 +135,7 @@ export class MainMenuState extends GameState {
!this.app.platformWrapper.getHasUnlimitedSavegames()
) {
this.app.analytics.trackUiClick("importgame_slot_limit_show");
- this.dialogs.showWarning(T.dialogs.oneSavegameLimit.title, T.dialogs.oneSavegameLimit.desc);
+ this.showSavegameSlotLimit();
return;
}
@@ -436,7 +438,7 @@ export class MainMenuState extends GameState {
label: null,
placeholder: "",
defaultValue: game.name || "",
- validator: val => val.match(regex),
+ validator: val => val.match(regex) && trim(val).length > 0,
});
const dialog = new DialogWithForm({
app: this.app,
@@ -449,7 +451,7 @@ export class MainMenuState extends GameState {
// When confirmed, save the name
dialog.buttonSignals.ok.add(() => {
- game.name = nameInput.getValue();
+ game.name = trim(nameInput.getValue());
this.app.savegameMgr.writeAsync();
this.renderSavegames();
});
@@ -488,8 +490,10 @@ export class MainMenuState extends GameState {
const signals = this.dialogs.showWarning(
T.dialogs.confirmSavegameDelete.title,
- T.dialogs.confirmSavegameDelete.text,
- ["delete:bad", "cancel:good"]
+ T.dialogs.confirmSavegameDelete.text
+ .replace("", game.name || T.mainMenu.savegameUnnamed)
+ .replace("", String(game.level)),
+ ["cancel:good", "delete:bad:timeout"]
);
signals.delete.add(() => {
@@ -522,6 +526,21 @@ export class MainMenuState extends GameState {
});
}
+ /**
+ * Shows a hint that the slot limit has been reached
+ */
+ showSavegameSlotLimit() {
+ const { getStandalone } = this.dialogs.showWarning(
+ T.dialogs.oneSavegameLimit.title,
+ T.dialogs.oneSavegameLimit.desc,
+ ["cancel:bad", "getStandalone:good"]
+ );
+ getStandalone.add(() => {
+ this.app.analytics.trackUiClick("visit_steampage_from_slot_limit");
+ this.app.platformWrapper.openExternalLink(THIRDPARTY_URLS.standaloneStorePage);
+ });
+ }
+
onSettingsButtonClicked() {
this.moveToState("SettingsState");
}
@@ -540,7 +559,7 @@ export class MainMenuState extends GameState {
!this.app.platformWrapper.getHasUnlimitedSavegames()
) {
this.app.analytics.trackUiClick("startgame_slot_limit_show");
- this.dialogs.showWarning(T.dialogs.oneSavegameLimit.title, T.dialogs.oneSavegameLimit.desc);
+ this.showSavegameSlotLimit();
return;
}
diff --git a/src/js/states/preload.js b/src/js/states/preload.js
index 0f47e8d6..b35b369d 100644
--- a/src/js/states/preload.js
+++ b/src/js/states/preload.js
@@ -1,293 +1,331 @@
-import { GameState } from "../core/game_state";
-import { createLogger } from "../core/logging";
-import { findNiceValue } from "../core/utils";
-import { cachebust } from "../core/cachebust";
-import { PlatformWrapperImplBrowser } from "../platform/browser/wrapper";
-import { T, autoDetectLanguageId, updateApplicationLanguage } from "../translations";
-import { HUDModalDialogs } from "../game/hud/parts/modal_dialogs";
-import { CHANGELOG } from "../changelog";
-import { globalConfig } from "../core/config";
-
-const logger = createLogger("state/preload");
-
-export class PreloadState extends GameState {
- constructor() {
- super("PreloadState");
- }
-
- getInnerHTML() {
- return `
-
-
- Booting
-
-
- 0%
-
-
-
- `;
- }
-
- getThemeMusic() {
- return null;
- }
-
- getHasFadeIn() {
- return false;
- }
-
- onEnter() {
- this.htmlElement.classList.add("prefab_LoadingState");
-
- const elementsToRemove = ["#loadingPreload", "#fontPreload"];
- for (let i = 0; i < elementsToRemove.length; ++i) {
- const elem = document.querySelector(elementsToRemove[i]);
- if (elem) {
- elem.remove();
- }
- }
-
- this.dialogs = new HUDModalDialogs(null, this.app);
- const dialogsElement = document.body.querySelector(".modalDialogParent");
- this.dialogs.initializeToElement(dialogsElement);
-
- /** @type {HTMLElement} */
- this.statusText = this.htmlElement.querySelector(".loadingStatus > .desc");
- /** @type {HTMLElement} */
- this.statusBar = this.htmlElement.querySelector(".loadingStatus > .bar > .inner");
- /** @type {HTMLElement} */
- this.statusBarText = this.htmlElement.querySelector(".loadingStatus > .bar > .status");
-
- this.currentStatus = "booting";
- this.currentIndex = 0;
-
- this.startLoading();
- }
-
- onLeave() {
- // this.dialogs.cleanup();
- }
-
- startLoading() {
- this.setStatus("Booting")
-
- .then(() => this.setStatus("Creating platform wrapper"))
- .then(() => this.app.platformWrapper.initialize())
-
- .then(() => this.setStatus("Initializing local storage"))
- .then(() => {
- const wrapper = this.app.platformWrapper;
- if (wrapper instanceof PlatformWrapperImplBrowser) {
- try {
- window.localStorage.setItem("local_storage_test", "1");
- window.localStorage.removeItem("local_storage_test");
- } catch (ex) {
- logger.error("Failed to read/write local storage:", ex);
- return new Promise(() => {
- alert(`Your brower does not support thirdparty cookies or you have disabled it in your security settings.\n\n
- In Chrome this setting is called "Block third-party cookies and site data".\n\n
- Please allow third party cookies and then reload the page.`);
- // Never return
- });
- }
- }
- })
-
- .then(() => this.setStatus("Creating storage"))
- .then(() => {
- return this.app.storage.initialize();
- })
-
- .then(() => this.setStatus("Initializing libraries"))
- .then(() => this.app.analytics.initialize())
- .then(() => this.app.gameAnalytics.initialize())
-
- .then(() => this.setStatus("Initializing settings"))
- .then(() => {
- return this.app.settings.initialize();
- })
-
- .then(() => {
- // Initialize fullscreen
- if (this.app.platformWrapper.getSupportsFullscreen()) {
- this.app.platformWrapper.setFullscreen(this.app.settings.getIsFullScreen());
- }
- })
-
- .then(() => this.setStatus("Initializing language"))
- .then(() => {
- if (this.app.settings.getLanguage() === "auto-detect") {
- const language = autoDetectLanguageId();
- logger.log("Setting language to", language);
- return this.app.settings.updateLanguage(language);
- }
- })
- .then(() => {
- const language = this.app.settings.getLanguage();
- updateApplicationLanguage(language);
- })
-
- .then(() => this.setStatus("Initializing sounds"))
- .then(() => {
- // Notice: We don't await the sounds loading itself
- return this.app.sound.initialize();
- })
-
- .then(() => {
- this.app.backgroundResourceLoader.startLoading();
- })
-
- .then(() => this.setStatus("Initializing savegame"))
- .then(() => {
- return this.app.savegameMgr.initialize().catch(err => {
- logger.error("Failed to initialize savegames:", err);
- alert(
- "Your savegames failed to load, it seems your data files got corrupted. I'm so sorry!\n\n(This can happen if your pc crashed while a game was saved).\n\nYou can try re-importing your savegames."
- );
- return this.app.savegameMgr.writeAsync();
- });
- })
-
- .then(() => this.setStatus("Downloading resources"))
- .then(() => {
- return this.app.backgroundResourceLoader.getPromiseForBareGame();
- })
-
- .then(() => this.setStatus("Checking changelog"))
- .then(() => {
- if (G_IS_DEV && globalConfig.debug.disableUpgradeNotification) {
- return;
- }
-
- return this.app.storage
- .readFileAsync("lastversion.bin")
- .catch(err => {
- logger.warn("Failed to read lastversion:", err);
- return G_BUILD_VERSION;
- })
- .then(version => {
- logger.log("Last version:", version, "App version:", G_BUILD_VERSION);
- this.app.storage.writeFileAsync("lastversion.bin", G_BUILD_VERSION);
- return version;
- })
- .then(version => {
- let changelogEntries = [];
- logger.log("Last seen version:", version);
-
- for (let i = 0; i < CHANGELOG.length; ++i) {
- if (CHANGELOG[i].version === version) {
- break;
- }
- changelogEntries.push(CHANGELOG[i]);
- }
- if (changelogEntries.length === 0) {
- return;
- }
-
- let dialogHtml = T.dialogs.updateSummary.desc;
- for (let i = 0; i < changelogEntries.length; ++i) {
- const entry = changelogEntries[i];
- dialogHtml += `
-
-
${entry.version}
-
${entry.date}
-
- ${entry.entries.map(text => `${text} `).join("")}
-
-
- `;
- }
-
- return new Promise(resolve => {
- this.dialogs.showInfo(T.dialogs.updateSummary.title, dialogHtml).ok.add(resolve);
- });
- });
- })
-
- .then(() => this.setStatus("Launching"))
- .then(
- () => {
- this.moveToState("MainMenuState");
- },
- err => {
- this.showFailMessage(err);
- }
- );
- }
-
- setStatus(text) {
- logger.log("✅ " + text);
- this.currentIndex += 1;
- this.currentStatus = text;
- this.statusText.innerText = text;
-
- const numSteps = 10; // FIXME
-
- const percentage = (this.currentIndex / numSteps) * 100.0;
- this.statusBar.style.width = percentage + "%";
- this.statusBarText.innerText = findNiceValue(percentage) + "%";
-
- return Promise.resolve();
- }
-
- showFailMessage(text) {
- logger.error("App init failed:", text);
-
- const email = "bugs@shapez.io";
-
- const subElement = document.createElement("div");
- subElement.classList.add("failureBox");
-
- subElement.innerHTML = `
-
-
-
-
-
-
- ${this.currentStatus} failed:
- ${text}
-
-
-
- Please send me an email with steps to reproduce and what you did before this happened:
-
${email}
-
-
-
- Reset App
- Build ${G_BUILD_VERSION} @ ${G_BUILD_COMMIT_HASH}
-
-
- `;
-
- this.htmlElement.classList.add("failure");
- this.htmlElement.appendChild(subElement);
-
- const resetBtn = subElement.querySelector("button.resetApp");
- this.trackClicks(resetBtn, this.showResetConfirm);
- }
-
- showResetConfirm() {
- if (confirm("Are you sure you want to reset the app? This will delete all your savegames")) {
- this.resetApp();
- }
- }
-
- resetApp() {
- this.app.settings
- .resetEverythingAsync()
- .then(() => {
- this.app.savegameMgr.resetEverythingAsync();
- })
- .then(() => {
- this.app.settings.resetEverythingAsync();
- })
- .then(() => {
- window.location.reload();
- });
- }
-}
+import { CHANGELOG } from "../changelog";
+import { cachebust } from "../core/cachebust";
+import { globalConfig } from "../core/config";
+import { GameState } from "../core/game_state";
+import { createLogger } from "../core/logging";
+import { findNiceValue } from "../core/utils";
+import { getRandomHint } from "../game/hints";
+import { HUDModalDialogs } from "../game/hud/parts/modal_dialogs";
+import { PlatformWrapperImplBrowser } from "../platform/browser/wrapper";
+import { autoDetectLanguageId, T, updateApplicationLanguage } from "../translations";
+
+const logger = createLogger("state/preload");
+
+export class PreloadState extends GameState {
+ constructor() {
+ super("PreloadState");
+ }
+
+ getInnerHTML() {
+ return `
+
+
+ Booting
+
+
+ 0%
+
+
+
+
+ `;
+ }
+
+ getThemeMusic() {
+ return null;
+ }
+
+ getHasFadeIn() {
+ return false;
+ }
+
+ onEnter() {
+ this.htmlElement.classList.add("prefab_LoadingState");
+
+ const elementsToRemove = ["#loadingPreload", "#fontPreload"];
+ for (let i = 0; i < elementsToRemove.length; ++i) {
+ const elem = document.querySelector(elementsToRemove[i]);
+ if (elem) {
+ elem.remove();
+ }
+ }
+
+ this.dialogs = new HUDModalDialogs(null, this.app);
+ const dialogsElement = document.body.querySelector(".modalDialogParent");
+ this.dialogs.initializeToElement(dialogsElement);
+
+ /** @type {HTMLElement} */
+ this.statusText = this.htmlElement.querySelector(".loadingStatus > .desc");
+ /** @type {HTMLElement} */
+ this.statusBar = this.htmlElement.querySelector(".loadingStatus > .bar > .inner");
+ /** @type {HTMLElement} */
+ this.statusBarText = this.htmlElement.querySelector(".loadingStatus > .bar > .status");
+
+ /** @type {HTMLElement} */
+ this.hintsText = this.htmlElement.querySelector(".prefab_GameHint");
+ this.lastHintShown = -1000;
+ this.nextHintDuration = 0;
+
+ this.currentStatus = "booting";
+ this.currentIndex = 0;
+
+ this.startLoading();
+ }
+
+ onLeave() {
+ // this.dialogs.cleanup();
+ }
+
+ startLoading() {
+ this.setStatus("Booting")
+
+ .then(() => this.setStatus("Creating platform wrapper"))
+ .then(() => this.app.platformWrapper.initialize())
+
+ .then(() => this.setStatus("Initializing local storage"))
+ .then(() => {
+ const wrapper = this.app.platformWrapper;
+ if (wrapper instanceof PlatformWrapperImplBrowser) {
+ try {
+ window.localStorage.setItem("local_storage_test", "1");
+ window.localStorage.removeItem("local_storage_test");
+ } catch (ex) {
+ logger.error("Failed to read/write local storage:", ex);
+ return new Promise(() => {
+ alert(`Your brower does not support thirdparty cookies or you have disabled it in your security settings.\n\n
+ In Chrome this setting is called "Block third-party cookies and site data".\n\n
+ Please allow third party cookies and then reload the page.`);
+ // Never return
+ });
+ }
+ }
+ })
+
+ .then(() => this.setStatus("Creating storage"))
+ .then(() => {
+ return this.app.storage.initialize();
+ })
+
+ .then(() => this.setStatus("Initializing libraries"))
+ .then(() => this.app.analytics.initialize())
+ .then(() => this.app.gameAnalytics.initialize())
+
+ .then(() => this.setStatus("Initializing settings"))
+ .then(() => {
+ return this.app.settings.initialize();
+ })
+
+ .then(() => {
+ // Initialize fullscreen
+ if (this.app.platformWrapper.getSupportsFullscreen()) {
+ this.app.platformWrapper.setFullscreen(this.app.settings.getIsFullScreen());
+ }
+ })
+
+ .then(() => this.setStatus("Initializing language"))
+ .then(() => {
+ if (this.app.settings.getLanguage() === "auto-detect") {
+ const language = autoDetectLanguageId();
+ logger.log("Setting language to", language);
+ return this.app.settings.updateLanguage(language);
+ }
+ })
+ .then(() => {
+ const language = this.app.settings.getLanguage();
+ updateApplicationLanguage(language);
+ })
+
+ .then(() => this.setStatus("Initializing sounds"))
+ .then(() => {
+ // Notice: We don't await the sounds loading itself
+ return this.app.sound.initialize();
+ })
+
+ .then(() => {
+ this.app.backgroundResourceLoader.startLoading();
+ })
+
+ .then(() => this.setStatus("Initializing savegame"))
+ .then(() => {
+ return this.app.savegameMgr.initialize().catch(err => {
+ logger.error("Failed to initialize savegames:", err);
+ alert(
+ "Your savegames failed to load, it seems your data files got corrupted. I'm so sorry!\n\n(This can happen if your pc crashed while a game was saved).\n\nYou can try re-importing your savegames."
+ );
+ return this.app.savegameMgr.writeAsync();
+ });
+ })
+
+ .then(() => this.setStatus("Downloading resources"))
+ .then(() => {
+ return this.app.backgroundResourceLoader.getPromiseForBareGame();
+ })
+
+ .then(() => this.setStatus("Checking changelog"))
+ .then(() => {
+ if (G_IS_DEV && globalConfig.debug.disableUpgradeNotification) {
+ return;
+ }
+
+ return this.app.storage
+ .readFileAsync("lastversion.bin")
+ .catch(err => {
+ logger.warn("Failed to read lastversion:", err);
+ return G_BUILD_VERSION;
+ })
+ .then(version => {
+ logger.log("Last version:", version, "App version:", G_BUILD_VERSION);
+ this.app.storage.writeFileAsync("lastversion.bin", G_BUILD_VERSION);
+ return version;
+ })
+ .then(version => {
+ let changelogEntries = [];
+ logger.log("Last seen version:", version);
+
+ for (let i = 0; i < CHANGELOG.length; ++i) {
+ if (CHANGELOG[i].version === version) {
+ break;
+ }
+ changelogEntries.push(CHANGELOG[i]);
+ }
+ if (changelogEntries.length === 0) {
+ return;
+ }
+
+ let dialogHtml = T.dialogs.updateSummary.desc;
+ for (let i = 0; i < changelogEntries.length; ++i) {
+ const entry = changelogEntries[i];
+ dialogHtml += `
+
+
${entry.version}
+
${entry.date}
+
+ ${entry.entries.map(text => `${text} `).join("")}
+
+
+ `;
+ }
+
+ return new Promise(resolve => {
+ this.dialogs.showInfo(T.dialogs.updateSummary.title, dialogHtml).ok.add(resolve);
+ });
+ });
+ })
+
+ .then(() => this.setStatus("Launching"))
+ .then(
+ () => {
+ this.moveToState("MainMenuState");
+ },
+ err => {
+ this.showFailMessage(err);
+ }
+ );
+ }
+
+ update() {
+ const now = performance.now();
+ if (now - this.lastHintShown > this.nextHintDuration) {
+ this.lastHintShown = now;
+ const hintText = getRandomHint();
+
+ this.hintsText.innerHTML = hintText;
+
+ /**
+ * Compute how long the user will need to read the hint.
+ * We calculate with 130 words per minute, with an average of 5 chars
+ * that is 650 characters / minute
+ */
+ this.nextHintDuration = Math.max(2500, (hintText.length / 650) * 60 * 1000);
+ }
+ }
+
+ onRender() {
+ this.update();
+ }
+
+ onBackgroundTick() {
+ this.update();
+ }
+
+ /**
+ *
+ * @param {string} text
+ */
+ setStatus(text) {
+ logger.log("✅ " + text);
+ this.currentIndex += 1;
+ this.currentStatus = text;
+ this.statusText.innerText = text;
+
+ const numSteps = 10; // FIXME
+
+ const percentage = (this.currentIndex / numSteps) * 100.0;
+ this.statusBar.style.width = percentage + "%";
+ this.statusBarText.innerText = findNiceValue(percentage) + "%";
+
+ return Promise.resolve();
+ }
+
+ showFailMessage(text) {
+ logger.error("App init failed:", text);
+
+ const email = "bugs@shapez.io";
+
+ const subElement = document.createElement("div");
+ subElement.classList.add("failureBox");
+
+ subElement.innerHTML = `
+
+
+
+
+
+
+ ${this.currentStatus} failed:
+ ${text}
+
+
+
+ Please send me an email with steps to reproduce and what you did before this happened:
+
${email}
+
+
+
+ Reset App
+ Build ${G_BUILD_VERSION} @ ${G_BUILD_COMMIT_HASH}
+
+
+ `;
+
+ this.htmlElement.classList.add("failure");
+ this.htmlElement.appendChild(subElement);
+
+ const resetBtn = subElement.querySelector("button.resetApp");
+ this.trackClicks(resetBtn, this.showResetConfirm);
+
+ this.hintsText.remove();
+ }
+
+ showResetConfirm() {
+ if (confirm("Are you sure you want to reset the app? This will delete all your savegames!")) {
+ this.resetApp();
+ }
+ }
+
+ resetApp() {
+ this.app.settings
+ .resetEverythingAsync()
+ .then(() => {
+ this.app.savegameMgr.resetEverythingAsync();
+ })
+ .then(() => {
+ this.app.settings.resetEverythingAsync();
+ })
+ .then(() => {
+ window.location.reload();
+ });
+ }
+}
diff --git a/translations/README.md b/translations/README.md
index 7695f022..596da8d8 100644
--- a/translations/README.md
+++ b/translations/README.md
@@ -1,80 +1,82 @@
-# Translations
-
-The base language is English and can be found [here](base-en.yaml).
-
-## Languages
-
-- [German](base-de.yaml)
-- [French](base-fr.yaml)
-- [Korean](base-kor.yaml)
-- [Dutch](base-nl.yaml)
-- [Polish](base-pl.yaml)
-- [Portuguese (Brazil)](base-pt-BR.yaml)
-- [Portuguese (Portugal)](base-pt-PT.yaml)
-- [Russian](base-ru.yaml)
-- [Greek](base-el.yaml)
-- [Italian](base-it.yaml)
-- [Romanian](base-ro.yaml)
-- [Swedish](base-sv.yaml)
-- [Chinese (Simplified)](base-zh-CN.yaml)
-- [Chinese (Traditional)](base-zh-TW.yaml)
-- [Spanish](base-es.yaml)
-- [Hungarian](base-hu.yaml)
-- [Turkish](base-tr.yaml)
-- [Japanese](base-ja.yaml)
-- [Lithuanian](base-lt.yaml)
-- [Arabic](base-ar.yaml)
-- [Norwegian](base-no.yaml)
-- [Kroatian](base-hr.yaml)
-- [Danish](base-da.yaml)
-- [Finnish](base-fi.yaml)
-- [Catalan](base-cat.yaml)
-- [Slovenian](base-sl.yaml)
-- [Ukrainian](base-uk.yaml)
-- [Indonesian](base-ind.yaml)
-- [Serbian](base-sr.yaml)
-
-(If you want to translate into a new language, see below!)
-
-## Editing existing translations
-
-If you want to edit an existing translation (Fixing typos, Updating it to a newer version, etc), you can just use the github file editor to edit the file.
-
-- Click the language you want to edit from the list above
-- Click the small "edit" symbol on the top right
-
-
-
-- Do the changes you wish to do (Be sure **not** to translate placeholders! For example, ` minutes` should get ` Minuten` and **not** ` Minuten`!)
-
-- Click "Propose Changes"
-
-
-
-- Click "Create pull request"
-
-
-
-- I will review your changes and make comments, and eventually merge them so they will be in the next release! Be sure to regulary check the created pull request for comments.
-
-## Adding a new language
-
-Please DM me on Discord (tobspr#5407), so I can add the language template for you.
-
-Please use the following template:
-
-```
-Hey, could you add a new translation?
-
-Language:
-Short code:
-Local Name:
-```
-
-You can find the short code [here](https://www.science.co.il/language/Codes.php) (In column `Code 2`).
-
-PS: I'm super busy, but I'll give my best to do it quickly!
-
-## Updating a language to the latest version
-
-Run `yarn syncTranslations` in the root directory to synchronize all translations to the latest version! This will remove obsolete keys and add newly added keys. (Run `yarn` before to install packes).
+# Translations
+
+The base language is English and can be found [here](base-en.yaml).
+
+## Languages
+
+- [German](base-de.yaml)
+- [French](base-fr.yaml)
+- [Korean](base-kor.yaml)
+- [Dutch](base-nl.yaml)
+- [Polish](base-pl.yaml)
+- [Portuguese (Brazil)](base-pt-BR.yaml)
+- [Portuguese (Portugal)](base-pt-PT.yaml)
+- [Russian](base-ru.yaml)
+- [Greek](base-el.yaml)
+- [Italian](base-it.yaml)
+- [Romanian](base-ro.yaml)
+- [Swedish](base-sv.yaml)
+- [Chinese (Simplified)](base-zh-CN.yaml)
+- [Chinese (Traditional)](base-zh-TW.yaml)
+- [Spanish](base-es.yaml)
+- [Hungarian](base-hu.yaml)
+- [Turkish](base-tr.yaml)
+- [Japanese](base-ja.yaml)
+- [Lithuanian](base-lt.yaml)
+- [Arabic](base-ar.yaml)
+- [Norwegian](base-no.yaml)
+- [Kroatian](base-hr.yaml)
+- [Danish](base-da.yaml)
+- [Finnish](base-fi.yaml)
+- [Catalan](base-cat.yaml)
+- [Slovenian](base-sl.yaml)
+- [Ukrainian](base-uk.yaml)
+- [Indonesian](base-ind.yaml)
+- [Serbian](base-sr.yaml)
+
+(If you want to translate into a new language, see below!)
+
+## Editing existing translations
+
+If you want to edit an existing translation (Fixing typos, updating it to a newer version, etc), you can just use the github file editor to edit the file.
+
+- Click the language you want to edit from the list above
+- Click the small "edit" symbol on the top right
+
+
+
+- Do the changes you wish to do (Be sure **not** to translate placeholders! For example, ` minutes` should get ` Minuten` and **not** ` Minuten`!)
+
+- Click "Propose Changes"
+
+
+
+- Click "Create pull request"
+
+
+
+- I will review your changes and make comments, and eventually merge them so they will be in the next release! Be sure to regulary check the created pull request for comments.
+
+## Adding a new language
+
+Please DM me on Discord (tobspr#5407), so I can add the language template for you.
+
+**Important: I am currently not accepting new languages until the wires update is out!**
+
+Please use the following template:
+
+```
+Hey, could you add a new translation?
+
+Language:
+Short code:
+Local Name:
+```
+
+You can find the short code [here](https://www.science.co.il/language/Codes.php) (In column `Code 2`).
+
+PS: I'm super busy, but I'll give my best to do it quickly!
+
+## Updating a language to the latest version
+
+Run `yarn syncTranslations` in the root directory to synchronize all translations to the latest version! This will remove obsolete keys and add newly added keys. (Run `yarn` before to install packages).
diff --git a/translations/base-de.yaml b/translations/base-de.yaml
index 84c8a57e..fee9615a 100644
--- a/translations/base-de.yaml
+++ b/translations/base-de.yaml
@@ -66,7 +66,7 @@ steamPage:
[*] Verschiedene Karten und Herausforderungen (z.B. Karten mit Hindernissen)
[*] Puzzle (Liefere die geforderte Form mit begrenztem Platz/limitierten Gebäuden)
[*] Eine Kampagne mit Gebäudekosten
- [*] Konfigurierbarer Kartengenerator (Ändere die Grösse/Anzahl/Dichte der Ressourcenflecken, den Seed und viel mehr)
+ [*] Konfigurierbarer Kartengenerator (Ändere die Grösse/Anzahl/Dichte der Ressourcenflecken, den Seed und vieles mehr)
[*] Mehr Formentypen
[*] Performanceverbesserungen (Das Spiel läuft bereits sehr gut!)
[*] Und vieles mehr!
@@ -256,7 +256,7 @@ dialogs:
title: Nützliche Hotkeys
desc: >-
Dieses Spiel hat viele Hotkeys, die den Bau von Fabriken vereinfachen und beschleunigen.
- Hier sind ein paar, aber prüfe am besten die Tastenbelegung-Einstellungen !
+ Hier sind ein paar Beispiele, aber prüfe am besten die Tastenbelegung-Einstellungen !
STRG
+ Ziehen: Wähle Areal aus.
UMSCH
: Halten, um mehrere Gebäude zu platzieren.
ALT
: Invertiere die Platzierungsrichtung der Förderbänder.
@@ -635,7 +635,7 @@ storyRewards:
no_reward:
title: Nächstes Level
desc: >-
- Dieses Level hat dir keine Belohnung gegeben, aber dafür das Nächste schon! PS: Denke daran, deine alten Fabriken nicht zu zerstören - Du wirst sie später alle noch brauchen, um Upgrades freizuschalten !
+ Dieses Level hat dir keine Belohnung gegeben, aber im Nächsten gibt es eine! PS: Denke daran, deine alten Fabriken nicht zu zerstören - Du wirst sie später alle noch brauchen, um Upgrades freizuschalten !
no_reward_freeplay:
title: Nächstes Level
@@ -694,7 +694,7 @@ settings:
movementSpeed:
title: Bewegungsgeschwindigkeit
description: >-
- Ändert die Geschwindigkeit, mit der der Bildschirm durch die Pfeiltasten bewegt wird.
+ Ändert die Geschwindigkeit, mit welcher der Bildschirm durch die Pfeiltasten bewegt wird.
speeds:
super_slow: Sehr langsam
slow: Langsam
@@ -711,7 +711,7 @@ settings:
enableColorBlindHelper:
title: Modus für Farbenblinde
description: >-
- Aktiviert verschiedene Werkzeuge, die dir das Spielen trotz Farbenblindheit ermöglichen.
+ Aktiviert verschiedene Werkzeuge, welche dir das Spielen trotz Farbenblindheit ermöglichen.
fullscreen:
title: Vollbild
@@ -775,7 +775,7 @@ settings:
rotationByBuilding:
title: Rotation pro Gebäudetyp
description: >-
- Jeder Gebäudetyp merkt sich einzeln, in welche Richtung er zeigt.
+ Jeder Gebäudetyp merkt sich eigenständig, in welche Richtung er zeigt.
Das fühlt sich möglicherweise besser an, wenn du häufig zwischen verschiedenen Gebäudetypen wechselst.
compactBuildingInfo:
@@ -786,7 +786,7 @@ settings:
disableCutDeleteWarnings:
title: Deaktiviere Warnungsdialog beim Löschen
description: >-
- Deaktiviert die Warnung, die beim Löschen und Ausschneiden von mehr als 100 Feldern angezeigt wird.
+ Deaktiviert die Warnung, welche beim Löschen und Ausschneiden von mehr als 100 Feldern angezeigt wird.
keybindings:
title: Tastenbelegung
diff --git a/translations/base-el.yaml b/translations/base-el.yaml
index a8c8b241..30f825e5 100644
--- a/translations/base-el.yaml
+++ b/translations/base-el.yaml
@@ -22,7 +22,7 @@
---
steamPage:
# This is the short text appearing on the steam page
- shortText: shapez.io is a game about building factories to automate the creation and combination of increasingly complex shapes within an infinite map.
+ shortText: Στο shapez.io χτήζεις εργοστάσια για να αυτοματοποιήσεις την δημιουργία και τον συνδιασμό σχημάτων αυξανόμενης πολυπλοκότητας σε έναν ατέλειωτο χάρτη.
# This is the long description for the steam page - It is contained here so you can help to translate it, and I will regulary update the store page.
# NOTICE:
@@ -31,63 +31,63 @@ steamPage:
longText: >-
[img]{STEAM_APP_IMAGE}/extras/store_page_gif.gif[/img]
- shapez.io is a game about building factories to automate the creation and processing of increasingly complex shapes across an infinitely expanding map.
- Upon delivering the requested shapes you will progress within the game and unlock upgrades to speed up your factory.
+ Στο shapez.io χτήζεις εργοστάσια για να αυτοματοποιήσεις την δημιουργία και τον συνδιασμό σχημάτων αυξανόμενης πολυπλοκότητας σε έναν ατέλειωτο χάρτη.
+ Όταν παραδώσεις τα απαιτούμενα σχήματα, θα προχωρήσεις στο παιχνίδι και θα ξεκλειδώσεις αναβαθμήσεις για να επιταχύνεις το εργοστάσιό σου.
- As the demand for shapes increases, you will have to scale up your factory to meet the demand - Don't forget about resources though, you will have to expand across the [b]infinite map[/b]!
+ Επειδή η ζήτηση για σχήματα αυξάνεται συνεχώς, θα πρέπει να επεκτείνεις το εργοστάσιό σου για να την ικανοποιήσεις - Μήν ξεχάσεις, για να βρείς όλους τους πόρους που χρειάζεσαι θα πρέπει να εξαπλωθείς στον [b]άτελείωτο χάρτη[/b]!
- Soon you will have to mix colors and paint your shapes with them - Combine red, green and blue color resources to produce different colors and paint shapes with it to satisfy the demand.
+ Σύντομα θα πρέπει να αναμείξεις χρώματα και να βάψεις σχήματα - Ανάμειξε κόκκινο, πράσινο και μπλέ για να φτιάξεις διαφορετικά χρώματα και να βάψεις σχήματα ώστε να ικανοποιήσεις την ζήτηση.
- This game features 18 progressive levels (Which should keep you busy for hours already!) but I'm constantly adding new content - There is a lot planned!
+ Το παιχνίδι έχει 18 βαθμιαία επίπεδα (που ήδη θα σε απασχολήσουν για ώρες!) και συνεχίζω να προσθέτω περιεχόμενο - Έχω ακόμα πολλά σχέδια!
- Purchasing the game gives you access to the standalone version which has additional features and you'll also receive access to newly developed features.
+ Αγόράζοντας το παιχνίδι λαμβάνεις την αυτόνομη έκδοση (standalone) με πολλές επιπλέον δυνατότητες, καθώς και πρόσβαση σε νέες δυνατότητες που ακόμα αναπτύσσονται.
- [b]Standalone Advantages[/b]
+ [b]Πλεονεκτήματα Αυτόνομης Έκδοσης[/b]
[list]
- [*] Dark Mode
- [*] Unlimited Waypoints
- [*] Unlimited Savegames
- [*] Additional settings
- [*] Coming soon: Wires & Energy! Aiming for (roughly) end of July 2020.
- [*] Coming soon: More Levels
- [*] Allows me to further develop shapez.io ❤️
+ [*] Σκοτεινή λειτουργία
+ [*] Απεριόριστα σημεία γρήγορης κίνησης της κάμερας στον χάρτη
+ [*] Απεριόριστα αποθηκευμένα παιχνίδια
+ [*] Πρόσθετες ρυθμίσεις
+ [*] Στο κοντινό μέλλον: Καλώδια και ενέργεια! Aναμένεται (περίπου) τέλος Ιουλίου 2020.
+ [*] Στο κοντινό μέλλον: Περισσότερα επίπεδα
+ [*] Μου επιτρέπει να αναπτήξω περεταίρω το shapez.io ❤️
[/list]
- [b]Future Updates[/b]
+ [b]Μελλοντικές ενημερώσεις[/b]
- I am updating the game very often and trying to push an update at least every week!
+ Ενημερώνω το παιχνίδι πολύ συχνά και προσπαθώ να προωγώ ενημερώσεις σχεδόν κάθε εβδομάδα!
[list]
- [*] Different maps and challenges (e.g. maps with obstacles)
- [*] Puzzles (Deliver the requested shape with a restricted area / set of buildings)
- [*] A story mode where buildings have a cost
- [*] Configurable map generator (Configure resource/shape size/density, seed and more)
- [*] Additional types of shapes
- [*] Performance improvements (The game already runs pretty well!)
- [*] And much more!
+ [*] Διαφορετικοί χάρτες και προκλήσεις (π.χ. χάρτες με εμπόδια)
+ [*] Πάζλ (Παράδωσε το αιτούμενο σχήμα με περιορισμένο χώρο / κτήρια)
+ [*] Ένα σενάριο όπου τα κτήρια έχουν κόστος
+ [*] Διαμορφώσιμη δημιουργία χάρτη (Με επιλογές για το μέγεθος και την πυκνότητα των πόρων και άλλα)
+ [*] Επιπλέον σχήματα!
+ [*] Βελτιώσεις απόδοσης (Το παιχνίδι λειτουργεί ήδη πολύ καλά!)
+ [*] Και πολλά άλλα!
[/list]
- [b]This game is open source![/b]
+ [b]Αυτό το παιχνίδι είναι ανοιχτού κώδικα![/b]
- Anybody can contribute, I'm actively involved in the community and attempt to review all suggestions and take feedback into consideration where possible.
- Be sure to check out my trello board for the full roadmap!
+ Όλοι μπορούν να συνεισφέρουν, συμμετέχω ενεργά στην κοινότητα και προσπαθώ να εξετάσω όλες τις προτάσεις και να λάβω υπόψη τα σχόλια όπου είναι δυνατόν.
+ Δείτε το trello board μου για τον πλήρη χάρτη πορείας!
- [b]Links[/b]
+ [b]Σύνδεσμοι[/b]
[list]
- [*] [url=https://discord.com/invite/HN7EVzV]Official Discord[/url]
- [*] [url=https://trello.com/b/ISQncpJP/shapezio]Roadmap[/url]
+ [*] [url=https://discord.com/invite/HN7EVzV]Επίσημο Discord[/url]
+ [*] [url=https://trello.com/b/ISQncpJP/shapezio]Χάρτης πορείας[/url]
[*] [url=https://www.reddit.com/r/shapezio]Subreddit[/url]
- [*] [url=https://github.com/tobspr/shapez.io]Source code (GitHub)[/url]
- [*] [url=https://github.com/tobspr/shapez.io/blob/master/translations/README.md]Help translate[/url]
+ [*] [url=https://github.com/tobspr/shapez.io]Πηγαίος κώδικας (GitHub)[/url]
+ [*] [url=https://github.com/tobspr/shapez.io/blob/master/translations/README.md]Βοήθησε με μεταφράσεις[/url]
[/list]
- discordLink: Official Discord - Chat with me!
+ discordLink: Επίσημο Discord - Συνομίλησε μαζί μου!
global:
- loading: Loading
- error: Error
+ loading: Φόρτωση
+ error: Σφάλμα
# How big numbers are rendered, e.g. "10,000"
thousandsDivider: ","
@@ -97,31 +97,31 @@ global:
# The suffix for large numbers, e.g. 1.3k, 400.2M, etc.
suffix:
- thousands: k
- millions: M
- billions: B
- trillions: T
+ thousands: χλ.
+ millions: εκ.
+ billions: δισ.
+ trillions: τρισ.
# Shown for infinitely big numbers
- infinite: inf
+ infinite: άπειρο
time:
# Used for formatting past time dates
- oneSecondAgo: one second ago
- xSecondsAgo: seconds ago
- oneMinuteAgo: one minute ago
- xMinutesAgo: minutes ago
- oneHourAgo: one hour ago
- xHoursAgo: hours ago
- oneDayAgo: one day ago
- xDaysAgo: days ago
+ oneSecondAgo: πριν ένα δευτερόλεπτο
+ xSecondsAgo: πριν δευτερόλεπτα
+ oneMinuteAgo: πριν ένα λεπτό
+ xMinutesAgo: πριν λεπτά
+ oneHourAgo: πριν μία ώρα
+ xHoursAgo: πριν ώρες
+ oneDayAgo: πριν μία ημέρα
+ xDaysAgo: πριν ημέρες
# Short formats for times, e.g. '5h 23m'
- secondsShort: s
- minutesAndSecondsShort: m s
- hoursAndMinutesShort: h s
+ secondsShort: δ
+ minutesAndSecondsShort: λ δ
+ hoursAndMinutesShort: ω λ
- xMinutes: minutes
+ xMinutes: λεπτά
keys:
tab: TAB
@@ -138,506 +138,504 @@ demoBanners:
Get the standalone to unlock all features!
mainMenu:
- play: Play
+ play: Παίξε
changelog: Changelog
- importSavegame: Import
- openSourceHint: This game is open source!
- discordLink: Official Discord Server
- helpTranslate: Help translate!
+ importSavegame: Εισαγωγή αποθηκευμένου παιχνιδιού
+ openSourceHint: Αυτό το παιχνίδι είναι ανοιχτού κώδικα!
+ discordLink: Επίσημο Discord Server
+ helpTranslate: Βοήθησε με μεταφράσεις!
# This is shown when using firefox and other browsers which are not supported.
browserWarning: >-
- Sorry, but the game is known to run slow on your browser! Get the standalone version or download chrome for the full experience.
+ Δυστυχώς, το παιχνίδι τρέχει αργά στο πρόγραμμα περιήγησής σας! Αποκτήστε την αυτόνομη έκδοση ή κατεβάστε το chrome για την πλήρη εμπειρία.
- savegameLevel: Level
- savegameLevelUnknown: Unknown Level
+ savegameLevel: Επίπεδο
+ savegameLevelUnknown: Άγνωστο Επίπεδο
- continue: Continue
- newGame: New Game
+ continue: Συνέχεια
+ newGame: Καινούριο παιχνίδι
madeBy: Made by
subreddit: Reddit
dialogs:
buttons:
ok: OK
- delete: Delete
- cancel: Cancel
- later: Later
- restart: Restart
- reset: Reset
- getStandalone: Get Standalone
- deleteGame: I know what I do
- viewUpdate: View Update
- showUpgrades: Show Upgrades
- showKeybindings: Show Keybindings
+ delete: Διαγραφή
+ cancel: Άκυρο
+ later: Αργότερα
+ restart: Επανεκκίνηση
+ reset: Επαναφορά
+ getStandalone: Απόκτησε την Αυτόνομη έκδοση
+ deleteGame: Ξέρω τί κάνω
+ viewUpdate: Προβολή ενημέρωσης
+ showUpgrades: Εμφάνιση αναβαθμίσεων
+ showKeybindings: Συνδυασμοί πλήκτρων
importSavegameError:
- title: Import Error
+ title: Σφάλμα εισαγωγής
text: >-
- Failed to import your savegame:
+ Αποτυχία εισαγωγής του αποθηκευμένου παιχνιδιού:
importSavegameSuccess:
- title: Savegame Imported
+ title: Εισαγωγή αποθηκευμένου παιχνιδιού
text: >-
- Your savegame has been successfully imported.
+ Η Εισαγωγή του αποθηκευμένου παιχνιδιού ήταν επιτυχής.
gameLoadFailure:
- title: Game is broken
+ title: Το παιχνίδι είναι κατεστραμμένο
text: >-
- Failed to load your savegame:
+ Η φώρτοση του αποθηκευμένου παιχνιδιού ήταν αποτυχής:
confirmSavegameDelete:
- title: Confirm deletion
+ title: Επιβεβαίωση διαγραφής
text: >-
- Are you sure you want to delete the game?
+ Είσαι βέβαιος/η ότι θέλεις να διαγράψεις το παιχνίδι;
savegameDeletionError:
- title: Failed to delete
+ title: Αποτυχία διαγραφής
text: >-
- Failed to delete the savegame:
+ Η διαγραφή του αποθηκευμένου παιχνιδιού ήταν αποτυχής:
restartRequired:
- title: Restart required
+ title: Χρειάζεται επανεκκίνηση
text: >-
- You need to restart the game to apply the settings.
+ Πρέπει να επανεκκινήσεις το παιχνίδι για να εφαρμόσεις τις ρυθμίσεις.
editKeybinding:
- title: Change Keybinding
- desc: Press the key or mouse button you want to assign, or escape to cancel.
+ title: Αλλαγή συνδιασμών πλήκτρων
+ desc: Πάτησε το πλήκτρο ή το κουμπί του ποντικιού που θέλεις να αντιστοιχίσεις, ή escape για ακύρωση.
resetKeybindingsConfirmation:
- title: Reset keybindings
- desc: This will reset all keybindings to their default values. Please confirm.
+ title: Επαναφορά συνδιασμών πλήκτρων
+ desc: Όλες οι συνδιασμών πλήκτρων θα επαναφερθούν στις προεπιλεγμένες τιμές τους. Επιβεβαίωση;
keybindingsResetOk:
- title: Keybindings reset
- desc: The keybindings have been reset to their respective defaults!
+ title: Συνδιασμοί πλήκτρων επαναφέρθηκαν
+ desc: Οι συνδιασμών πλήκτρων επαναφέρθηκαν στις προεπιλεγμένες τιμές τους!
featureRestriction:
- title: Demo Version
- desc: You tried to access a feature () which is not available in the demo. Consider to get the standalone for the full experience!
+ title: Έκδοση Demo
+ desc: Προσπάθησες να χρησιμοποιήσεις μία δυνατότητα που δεν είναι διαθέσιμη στην έκδοση demo. Αποκτήστε την αυτόνομη έκδοση για την ολοκληρομένη εμπειρία!
oneSavegameLimit:
- title: Limited savegames
- desc: You can only have one savegame at a time in the demo version. Please remove the existing one or get the standalone!
+ title: Περιορισμένα αποθηκευμένα παιχνίδια
+ desc: Στην demo έκδοση μπορείς να έχεις μόνο ένα αποθηκευμένο παιχνίδι. Παρακαλώ διάγραψε το υπάρχον αποθηκευμένο παιχνίδι ή απόκτησε την αθτόνομη έκδοση!
updateSummary:
- title: New update!
+ title: Νέα αναβάθμιση!
desc: >-
- Here are the changes since you last played:
+ Αυτές είναι οι αλλαγές από την τελευταία φορά που έπαιξες:
upgradesIntroduction:
- title: Unlock Upgrades
+ title: Ξεκλείδωμα αναβαθμίσεων
desc: >-
- All shapes you produce can be used to unlock upgrades - Don't destroy your old factories!
- The upgrades tab can be found on the top right corner of the screen.
+ Όλα τα σχήματα που παράγεις μπορούν να χρησιμοποιηθούν για να ξεκλειδώσεις αναβαθμίσεις - Μην καταστρέψεις τα παλιά σου εργοστάσια!
+ Η καρτέλα αναβαθμίσεων βρίσκεται στην επάνω δεξιά γωνία της οθόνης.
massDeleteConfirm:
- title: Confirm delete
+ title: Επιβεβαίωση διαγραφής
desc: >-
- You are deleting a lot of buildings ( to be exact)! Are you sure you want to do this?
+ Ετοιμάζεσαι να διαγράψεις πολλά κτήρια ( για την ακρίβεια)! Είσαι βέβαιος/η ότι θέλεις να το κάνεις αυτό;
blueprintsNotUnlocked:
- title: Not unlocked yet
+ title: Αυτή η δυνατότητα δεν έχει ξεκλειδωθεί ακόμα
desc: >-
- Blueprints have not been unlocked yet! Complete more levels to unlock them.
+ Τα σχεδιαγράμματα δεν έχουν ξεκλειδωθεί ακόμα! Ολοκλήρωσε περισσότερα επίπεδα για να τα ξεκλειδώσεις.
keybindingsIntroduction:
- title: Useful keybindings
+ title: Χρήσιμοι Συνδιασμοί πλήκτρων
desc: >-
- This game has a lot of keybindings which make it easier to build big factories.
- Here are a few, but be sure to check out the keybindings !
- CTRL
+ Drag: Select area to copy / delete.
- SHIFT
: Hold to place multiple of one building.
- ALT
: Invert orientation of placed belts.
+ Αυτό το παιχνίδι έχει πολλούς συνδιασμούς πλήκτρων που διευκολύνουν στο χτήσιμο μεγάλων εργοστασίων.
+ Εδώ είναι μερικοί από αυτούς. Για τους υπόλοιπους αναφέρσου στην ενότητα Συνδιασμοί πλήκτρων
+ CTRL
+ Σύρε: Επιλογή περιοχής για αντιγραφή / διαγραφή.
+ SHIFT
: Κράτα πατημένο για να χτίσεις πάνω από ένα κτήριο.
+ ALT
: Αντιστρέφει τον προσανατολισμό των τοποθετούμενων ιμάντων.
createMarker:
- title: New Marker
- desc: Give it a meaningful name, you can also include a short key of a shape (Which you can generate here )
- titleEdit: Edit Marker
+ title: Νέο Σημάδι
+ desc: Δώσ' του ένα όνομα με νόημα. Μπορείς επίσης να χρησημοποιήσεις και τον σύντομο κώδικα ενός σχήματος (τον οποίο μπορείς να βρείς εδώ )
+ titleEdit: Επεξεργασία Σημαδιού
markerDemoLimit:
- desc: You can only create two custom markers in the demo. Get the standalone for unlimited markers!
+ desc: Στην έκδωση demo μπορείς να βάλεις μέχρι δύο σημάδια στον χάρτη. Αποκτήστε την αυτόνομη έκδοση για να μπορείς να βάλεις απεριόριστα σημάδια στον χάρτη!
massCutConfirm:
- title: Confirm cut
+ title: Επιβεβαίωση αποκοπής
desc: >-
- You are cutting a lot of buildings ( to be exact)! Are you sure you
- want to do this?
+ Ετοιμάζεσαι να αποκόψεις πολλά κτήρια ( φια την ακρίβεια)! Είσαι βέβαιος/η ότι θέλεις να το κάνεις αυτό;
exportScreenshotWarning:
- title: Export screenshot
+ title: Εξαγωγή στιγμιότυπου οθόνης
desc: >-
- You requested to export your base as a screenshot. Please note that this can
- be quite slow for a big base and even crash your game!
+ Ζήτησες να εξαγάγεις τη βάση σου ως στιγμιότυπο οθόνης. Λάβε υπόψη ότι αυτό μπορεί να είναι αρκετά αργό για μια μεγάλη βάση και μπορεί ακόμη και να διακόψει (crash) το παιχνίδι σου!
massCutInsufficientConfirm:
- title: Confirm cut
- desc: You can not afford to paste this area! Are you sure you want to cut it?
+ title: Επιβεβαίωση αποκοπής
+ desc: Δεν έχεις τους πόρους να επικολλήσεις αυτήν την περιοχή! Είσαι βέβαιος/η ότι θέλεις να την αποκόψεις;
ingame:
# This is shown in the top left corner and displays useful keybindings in
# every situation
keybindingsOverlay:
- moveMap: Move
- selectBuildings: Select area
- stopPlacement: Stop placement
- rotateBuilding: Rotate building
- placeMultiple: Place multiple
- reverseOrientation: Reverse orientation
- disableAutoOrientation: Disable auto orientation
- toggleHud: Toggle HUD
- placeBuilding: Place building
- createMarker: Create Marker
- delete: Destroy
- pasteLastBlueprint: Paste last blueprint
- lockBeltDirection: Enable belt planner
- plannerSwitchSide: Flip planner side
- cutSelection: Cut
- copySelection: Copy
- clearSelection: Clear Selection
- pipette: Pipette
- switchLayers: Switch layers
+ moveMap: Κίνηση
+ selectBuildings: Επιλογή περιοχής
+ stopPlacement: Διακοπή τοποθέτησης
+ rotateBuilding: Περιστροφή κτηρίου
+ placeMultiple: Τοποθέτηση πολλαπλών κτηρίων
+ reverseOrientation: Αντιστροφή προσανατολισμού ιμάντα
+ disableAutoOrientation: Απενεργοποίηση αυτόματου προσανατολισμού
+ toggleHud: Εναλλαγή HUD
+ placeBuilding: Τοποθέτηση κτηρίου
+ createMarker: Δημιουργία σημαδιού
+ delete: Διαγραφή
+ pasteLastBlueprint: Επικόλληση τελευταίου σχεδιαγράμματος
+ lockBeltDirection: Ενεργοποίηση σχεδιαστή ιμάντα
+ plannerSwitchSide: Αλλαγή πλευράς σχεδιαστή
+ cutSelection: Αποκοπή
+ copySelection: Αντιγραφή
+ clearSelection: Εκκαθαρισμός επιλογής
+ pipette: Σταγονόμετρο
+ switchLayers: Εναλλαγή στρώματος
# Everything related to placing buildings (I.e. as soon as you selected a building
# from the toolbar)
buildingPlacement:
# Buildings can have different variants which are unlocked at later levels,
# and this is the hint shown when there are multiple variants available.
- cycleBuildingVariants: Press to cycle variants.
+ cycleBuildingVariants: Πάτησε για εναλλαγή μεταξύ παραλλαγών.
# Shows the hotkey in the ui, e.g. "Hotkey: Q"
hotkeyLabel: >-
Hotkey:
infoTexts:
- speed: Speed
- range: Range
- storage: Storage
- oneItemPerSecond: 1 item / second
- itemsPerSecond: items / s
+ speed: Ταχύτητα
+ range: Απόσταση
+ storage: Αποθηκευτικός χώρος
+ oneItemPerSecond: 1 είδος / δευτερόλεπτο
+ itemsPerSecond: είδη / δ
itemsPerSecondDouble: (x2)
- tiles: tiles
+ tiles: πλακάκια
# The notification when completing a level
levelCompleteNotification:
# is replaced by the actual level, so this gets 'Level 03' for example.
- levelTitle: Level
- completed: Completed
- unlockText: Unlocked !
- buttonNextLevel: Next Level
+ levelTitle: Επίπεδο
+ completed: Ολοκληρώθηκε
+ unlockText: Ξεκλειδώθηκε !
+ buttonNextLevel: Επόμενο επίπεδο
# Notifications on the lower right
notifications:
- newUpgrade: A new upgrade is available!
- gameSaved: Your game has been saved.
+ newUpgrade: Μια νέα αναβάθμιση είναι διαθέσιμη!
+ gameSaved: Το παιχνίδι έχει αποθηκευτεί.
# The "Upgrades" window
shop:
- title: Upgrades
- buttonUnlock: Upgrade
+ title: Αναβαθμίσεις
+ buttonUnlock: Αναβάθμιση
# Gets replaced to e.g. "Tier IX"
- tier: Tier
+ tier: Βαθμίδα
# The roman number for each tier
tierLabels: [I, II, III, IV, V, VI, VII, VIII, IX, X]
- maximumLevel: MAXIMUM LEVEL (Speed x)
+ maximumLevel: ΜΕΓΙΣΤΟ ΕΠΙΠΕΔΟ (Ταχύτητα x)
# The "Statistics" window
statistics:
- title: Statistics
+ title: Στατιστικά
dataSources:
stored:
- title: Stored
- description: Displaying amount of stored shapes in your central building.
+ title: Αποθηκευμένα
+ description: Εμφάνιση ποσού αποθηκευμένων σχημάτων στο κεντρικό σου κτήριο.
produced:
- title: Produced
- description: Displaying all shapes your whole factory produces, including intermediate products.
+ title: Παραγμένα
+ description: Εμφάνιση όλων των σχημάτων που παράγει ολόκληρο το εργοστάσιό σου, συμπεριλαμβανομένων των ενδιάμεσων προϊόντων.
delivered:
- title: Delivered
- description: Displaying shapes which are delivered to your central building.
- noShapesProduced: No shapes have been produced so far.
+ title: Παραδωμένα
+ description: Εμφάνιση σχημάτων που παραδίδονται στο κεντρικό σου κτήριο.
+ noShapesProduced: Δεν έχεις παράξει σχήματα ακόμα.
# Displays the shapes per minute, e.g. '523 / m'
- shapesPerMinute: / m
+ shapesPerMinute: / λ
# Settings menu, when you press "ESC"
settingsMenu:
- playtime: Playtime
+ playtime: Χρόνος που έπαιξες
- buildingsPlaced: Buildings
- beltsPlaced: Belts
+ buildingsPlaced: Κτήρια
+ beltsPlaced: Ιμάντες
buttons:
- continue: Continue
- settings: Settings
- menu: Return to menu
+ continue: Συνέχεια
+ settings: Ρυθμίσεις
+ menu: Επιστροφή στο μενού
# Bottom left tutorial hints
tutorialHints:
- title: Need help?
- showHint: Show hint
- hideHint: Close
+ title: Χρειάζεσε βοήθεια;
+ showHint: Εμφάνιση υπόδειξης
+ hideHint: Kλείσιμο
# When placing a blueprint
blueprintPlacer:
- cost: Cost
+ cost: Κόστος
# Map markers
waypoints:
- waypoints: Markers
+ waypoints: Σημάδι
hub: HUB
- description: Left-click a marker to jump to it, right-click to delete it. Press to create a marker from the current view, or right-click to create a marker at the selected location.
- creationSuccessNotification: Marker has been created.
+ description: Κάνε αριστερό κλικ σε ένα σημάδι για να μεταβείς σε αυτό, κάνε δεξί κλικ για να το διαγράψεις. Πάτησε για να δημιουργήσεις ένα σημάδι από την τρέχουσα προβολή ή δεξί κλικ για να δημιουργήσεις ένα σημάδι στην επιλεγμένη τοποθεσία.
+ creationSuccessNotification: Το σημάδι δημιουργήθηκε.
# Interactive tutorial
interactiveTutorial:
title: Tutorial
hints:
- 1_1_extractor: Place an extractor on top of a circle shape to extract it!
+ 1_1_extractor: Τοποθέτησε έναν αποσπαστή πάνω από ένα σχήμα κύκλου για να το αποσπάεις!
1_2_conveyor: >-
- Connect the extractor with a conveyor belt to your hub! Tip: Click and drag the belt with your mouse!
+ Σύνδεσε τον αποσπαστή με έναν μεταφορικό ιμάντα στο κεντρικό σου κτήριο! Συμβουλή: Κάνε κλικ και σύρε τη ζώνη με το ποντίκι σου!
1_3_expand: >-
- This is NOT an idle game! Build more extractors and belts to finish the goal quicker. Tip: Hold SHIFT to place multiple extractors, and use R to rotate them.
+ Αυτό ΔΕΝ είναι ένα αδρανές παιχνίδι! Δημιούργησε περισσότερους αποσπαστές και ιμάντες για να ολοκληρώσεις τον στόχο σου πιο γρήγορα. Συμβουλή: Κράτησε το πλήκτρο SHIFT για να τοποθετήσεις πολλούς αποσπαστές και χρησιμοποιήστε το R για να τους περιστρέψεις.
colors:
- red: Red
- green: Green
- blue: Blue
- yellow: Yellow
- purple: Purple
- cyan: Cyan
- white: White
- uncolored: No color
- black: Black
+ red: Κόκκινο
+ green: Πράσινο
+ blue: Μπλε
+ yellow: Κίτρινο
+ purple: Μωβ
+ cyan: Γαλάζιο
+ white: Λευκό
+ uncolored: Χωρίς χρώμα
+ black: Μαύρο
shapeViewer:
- title: Layers
- empty: Empty
- copyKey: Copy Key
+ title: Στρώματα
+ empty: Κενό
+ copyKey: Αντιγραφή κώδικα
# All shop upgrades
shopUpgrades:
belt:
- name: Belts, Distributor & Tunnels
- description: Speed x → x
+ name: Ιμάντες, Διανομείς & Σήραγγες
+ description: Ταχύτητα x → x
miner:
- name: Extraction
- description: Speed x → x
+ name: Απόσπαση
+ description: Ταχύτητα x → x
processors:
- name: Cutting, Rotating & Stacking
- description: Speed x → x
+ name: Κοπή, Περιστροφή & Στοίβαξη
+ description: Ταχύτητα x → x
painting:
- name: Mixing & Painting
- description: Speed x → x
+ name: Ανάμειξη & Βαφή
+ description: Ταχύτητα x → x
# Buildings and their name / description
buildings:
belt:
default:
- name: &belt Conveyor Belt
- description: Transports items, hold and drag to place multiple.
+ name: &belt Μεταφορικός Ιμάντας
+ description: Μεταφέρει είδη. Κράτα πατημένο και σύρε για να τοποθετήσεις πολλαπλούς ιμάντες.
miner: # Internal name for the Extractor
default:
- name: &miner Extractor
- description: Place over a shape or color to extract it.
+ name: &miner Αποσπαστής
+ description: Τοποθέτησε πάνω από ένα σχήμα ή χρώμα για να το αποσπάσεις.
chainable:
- name: Extractor (Chain)
- description: Place over a shape or color to extract it. Can be chained.
+ name: Αποσπαστής (Αλυσιδωτός)
+ description: Τοποθέτησε πάνω από ένα σχήμα ή χρώμα για να το αποσπάσεις. Μπορούν να συνδεθούν σε σειρά.
underground_belt: # Internal name for the Tunnel
default:
- name: &underground_belt Tunnel
- description: Allows to tunnel resources under buildings and belts.
+ name: &underground_belt Σήραγγα
+ description: Μεταφέρει είδη κάτω από κτήρια και μεταφορικούς ιμάντες.
tier2:
- name: Tunnel Tier II
- description: Allows to tunnel resources under buildings and belts.
+ name: Σήραγγα Βαθμίδα II
+ description: Μεταφέρει είδη κάτω από κτήρια και μεταφορικούς ιμάντες.
splitter: # Internal name for the Balancer
default:
- name: &splitter Balancer
- description: Multifunctional - Evenly distributes all inputs onto all outputs.
+ name: &splitter Ισορροπηστής
+ description: Πολυλειτουργικό - κατανέμει ομοιόμορφα είδη από όλες τις εισόδους σε όλες τις εξόδους.
compact:
- name: Merger (compact)
- description: Merges two conveyor belts into one.
+ name: Συγχωνευτής (συμπαγής)
+ description: Συγχωνεύει δύο μεταφορικούς ιμάντες σε έναν.
compact-inverse:
- name: Merger (compact)
- description: Merges two conveyor belts into one.
+ name: Συγχωνευτής (συμπαγής)
+ description: Συγχωνεύει δύο μεταφορικούς ιμάντες σε έναν.
cutter:
default:
- name: &cutter Cutter
- description: Cuts shapes from top to bottom and outputs both halfs. If you use only one part, be sure to destroy the other part or it will stall!
+ name: &cutter Κόπτης
+ description: Κόβει σχήματα από πάνω προς τα κάτω και παράγει και τα δύο μισά. Εάν χρησιμοποιείς μόνο το ένα κομμάτι, φρόντισε να καταστρέψεις το άλλο κομμάτι, διαφορετικά η λειτουργία θα σταματήσει!
quad:
- name: Cutter (Quad)
- description: Cuts shapes into four parts. If you use only one part, be sure to destroy the other part or it will stall!
+ name: Κόπτης (Τετάρτων)
+ description: Κόβει σχήματα σε τέσσερα κομμάτια. Εάν χρησιμοποιείς μόνο το ένα κομμάτι, φρόντισε να καταστρέψεις τα άλλα κομμάτια, διαφορετικά η λειτουργία θα σταματήσει!
rotater:
default:
- name: &rotater Rotate
- description: Rotates shapes clockwise by 90 degrees.
+ name: &rotater Περιστροφέας
+ description: Περιστρέφει τα σχήματα δεξιόστροφα κατά 90 μοίρες.
ccw:
- name: Rotate (CCW)
- description: Rotates shapes counter clockwise by 90 degrees.
+ name: Περιστροφέας (Αρστ.)
+ description: Περιστρέφει τα σχήματα αριστερόστροφα κατά 90 μοίρες.
fl:
- name: Rotate (180)
- description: Rotates shapes by 180 degrees.
+ name: Περιστροφέας (180)
+ description: Περιστρέφει τα σχήματα κατά 180 μοίρες.
stacker:
default:
- name: &stacker Stacker
- description: Stacks both items. If they can not be merged, the right item is placed above the left item.
+ name: &stacker Στοίβαχτής
+ description: Στοιβάζει και τα δύο είδη. Εάν δεν μπορούν να συγχωνευτούν, το δεξί είδος τοποθετείται πάνω από το αριστερό είδος.
mixer:
default:
- name: &mixer Color Mixer
- description: Mixes two colors using additive blending.
+ name: &mixer Αναμείκτης Χρωμάτων
+ description: Αναμειγνύει δύο χρώματα χρησιμοποιώντας ανάμιξη πρόσθετων.
painter:
default:
- name: &painter Painter
- description: &painter_desc Colors the whole shape on the left input with the color from the right input.
+ name: &painter Βαφέας
+ description: &painter_desc Χρωματίζει ολόκληρο το σχήμα στην αριστερή είσοδο με το χρώμα από τη δεξιά είσοδο.
double:
- name: Painter (Double)
- description: Colors the shapes on the left inputs with the color from the top input.
+ name: Βαφέας (Διπλός)
+ description: Χρωματίζει τα σχήματα από τις αριστερές εισόδους με το χρώμα από την επάνω είσοδο.
quad:
- name: Painter (Quad)
- description: Allows to color each quadrant of the shape with a different color.
+ name: Βαφέας (Τετάρτων)
+ description: Επιτρέπει να χρωματίσει κάθε τεταρτημόριο του σχήματος με διαφορετικό χρώμα.
mirrored:
name: *painter
description: *painter_desc
trash:
default:
- name: &trash Trash
- description: Accepts inputs from all sides and destroys them. Forever.
+ name: &trash Κάδος απορριμμάτων
+ description: Δέχεται είδη από όλες τις πλευρές και τα καταστρέφει. Για πάντα.
storage:
- name: Storage
- description: Stores excess items, up to a given capacity. Can be used as an overflow gate.
+ name: Αποθήκη
+ description: Αποθηκεύει επιπλέον είδη, έως μια δεδομένη χωρητικότητα. Μπορεί να χρησιμοποιηθεί ως πύλη υπερχείλισης.
hub:
- deliver: Deliver
- toUnlock: to unlock
+ deliver: Παράδωσε
+ toUnlock: για να ξεκλειδώσεις
levelShortcut: LVL
wire:
default:
- name: Energy Wire
- description: Allows you to transport energy.
+ name: Καλώδιο ενέργειας
+ description: Σου επιτρέπει να μεταφέρεις ενέργεια.
advanced_processor:
default:
- name: Color Inverter
- description: Accepts a color or shape and inverts it.
+ name: Μετατροπέας χρώματος
+ description: Δέχεται ένα χρώμα ή σχήμα και το αντιστρέφει.
energy_generator:
- deliver: Deliver
- toGenerateEnergy: For
+ deliver: Παράδωσε
+ toGenerateEnergy: Για
default:
- name: Energy Generator
- description: Generates energy by consuming shapes.
+ name: Γεννήτρια ενέργειας
+ description: Παράγει ενέργεια καταναλώνοντας σχήματα.
wire_crossings:
default:
- name: Wire Splitter
- description: Splits a energy wire into two.
+ name: Διαχωριστής καλωδίων
+ description: Χωρίζει ένα καλώδιο ενέργειας σε δύο.
merger:
- name: Wire Merger
- description: Merges two energy wires into one.
+ name: Συγχωνευτής καλωδίων
+ description: Συγχωνεύει δύο καλώδια ενέργειας σε ένα.
storyRewards:
# Those are the rewards gained from completing the store
reward_cutter_and_trash:
- title: Cutting Shapes
- desc: You just unlocked the cutter - it cuts shapes half from top to bottom regardless of its orientation! Be sure to get rid of the waste, or otherwise it will stall - For this purpose I gave you a trash, which destroys everything you put into it!
+ title: Κοπή σχημάτων
+ desc: Μόλις ξεκλείδωσες τον κόπτη - κόβει σχήματα κατά το ήμισυ από πάνω προς τα κάτω ανεξάρτητα από τον προσανατολισμό του! Φρόντισε να καταστρέψεις κομμάτια που δεω χρησημοποιείς αλλιώς η λειτουργία θα σταματήσει - Για το σκοπό αυτό σου έδωσα τον κάδο απορριμμάτων, ο οποίος καταστρέφει ό,τι είδη μεταφερθούν εκεί!
reward_rotater:
- title: Rotating
- desc: The rotater has been unlocked! It rotates shapes clockwise by 90 degrees.
+ title: Περιστροφή
+ desc: Ο Περιστροφέας ξεκλειδώθηκε! Το κτήριο αυτό περιστρέφει τα σχήματα δεξιόστροφα κατά 90 μοίρες.
reward_painter:
- title: Painting
+ title: Βαφή
desc: >-
- The painter has been unlocked - Extract some color veins (just as you do with shapes) and combine it with a shape in the painter to color them! PS: If you are colorblind, there is a color blind mode in the settings!
+ Μόλις ξεκλειδώθηκε ο Βαφέας - Απόσπασε μερικά χρώματα (όπως κάνεις με τα σχήματα) και συνδύασέ τα με ένα σχήμα στον βαφέα για να τα χρωματίσεις! PS: Εάν πάσχεις από αχρωματοψία, τυφλοί, υπάρχει η λειτουργία αχρωματοψίας στις ρυθμίσεις!
reward_mixer:
- title: Color Mixing
- desc: The mixer has been unlocked - Combine two colors using additive blending with this building!
+ title: Ανάμιξη Χρωμάτων
+ desc: Ο Αναμείκτης χρωμάτων είναι διαθέσιμος - Συνδύαστε δύο χρώματα ακολουθόντας ανάμιξη πρόσθετων με αυτό το κτήριο!
reward_stacker:
- title: Combiner
- desc: You can now combine shapes with the combiner ! Both inputs are combined, and if they can be put next to each other, they will be fused . If not, the right input is stacked on top of the left input!
+ title: Στοίβαχτής
+ desc: Τώρα μπορείς να συνδυάσεις σχήματα με τον Στοίβαχτής ! Εαν τα σχήματα από τις δύο εισόδους μπορούν να τοποθετηθούν το ένα δίπλα στο άλλο θα συμπτυχθούν . Εάν όχι, το σχήμα της δεηιάς εισώδου στοιβάζεται πάνω από το σχήμα της αριστερής!
reward_splitter:
- title: Splitter/Merger
- desc: The multifunctional balancer has been unlocked - It can be used to build bigger factories by splitting and merging items onto multiple belts!
+ title: Διαχωρισμός/Συγχώνευση
+ desc: Ο πολυλειτουργικός Ισορροπηστής είναι πλέον διαθέσιμος - Μπορεί να χρησιμοποιηθεί για την κατασκευή μεγαλύτερων εργοστασίων με διαχωρισμό και συγχώνευση ειδών σε/από πολλούς μεταφορικούς ιμάντες!
reward_tunnel:
- title: Tunnel
- desc: The tunnel has been unlocked - You can now pipe items through belts and buildings with it!
+ title: Σήραγγα
+ desc: Το Σήραγγα είναι πλέον διαθέσιμο - Τώρα μπορείς να διοχετεύσεις είδη κάτω από ιμάντες και κτήρια!
reward_rotater_ccw:
- title: CCW Rotating
- desc: You have unlocked a variant of the rotater - It allows to rotate counter clockwise! To build it, select the rotater and press 'T' to cycle its variants !
+ title: Περιστροφή (Αρστ.)
+ desc: Ξεκλείδωσες μια παραλλαγή του Περιστροφέα - Επιτρέπει αριστερόστροφη περιστροφή! Για να τον τοποθετήσεις, επίλεξε τον περιστροφέα και πάτησε 'T' για να κυλίσεις ανάμεσα στις παραλλαγές του !
reward_miner_chainable:
- title: Chaining Extractor
- desc: You have unlocked the chaining extractor ! It can forward its resources to other extractors so you can more efficiently extract resources!
+ title: Αλυσιδωτός Αποσπαστής
+ desc: Ξεκλείδωσες τον Αλυσιδωτός Αποσπαστής ! Μπορεί να προωθήσει τους αποσπασμένους πόρους σε άλλους αποσπαστές, ώστε να μπορείτε να αποσπάσεις πιο αποτελεσματικά πόρους!
reward_underground_belt_tier_2:
- title: Tunnel Tier II
- desc: You have unlocked a new variant of the tunnel - It has a bigger range , and you can also mix-n-match those tunnels now!
+ title: Σήραγγα Βαθμίδα II
+ desc: Ξεκλείδωσες μια νέα παραλλαγή της Σήραγγας - Καλύπτει μεγαλύτερη απόσταση και επιτρέπει το "πλέξιμο" διαφορετικών βαθμίδων σήραγγας!
reward_splitter_compact:
- title: Compact Balancer
+ title: Συμπαγής Ισορροπηστής
desc: >-
- You have unlocked a compact variant of the balancer - It accepts two inputs and merges them into one!
+ Ξεκλείδωσες μια συμπαγή παραλλαγή του Ισορροπηστή . Δέχεται είδη από δύο ιμάντες και τους συγχωνεύει σε έναν!
reward_cutter_quad:
- title: Quad Cutting
- desc: You have unlocked a variant of the cutter - It allows you to cut shapes in four parts instead of just two!
+ title: Κόπτης Τετάρτων
+ desc: Ξεκλείδωσες μια παραλλαγή του Κόπτη - Σου επιτρέπει να κόψεις σχήματα σε τέσσερα κομμάτια αντί για δύο!
reward_painter_double:
- title: Double Painting
- desc: You have unlocked a variant of the painter - It works as the regular painter but processes two shapes at once consuming just one color instead of two!
+ title: Διπλός Βαφέας
+ desc: Ξεκλείδωσες μια παραλλαγή του Βαφέα - Λειτουργεί όπως ο κανονικός βαφέας, αλλά επεξεργάζεται δύο σχήματα ταυτόχρονα , καταναλώνοντας μόνο ένα χρώμα αντί για δύο!
reward_painter_quad:
- title: Quad Painting
- desc: You have unlocked a variant of the painter - It allows to paint each part of the shape individually!
+ title: Βαφέας Τετάρτων
+ desc: Ξεκλείδωσες μια παραλλαγή του Βαφέα - Σου επιτρέπει να βάψεις κάθε τεταρτημόριο του σχήματος ξεχωριστά!
reward_storage:
- title: Storage Buffer
- desc: You have unlocked a variant of the trash - It allows to store items up to a given capacity!
+ title: Αποθηκευτικός χώρος
+ desc: Ξεκλείδωσες μια παραλλαγή του Κάδου Απορριμμάτων - Επιτρέπει την αποθήκευση ειδών έως μια δεδομένη χωρητικότητα!
reward_freeplay:
- title: Freeplay
- desc: You did it! You unlocked the free-play mode ! This means that shapes are now randomly generated! (No worries, more content is planned for the standalone!)
+ title: Ελεύθερο παιχνίδι
+ desc: Τα κατάφερες! Ξεκλείδωσες την λειτουργία ελεύθερου παιχνιδιού ! Από εδώ και πέρα τα σχήματα δημιουργούνται τυχαία! (Μην ανυσηχείς, περισσότερο περιεχόμενο έρχεται σύντομα στην αυτόνομη έκδοση!)
reward_blueprints:
- title: Blueprints
- desc: You can now copy and paste parts of your factory! Select an area (Hold CTRL, then drag with your mouse), and press 'C' to copy it. Pasting it is not free , you need to produce blueprint shapes to afford it! (Those you just delivered).
+ title: Σχεδιαγράμματα
+ desc: Μπορείς πλέον να κάνεις αντιγραφή και επικόλληση στα μέρη του εργοστασίου σου! Επίλεξε μια περιοχή (Κράτα πατημένο το CTRL, και τράβα το ποντίκι σου), και πάτησε 'C' για να αντιγράψεις τα κτήρια στην επιλεγμένη περιοχή. Η επικόλληση δεν είναι δωρεάν , θα πρέπει να παράγεις σχήματα σχεδιαγράμματος για να χρησημοποιήσεις αυτή την δυνατότητα! (Τα σχήματα που μόλις παρέδωσες).
# Special reward, which is shown when there is no reward actually
no_reward:
- title: Next level
+ title: Επόμενο Επίπεδο
desc: >-
- This level gave you no reward, but the next one will! PS: Better don't destroy your existing factory - You need all those shapes later again to unlock upgrades !
+ Αυτό το επίπεδο δεν σου παρήχε κάποια αμοιβή, άλλα το επόμενο επίπεδο θα σου δώσει! Υ.Γ.: Καλύτερα μην καταστρέψεις το υπάρχον σου εργοστάσιο - θα χρειαστείς όλα αυτά τα σχήματα ξανά αργότερα για να ξεκλειδώσεις αναβαθμίσεις !
no_reward_freeplay:
- title: Next level
+ title: Επόμενο Επίπεδο
desc: >-
- Congratulations! By the way, more content is planned for the standalone!
+ Συγχαριτήρια! Παρεμπιπτόντως, περισσότερο περιεχόμενο θα έρθει σύντομα στην αυτόνομη έκδοση!
settings:
- title: Settings
+ title: Ρυθμίσεις
categories:
- general: General
- userInterface: User Interface
- advanced: Advanced
+ general: Γενικές
+ userInterface: Περιβάλλον χρήστη
+ advanced: Προχωρημένα
versionBadges:
dev: Development
@@ -647,161 +645,162 @@ settings:
labels:
uiScale:
- title: Interface scale
+ title: Κλίμακα περιβάλλοντος χρήστη
description: >-
- Changes the size of the user interface. The interface will still scale based on your device resolution, but this setting controls the amount of scale.
+ Αλλάζει το μέγεθος του περιβάλλοντος χρήστη. Το περιβάλλον χρήστη θα κλιμακωθεί με βάση την ανάλυση της συσκευής σας, αλλά αυτή η ρύθμιση ελέγχει το μέγεθος εντώς αυτής της κλίμακας.
scales:
- super_small: Super small
- small: Small
- regular: Regular
- large: Large
- huge: Huge
+ super_small: Πολύ μικρό
+ small: Μικρό
+ regular: Κανονικό
+ large: Μεγάλο
+ huge: Πολύ μεγάλο
scrollWheelSensitivity:
- title: Zoom sensitivity
+ title: Ευαισθησία ζουμ
description: >-
- Changes how sensitive the zoom is (Either mouse wheel or trackpad).
+ Αλλάζει πόσο ευαίσθητο είναι το ζουμ (Είτε με τον τροχό ποντικιού ή με trackpad).
sensitivity:
- super_slow: Super slow
- slow: Slow
- regular: Regular
- fast: Fast
- super_fast: Super fast
+ super_slow: Πολύ αργό
+ slow: Αργό
+ regular: Κανονικό
+ fast: Γρήγορο
+ super_fast: Πολύ γρήγορο
language:
- title: Language
+ title: Γλώσσα
description: >-
- Change the language. All translations are user contributed and might be incomplete!
+ Αλλάξτε τη γλώσσα. Γιά όλες τις μεταφράσεις έχουν συνεισφέρει χρήστες. Μερικές μεταφράσεις ενδέχεται να είναι ελλιπείς!
fullscreen:
- title: Fullscreen
+ title: Λειτουργία πλήρους οθόνης
description: >-
- It is recommended to play the game in fullscreen to get the best experience. Only available in the standalone.
+ Για την καλύτερη δυνατή εμπειρία συνιστάται η λειτουργία πλήρους οθόνης. Διατίθεται μόνο στην αυτόνομη έκδοση.
soundsMuted:
- title: Mute Sounds
+ title: Σίγαση ήχων
description: >-
- If enabled, mutes all sound effects.
+ Εάν είναι ενεργοποιημένο, σβήνει όλα τα ηχητικά εφέ.
musicMuted:
- title: Mute Music
+ title: Σίγαση μουσικής
description: >-
- If enabled, mutes all music.
+ Εάν είναι ενεργοποιημένο, σβήνει την μουσική.
theme:
- title: Game theme
+ title: Λειτουργία παιχνιδιού
description: >-
- Choose the game theme (light / dark).
+ Επίλεξε το την λειτουργία του παιχνιδιού (Φωτεινή / Σκοτεινή).
themes:
- dark: Dark
- light: Light
+ dark: Σκοτεινή
+ light: Φωτεινή
refreshRate:
- title: Simulation Target
+ title: Στόχος Προσομοίωσης
description: >-
- If you have a 144hz monitor, change the refresh rate here so the game will properly simulate at higher refresh rates. This might actually decrease the FPS if your computer is too slow.
+ Εάν έχεις οθόνη 144hz, άλλαξε τον ρυθμό ανανέωσης εδώ, ώστε το παιχνίδι να προσομοιωθεί σωστά σε υψηλότερους ρυθμούς ανανέωσης. Μπορεί να μειώσει τα FPS εάν ο υπολογιστής σου είναι πολύ αργός.
alwaysMultiplace:
- title: Multiplace
+ title: Πολλαπλή τοποθέτηση
description: >-
- If enabled, all buildings will stay selected after placement until you cancel it. This is equivalent to holding SHIFT permanently.
+ Εάν είναι ενεργοποιημένο, όλα τα κτίρια θα παραμείνουν επιλεγμένα μετά την τοποθέτηση έως ότου ακυρώσεις την επιλογή. Αυτό ισοδυναμεί με μόνιμο κράτημα του SHIFT.
offerHints:
- title: Hints & Tutorials
+ title: Συμβουλές & Οδηγίες
description: >-
- Whether to offer hints and tutorials while playing. Also hides certain UI elements onto a given level to make it easier to get into the game.
+ Αν θέλεις να προσφέρονται συμβουλές και οδηγίες ενώ παίζεις. Επίσης κρύβει ορισμένα στοιχεία του περιβάλλοντος χρήστη έως ένα δεδομένο επίπεδο, για να διευκολύνει το παιχνίδι για νέους χρήστες.
movementSpeed:
- title: Movement speed
- description: Changes how fast the view moves when using the keyboard.
+ title: Ταχύτητα κίνησης
+ description: Αλλάζει την ταχύτητα κίνησης όταν χρησιμοποιείς το πληκτρολόγιο.
speeds:
- super_slow: Super slow
- slow: Slow
- regular: Regular
- fast: Fast
- super_fast: Super Fast
- extremely_fast: Extremely Fast
+ super_slow: Πολύ αργή
+ slow: Αργή
+ regular: Κανονική
+ fast: Γρήγορη
+ super_fast: Πολύ γρήγορη
+ extremely_fast: Πάρα πολύ γρήγορη
enableTunnelSmartplace:
- title: Smart Tunnels
+ title: Έξυπνες σήραγγες
description: >-
- When enabled, placing tunnels will automatically remove unnecessary belts.
- This also enables to drag tunnels and excess tunnels will get removed.
+ Όταν ενεργοποιηθεί, η τοποθέτηση σηράγγων θα αφαιρέσει αυτόματα τις περιττές ζώνες.
+ Αυτό σου επιτρέπει επίσης να σύρεις το ποντίκι με την σήραγγα επιλεγμένη, και οι περιττές σήραγγες θα αφαιρεθούν.
+
vignette:
- title: Vignette
+ title: Βινιέτα
description: >-
- Enables the vignette which darkens the screen corners and makes text easier
- to read.
+ Ενεργοποιεί την Βιωιέτα, που σκουραίνει τις γωνίες της οθόνης και διευκολύνει την ανάγνωση του κειμένου.
autosaveInterval:
- title: Autosave Interval
+ title: Διάστημα μεταξύ αυτόματων αποθηκεύσεων
description: >-
- Controls how often the game saves automatically. You can also disable it
- entirely here.
+ Ελέγχει πόσο συχνά το παιχνίδι αποθηκεύεται αυτόματα.
+ Εδώ μπορείς επίσης να απενεργοποιήσεις την λειτουργία εντελώς.
+
intervals:
- one_minute: 1 Minute
- two_minutes: 2 Minutes
- five_minutes: 5 Minutes
- ten_minutes: 10 Minutes
- twenty_minutes: 20 Minutes
- disabled: Disabled
+ one_minute: 1 Λεπτό
+ two_minutes: 2 Λεπτά
+ five_minutes: 5 Λεπτά
+ ten_minutes: 10 Λεπτά
+ twenty_minutes: 20 Λεπτά
+ disabled: Απενεργοποιημένο
compactBuildingInfo:
- title: Compact Building Infos
+ title: Σύντομες πληροφορίες κτηρίων
description: >-
- Shortens info boxes for buildings by only showing their ratios. Otherwise a
- description and image is shown.
+ Συντομεύει τα πλαίσια πληροφοριών για κτίρια δείχνοντας μόνο την ταχύτητα λειτουργίας τους.
+ Διαφορετικά εμφανίζεται μια περιγραφή και εικόνα.
disableCutDeleteWarnings:
- title: Disable Cut/Delete Warnings
+ title: Απενεργοποίηση προειδοποιήσεων αποκοπής / διαγραφής
description: >-
- Disable the warning dialogs brought up when cutting/deleting more than 100
- entities.
+ Απενεργοποιεί τους διαλόγους προειδοποίησης που εμφανίζονται όταν κόβεις / διαγράφεις περισσότερα από 100 κτήρια.
enableColorBlindHelper:
- title: Color Blind Mode
- description: Enables various tools which allow to play the game if you are color blind.
+ title: Λειτουργία αχρωματοψίας
+ description: Ενεργοποιεί διάφορα εργαλεία που επιτρέπουν να παίξεiw το παιχνίδι αν πάσχεις από αχρωματοψία.
rotationByBuilding:
- title: Rotation by building type
+ title: Περιστροφή ανά τύπο κτιρίου
description: >-
- Each building type remembers the rotation you last set it to individually.
- This may be more comfortable if you frequently switch between placing
- different building types.
+ Κάθε τύπος κτιρίου θυμάται την περιστροφή που όρισες στην τελευταία χρήση.
+ Μπορεί να είναι πιο άνετο εάν κάνεις εναλλαγή κτηρίων μεταξύ τοποθέτησης διαφορετικών τύπων κτηρίων.
keybindings:
- title: Keybindings
+ title: Συνδιασμοί πλήκτρων
hint: >-
- Tip: Be sure to make use of CTRL, SHIFT and ALT! They enable different placement options.
+ Συμβουλή: Φρόντισε να χρησιμοποιήσεις τα πλήκτρα CTRL, SHIFT και ALT! Ενεργοποιούν διαφορετικές επιλογές τοποθέτησης.
- resetKeybindings: Reset Keyinbindings
+ resetKeybindings: Επαναφορά συνδιασμών πλήκτρων
categoryLabels:
- general: Application
- ingame: Game
- navigation: Navigating
- placement: Placement
- massSelect: Mass Select
- buildings: Building Shortcuts
- placementModifiers: Placement Modifiers
+ general: Εφαρμογή
+ ingame: Παιχνίδι
+ navigation: Πλοήγηση
+ placement: Τοποθέτηση
+ massSelect: Μαζική Επιλογή
+ buildings: Συντομεύσεις Κτηρίων
+ placementModifiers: Τροποποιητές τοποθέτησης
mappings:
- confirm: Confirm
- back: Back
- mapMoveUp: Move Up
- mapMoveRight: Move Right
- mapMoveDown: Move Down
- mapMoveLeft: Move Left
- centerMap: Center Map
+ confirm: Επιβεβαίωση
+ back: Πίσω
+ mapMoveUp: Κίνηση προς τα Πάνω
+ mapMoveRight: Κίνηση προς τα Δεξιά
+ mapMoveDown: Κίνηση προς τα Κάτω
+ mapMoveLeft: Κίνηση προς τα Αριστερά
+ centerMap: Kεντράρισμα του χάρτη
- mapZoomIn: Zoom in
- mapZoomOut: Zoom out
- createMarker: Create Marker
+ mapZoomIn: Μεγέθυνση
+ mapZoomOut: Σμίκρυνση
+ createMarker: Δημηουργία Σημαδιού
- menuOpenShop: Upgrades
- menuOpenStats: Statistics
+ menuOpenShop: Αναβαθμίσεις
+ menuOpenStats: Στατιστικές
- toggleHud: Toggle HUD
- toggleFPSInfo: Toggle FPS and Debug Info
+ toggleHud: Εναλλαγή HUD
+ toggleFPSInfo: Εναλλαγή FPS και Πληροφοριών εντοπισμού σφαλμάτων
+
+ # --- Do not translate the values in this section
belt: *belt
splitter: *splitter
underground_belt: *underground_belt
@@ -812,63 +811,67 @@ keybindings:
mixer: *mixer
painter: *painter
trash: *trash
+ # ---
- rotateWhilePlacing: Rotate
+ rotateWhilePlacing: Περιστροφή
rotateInverseModifier: >-
- Modifier: Rotate CCW instead
- cycleBuildingVariants: Cycle Variants
- confirmMassDelete: Confirm Mass Delete
- cycleBuildings: Cycle Buildings
+ Modifier: Αριστερόστροφη περιστροφή
+ cycleBuildingVariants: Επιλογή Παραλλαγής
+ confirmMassDelete: Επιβεβαίωση μαζικής διαγραφής
+ cycleBuildings: Επιλογή Κτηρίου
- massSelectStart: Hold and drag to start
- massSelectSelectMultiple: Select multiple areas
- massSelectCopy: Copy area
+ massSelectStart: Κράτησε πατημένο και σείρε για να ξεκινήσεις
+ massSelectSelectMultiple: Επίλεξε πολλές περιοχές
+ massSelectCopy: Αντιγραφή περιοχής
- placementDisableAutoOrientation: Disable automatic orientation
- placeMultiple: Stay in placement mode
- placeInverse: Invert automatic belt orientation
- pasteLastBlueprint: Paste last blueprint
- massSelectCut: Cut area
- exportScreenshot: Export whole Base as Image
- mapMoveFaster: Move Faster
- lockBeltDirection: Enable belt planner
- switchDirectionLockSide: "Planner: Switch side"
- pipette: Pipette
- menuClose: Close Menu
- switchLayers: Switch layers
- advanced_processor: Color Inverter
- energy_generator: Energy Generator
- wire: Energy Wire
+ placementDisableAutoOrientation: Απενεργοποίηση αυτόματου προσανατολισμού
+ placeMultiple: Παραμονή σε λειτουργία τοποθέτησης
+ placeInverse: Αντιστροφή αυτόματου προσανατολισμό του ιμάντα
+ pasteLastBlueprint: Επικόλληση τελευταίου σχεδιαγράμματος
+ massSelectCut: Αποκοπή περιοχής
+ exportScreenshot: Εξαγωγή ολόκληρης της βάσης ως εικόνα
+ mapMoveFaster: Ταχλυτερη κίνηση
+ lockBeltDirection: Ενεργοποίηση σχεδιαστή ιμάντα
+ switchDirectionLockSide: >-
+ Σχεδιαστής: Αλλαγή πλευράς
+
+ pipette: Σταγονόμετρο
+ menuClose: Κλείσιμο μενού
+ switchLayers: Εναλλαγή επιπέδων
+ advanced_processor: Μετατροπέας χρώματος
+ energy_generator: Γεννήτρια ενέργειας
+ wire: Καλώδιο ενέργειας
about:
- title: About this Game
+ title: Σχετικά με αυτό το παιχνίδι
body: >-
- This game is open source and developed by Tobias Springer (this is me).
+ Αυτό το παιχνίδι είναι ανοιχτού κώδικα και αναπτύχθηκε από τους Tobias Springer (αυτός είμαι εγώ).
- If you want to contribute, check out shapez.io on github .
+ Αν θέλεις να συνεισφέρεις, δες το shapez.io στο github .
- This game wouldn't have been possible without the great Discord community
- around my games - You should really join the discord server !
+ Αυτό το παιχνίδι δεν θα ήταν δυνατό χωρίς τη μεγάλη κοινότητα Discord
+ γύρω από τα παιχνίδια μου - Σας συνιστώ πραγματικά να εγγραφείτε στον
+ discord server !
- The soundtrack was made by Peppsen - He's awesome.
+ Το soundtrack δημιουργήθηκε από τους Peppsen - Είναι φοβεροί.
- Finally, huge thanks to my best friend Niklas - Without our
- factorio sessions this game would never have existed.
+ Τέλος, ευχαριστώ πολύ τον καλύτερο μου φίλο Niklas - Χωρίς
+ τις συνεδρίες μασ στο Factorio αυτό το παιχνίδι δεν θα υπήρχε.
changelog:
title: Changelog
demo:
features:
- restoringGames: Restoring savegames
- importingGames: Importing savegames
- oneGameLimit: Limited to one savegame
- customizeKeybindings: Customizing Keybindings
- exportingBase: Exporting whole Base as Image
+ restoringGames: Επαναφορά αποθηκευμένων παιχνιδιών
+ importingGames: Εισαγωγή αποθηκευμένων παιχνιδιών
+ oneGameLimit: Περιορίζεται σε ένα αποθηκευμένο παιχνίδι
+ customizeKeybindings: Προσαρμογή συνδιασμών πλήκτρων
+ exportingBase: Εξαγωγή ολόκληρης της βάσης ως εικόνα
- settingNotAvailable: Not available in the demo.
+ settingNotAvailable: Δεν είναι διαθέσιμο στο demo.
diff --git a/translations/base-en.yaml b/translations/base-en.yaml
index 28fef7e2..193a2d04 100644
--- a/translations/base-en.yaml
+++ b/translations/base-en.yaml
@@ -191,7 +191,9 @@ dialogs:
confirmSavegameDelete:
title: Confirm deletion
text: >-
- Are you sure you want to delete the game?
+ Are you sure you want to delete the following game?
+ '' at level
+ This can not be undone!
savegameDeletionError:
title: Failed to delete
@@ -378,7 +380,10 @@ ingame:
noShapesProduced: No shapes have been produced so far.
# Displays the shapes per second, e.g. '523 / s'
- shapesPerSecond: / s
+ shapesDisplayUnits:
+ second: / s
+ minute: / m
+ hour: / h
# Settings menu, when you press "ESC"
settingsMenu:
@@ -390,7 +395,7 @@ ingame:
buttons:
continue: Continue
settings: Settings
- menu: Return to menu
+ menu: Menu
# Bottom left tutorial hints
tutorialHints:
@@ -479,25 +484,25 @@ buildings:
name: Tunnel Tier II
description: Allows you to tunnel resources under buildings and belts.
- # Internal name for the Balancer
- splitter:
+ # Balancer
+ balancer:
default:
- name: &splitter Balancer
+ name: &balancer Balancer
description: Multifunctional - Evenly distributes all inputs onto all outputs.
- compact:
+ merger:
name: Merger (compact)
description: Merges two conveyor belts into one.
- compact-inverse:
+ merger-inverse:
name: Merger (compact)
description: Merges two conveyor belts into one.
- compact-merge:
+ splitter:
name: Splitter (compact)
description: Splits one conveyor belt into two.
- compact-merge-inverse:
+ splitter-inverse:
name: Splitter (compact)
description: Splits one conveyor belt into two.
@@ -516,7 +521,7 @@ buildings:
ccw:
name: Rotate (CCW)
description: Rotates shapes counter-clockwise by 90 degrees.
- fl:
+ rotate180:
name: Rotate (180)
description: Rotates shapes by 180 degrees.
@@ -637,6 +642,14 @@ buildings:
name: Compare
description: Returns true if both items are exactly equal. Can compare shapes, items and booleans.
+ stacker:
+ name: Virtual Stacker
+ description: Virtually stacks the right shape onto the left.
+
+ painter:
+ name: Virtual Painter
+ description: Virtually paints the shape from the bottom input with the shape on the right input.
+
storyRewards:
# Those are the rewards gained from completing the store
reward_cutter_and_trash:
@@ -660,8 +673,8 @@ storyRewards:
title: Combiner
desc: You can now combine shapes with the combiner ! Both inputs are combined, and if they can be put next to each other, they will be fused . If not, the right input is stacked on top of the left input!
- reward_splitter:
- title: Splitter/Merger
+ reward_balancer:
+ title: Balancer
desc: The multifunctional balancer has been unlocked - It can be used to build bigger factories by splitting and merging items onto multiple belts!
reward_tunnel:
@@ -680,10 +693,15 @@ storyRewards:
title: Tunnel Tier II
desc: You have unlocked a new variant of the tunnel - It has a bigger range , and you can also mix-n-match those tunnels now!
- reward_splitter_compact:
- title: Compact Balancer
+ reward_merger:
+ title: Compact Merger
desc: >-
- You have unlocked a compact variant of the balancer - It accepts two inputs and merges them into one belt!
+ You have unlocked a merger variant of the balancer - It accepts two inputs and merges them into one belt!
+
+ reward_splitter:
+ title: Compact Splitter
+ desc: >-
+ You have unlocked a merger variant of the balancer - It accepts one input and splits them into two!
reward_cutter_quad:
title: Quad Cutting
@@ -709,6 +727,10 @@ storyRewards:
title: Blueprints
desc: You can now copy and paste parts of your factory! Select an area (Hold CTRL, then drag with your mouse), and press 'C' to copy it. Pasting it is not free , you need to produce blueprint shapes to afford it! (Those you just delivered).
+ reward_rotater_180:
+ title: Rotater (180 degrees)
+ desc: You just unlocked the 180 degress rotater ! - It allows you to rotate a shape by 180 degress (Surprise! :D)
+
# Special reward, which is shown when there is no reward actually
no_reward:
title: Next level
@@ -775,7 +797,7 @@ settings:
movementSpeed:
title: Movement speed
description: >-
- Changes how fast the view moves when using the keyboard.
+ Changes how fast the view moves when using the keyboard or moving the mouse to the screen borders.
speeds:
super_slow: Super slow
slow: Slow
@@ -830,7 +852,7 @@ settings:
refreshRate:
title: Tick Rate
description: >-
- The game will automatically adjust the tickrate to be between this target tickrate and half of it. For example, with a tickrate of 60hz, the game will try to stay at 60hz, and if your computer can't handle it it will go down until it eventually reaches 30hz.
+ This determines how many game ticks happen per second. In general, a higher tick rate means better precision but also worse performance. On lower tickrates, the throughput may not be exact.
alwaysMultiplace:
title: Multiplace
@@ -898,12 +920,22 @@ settings:
description: >-
Enabled by default, selects the miner if you use the pipette when hovering a resource patch.
+ simplifiedBelts:
+ title: Simplified Belts (Ugly)
+ description: >-
+ Does not render belt items except when hovering the belt to save performance. I do not recommend to play with this setting if you do not absolutely need the performance.
+
+ enableMousePan:
+ title: Enable Mouse Pan
+ description: >-
+ Allows to move the map by moving the cursor to the edges of the screen. The speed depends on the Movement Speed setting.
+
keybindings:
title: Keybindings
hint: >-
Tip: Be sure to make use of CTRL, SHIFT and ALT! They enable different placement options.
- resetKeybindings: Reset Keybindings
+ resetKeybindings: Reset
categoryLabels:
general: Application
@@ -939,7 +971,7 @@ keybindings:
# --- Do not translate the values in this section
belt: *belt
- splitter: *splitter
+ balancer: *balancer
underground_belt: *underground_belt
miner: *miner
cutter: *cutter
@@ -1004,3 +1036,56 @@ demo:
exportingBase: Exporting whole Base as Image
settingNotAvailable: Not available in the demo.
+
+tips:
+ - The hub accepts input of any kind, not just the current shape!
+ - Make sure your factories are modular - it will pay out!
+ - Don't build too close to the hub, or it will be a huge chaos!
+ - If stacking does not work, try switching the inputs.
+ - You can toggle the belt planner direction by pressing R .
+ - Holding CTRL allows dragging of belts without auto-orientation.
+ - Ratios stay the same, as long as all upgrades are on the same Tier.
+ - Serial execution is more efficient than parallel.
+ - You will unlock more variants of buildings later in the game!
+ - You can use T to switch between different variants.
+ - Symmetry is key!
+ - You can weave different tiers of tunnels.
+ - Try to build compact factories - it will pay out!
+ - The painter has a mirrored variant which you can select with T
+ - Having the right building ratios will maximize efficiency.
+ - At maximum level, 5 extractors will fill a single belt.
+ - Don't forget about tunnels!
+ - You don't need to divide up items evenly for full efficiency.
+ - Holding SHIFT will activate the belt planner, letting you place long lines of belts easily.
+ - Cutters always cut vertically, regardless of their orientation.
+ - To get white mix all three colors.
+ - The storage buffer priorities the first output.
+ - Invest time to build repeatable designs - it's worth it!
+ - Holding CTRL allows to place multiple buildings.
+ - You can hold ALT to invert the direction of placed belts.
+ - Efficiency is key!
+ - Shape patches that are further away from the hub are more complex.
+ - Machines have a limited speed, divide them up for maximum efficiency.
+ - Use balancers to maximize your efficiency.
+ - Organization is important. Try not to cross conveyors too much.
+ - Plan in advance, or it will be a huge chaos!
+ - Don't remove your old factories! You'll need them to unlock upgrades.
+ - Try beating level 18 on your own before seeking for help!
+ - Don't complicate things, try to stay simple and you'll go far.
+ - You may need to re-use factories later in the game. Plan your factories to be re-usable.
+ - Sometimes, you can find a needed shape in the map without creating it with stackers.
+ - Full windmills / pinwheels can never spawn naturally.
+ - Color your shapes before cutting for maximum efficiency.
+ - With modules, space is merely a perception; a concern for mortal men.
+ - Make a separate blueprint factory. They're important for modules.
+ - Have a closer look on the color mixer, and your questions will be answered.
+ - Use CTRL + Click to select an area.
+ - Building too close to the hub can get in the way of later projects.
+ - The pin icon next to each shape in the upgrade list pins it to the screen.
+ - Mix all primary colours together to make white!
+ - You have an infinite map, don't cramp your factory, expand!
+ - Also try Factorio! It's my favourite game.
+ - The quad cutter cuts clockwise starting from the top right!
+ - You can download your savegames in the main menu!
+ - This game has a lot of useful keybindings! Be sure to check out the settings page.
+ - This game has a lot of settings, be sure to check them out!
diff --git a/translations/base-fi.yaml b/translations/base-fi.yaml
index 5acc58cf..17ad35d6 100644
--- a/translations/base-fi.yaml
+++ b/translations/base-fi.yaml
@@ -168,7 +168,7 @@ dialogs:
deleteGame: Tiedän mitä olen tekemässä
viewUpdate: Näytä päivitys
showUpgrades: Näytä Päivitykset
- showKeybindings: Show Keybindings
+ showKeybindings: Näytä pikanäppäimet
importSavegameError:
title: Tuonti Virhe
@@ -258,7 +258,7 @@ dialogs:
createMarker:
title: Uusi Merkki
desc: Anna merkille kuvaava nimi, voit myös sisällyttää muodon lyhyen avaimen siihen. (Lyhyen avaimen voit luoda täällä )
- titleEdit: Edit Marker
+ titleEdit: Muokkaa merkkiä
markerDemoLimit:
desc: Voit tehdä vain kaksi mukautettua merkkiä demoversiossa. Hanki itsenäinen versio saadaksesi loputtoman määrän merkkejä!
@@ -267,8 +267,8 @@ dialogs:
title: Vie kuvakaappaus
desc: Pyysit tukikohtasi viemistä kuvakaappauksena. Huomaa, että tämä voi olla melko hidasta isolla tukikohdalla ja voi jopa kaataa pelisi!
massCutInsufficientConfirm:
- title: Confirm cut
- desc: You can not afford to paste this area! Are you sure you want to cut it?
+ title: Vahvista leikkaus
+ desc: Sinulla ei ole varaa leikata tätä aluetta! Oletko varma että haluat leikata sen?
ingame:
# This is shown in the top left corner and displays useful keybindings in
@@ -303,8 +303,8 @@ ingame:
purple: Violetti
cyan: Syaani
white: Valkoinen
- uncolored: Ei Väriä
- black: Black
+ uncolored: Väritön
+ black: Musta
# Everything related to placing buildings (I.e. as soon as you selected a building
# from the toolbar)
@@ -465,7 +465,7 @@ buildings:
tier2:
name: Tunneli Taso II
- description: Sallii resurssien kuljetuksen rakennuksien ja hihnojen alta.
+ description: Sallii resurssien kuljetuksen rakennuksien ja hihnojen alta pidemmältä kantamalta.
splitter: # Internal name for the Balancer
default:
@@ -498,11 +498,11 @@ buildings:
name: &rotater Kääntäjä
description: Kääntää muotoja 90 astetta myötäpäivään.
ccw:
- name: Rotate (Vastapäivään)
+ name: Kääntäjä (Vastapäivään)
description: Kääntää muotoja 90 astetta vastapäivään.
fl:
- name: Rotate (180)
- description: Rotates shapes by 180 degrees.
+ name: Kääntäkä (180)
+ description: Kääntää muotoja 180 astetta.
stacker:
default:
@@ -550,11 +550,11 @@ buildings:
description: Tuottaa sähköä kuluttamalla muotoja. Jokainen sähkögeneraattori vaatii eri muotoja.
wire_crossings:
default:
- name: Wire Splitter
- description: Splits a energy wire into two.
+ name: Johdon jakaja
+ description: Jakaa energiajohdon kahteen.
merger:
- name: Wire Merger
- description: Merges two energy wires into one.
+ name: Johtojen yhdistäjä
+ description: Yhdistää kaksi energiajohtoa yhteen.
storyRewards:
# Those are the rewards gained from completing the store
@@ -642,9 +642,9 @@ storyRewards:
settings:
title: Asetukset
categories:
- general: General
- userInterface: User Interface
- advanced: Advanced
+ general: Yleinen
+ userInterface: Käyttöliittyma
+ advanced: Kehittynyt
versionBadges:
dev: Kehitys
@@ -736,17 +736,17 @@ settings:
refreshRate:
title: Simulaatiotavoite
description: >-
- Jos sinulla on 144hz näyttö, muuta virkistystaajuus täällä jotta pelin simulaatio toimii oikein isommilla virkistystaajuuksilla. Tämä voi laskea FPS nopeutta jos tietokoneesi on liian hidas.
+ Jos sinulla on 144hz näyttö, muuta virkistystaajuus täällä jotta pelin simulaatio toimii oikein isommilla virkistystaajuuksilla. Tämä voi laskea FPS nopeutta, jos tietokoneesi on liian hidas.
alwaysMultiplace:
title: Monisijoitus
description: >-
- Jos käytössä, kaikki rakennukset pysyvät valittuina sijoittamisen jälkeen kunnes peruutat sen. Tämä vastaa SHIFT:in pitämistö pohjassa ikuisesti.
+ Jos käytössä, kaikki rakennukset pysyvät valittuina sijoittamisen jälkeen kunnes peruutat sen. Tämä vastaa SHIFT:in pitämistä pohjassa ikuisesti.
offerHints:
title: Vihjeet & Oppaat
description: >-
- Tarjotaanko pelaamisen aikana vihjeitä ja oppaita. Myös piilottaa tietyt käyttöliittymäelementit tietyn tason mukaan, jotta alkuunpääseminen olisi helpompaa.
+ Tarjoaa pelaamisen aikana vihjeitä ja oppaita. Myös piilottaa tietyt käyttöliittymäelementit tietyn tason mukaan, jotta alkuunpääseminen olisi helpompaa.
enableTunnelSmartplace:
title: Älykkäät Tunnelit
@@ -771,12 +771,12 @@ settings:
disableCutDeleteWarnings:
title: Poista Leikkaus/Poisto Varoitukset
description: >-
- Poista varoitusikkunat dialogs brought up when cutting/deleting more than 100 entities.
+ Poista varoitusikkunat jotka ilmestyy kun leikkaat/poistat enemmän kuin 100 entiteettiä
keybindings:
title: Pikanäppäimet
hint: >-
- Tip: Muista käyttää CTRL, VAIHTO and ALT! Ne ottavat käyttöön erilaisia sijoitteluvaihtoehtoja.
+ Tip: Muista käyttää CTRL, VAIHTO ja ALT! Ne ottavat käyttöön erilaisia sijoitteluvaihtoehtoja.
resetKeybindings: Nollaa Pikanäppäimet
@@ -843,13 +843,13 @@ keybindings:
placementDisableAutoOrientation: Poista automaattinen suunta käytöstä
placeMultiple: Pysy sijoittamistilassa
- placeInverse: Käännä automaattinen hihnan suunta
- menuClose: Close Menu
+ placeInverse: Käännä automaattinen hihnan suunta päinvastoin
+ menuClose: Sulje valikko
about:
title: Tietoja tästä pelistä
body: >-
- Tämä peli on avoimen lähdekoodin ja kehitettä on Tobias Springer (tämä on minä).
+ Tämä peli on avointa lähdekoodia ja kehittäjä on Tobias Springer (tämä on minä).
Jos haluat osallistua, tarkista shapez.io githubissa .
diff --git a/translations/base-fr.yaml b/translations/base-fr.yaml
index 0504956a..704f8896 100644
--- a/translations/base-fr.yaml
+++ b/translations/base-fr.yaml
@@ -32,15 +32,15 @@ steamPage:
[img]{STEAM_APP_IMAGE}/extras/store_page_gif.gif[/img]
shapez.io est un jeu dans lequel vous devrez construire des usines pour automatiser la création et la combinaison de formes de plus en plus complexes sur une carte infinie.
- Lors de la livraison des formes requises vous progresserez et débloquerez des améliorations pour accélerer votre usine.
+ En livrant les formes requises, vous progresserez et débloquerez des améliorations pour accélérer votre usine.
- Au vu de l'augmentation des demandes de formes, vous devrez agrandir votre usine pour répondre à la forte demande - Mais n'oubliez pas les ressources, vous drevrez vous étendre au milieu de cette [b]carte infinie[/b] !
+ Vous devrez agrandir votre usine pour répondre à l’augmentation de la demande en formes — Mais n’oubliez pas les ressources, vous devrez vous étendre au milieu de cette [b]carte infinie[/b] !
- Bientôt vous devrez mixer les couleurs et peindre vos formes avec - Combinez les ressources de couleurs rouge, verte et bleue pour produire différentes couleurs et peindre les formes avec pour satisfaire la demande.
+ Bientôt, vous devrez mélanger les couleurs et peindre vos formes avec — Combinez les ressources de couleurs rouge, verte et bleue pour produire différentes couleurs et peindre les formes avec pour satisfaire la demande.
- Ce jeu propose 18 niveaux progressifs (qui devraient déjà vous occuper quelques heures !) mais j'ajoute constamment de nouveau contenus - Il y en a beaucoup de prévus !
+ Ce jeu propose 18 niveaux progressifs (qui devraient déjà vous occuper quelques heures !) mais je développe constamment plus de contenu — Il y a beaucoup de choses prévues !
- Acheter le jeu vous donne accès à la version complète qui a des fonctionnalités additionnelles et vous recevrez aussi un accès à des fonctionnalités fraîchement développées.
+ Acheter le jeu vous donne accès à la version complète qui a des fonctionnalités supplémentaires, et vous pourrez aussi accéder aux fonctionnalités fraîchement développées.
[b]Avantages de la version complète (standalone)[/b]
@@ -48,30 +48,30 @@ steamPage:
[*] Mode sombre
[*] Balises infinies
[*] Parties infinies
- [*] Plus d'options
- [*] Prochainement: Câbles et énergie ! Prévu pour (environ) fin Juillet 2020.
- [*] Prochainement: Plus de niveaux
- [*] Aidez moi à continuer de développer shapez.io ❤️
+ [*] Plus d’options
+ [*] Prochainement : Câbles et énergie ! Prévu pour (environ) fin juillet 2020.
+ [*] Prochainement : Plus de niveaux
+ [*] Aidez-moi à continuer de développer shapez.io ❤️
[/list]
- [b]Mises à jour futures[/b]
+ [b]Mises à jour à venir[/b]
- Je fais souvent des mises à jour et essaye d'en sortir une par semaine!
+ Je fais souvent des mises à jour et j’essaye d’en sortir une par semaine !
[list]
[*] Différentes cartes et challenges (e.g. carte avec obstacles)
- [*] Puzzles (Délivrer la forme requise avec une zone limitée/jeu de bâtiments)
+ [*] Casse-tête (Livrer la forme requise avec une zone limitée / jeu de bâtiments)
[*] Un mode histoire où les bâtiments ont un coût
- [*] Générateur de carte configurable (configuration des ressources/formes/taille/densitée, seed et plus)
- [*] Plus de formes
- [*] Amélioration des performances (Le jeu tourne déjà plutot bien !)
- [*] Et bien plus !
+ [*] Générateur de carte configurable (configuration des ressources / formes / taille / densité, graine aléatoire et plus)
+ [*] Plus de niveaux
+ [*] Amélioration des performances (Le jeu tourne déjà plutôt bien !)
+ [*] Et bien plus !
[/list]
- [b]Ce jeu est open source ![/b]
+ [b]Ce jeu est open source ![/b]
- Tout le monde peut contribuer, je suis très impliqué dans la communauté et j'essaye de répondre à toutes les suggestions et prendre en compte vos retours si possible.
- Jetez un coup d'œil à mon Trello pour le suivi du projet et la planification du développement !
+ Tout le monde peut contribuer, je suis très impliqué dans la communauté et j’essaye de répondre à toutes les suggestions et prendre en compte vos retours si possible.
+ Jetez un coup d’œil à mon Trello pour le suivi du projet et les plans de développement !
[b]Liens[/b]
[list]
@@ -82,19 +82,20 @@ steamPage:
[*] [url=https://github.com/tobspr/shapez.io/blob/master/translations/README.md]Aidez à traduire[/url]
[/list]
- discordLink: Discord officiel - Parlez avec moi!
+ discordLink: Discord officiel — Parlez avec moi !
global:
loading: Chargement
error: Erreur
# How big numbers are rendered, e.g. "10,000"
- thousandsDivider: " "
+ # En français, le séparateur des milliers est l’espace (fine) insécable
+ thousandsDivider: " "
# What symbol to use to seperate the integer part from the fractional part of a number, e.g. "0.4"
decimalSeparator: ","
- # The suffix for large numbers, e.g. 1.3k, 400.2M, etc. cf wikipedia système international d'unité
+ # The suffix for large numbers, e.g. 1.3k, 400.2M, etc. cf wikipedia système international d’unité
# For french: https://fr.wikipedia.org/wiki/Pr%C3%A9fixes_du_Syst%C3%A8me_international_d%27unit%C3%A9s
suffix:
thousands: k
@@ -108,20 +109,20 @@ global:
time:
# Used for formatting past time dates
oneSecondAgo: il y a une seconde
- xSecondsAgo: il y a secondes
+ xSecondsAgo: il y a secondes
oneMinuteAgo: il y a une minute
- xMinutesAgo: il y a minutes
+ xMinutesAgo: il y a minutes
oneHourAgo: il y a une heure
- xHoursAgo: il y a heures
+ xHoursAgo: il y a heures
oneDayAgo: il y a un jour
- xDaysAgo: il y a jours
+ xDaysAgo: il y a jours
# Short formats for times, e.g. '5h 23m'
- secondsShort: s
- minutesAndSecondsShort: m s
- hoursAndMinutesShort: h m
+ secondsShort: s
+ minutesAndSecondsShort: m s
+ hoursAndMinutesShort: h m
- xMinutes: minutes
+ xMinutes: minutes
keys:
tab: TAB
@@ -135,21 +136,21 @@ demoBanners:
# This is the "advertisement" shown in the main menu and other various places
title: Version démo
intro: >-
- Achetez la version complète pour débloquer toutes les fonctionnalités !
+ Achetez la version complète pour débloquer toutes les fonctionnalités !
mainMenu:
play: Jouer
changelog: Historique
importSavegame: Importer
- openSourceHint: Ce jeu est open source !
+ openSourceHint: Ce jeu est open source !
discordLink: Serveur Discord officiel
- helpTranslate: Contribuez à la traduction !
+ helpTranslate: Contribuez à la traduction !
# This is shown when using firefox and other browsers which are not supported.
browserWarning: >-
- Désolé, ce jeu est connu pour tourner lentement sur votre navigateur web ! Procurez-vous la version complète ou téléchargez Chrome pour une meilleure expérience.
+ Désolé, ce jeu sera lent sur votre navigateur web ! Procurez-vous la version complète ou téléchargez Chrome pour une meilleure expérience.
- savegameLevel: Niveau
+ savegameLevel: Niveau
savegameLevelUnknown: Niveau inconnu
continue: Continuer
@@ -165,16 +166,16 @@ dialogs:
later: Plus tard
restart: Relancer
reset: Réinitialiser
- getStandalone: Se procurer la version complète
+ getStandalone: Obtenir la version complète
deleteGame: Je sais ce que je fais
viewUpdate: Voir les mises à jour
showUpgrades: Montrer les améliorations
showKeybindings: Montrer les raccourcis
importSavegameError:
- title: Erreur d'importation
+ title: Erreur d’importation
text: >-
- Impossible d'importer votre sauvegarde:
+ Impossible d’importer votre sauvegarde :
importSavegameSuccess:
title: Sauvegarde importée
@@ -184,17 +185,17 @@ dialogs:
gameLoadFailure:
title: La sauvegarde est corrompue
text: >-
- Impossible de charger votre sauvegarde:
+ Impossible de charger votre sauvegarde :
confirmSavegameDelete:
title: Confirmez la suppression
text: >-
- Êtes-vous certains de vouloir supprimer votre partie ?
+ Êtes-vous sûr de vouloir supprimer votre partie ?
savegameDeletionError:
title: Impossible de supprimer
text: >-
- Impossible de supprimer votre sauvegarde:
+ Impossible de supprimer votre sauvegarde :
restartRequired:
title: Redémarrage requis
@@ -211,91 +212,91 @@ dialogs:
keybindingsResetOk:
title: Réinitialisation des contrôles
- desc: Les contrôles ont été réinitialisés dans leur état par défaut respectifs !
+ desc: Les contrôles ont été remis à défaut !
featureRestriction:
title: Version démo
- desc: Vous avez essayé d'accéder à la fonction () qui n'est pas disponible dans la démo. Considérez l'achat de la version complète pour une expérience optimale !
+ desc: Vous avez essayé d’accéder à la fonction () qui n’est pas disponible dans la démo. Pensez à acheter la version complète pour une expérience optimale !
oneSavegameLimit:
title: Sauvegardes limitées
- desc: Vous ne pouvez avoir qu'une seule sauvegarde en même temps dans la version démo. Merci d'effacer celle en cours ou alternativement de vous procurer la version complète !
+ desc: Vous ne pouvez avoir qu’une seule sauvegarde en même temps dans la version démo. Merci d’effacer celle en cours ou bien de vous procurer la version complète !
updateSummary:
- title: Nouvelle mise à jour !
+ title: Nouvelle mise à jour !
desc: >-
- Voici les modifications depuis votre dernière session:
+ Voici les changements depuis votre dernière session :
upgradesIntroduction:
title: Débloquer les améliorations
desc: >-
- Toutes les formes que vous produisez peuvent être utilisées pour débloquer des améliorations - Ne détruisez pas vos anciennes usines !
- L'onglet des améliorations se trouve dans le coin supérieur droit de l'écran.
+ Toutes les formes que vous produisez peuvent être utilisées pour débloquer des améliorations — Ne détruisez pas vos anciennes usines !
+ L’onglet des améliorations se trouve dans le coin supérieur droit de l’écran.
massDeleteConfirm:
title: Confirmation de suppression
desc: >-
- Vous allez supprimer pas mal de bâtiments ( pour être exact) ! Êtes vous certains de vouloir faire ça ?
+ Vous allez supprimer beaucoup de bâtiments ( pour être précis) ! Êtes-vous sûr de vouloir faire ça ?
massCutConfirm:
title: Confirmer la coupure
desc: >-
- Vous vous apprêtez à couper beaucoup de bâtiments ( pour être précis) ! Êtes-vous certains de vouloir faire ça ?
+ Vous allez couper beaucoup de bâtiments ( pour être précis) ! Êtes-vous sûr de vouloir faire ça ?
blueprintsNotUnlocked:
title: Pas encore débloqué
desc: >-
- Les patrons n'ont pas encore étés débloqués ! Terminez encore quelques niveaux pour y avoir accès.
+ Les patrons n’ont pas encore été débloqués ! Terminez le niveau 12 pour y avoir accès.
keybindingsIntroduction:
title: Raccourcis utiles
desc: >-
Le jeu a de nombreux raccourcis facilitant la construction de grandes usines.
- En voici quelques uns, n'hésitez pas à aller découvrir les raccourcis !
- CTRL
+ Glisser: Sélectionne une zone à copier / effacer.
- SHIFT
: Laissez appuyé pour placer plusieurs fois le même bâtiment.
- ALT
: Inverse l'orientation des convoyeurs placés.
+ En voici quelques-uns, n’hésitez pas à aller découvrir les raccourcis !
+ CTRL
+ glisser : Sélectionne une zone à copier / effacer.
+ MAJ
: Laissez appuyé pour placer plusieurs fois le même bâtiment.
+ ALT
: Inverse l’orientation des convoyeurs placés.
createMarker:
title: Nouvelle balise
- desc: Donnez-lui un nom, vous pouvez aussi inclure le raccourci d'une forme (Que vous pouvez générer ici )
- titleEdit: Éditer cette balise
+ desc: Donnez-lui un nom, vous pouvez aussi inclure le raccourci d’une forme (que vous pouvez générer ici ).
+ titleEdit: Modifier cette balise
markerDemoLimit:
- desc: Vous ne pouvez créer que deux balises dans la démo. Achetez la version complète pour en faire autant que vous voulez !
+ desc: Vous ne pouvez créer que deux balises dans la démo. Achetez la version complète pour en placer autant que vous voulez !
exportScreenshotWarning:
- title: Exporter une capture d'écran
+ title: Exporter une capture d’écran
desc: >-
- Vous avez demandé à exporter votre base sous la forme d'une capture d'écran. Soyez conscient que cela peut s'avérer passablement lent pour une grande base, voire même faire planter votre jeu !
+ Vous avez demandé à exporter une capture d’écran de votre base. Soyez conscient que cela peut s’avérer passablement lent pour une grande base, voire faire planter votre jeu !
massCutInsufficientConfirm:
title: Confirmer la coupe
- desc: Vous n'avez pas les moyens de copier cette zone ! Etes vous certain de vouloir la couper ?
+ desc: Vous n’avez pas les moyens de copier cette zone ! Êtes-vous sûr de vouloir la couper ?
ingame:
# This is shown in the top left corner and displays useful keybindings in
# every situation
keybindingsOverlay:
moveMap: Déplacer
- selectBuildings: Sélection d'une zone
- stopPlacement: Arrêter le placement
+ selectBuildings: Sélection d’une zone
+ stopPlacement: Arrêter de placer
rotateBuilding: Tourner le bâtiment
placeMultiple: Placement multiple
- reverseOrientation: Changer l'orientation
- disableAutoOrientation: Désactiver l'orientation automatique
- toggleHud: Basculer l'affichage tête haute (ATH)
+ reverseOrientation: Changer l’orientation
+ disableAutoOrientation: Désactiver l’orientation automatique
+ toggleHud: Basculer l’affichage tête haute (ATH)
placeBuilding: Placer un bâtiment
createMarker: Créer une balise
delete: Supprimer
pasteLastBlueprint: Copier le dernier patron
- lockBeltDirection: Utiliser le plannificateur de convoyeurs
- plannerSwitchSide: Échanger la direction du plannificateur
+ lockBeltDirection: Utiliser le planificateur de convoyeurs
+ plannerSwitchSide: Inverser la direction du planificateur
cutSelection: Couper
copySelection: Copier
clearSelection: Effacer la sélection
pipette: Pipette
- switchLayers: Échanger les calques
+ switchLayers: Changer de calque
# Everything related to placing buildings (I.e. as soon as you selected a building
# from the toolbar)
@@ -306,29 +307,29 @@ ingame:
# Shows the hotkey in the ui, e.g. "Hotkey: Q"
hotkeyLabel: >-
- Raccourci:
+ Raccourci :
infoTexts:
speed: Vitesse
range: Portée
storage: Espace de stockage
- oneItemPerSecond: 1 forme / s
- itemsPerSecond: formes / s
- itemsPerSecondDouble: (x2)
+ oneItemPerSecond: 1 forme ⁄ s
+ itemsPerSecond: formes ⁄ s
+ itemsPerSecondDouble: (×2)
- tiles: cases
+ tiles: cases
# The notification when completing a level
levelCompleteNotification:
# is replaced by the actual level, so this gets 'Level 03' for example.
- levelTitle: Niveau
+ levelTitle: Niveau
completed: Terminé
- unlockText: débloqué !
+ unlockText: débloqué !
buttonNextLevel: Niveau suivant
# Notifications on the lower right
notifications:
- newUpgrade: Une nouvelle amélioration est disponible !
+ newUpgrade: Une nouvelle amélioration est disponible !
gameSaved: Votre partie a été sauvegardée.
# The "Upgrades" window
@@ -337,11 +338,11 @@ ingame:
buttonUnlock: Améliorer
# Gets replaced to e.g. "Tier IX"
- tier: Niveau
+ tier: Niveau
# The roman number for each tier
tierLabels: [I, II, III, IV, V, VI, VII, VIII, IX, X]
- maximumLevel: NIVEAU MAXIMAL (Vitesse x