diff --git a/CHANGELOG.md b/CHANGELOG.md index 56084bf..208ef67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## v1.2.0 + +Two panel improvements. **All co-op players must update together**: earlier versions refuse an Apply that stores nothing. Saves load both ways with v1.1.x. + +- Set every good to 0% (for example with Clear all) and click **Apply: store nothing** to make a warehouse or pile store nothing, like a newly built one. Before, Apply stayed unavailable unless the total was 100%. Stock already there is kept and can be hauled out. Like any lowered limit, it waits for deliveries already on their way. +- While your draft differs from the building's current settings, the Apply button has an orange ring and bold text, so a waiting change is visible even when the message under the goods list is scrolled out of view. + ## v1.1.1 Two fixes from the v1.1.0 reviews. Saves load both ways with v1.1.0; co-op players should update together. diff --git a/Directory.Build.props b/Directory.Build.props index 6042338..fcf7999 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -3,6 +3,6 @@ with it (and the startup log line reads it from the assembly). build.ps1 refuses to build when packaging/MixedStorage/version-1.1/manifest.json says otherwise, and to package a DLL built with another. --> - 1.1.1 + 1.2.0 diff --git a/README.md b/README.md index c9b3c01..7982ad3 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ Divide a building's capacity by percentage. For example, a 1,200-capacity warehouse can reserve **50% for carrots (600)** and **50% for gears (600)**. Percentages reserve space; they do not create goods or instantly fill the building. -**[Download MixedStorage v1.1.1](https://github.com/timbermods/MixedStorage/releases/download/v1.1.1/MixedStorage-v1.1.1.zip)** · [Release notes](https://github.com/timbermods/MixedStorage/releases/tag/v1.1.1) · [Report a problem](https://github.com/timbermods/MixedStorage/issues) · [Website](https://timbermods.github.io/MixedStorage/) +**[Download MixedStorage v1.2.0](https://github.com/timbermods/MixedStorage/releases/download/v1.2.0/MixedStorage-v1.2.0.zip)** · [Release notes](https://github.com/timbermods/MixedStorage/releases/tag/v1.2.0) · [Report a problem](https://github.com/timbermods/MixedStorage/issues) · [Website](https://timbermods.github.io/MixedStorage/) -> **v1.1.1** is the current release, built for Timberborn **1.1.2.4**. One download covers single-player and BeaverBuddies multiplayer. +> **v1.2.0** is the current release, built for Timberborn **1.1.2.4**. One download covers single-player and BeaverBuddies multiplayer. image @@ -22,7 +22,7 @@ Divide a building's capacity by percentage. For example, a 1,200-capacity wareho ## Install -1. Download **MixedStorage-v1.1.1.zip** above. On the release page, choose that file under **Assets**, not **Source code**. +1. Download **MixedStorage-v1.2.0.zip** above. On the release page, choose that file under **Assets**, not **Source code**. 2. Close Timberborn. Extract the ZIP's **MixedStorage** folder into your Timberborn **Mods** folder—normally `Documents\Timberborn\Mods` on Windows. 3. Check that `Documents\Timberborn\Mods\MixedStorage\version-1.1\manifest.json` exists. Avoid an extra nested MixedStorage folder. 4. Install **Harmony** 2.4.1 or newer from the [Steam Workshop](https://steamcommunity.com/sharedfiles/filedetails/?id=3284904751) if you don't have it. Enable **Harmony** and **MixedStorage** in the game's mod manager, then restart when prompted. @@ -40,13 +40,15 @@ Divide a building's capacity by percentage. For example, a 1,200-capacity wareho For the example above, enter `50` for carrots and `50` for gears, with everything else at `0`. A 1,200-capacity warehouse will allow 600 of each. -**Edits are drafts until you click Apply.** The top summary continues to show the applied settings and actual stock while you edit, search, or filter. Normal hauling rules determine when goods arrive. +To store nothing in a building, set every good to 0% (for example with **Clear all**) and click **Apply: store nothing**. It then stores nothing, like a newly built one. Stock already there is kept and can be hauled out. + +**Edits are drafts until you click Apply.** While the draft differs from the building's current settings, the Apply button gets an orange border and bold text. The top summary continues to show the applied settings and actual stock while you edit, search, or filter. Normal hauling rules determine when goods arrive. | Control | What it does | | --- | --- | | **Max** | Sets that good to 100% and all others to 0%. Click Apply to confirm. | | **× beside a percentage** | Resets that good's draft percentage to 0%. | -| **Clear all** | Clears draft percentages. Current allocations stay active until you apply a valid replacement. | +| **Clear all** | Sets every draft percentage to 0%. Apply it to store nothing, or enter new percentages. Current allocations stay active until you click Apply. | | **Revert** | Discards edits and restores the current settings. | | **Allocated goods only** | Shows goods with a nonzero draft percentage. | | **Copy allocations** | Copies a valid draft totaling 100%. | @@ -89,7 +91,7 @@ Applied allocations synchronize through BeaverBuddies. Apply may briefly show a | Problem | Check this | | --- | --- | | Mod does not appear | Check the folder structure, enable Harmony and MixedStorage, and restart. | -| Apply is unavailable | Every percentage must be valid and the total must be exactly 100%. Goods marked "(not accepted here)" or "(unavailable)", which a saved allocation can still hold after a goods mod is removed, must be set to 0%. Wait if a multiplayer change is queued. | +| Apply is unavailable | Every percentage must be valid and the total must be exactly 100%, or 0% to store nothing. Goods marked "(not accepted here)" or "(unavailable)", which a saved allocation can still hold after a goods mod is removed, must be set to 0%. Wait if a multiplayer change is queued. | | Paste is rejected | The destination must accept every good with a nonzero copied percentage. | | Lower limit is rejected | Wait for incoming deliveries to finish. | | Startup mentions the old addon | Remove or disable MixedStorage-BeaverBuddies, then fully restart. | @@ -110,7 +112,7 @@ Built against **Timberborn 1.1.2.4**. The bundled multiplayer integration is built against the **[BeaverBuddies Stability Fork](https://github.com/timbermods/BeaverBuddies-Stability-Fork)** (formerly called Stability Preview), which is the build to use. Every Stability Fork release so far, 1.0.0 through 1.1.12, has everything the integration needs; install the latest. At startup, MixedStorage checks the installed BeaverBuddies for every part it uses. If anything is missing, it turns co-op Apply off rather than risk a desync, and Player.log names what is missing. The original [BeaverBuddies](https://github.com/thomaswp/BeaverBuddies) by thomaswp and contributors, and BeaverBuddies MultiColony (Beta), have not been tested with MixedStorage. -Players have reported successful use of earlier builds, and the **v0.5.8 layout, including the dev-mode panel, and the v0.5.7 storage visuals have been verified in game**; v1.0.0 and v1.1.x leave both unchanged. The v1.0.0 and v1.1.x changes (Copy settings, error messages, loading damaged saves, the Supply mode order, the panel's reason for an unavailable Apply, patch order, and leaving mixed storage with a removed good or through the map editor's undo) have not been played in game yet. Automated allocation, geometry, native API, and optional multiplayer loading checks also pass, but these do not replace live gameplay testing. +Players have reported successful use of earlier builds, and the **v0.5.8 layout, including the dev-mode panel, and the v0.5.7 storage visuals have been verified in game**; v1.0.0 through v1.2.0 leave both unchanged apart from v1.2.0's orange ring around Apply. The v1.0.0 to v1.2.0 changes (Copy settings, error messages, loading damaged saves, the Supply mode order, the panel's reason for an unavailable Apply, patch order, leaving mixed storage with a removed good or through the map editor's undo, and in v1.2.0 storing nothing and the Apply ring) have not been played in game yet. Automated allocation, geometry, native API, and optional multiplayer loading checks also pass, but these do not replace live gameplay testing. See the [changelog](CHANGELOG.md) for version history and [developer notes](docs/DEVELOPMENT.md) for build instructions and technical details. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 3dbf9c0..f7061eb 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -18,7 +18,9 @@ The allocation checks need no game files, so GitHub Actions also runs them on ev Percentages use integer units totaling 10,000. Whole-item limits use largest-remainder rounding with ordinal good-ID ordering for ties. Incoming reservations guard against conflicting limit reductions; existing excess stock is preserved. Copy/paste transfers percentages atomically into a draft and rejects incompatible goods. Hauling mode and priority are not copied. In Supply mode a mixed building offers its allocated goods with the most unreserved stock first, ordinal good IDs breaking ties (`AllocationPlan.SupplyCandidates`). Goods without unreserved stock are skipped: the game's search for a building to take one scans the whole district and can only fail, so skipping them never changes which good is carried. Those searches did fill the building's cached road route map, which a few of the game's path queries use only when it is already filled, so co-op players still need the same MixedStorage build. -The game's Copy settings tool (called Duplicate settings in the game's code and in these notes) calls `SingleGoodAllower.DuplicateFrom`. A mixed source applies its allocation to the target through the same checks as Apply. They run before the base game's copy of the single good, so when they reject it that copy is skipped and logged, and the target keeps its allocation or single good whether or not it was mixed. The tool copies each of the building's other settings separately, such as the storage mode (`StockpilePriority`), so those still apply. A source set to store nothing, such as a building just placed, leaves a mixed target's allocation alone (the base game would clear the target's good), so copying the storage mode from a new building does not wipe a tuned allocation, which has no undo. Any other source gives the target that building's single good, as in the base game, so a mixed target first leaves mixed mode (`StorageState.Deactivate`). That is the only way back to the base game's rules. The storage panel stores a single good as a 100% allocation, so such a source is a building given a single good in the goods dropdown of the game's building list (`StockpileDropdownProvider`, which still works on a building without an allocation; `AllowPatch` and `DisallowPatch` ignore it on a mixed one), a warehouse or pile from before the mod, or a storage the mod does not manage, such as the map editor's reserve storage or another mod's storage. Leaving lowers limits too, so it gets Apply's incoming-delivery guard: the base game has room only for the kept good, and none for it while any other good is in stock. A delivery that would no longer fit refuses the copy the same way, before the base game's copy runs. The decision is `AllocationPlan.PlanCopy`, and what the patch then does (leave, run the base game's copy, apply, or log a refusal) is `AllocationPlan.Steps`; the allocation tests cover both. BeaverBuddies replays the tool on every player (`DuplicationEvent`), and the decision reads only simulation state (accepted goods, capacity, stock and reservations), so every player decides the same. Leaving mixed mode announces every formerly allocated good the building accepts, because the game's `InventoryRegistry` caches which buildings have room for each good and only updates a good when it is announced. A good the building does not accept is limited to 0 by the game whatever the allocation says, and a saved allocation can name a good the game no longer knows (after a goods mod is removed), which `InventoryRegistry` would throw on, so neither is announced. During those announcements the visuals are pointed at the representative good, so the pile keeps showing what it holds. Loading also mirrors the save: a mixed building reloaded without an allocation (the map editor's undo) leaves mixed mode the same way, and one reloaded with another allocation announces the goods of both. A building loaded from a save is never mixed before its own load, so a normal save load announces nothing. A redraw queued before a building left mixed mode finds no allocation and puts the native pile back instead of disabling the mixed visuals. +The game's Copy settings tool (called Duplicate settings in the game's code and in these notes) calls `SingleGoodAllower.DuplicateFrom`. A mixed source applies its allocation to the target through the same checks as Apply. They run before the base game's copy of the single good, so when they reject it that copy is skipped and logged, and the target keeps its allocation or single good whether or not it was mixed. The tool copies each of the building's other settings separately, such as the storage mode (`StockpilePriority`), so those still apply. A source set to store nothing, such as a building just placed, leaves a mixed target's allocation alone (the base game would clear the target's good), so copying the storage mode from a new building does not wipe a tuned allocation, which has no undo. Any other source gives the target that building's single good, as in the base game, so a mixed target first leaves mixed mode (`StorageState.Deactivate`). Apart from applying all 0% (below), that is the only way back to the base game's rules. The storage panel stores a single good as a 100% allocation, so such a source is a building given a single good in the goods dropdown of the game's building list (`StockpileDropdownProvider`, which still works on a building without an allocation; `AllowPatch` and `DisallowPatch` ignore it on a mixed one), a warehouse or pile from before the mod, or a storage the mod does not manage, such as the map editor's reserve storage or another mod's storage. Leaving lowers limits too, so it gets Apply's incoming-delivery guard: the base game has room only for the kept good, and none for it while any other good is in stock. A delivery that would no longer fit refuses the copy the same way, before the base game's copy runs. The decision is `AllocationPlan.PlanCopy`, and what the patch then does (leave, run the base game's copy, apply, or log a refusal) is `AllocationPlan.Steps`; the allocation tests cover both. BeaverBuddies replays the tool on every player (`DuplicationEvent`), and the decision reads only simulation state (accepted goods, capacity, stock and reservations), so every player decides the same. Leaving mixed mode announces every formerly allocated good the building accepts, because the game's `InventoryRegistry` caches which buildings have room for each good and only updates a good when it is announced. A good the building does not accept is limited to 0 by the game whatever the allocation says, and a saved allocation can name a good the game no longer knows (after a goods mod is removed), which `InventoryRegistry` would throw on, so neither is announced. During those announcements the visuals are pointed at the representative good, so the pile keeps showing what it holds. Loading also mirrors the save: a mixed building reloaded without an allocation (the map editor's undo) leaves mixed mode the same way, and one reloaded with another allocation announces the goods of both. A building loaded from a save is never mixed before its own load, so a normal save load announces nothing. A redraw queued before a building left mixed mode finds no allocation and puts the native pile back instead of disabling the mixed visuals. + +Apply with every good at 0% (`AllocationPlan.IsNothing`) makes the building store nothing, the base game's state for a building just placed. It is sent as the payload `AllocationPlan.Nothing` (`1|`, an allocation of no goods), which `DeserializeCommand` reads back as an empty plan. Saves never hold it, and `Deserialize` still refuses it. Earlier versions refuse it as unreadable, so co-op players must run the same version. `StorageState.TryClear` leaves mixed mode like a copy does, then calls the base game's `Disallow`. Every limit drops to 0, so it waits for every incoming delivery (`AllocationPlan.CanLeave` with no kept good), and stock already there stays as excess. While allocations are frozen it is refused on a mixed building, which could not leave mixed mode; on a single-good building it is only the base game's `Disallow`. It bumps `Revision` either way, so an open editor on every player reloads its draft. Every announcement goes through the game's private `SingleGoodAllower.InvokeDisallowedGoodsChangedEvent(string)`, looked up by signature when `ModStarter` starts. If a game update renames or changes it, `ModStarter` logs why and allocations are frozen instead of half-applied: Apply is refused with that reason, and so is every copy that would set or leave an allocation (from a mixed building, or onto one), while copies between single-good buildings work as in the base game. A mixed building stays mixed, and saved allocations keep limiting their buildings. The game still starts: `ModStarter` reads this through `AllocationProblem`, which also reports, rather than throws, a `StorageState` that cannot load at all. Frozen mode depends on the installed game, so every co-op player must run the same game version; BeaverBuddies only warns when they differ, and a player whose game lacks the method would refuse changes the others apply. @@ -44,13 +46,13 @@ Native goods meshes and materials are reused. Complete primary/secondary mesh ce Updates are coalesced to at most five rebuilds per building per second. A building none of whose drawn sections is visible to a camera (`Renderer.isVisible`) is redrawn at most once every two seconds and catches up when it comes into view; storage with nothing drawn yet is always built immediately. A rebuild redraws only the sections whose good changed fill level. Section boundaries depend on the allocation and on each good's full-capacity footprint, cached per good and capacity, not on stock, so new allocations or a capacity change redraw every section and a delivery redraws one. A section copies only the vertices of its own cells out of the native variant mesh into reused buffers, and moves them with a plain offset when the native object has no rotation or scale, so a redraw allocates almost no managed memory. Reflection lookups on the native (internal) types are resolved once per type. Generated meshes/materials have lifecycle cleanup, and a building that leaves mixed mode goes back to the native visuals. Rendering does not intentionally consume simulation randomness or add multiplayer commands. -The editor has one scrolling body and a fixed footer containing Copy/Paste allocations, the allocation total, and Clear/Revert/Apply. The shared native `EntityPanel` targets 440 UI units, bounded by the viewport, so every fragment stretches to the same width. Its original inline width is restored when the storage view closes, detaches, or switches to an unsupported selection. Height is based on available space below the allocation editor's current position, less the height of any visible fragments the game stacks beneath it in the same column (for example the Construction site panel while a building is unfinished) and, with dev mode on, the debug panel the game shows after them (`DiagnosticFragments`, a sibling of `Fragments` directly under the `EntityPanel`, which holds buttons such as Finish now), so those stay on screen. The game's own layout files are readable in `Timberborn_Data\StreamingAssets\Modding\UI.zip`. +The editor has one scrolling body and a fixed footer containing Copy/Paste allocations, the allocation total, and Clear/Revert/Apply. The message line scrolls with the body, so while Apply is available and the draft differs from the applied settings (`AllocationPlan.Differs` against `StorageState.Draft`), Apply gets a 2px border in the game's stock-bar orange and bold text. `NineSliceButton` draws its background in the padding rect, inside the border, so the border rings the button's own cream frame instead of being painted over. The check also runs on the panel's 0.4-second refresh, because the goods dropdown of the game's building list changes a single-good building without a new `Revision`. The shared native `EntityPanel` targets 440 UI units, bounded by the viewport, so every fragment stretches to the same width. Its original inline width is restored when the storage view closes, detaches, or switches to an unsupported selection. Height is based on available space below the allocation editor's current position, less the height of any visible fragments the game stacks beneath it in the same column (for example the Construction site panel while a building is unfinished) and, with dev mode on, the debug panel the game shows after them (`DiagnosticFragments`, a sibling of `Fragments` directly under the `EntityPanel`, which holds buttons such as Finish now), so those stay on screen. The game's own layout files are readable in `Timberborn_Data\StreamingAssets\Modding\UI.zip`. The mod reuses the installed game's styles and assets: `NineSliceVisualElement` panels, `bg-sub-box--green` and `bg-sub-box--blue` frames, `button-game` buttons from the native DebugButton template, native TextFields cloned from the InputBox template, and the game's checkbox/scrollbar styles. Game art is not bundled in the mod. Existing summary sizes and allocation controls are retained. Appearance at different resolutions and UI scales still needs verification. ## Validation -- 19,115 allocation assertions: 2,000 randomized splits, lists up to 100 goods, capacities 20/30/180/200/1000/1200, validation, rounding, persistence (every malformed saved value fails the one way loading handles), Duplicate settings decisions and what the patch does with each (including 2,000 random copies that must decide the same whatever order the goods are listed in), delivery guards, Supply order (2,000 randomized stock levels, each carrying the same good as the unfiltered order it replaced), and the editor's total line (1,000 randomized drafts, each allowing Apply exactly as before). +- 19,138 allocation assertions: 2,000 randomized splits, lists up to 100 goods, capacities 20/30/180/200/1000/1200, validation, rounding, persistence (every malformed saved value fails the one way loading handles), Duplicate settings decisions and what the patch does with each (including 2,000 random copies that must decide the same whatever order the goods are listed in), delivery guards, Supply order (2,000 randomized stock levels, each carrying the same good as the unfiltered order it replaced), and the editor's total line (1,000 randomized drafts, each allowing Apply exactly as before), storing nothing (the all-0% draft, its Apply payload and delivery guard), and when Apply is highlighted. - All 11 supported template names checked against the game's Blueprints.zip: each has exactly one `.blueprint.json`, with that template name and Box (warehouse) or Pileable (pile) goods. - Every Harmony patch in the built DLL checked against installed game assemblies (`visual-tests/PatchTargetTests.cs`), resolved the way Harmony does at startup: 22 targets in 20 patch classes, the 4 injected `___` fields and the 11 other named parameters, with their types. A renamed target would otherwise throw from `PatchAll` and stop the game from starting. The same test checks the 6 reflection handles the mod keeps in static fields, the 8 native visualizer members `MixedContentsRenderer` reads by name, that the mod reads the installed BeaverBuddies' `EventIO.IsNull` as "no connection", and that LateGamePerformance's two trusted patches keep their names and Harmony id, with no other patch on the methods its counting workers call, on its 15 saving helpers, or on anything one of the game's component `Save` methods calls directly (read from their IL). - 201 whole-cell partition cases covering boundary ownership, complete topology, compact vertices, per-vertex attributes, and unknown-topology fallback. @@ -60,7 +62,7 @@ The mod reuses the installed game's styles and assets: `NineSliceVisualElement` - Isolated loading processes with and without BeaverBuddies check eager main-type enumeration, bridge event discovery, delegate installation, repeated initialization, and obsolete-addon rejection. A stub BeaverBuddies with one member missing (`loading-tests/StubBeaverBuddies`) checks that an incompatible build is skipped without stopping startup, that the reason names exactly that member, that a failed bridge is not loaded twice, and that Apply without the bridge only counts as single-player when BeaverBuddies reports no connection. They also check that every prefix that can replace the game's method (every prefix returning `bool`, in every class Harmony's `PatchAll` would patch) carries `[HarmonyPriority(Priority.Last)]`, on the method or on its class. - BeaverBuddies replays the Duplicate settings tool on every player. A loading check walks the IL of the patches that run inside that replay, and of every mod method they call, and fails if any of them reads the panel's message or pending state, the panel or renderer, submits a command, or reads a clock, input or random numbers (`loading-tests/ReplayChecks.cs`). Two control scans check that it finds such state where the mod does use it. -Loading checks run under .NET, not inside Unity/Mono. They do not establish live multiplayer compatibility. Builds pass without compiler warnings; v0.5.8's layout has been visually verified in game, and v1.0.0 and v1.1.x leave it unchanged. The v1.0.0 and v1.1.x Duplicate settings, startup, loading, Supply order, editor status, patch priority and announcement changes have not been exercised in game yet. The mod's startup log line reads its version from the assembly, and both DLLs take theirs from `Directory.Build.props`, so a release bump touches only that file, the manifest, the README and changelog, and the website's Project status note in `site/index.html`. `tests/check-version.ps1`, which `build.ps1` runs before building and CI runs on every pull request, fails when the manifest's version differs from `Directory.Build.props` or a mod `.csproj` sets its own ``, and `build.ps1` stops before packaging when a built DLL carries another version. +Loading checks run under .NET, not inside Unity/Mono. They do not establish live multiplayer compatibility. Builds pass without compiler warnings; v0.5.8's layout has been visually verified in game, and v1.0.0 through v1.2.0 leave it unchanged apart from v1.2.0's ring around Apply. The v1.0.0 to v1.2.0 Duplicate settings, startup, loading, Supply order, editor status, patch priority, announcement, store-nothing and Apply ring changes have not been exercised in game yet. The mod's startup log line reads its version from the assembly, and both DLLs take theirs from `Directory.Build.props`, so a release bump touches only that file, the manifest, the README and changelog, and the website's Project status note in `site/index.html`. `tests/check-version.ps1`, which `build.ps1` runs before building and CI runs on every pull request, fails when the manifest's version differs from `Directory.Build.props` or a mod `.csproj` sets its own ``, and `build.ps1` stops before packaging when a built DLL carries another version. ## Website diff --git a/packaging/MixedStorage/version-1.1/manifest.json b/packaging/MixedStorage/version-1.1/manifest.json index e931c67..54a78a8 100644 --- a/packaging/MixedStorage/version-1.1/manifest.json +++ b/packaging/MixedStorage/version-1.1/manifest.json @@ -1,8 +1,8 @@ { "Name": "MixedStorage", - "Version": "1.1.1", + "Version": "1.2.0", "Id": "kyler.mixedstorage", "MinimumGameVersion": "1.1.2.4", - "Description": "Per-good percentage allocations for warehouses and small, large, industrial and underground piles. Uses each building's allowed goods. Search, set exact percentages, and apply only when the total is 100%.", + "Description": "Per-good percentage allocations for warehouses and small, large, industrial and underground piles. Uses each building's allowed goods. Search, set exact percentages, and apply when the total is 100%, or 0% to store nothing.", "RequiredMods": [{ "Id": "Harmony", "MinimumVersion": "2.4.1" }] } diff --git a/site/assets/demo.js b/site/assets/demo.js index 4e33f17..db1d21e 100644 --- a/site/assets/demo.js +++ b/site/assets/demo.js @@ -115,23 +115,31 @@ function validate() { var fieldsOk = GOODS.every(function (g) { return state.valid[g.id]; }); var total = GOODS.reduce(function (a, g) { return a + state.draft[g.id]; }, 0); - var valid = fieldsOk && total === TOTAL; + // Every good at 0% applies too: the building then stores nothing, as when it was just built. + var nothing = fieldsOk && total === 0; + var valid = fieldsOk && (total === TOTAL || nothing); els.apply.disabled = !valid; - els.copy.disabled = !valid; + els.apply.textContent = nothing ? 'Apply: store nothing' : 'Apply 100%'; + els.copy.disabled = !valid || nothing; els.paste.disabled = !state.copied; if (!fieldsOk) els.total.textContent = 'Enter valid percentages (0–100, 2 decimals)'; + else if (nothing) els.total.textContent = '0% allocated — Apply to store nothing'; else if (total === TOTAL) els.total.textContent = '100% / 100% allocated'; else els.total.textContent = fmt(total) + '% / 100% — ' + fmt(Math.abs(total - TOTAL)) + (total < TOTAL ? '% remaining' : '% over'); els.total.classList.toggle('is-bad', !valid); - var preview = valid ? limitsFor(state.draft) : null; - GOODS.forEach(function (g) { rowEls[g.id].limit.textContent = preview ? String(preview[g.id]) : '—'; }); + var preview = valid && !nothing ? limitsFor(state.draft) : null; + GOODS.forEach(function (g) { rowEls[g.id].limit.textContent = preview ? String(preview[g.id]) : nothing ? '0' : '—'; }); var zero = preview ? GOODS.filter(function (g) { return state.draft[g.id] > 0 && preview[g.id] === 0; }).length : 0; - els.round.textContent = zero > 0 - ? zero + ' allocated good(s) round to 0 items. Increase their shares or use larger storage.' + els.round.textContent = nothing ? 'Every limit becomes 0. Stock already here is kept and can be hauled out.' + : zero > 0 ? zero + ' allocated good(s) round to 0 items. Increase their shares or use larger storage.' : 'Limits round to whole items; leftover slots go to the largest fractions. All slots are allocated.'; els.round.classList.toggle('is-bad', zero > 0); + + // Apply stands out while pressing it would change the building. + var changed = GOODS.some(function (g) { return state.draft[g.id] !== (state.applied[g.id] || 0); }); + els.apply.classList.toggle('is-pending', valid && changed); } function filter() { @@ -150,8 +158,8 @@ var allocated = GOODS.filter(function (g) { return state.applied[g.id] > 0; }); var limits = limitsFor(state.applied); var totalStock = GOODS.reduce(function (a, g) { return a + (state.stock[g.id] || 0); }, 0); - els.summary.textContent = totalStock + ' / ' + state.capacity + ' items · ' + allocated.length + - (allocated.length === 1 ? ' good allocated' : ' goods allocated'); + els.summary.textContent = totalStock + ' / ' + state.capacity + ' items · ' + (allocated.length === 0 ? 'Stores nothing' : + allocated.length + (allocated.length === 1 ? ' good allocated' : ' goods allocated')); var html = '', shown = 0; GOODS.forEach(function (g) { @@ -178,8 +186,10 @@ if (!fieldsOk || els.apply.disabled) return; state.applied = {}; GOODS.forEach(function (g) { if (state.draft[g.id] > 0) state.applied[g.id] = state.draft[g.id]; }); + var nothing = Object.keys(state.applied).length === 0; loadDraft(); - setMsg('Applied. Excess stock is preserved and can be hauled out.', 'good'); + setMsg(nothing ? 'Applied. This building stores nothing now; stock already here can be hauled out.' + : 'Applied. Excess stock is preserved and can be hauled out.', 'good'); } function revealList() { var top = els.head.getBoundingClientRect().top - els.scroll.getBoundingClientRect().top + els.scroll.scrollTop - 4; @@ -220,7 +230,7 @@ els.revert.addEventListener('click', function () { loadDraft(); setMsg('Draft reverted.', ''); }); els.clear.addEventListener('click', function () { els.only.checked = false; - setDraft({}, 'Draft cleared. Existing allocations remain active until Apply.'); + setDraft({}, 'Draft cleared. Apply to store nothing here, or set new percentages. Nothing changes until Apply.'); }); els.copy.addEventListener('click', function () { if (els.copy.disabled) return; diff --git a/site/assets/game-panel.css b/site/assets/game-panel.css index 64735b6..24203c7 100644 --- a/site/assets/game-panel.css +++ b/site/assets/game-panel.css @@ -148,6 +148,8 @@ .ig-total.is-bad { color: var(--ig-bad); } .ig-actions { display: flex; gap: 4px; margin-top: 6px; padding-right: 7px; } .ig-actions .ig-apply { flex: 1 1 0; margin-right: 0; } +/* Unapplied changes: an orange ring around the button's own frame, as in the mod. */ +.ig-apply.is-pending { font-weight: 700; box-shadow: 0 0 0 2px var(--ig-orange), inset 0 0 0 1.5px var(--ig-tan-line); } .ig-clip .ig-btn { margin-right: 0; } @media (max-width: 900px) { diff --git a/site/faq.html b/site/faq.html index 93766b5..a2b9cea 100644 --- a/site/faq.html +++ b/site/faq.html @@ -56,11 +56,11 @@

General

What happens if I remove MixedStorage?

Close Timberborn, then disable MixedStorage in the mod manager or delete its folder. In saves that used it, each mixed building goes back to storing only its largest allocated good. As when you switch a warehouse to a different good in the base game, haulers empty out the other goods, and may move some of the kept good too, before the building fills with it again.

Is it an official Timberborn mod?

No. It's an unofficial community mod and isn't affiliated with or endorsed by Mechanistry.

Using it

-
Why does the total have to be exactly 100%?

So the building's whole capacity is allocated. Apply stays unavailable until the total is exactly 100%, and the line under the list tells you how much is remaining or over.

+
Why does the total have to be exactly 100%?

So the building's whole capacity is allocated. Apply stays unavailable until the total is exactly 100%, and the line under the list tells you how much is remaining or over. The one exception is 0%: with every good at 0%, Apply: store nothing makes the building store nothing, like a newly built one.

What does 0% mean?

A good at 0% is disabled in that building. Leave goods you don't want at 0%.

How precise can percentages be?

Two decimal places, so down to 0.01%.

-
What does Max do? How do I go back to a single good?

Max sets that good to 100% and every other good to 0% in your draft. Click Apply 100% to confirm. That's also how you give one good the whole building again.

To turn a mixed building back into a normal single-good one, use the game's Copy settings tool from a normal building that stores a good this one accepts. To make such a building, pick a good for a building without an allocation, such as one just built, in the goods dropdown of the game's building list. If a delivery already on its way would no longer fit, the building stays mixed and Player.log says why; copy again once it has arrived. Once it is a normal building, clearing its good in that dropdown makes it store nothing. Copying from a building set to store nothing leaves the allocation as it is.

-
Are my edits applied immediately?

No. Edits are drafts until you click Apply. Revert discards them, and Clear all clears the draft. Current allocations stay active until you apply a valid replacement.

+
What does Max do? How do I go back to a single good?

Max sets that good to 100% and every other good to 0% in your draft. Click Apply 100% to confirm. That's also how you give one good the whole building again.

To turn a mixed building back into a normal single-good one, use the game's Copy settings tool from a normal building that stores a good this one accepts. To make such a building, pick a good for a building without an allocation, such as one just built, in the goods dropdown of the game's building list. If a delivery already on its way would no longer fit, the building stays mixed and Player.log says why; copy again once it has arrived. To make a mixed building store nothing instead, click Clear all and then Apply: store nothing. Copying from a building set to store nothing leaves the allocation as it is.

+
Are my edits applied immediately?

No. Edits are drafts until you click Apply. Revert discards them, and Clear all sets every good to 0%. Current allocations stay active until you click Apply. While your draft differs from the building's settings, the Apply button has an orange border.

Can I copy an allocation to other buildings?

Yes. Click Copy allocations, select another building, click Paste allocations, then Apply. Item limits are recalculated for the destination's capacity, and the destination must accept every copied good with a nonzero percentage. Stock, hauling mode, and hauler priority aren't copied, and the copied settings are kept only until you close the game.

The game's own Copy settings tool works too and applies the percentages straight away. If the target doesn't accept all of those goods, or an incoming delivery conflicts, the target keeps its current goods and percentages and Player.log says why. The tool's other settings, such as the storage mode, are still copied.

Do Accept, Obtain, Supply, Empty, and hauler priority still work?

Yes. Those continue to use the game's own hauling system.

Does the summary at the top change when I search or filter?

No. It always shows the applied settings and actual stock, including incoming and excess goods, regardless of search or filters.

diff --git a/site/index.html b/site/index.html index 3e3eae8..e008c59 100644 --- a/site/index.html +++ b/site/index.html @@ -88,7 +88,7 @@

Many goods. One building.

Divide a building's capacity, good by good

A 1,200-capacity warehouse can reserve 50% for carrots (600) and 50% for gears (600). Percentages reserve space. They don't create goods or instantly fill the building, so your beavers keep hauling by the normal rules.

-

Mix goods by percentage

Give any good the building normally accepts a share of its capacity, down to 0.01%. Shares must total exactly 100%, so every slot has a purpose.

+

Mix goods by percentage

Give any good the building normally accepts a share of its capacity, down to 0.01%. Shares must total exactly 100%, so every slot has a purpose. Set everything to 0% to store nothing.

Stock at a glance

Summary cards show each good's icon, stored / limit count, allocated percentage, and a fill bar, including incoming deliveries and excess stock.

Quick setup

Search the goods list, show only allocated goods, click Max to give one good everything, or copy an allocation and paste it into another compatible building. The game's own Copy settings tool copies allocations too. Edits stay drafts until you Apply.

Safe with your stock

Lowering a limit never deletes goods. Extras are flagged as excess and leave the normal way, and deliveries already on their way are counted before a change is accepted.

@@ -255,7 +255,7 @@

Up and running in three steps

Project status

-

MixedStorage 1.1.1 is the current release. Its panel layout and storage visuals are unchanged from v0.5.8, which was checked in game. The changes since then (the game's Copy settings tool, clearer error messages, loading damaged saves, the Supply mode order, the reason shown when Apply is unavailable, patch order, and in 1.1.1 leaving mixed storage safely) haven't been played in game yet. Players have reported successful use of earlier builds, and automated checks cover the allocation math, mesh geometry, native game API calls, and optional multiplayer loading. Those checks don't replace live gameplay testing, particularly for multiplayer.

+

MixedStorage 1.2.0 is the current release. Its panel layout and storage visuals are unchanged from v0.5.8, which was checked in game, apart from 1.2.0's orange ring around Apply. The changes since then (the game's Copy settings tool, clearer error messages, loading damaged saves, the Supply mode order, the reason shown when Apply is unavailable, patch order, leaving mixed storage safely, and in 1.2.0 storing nothing and the Apply ring) haven't been played in game yet. Players have reported successful use of earlier builds, and automated checks cover the allocation math, mesh geometry, native game API calls, and optional multiplayer loading. Those checks don't replace live gameplay testing, particularly for multiplayer.

Found something odd? Check the troubleshooting guide or open an issue.

diff --git a/site/install.html b/site/install.html index 6b7f2d5..8e54e69 100644 --- a/site/install.html +++ b/site/install.html @@ -122,7 +122,7 @@

The controls

MaxSets that good to 100% and all others to 0%. Click Apply to confirm. × beside a percentageResets that good's draft percentage to 0%. - Clear allClears draft percentages. Current allocations stay active until you apply a valid replacement. + Clear allSets every draft percentage to 0%. Apply it to store nothing, or enter new percentages. Current allocations stay active until you click Apply. RevertDiscards edits and restores the current settings. Allocated goods onlyShows goods with a nonzero draft percentage. Copy allocationsCopies a valid draft totaling 100%. diff --git a/site/troubleshooting.html b/site/troubleshooting.html index efe8263..94dc984 100644 --- a/site/troubleshooting.html +++ b/site/troubleshooting.html @@ -60,7 +60,7 @@

Common problems

A building lost its allocation

Why it happens

  • The game's Copy settings tool was used from a normal building. That turns a mixed building back into a normal single-good one, the same way it copies a single good between normal buildings.
  • Its saved allocation couldn't be read, for example because the save file was damaged. MixedStorage skips it rather than stop the whole save from loading. The building keeps its normal single good, and Player.log has a line starting [MixedStorage] Ignoring an unreadable saved allocation.

What to do

Set the percentages again and click Apply 100%. If a save keeps losing allocations, report it with that log line.

Copy settings didn't copy my allocation

Why it happens

The game's Copy settings tool applies a mixed building's percentages to the target straight away, using the same checks as Apply. If the target doesn't accept every allocated good, or an incoming delivery conflicts with a lower limit, the allocation isn't copied and the target keeps its current goods and percentages. The tool's other settings, such as the storage mode, are still copied. Copying from a normal building, which turns a mixed building back into a normal one, is skipped the same way when a delivery already on its way would no longer fit. Player.log has a line starting [MixedStorage] Copied allocations were not applied with the reason.

What to do

Copy to a building that accepts the same goods, or wait for incoming deliveries to finish and copy again. For a building that accepts different goods, set its percentages in its own Storage Allocation panel.

There's no Storage Allocation panel when I select a building

Why it happens

Only the supported warehouses and piles get the panel. Tanks, map-editor reserve storage, and other storage buildings don't. It's also missing if the mod isn't enabled or failed to load.

What to do

  1. Compare your building with the supported list.
  2. Confirm MixedStorage and Harmony are both enabled.
  3. Search Player.log for [MixedStorage]. A working install logs a “loaded” line at startup, and a failure shows an error there.
-
Apply 100% is grayed out

Why it happens

Apply only unlocks when the draft is valid. The line under the goods list tells you which rule you're breaking:

  • Enter valid percentages (0–100, 2 decimals): one box has something invalid, such as letters, a negative number, more than two decimals, or a value over 100.
  • NN% / 100% — NN% remaining (or over): the total must be exactly 100%.
  • Set unavailable goods to 0% before applying: a good marked “(not accepted here)” or “(unavailable)” still has a percentage. A saved allocation can hold one after a goods mod is removed. Set it to 0%.
  • A multiplayer change is queued and hasn't been applied yet.

What to do

Fix the box or total the message points at. Max on one good gives you a valid draft instantly, and Revert restores the current settings. If a multiplayer change is queued, wait a moment for the next simulation tick.

+
Apply 100% is grayed out

Why it happens

Apply only unlocks when the draft is valid. The line under the goods list tells you which rule you're breaking:

  • Enter valid percentages (0–100, 2 decimals): one box has something invalid, such as letters, a negative number, more than two decimals, or a value over 100.
  • NN% / 100% — NN% remaining (or over): the total must be exactly 100%, or 0% to store nothing.
  • Set unavailable goods to 0% before applying: a good marked “(not accepted here)” or “(unavailable)” still has a percentage. A saved allocation can hold one after a goods mod is removed. Set it to 0%.
  • A multiplayer change is queued and hasn't been applied yet.

What to do

Fix the box or total the message points at. Max on one good gives you a valid draft instantly, and Revert restores the current settings. If a multiplayer change is queued, wait a moment for the next simulation tick.

Apply says “Wait for incoming deliveries to finish before lowering their limits”

Why it happens

Haulers are already carrying goods to this building, and the new limit would be lower than what's stored plus what's on its way. Incoming deliveries count toward limits.

What to do

Wait for the deliveries to finish, then click Apply again.

Paste allocations is grayed out or rejected

Why it happens

  • Nothing has been copied yet. Copy allocations works only on a valid draft totaling 100%.
  • Copied settings are kept only until you close the game, so restarting the game forgets them.
  • The destination must accept every good with a nonzero copied percentage. Otherwise you'll see “Cannot paste: this building does not accept all copied goods. Draft unchanged.”

What to do

Copy from a valid building, select a compatible destination, click Paste, and then click Apply to confirm. Stock, hauling mode, and hauler priority are never copied.

One of my goods has a limit of 0

Why it happens

Percentages become whole-item limits, and a tiny share of a small building can round down to zero items. The panel warns you: “N allocated good(s) round to 0 items. Increase their shares or use larger storage.” The limits still add up to the building's full capacity.

What to do

Increase that good's share, or use a larger storage building. The demo on the home page shows how the rounding works.

diff --git a/source/AllocationCommands.cs b/source/AllocationCommands.cs index 1177e69..c00da4e 100644 --- a/source/AllocationCommands.cs +++ b/source/AllocationCommands.cs @@ -45,8 +45,14 @@ public static bool ApplyReplay(SingleGoodAllower allower, string payload, out st var state = StorageState.Get(allower); if (state == null) { message = "Storage no longer exists or is unsupported."; return false; } Dictionary plan; - try { plan = AllocationPlan.Deserialize(payload); } + try { plan = AllocationPlan.DeserializeCommand(payload); } catch (FormatException) { message = "The allocation could not be read. Nothing was changed."; return false; } + if (plan.Count == 0) + { + if (!state.TryClear(out message)) return false; + message = "Applied. This building stores nothing now; stock already here can be hauled out."; + return true; + } if (!state.TryApply(plan, out message)) return false; message = "Applied. Excess stock is preserved and can be hauled out."; return true; diff --git a/source/AllocationPlan.cs b/source/AllocationPlan.cs index eae2b84..d7703bd 100644 --- a/source/AllocationPlan.cs +++ b/source/AllocationPlan.cs @@ -69,12 +69,24 @@ public static bool IsValid(IReadOnlyDictionary shares) => shares.All(x => !string.IsNullOrEmpty(x.Key) && x.Value >= 0 && x.Value <= Total) && shares.Sum(x => (long)x.Value) == Total; - // The editor's total line, and whether its draft may be applied or copied. A saved allocation can still name a - // good this building does not accept, for example after a goods mod was removed. Such a draft can total - // 100% and still not apply (StorageState.CanApply), so the line says what to change instead. + // A draft with every good at 0%. Applying it makes the building store nothing, as when it was just built + // (StorageState.TryClear), instead of being refused for not totaling 100%. + public static bool IsNothing(IReadOnlyDictionary draft) => + draft != null && draft.Count > 0 && draft.Values.All(x => x == 0); + + // Whether the editor's draft differs from what the building has applied (StorageState.Draft), so the editor + // can point at Apply. + public static bool Differs(IReadOnlyDictionary draft, IReadOnlyDictionary applied) => + draft.Count != applied.Count || draft.Any(x => !applied.TryGetValue(x.Key, out int share) || share != x.Value); + + // The editor's total line, and whether its draft may be applied. A saved allocation can still name a good this + // building does not accept, for example after a goods mod was removed. Such a draft can total 100% and still + // not apply (StorageState.CanApply), so the line says what to change instead. A draft of all 0% applies too, + // but only a valid allocation can be copied. public static (bool Valid, string Text) DraftStatus(IReadOnlyDictionary draft, Func takes, bool fieldsValid) { if (!fieldsValid) return (false, "Enter valid percentages (0–100, 2 decimals)"); + if (IsNothing(draft)) return (true, "0% allocated — Apply to store nothing"); long total = draft.Values.Sum(x => (long)x); if (total != Total) return (false, (total / 100m).ToString("0.##") + "% / 100% — " + (Math.Abs(total - Total) / 100m).ToString("0.##") + @@ -180,6 +192,16 @@ public static string Serialize(IReadOnlyDictionary shares) .Select(x => Uri.EscapeDataString(x.Key) + "=" + x.Value.ToString(CultureInfo.InvariantCulture))); } + // Apply's payload for a draft of all 0% (IsNothing). Saves never hold it: a building that stores nothing has no + // allocation. Earlier versions cannot read it, so co-op players must run the same version. + public const string Nothing = "1|"; + + public static string SerializeCommand(IReadOnlyDictionary draft) => IsNothing(draft) ? Nothing : Serialize(draft); + + // An Apply payload: an allocation, or no goods at all for Nothing. + public static Dictionary DeserializeCommand(string value) => + value == Nothing ? new Dictionary(StringComparer.Ordinal) : Deserialize(value); + public static Dictionary Deserialize(string value) { if (value == null || !value.StartsWith("1|", StringComparison.Ordinal)) throw new FormatException("Unsupported allocation format."); diff --git a/source/StorageState.cs b/source/StorageState.cs index 7512781..8afc717 100644 --- a/source/StorageState.cs +++ b/source/StorageState.cs @@ -111,6 +111,20 @@ public bool TryApply(IReadOnlyDictionary draft, out string error) return true; } + // Apply with every good at 0%: the building stores nothing, as when it was just built. It leaves mixed mode + // and gives up its single good. Every limit drops to 0, so it gets the same incoming-delivery guard as any + // other lowered limit; stock already here stays as excess. + public bool TryClear(out string error) + { + error = Active ? UnavailableReason : null; + if (error != null || !AllocationPlan.CanLeave(null, this, out error)) return false; + Deactivate(); + Allower.Disallow(); + // An open editor reloads its draft, also when the building was not mixed. + Revision++; + return true; + } + private void SetShares(IReadOnlyDictionary shares) { Shares = shares?.Where(x => x.Value > 0).ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal); diff --git a/source/StorageView.cs b/source/StorageView.cs index d9c4019..2a36eb6 100644 --- a/source/StorageView.cs +++ b/source/StorageView.cs @@ -50,6 +50,8 @@ private sealed class Row private static readonly Color Divider = new Color(.8f, .75f, .55f, .3f); private static readonly Color Error = new Color(1f, .52f, .43f); private static readonly Color Green = new Color(.57f, .89f, .66f); + // The game's orange, as on its stock bars; the button's own cream frame stays inside the ring. + private static readonly Color Highlight = new Color(1f, .65f, .06f); private readonly IGoodService _goods; private readonly VisualElementLoader _visualElementLoader; private readonly VisualTreeAsset _inputTemplate; @@ -76,6 +78,7 @@ private sealed class Row private int _revision; private int _messageRevision; private float _nextRefresh; + private bool _applyHighlighted; private VisualElement _entityPanel; private StyleLength _originalPanelWidth; public VisualElement Root { get; } @@ -352,20 +355,40 @@ private void LoadDraft() private void Validate() { var (valid, status) = AllocationPlan.DraftStatus(_draft, _state.Inventory.Takes, _rows.All(x => x.Valid)); + bool nothing = valid && AllocationPlan.IsNothing(_draft); _apply.SetEnabled(valid && !_state.Pending); - _copy.SetEnabled(valid); + _apply.text = nothing ? "Apply: store nothing" : "Apply 100%"; + _copy.SetEnabled(valid && !nothing); _paste.SetEnabled(_copiedAllocation != null && !_state.Pending); _total.text = status; _total.style.color = valid ? Green : Error; // Point at the goods that keep Apply off. foreach (var row in _rows) row.NameLabel.style.color = !row.Accepted && _draft[row.Id] > 0 ? new StyleColor(Error) : new StyleColor(StyleKeyword.Null); - _preview = valid ? AllocationPlan.Capacities(_draft, _state.Inventory.Capacity) : null; - foreach (var row in _rows) row.Limit.text = _preview != null ? _preview[row.Id].ToString() : "—"; + _preview = valid && !nothing ? AllocationPlan.Capacities(_draft, _state.Inventory.Capacity) : null; + foreach (var row in _rows) row.Limit.text = _preview != null ? _preview[row.Id].ToString() : nothing ? "0" : "—"; int zeroSlots = _preview == null ? 0 : _draft.Count(x => x.Value > 0 && _preview[x.Key] == 0); - _rounding.text = zeroSlots > 0 ? zeroSlots + " allocated good(s) round to 0 items. Increase their shares or use larger storage." : + _rounding.text = nothing ? "Every limit becomes 0. Stock already here is kept and can be hauled out." : + zeroSlots > 0 ? zeroSlots + " allocated good(s) round to 0 items. Increase their shares or use larger storage." : "Limits round to whole items; leftover slots go to the largest fractions. All slots are allocated."; _rounding.style.color = zeroSlots > 0 ? Error : Muted; + ShowUnapplied(); + } + + // The message line can be scrolled out of view, so Apply itself stands out while pressing it would change + // the building. NineSliceButton draws its background inside the border, so the border is a ring around it. + private void ShowUnapplied() + { + bool on = _apply.enabledSelf && AllocationPlan.Differs(_draft, _state.Draft()); + if (on == _applyHighlighted) return; + _applyHighlighted = on; + var width = on ? new StyleFloat(2) : new StyleFloat(StyleKeyword.Null); + var color = on ? new StyleColor(Highlight) : new StyleColor(StyleKeyword.Null); + var radius = on ? new StyleLength(3) : new StyleLength(StyleKeyword.Null); + _apply.style.borderTopWidth = _apply.style.borderBottomWidth = _apply.style.borderLeftWidth = _apply.style.borderRightWidth = width; + _apply.style.borderTopColor = _apply.style.borderBottomColor = _apply.style.borderLeftColor = _apply.style.borderRightColor = color; + _apply.style.borderTopLeftRadius = _apply.style.borderTopRightRadius = _apply.style.borderBottomLeftRadius = _apply.style.borderBottomRightRadius = radius; + _apply.style.unityFontStyleAndWeight = on ? new StyleEnum(FontStyle.Bold) : new StyleEnum(StyleKeyword.Null); } private void Filter() @@ -393,7 +416,7 @@ private void ClearDraft() SetInputValidity(row.Percent, true); } _allocatedOnly.SetValueWithoutNotify(false); - _message.text = "Draft cleared. Existing allocations remain active until Apply."; + _message.text = "Draft cleared. Apply to store nothing here, or set new percentages. Nothing changes until Apply."; _message.style.color = Muted; Validate(); Filter(); } @@ -439,7 +462,7 @@ private void Apply() { if (_rows.Any(x => !x.Valid)) return; SubmissionResult result; - try { result = AllocationCommands.Submit(_state, AllocationPlan.Serialize(_draft)); } + try { result = AllocationCommands.Submit(_state, AllocationPlan.SerializeCommand(_draft)); } catch (Exception ex) { // Otherwise the click would just do nothing; the log keeps the full details. @@ -454,7 +477,7 @@ private void Apply() _state.Pending = true; _message.text = "Queued for multiplayer. Applies on the next simulation tick."; _message.style.color = Muted; - _apply.SetEnabled(false); + Validate(); } else ShowResult(); RefreshStock(); @@ -469,6 +492,8 @@ public void Refresh() if (_messageRevision != _state.MessageRevision) { ShowResult(); Validate(); } if (Time.unscaledTime < _nextRefresh) return; _nextRefresh = Time.unscaledTime + .4f; + // The building's good can also change without a new revision (the goods dropdown of the game's building list). + ShowUnapplied(); RefreshStock(); } @@ -546,7 +571,8 @@ private void RefreshStock() { var inventory = _state.Inventory; _summary.text = inventory.TotalAmountInStock + " / " + inventory.Capacity + " items · " + - (_state.Active ? _state.Shares.Count + (_state.Shares.Count == 1 ? " good allocated" : " goods allocated") : "Single-good settings active"); + (_state.Active ? _state.Shares.Count + (_state.Shares.Count == 1 ? " good allocated" : " goods allocated") : + _state.Allower.HasAllowedGood ? "Single-good settings active" : "Stores nothing"); int visibleContents = 0; foreach (var row in _rows) { diff --git a/tests/Program.cs b/tests/Program.cs index 18ac8c3..46b1594 100644 --- a/tests/Program.cs +++ b/tests/Program.cs @@ -137,6 +137,47 @@ void Status(IReadOnlyDictionary draft, Func takes, bo "Apply is available exactly for a readable 100% draft of accepted goods"); } +// Every good at 0% (Clear all, or resetting the last allocated good) applies too: the building stores nothing, as when +// it was just built. Copy stays off for it (StorageView.Validate), since there is no allocation to copy. +const string NothingText = "0% allocated — Apply to store nothing"; +Status(new Dictionary { ["Log"] = 0, ["Plank"] = 0 }, _ => true, true, true, NothingText, "A draft of all 0% can be applied"); +Status(new Dictionary { ["Log"] = 0 }, _ => false, true, true, NothingText, "Goods this building does not accept may stay at 0% when storing nothing"); +Status(new Dictionary { ["Log"] = 0 }, _ => true, false, false, "Enter valid percentages (0–100, 2 decimals)", "Unreadable fields still come first"); +Check(AllocationPlan.IsNothing(new Dictionary { ["Log"] = 0, ["Plank"] = 0 }), "All 0% stores nothing"); +Check(!AllocationPlan.IsNothing(new Dictionary { ["Log"] = 0, ["Plank"] = 1 }), "0.01% of one good is not nothing"); +Check(!AllocationPlan.IsNothing(new Dictionary()) && !AllocationPlan.IsNothing(null), "A draft without goods is not an Apply to store nothing"); +// Apply's payload: an allocation reads back as before, and storing nothing as no goods. Saves never read the latter. +var nothingDraft = new Dictionary { ["Log"] = 0, ["Plank"] = 0 }; +Check(AllocationPlan.SerializeCommand(nothingDraft) == AllocationPlan.Nothing && AllocationPlan.DeserializeCommand(AllocationPlan.Nothing).Count == 0, + "Storing nothing is sent as no goods"); +var halves = new Dictionary { ["Log"] = 5000, ["Plank"] = 5000, ["Gear"] = 0 }; +var sentHalves = AllocationPlan.DeserializeCommand(AllocationPlan.SerializeCommand(halves)); +Check(sentHalves.Count == 2 && sentHalves["Log"] == 5000 && sentHalves["Plank"] == 5000, "An allocation is sent as before"); +Check(AllocationPlan.SerializeCommand(halves) == AllocationPlan.Serialize(halves), "An allocation's payload is unchanged, so saves are too"); +Reject(() => AllocationPlan.Deserialize(AllocationPlan.Nothing), "A save cannot hold an allocation of nothing"); +Reject(() => AllocationPlan.SerializeCommand(new Dictionary { ["Log"] = 5000 }), "A 50% draft cannot be sent"); +foreach (string malformed in new[] { null, "", "1", "1|A", "1|A=9999", "2|" }) +{ + bool format = false; + try { AllocationPlan.DeserializeCommand(malformed); } catch (FormatException) { format = true; } + Check(format, "A malformed Apply payload fails with FormatException: " + (malformed ?? "null")); +} +// Storing nothing lowers every limit to 0, so it waits for every incoming delivery (StorageState.TryClear). +var clearing = new FakeStorage(180, "Log", "Plank"); +clearing.StockOf["Log"] = 40; +Check(AllocationPlan.CanLeave(null, clearing, out string clearError) && clearError == null, "Stock alone does not stop storing nothing; it stays as excess"); +clearing.IncomingOf["Plank"] = 5; +Check(!AllocationPlan.CanLeave(null, clearing, out clearError) && clearError == "Wait for incoming deliveries to finish before lowering their limits.", + "Storing nothing waits for an incoming delivery"); + +// Apply stands out while the draft differs from what the building has applied (StorageView.ShowUnapplied). +var applied = new Dictionary { ["Log"] = 10000, ["Plank"] = 0 }; +Check(!AllocationPlan.Differs(new Dictionary { ["Plank"] = 0, ["Log"] = 10000 }, applied), "The applied allocation, in any order, is not a change"); +Check(AllocationPlan.Differs(new Dictionary { ["Log"] = 0, ["Plank"] = 10000 }, applied), "Max on another good is a change"); +Check(AllocationPlan.Differs(new Dictionary { ["Log"] = 0, ["Plank"] = 0 }, applied), "Clearing every good is a change"); +Check(AllocationPlan.Differs(new Dictionary { ["Log"] = 10000 }, applied) && + AllocationPlan.Differs(new Dictionary { ["Log"] = 10000, ["Gear"] = 0 }, applied), "A different list of goods is a change"); + var maxPlan = AllocationPlan.Max(new[] { "Log", "Plank", "ScrapMetal" }, "Plank"); Check(maxPlan["Plank"] == 10000 && maxPlan["Log"] == 0 && maxPlan["ScrapMetal"] == 0, "Max clears every other good"); Reject(() => AllocationPlan.Max(new[] { "Log" }, "Bread"), "Max rejects unavailable good");