Merge branch 'feature/cheque-exact-match-expire-icon'
@@ -3,6 +3,7 @@ import
3
3
itemDefinition,
4
4
itemDescription,
5
5
itemOriginSummary,
6
itemExtraTooltipLines,
6
7
itemAssetPathForStack,
7
8
itemDisplayName,
8
9
formatQuantity,
@@ -12,6 +13,7 @@ import
12
13
} from "/shared/definitions/items.js";
13
14
import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
14
15
import { stackQuantity } from "/shared/items/inventory.js";
16
import { countIdenticalInSlots } from "/shared/items/cheque.js";
15
17
import { formatLetterSignature } from "/shared/courier/systemLetters.js";
16
18
import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";
17
19
import { spellDefinition } from "/shared/definitions/spells.js";
@@ -747,7 +749,7 @@ export function initInventory ({
747
749
if (!writeChequeState)
748
750
{ return; }
749
751
writeChequeState.vaultSlotIndex = index;
750
writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableOf(slot.itemId);
752
writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableMatching(slot);
751
753
document.getElementById("write-cheque-item").textContent =
752
754
`${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
753
755
const qtyInput = document.getElementById("write-cheque-qty");
@@ -1040,7 +1042,7 @@ export function initInventory ({
1040
1042
writeChequeState.vaultSlotIndex = index;
1041
1043
writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance
1042
1044
? 1
1043
: availableOf(slot.itemId);
1045
: availableMatching(slot);
1044
1046
document.getElementById("write-cheque-item").textContent =
1045
1047
`${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
1046
1048
const qtyInput = document.getElementById("write-cheque-qty");
@@ -1066,6 +1068,11 @@ export function initInventory ({
1066
1068
});
1067
1069
}
1068
1070
1071
function availableMatching (reference)
1072
{
1073
return countIdenticalInSlots(bag.vault ?? [], reference);
1074
}
1075
1069
1076
function availableOf (itemId)
1070
1077
{
1071
1078
let total = 0;
@@ -1102,6 +1109,8 @@ export function initInventory ({
1102
1109
{ lines.push(origin); }
1103
1110
if (desc)
1104
1111
{ lines.push(desc); }
1112
for (const extra of itemExtraTooltipLines(slot))
1113
{ lines.push(extra); }
1105
1114
return lines.join("\n");
1106
1115
}
1107
1116
@@ -3,6 +3,7 @@ import3
itemDefinition,3
itemDefinition,4
itemDescription,4
itemDescription,5
itemOriginSummary,5
itemOriginSummary,6
itemExtraTooltipLines,6
itemAssetPathForStack,7
itemAssetPathForStack,7
itemDisplayName,8
itemDisplayName,8
formatQuantity,9
formatQuantity,@@ -12,6 +13,7 @@ import12
} from "/shared/definitions/items.js";13
} from "/shared/definitions/items.js";13
import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";14
import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";14
import { stackQuantity } from "/shared/items/inventory.js";15
import { stackQuantity } from "/shared/items/inventory.js";16
import { countIdenticalInSlots } from "/shared/items/cheque.js";15
import { formatLetterSignature } from "/shared/courier/systemLetters.js";17
import { formatLetterSignature } from "/shared/courier/systemLetters.js";16
import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";18
import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";17
import { spellDefinition } from "/shared/definitions/spells.js";19
import { spellDefinition } from "/shared/definitions/spells.js";@@ -747,7 +749,7 @@ export function initInventory ({747
if (!writeChequeState)749
if (!writeChequeState)748
{ return; }750
{ return; }749
writeChequeState.vaultSlotIndex = index;751
writeChequeState.vaultSlotIndex = index;750
writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableOf(slot.itemId);752
writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableMatching(slot);751
document.getElementById("write-cheque-item").textContent =753
document.getElementById("write-cheque-item").textContent =752
`${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;754
`${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;753
const qtyInput = document.getElementById("write-cheque-qty");755
const qtyInput = document.getElementById("write-cheque-qty");@@ -1040,7 +1042,7 @@ export function initInventory ({1040
writeChequeState.vaultSlotIndex = index;1042
writeChequeState.vaultSlotIndex = index;1041
writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance1043
writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance1042
? 11044
? 11043
: availableOf(slot.itemId);1045
: availableMatching(slot);1044
document.getElementById("write-cheque-item").textContent =1046
document.getElementById("write-cheque-item").textContent =1045
`${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;1047
`${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;1046
const qtyInput = document.getElementById("write-cheque-qty");1048
const qtyInput = document.getElementById("write-cheque-qty");@@ -1066,6 +1068,11 @@ export function initInventory ({1066
});1068
});1067
}1069
}1068
1070
1071
function availableMatching (reference)1072
{1073
return countIdenticalInSlots(bag.vault ?? [], reference);1074
}1075
1069
function availableOf (itemId)1076
function availableOf (itemId)1070
{1077
{1071
let total = 0;1078
let total = 0;@@ -1102,6 +1109,8 @@ export function initInventory ({1102
{ lines.push(origin); }1109
{ lines.push(origin); }1103
if (desc)1110
if (desc)1104
{ lines.push(desc); }1111
{ lines.push(desc); }1112
for (const extra of itemExtraTooltipLines(slot))1113
{ lines.push(extra); }1105
return lines.join("\n");1114
return lines.join("\n");1106
}1115
}1107
1116
@@ -1,6 +1,7 @@
1
1
import { ItemId, itemDefinition, itemAssetPathForStack } from "/shared/definitions/items.js";
2
2
import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
3
3
import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
4
import { chequeReservedGoodsStack, isFilledChequeStack } from "/shared/items/cheque.js";
4
5
import
5
6
{
6
7
applyMagentaTintToImageData,
@@ -152,31 +153,80 @@ export function isPotionStack (stack)
152
153
|| (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye");
153
154
}
154
155
155
/** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
156
export function applyItemIcon (img, stack, fallbackPath)
156
/** Resolve a stack to a UI icon data URL (tint / potion / framed when needed). */
157
export async function itemIconDataUrl (stack)
157
158
{
158
if (!img)
159
{ return; }
160
const path = fallbackPath || itemAssetPathForStack(stack);
161
img.src = path;
159
const path = itemAssetPathForStack(stack);
162
160
const def = itemDefinition(stack?.itemId);
163
161
const frames = def?.frames | 0 || 1;
164
162
if (frames > 1 && itemMaxCharges(def) != null)
165
163
{
166
const frameIndex = chargeSpriteFrameIndex(stack);
167
framedItemIconDataUrl(path, frameIndex, def.framesPerRow ?? 1, frames).then((url) =>
168
{
169
img.src = url;
170
}).catch(() =>
171
{
172
img.src = path;
173
});
174
return;
164
return framedItemIconDataUrl(
165
path,
166
chargeSpriteFrameIndex(stack),
167
def.framesPerRow ?? 1,
168
frames
169
);
175
170
}
176
171
const dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
177
172
if (dualTint)
173
{ return dualTintedItemIconDataUrl(path, dualTint); }
174
const tint = resolveItemTint(stack, def);
175
if (tint && isPotionStack(stack))
176
{ return potionIconDataUrl(stack.instance); }
177
if (tint)
178
{ return tintedItemIconDataUrl(path, tint); }
179
return path;
180
}
181
182
/** Cheque paper with reserved goods icon centered at 50% scale. */
183
export async function filledChequeIconDataUrl (chequeStack)
184
{
185
const goods = chequeReservedGoodsStack(chequeStack);
186
const chequePath = itemAssetPathForStack(chequeStack);
187
if (!goods?.itemId)
188
{ return chequePath; }
189
const goodsKey = JSON.stringify({
190
itemId: goods.itemId,
191
quantity: goods.quantity,
192
instance: goods.instance
193
});
194
const cacheKey = `cheque|${goodsKey}`;
195
if (urlCache.has(cacheKey))
196
{ return urlCache.get(cacheKey); }
197
198
const [chequeImg, goodsUrl] = await Promise.all([
199
loadImage(chequePath),
200
itemIconDataUrl(goods)
201
]);
202
const goodsImg = await loadImage(goodsUrl);
203
const size = SPRITE_SIZE_PX;
204
const canvas = document.createElement("canvas");
205
canvas.width = size;
206
canvas.height = size;
207
const ctx = canvas.getContext("2d");
208
ctx.imageSmoothingEnabled = false;
209
ctx.clearRect(0, 0, size, size);
210
ctx.drawImage(chequeImg, 0, 0, size, size);
211
const half = size * 0.5;
212
const ox = (size - half) / 2;
213
const oy = (size - half) / 2;
214
ctx.drawImage(goodsImg, 0, 0, goodsImg.width || size, goodsImg.height || size, ox, oy, half, half);
215
const url = canvas.toDataURL("image/png");
216
urlCache.set(cacheKey, url);
217
return url;
218
}
219
220
/** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
221
export function applyItemIcon (img, stack, fallbackPath)
222
{
223
if (!img)
224
{ return; }
225
const path = fallbackPath || itemAssetPathForStack(stack);
226
img.src = path;
227
if (isFilledChequeStack(stack))
178
228
{
179
dualTintedItemIconDataUrl(path, dualTint).then((url) =>
229
filledChequeIconDataUrl(stack).then((url) =>
180
230
{
181
231
img.src = url;
182
232
}).catch(() =>
@@ -185,15 +235,10 @@ export function applyItemIcon (img, stack, fallbackPath)
185
235
});
186
236
return;
187
237
}
188
const tint = resolveItemTint(stack, def);
189
if (!tint)
190
{ return; }
191
const work = isPotionStack(stack)
192
? potionIconDataUrl(stack.instance)
193
: tintedItemIconDataUrl(path, tint);
194
work.then((url) =>
238
itemIconDataUrl(stack).then((url) =>
195
239
{
196
img.src = url;
240
if (url !== path)
241
{ img.src = url; }
197
242
}).catch(() =>
198
243
{
199
244
img.src = path;
@@ -1,6 +1,7 @@1
import { ItemId, itemDefinition, itemAssetPathForStack } from "/shared/definitions/items.js";1
import { ItemId, itemDefinition, itemAssetPathForStack } from "/shared/definitions/items.js";2
import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";2
import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";3
import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";3
import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";4
import { chequeReservedGoodsStack, isFilledChequeStack } from "/shared/items/cheque.js";4
import5
import5
{6
{6
applyMagentaTintToImageData,7
applyMagentaTintToImageData,@@ -152,31 +153,80 @@ export function isPotionStack (stack)152
|| (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye");153
|| (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye");153
}154
}154
155
155
/** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */156
/** Resolve a stack to a UI icon data URL (tint / potion / framed when needed). */156
export function applyItemIcon (img, stack, fallbackPath)157
export async function itemIconDataUrl (stack)157
{158
{158
if (!img)159
const path = itemAssetPathForStack(stack);159
{ return; }160
const path = fallbackPath || itemAssetPathForStack(stack);161
img.src = path;162
const def = itemDefinition(stack?.itemId);160
const def = itemDefinition(stack?.itemId);163
const frames = def?.frames | 0 || 1;161
const frames = def?.frames | 0 || 1;164
if (frames > 1 && itemMaxCharges(def) != null)162
if (frames > 1 && itemMaxCharges(def) != null)165
{163
{166
const frameIndex = chargeSpriteFrameIndex(stack);164
return framedItemIconDataUrl(167
framedItemIconDataUrl(path, frameIndex, def.framesPerRow ?? 1, frames).then((url) =>165
path,168
{166
chargeSpriteFrameIndex(stack),169
img.src = url;167
def.framesPerRow ?? 1,170
}).catch(() =>168
frames171
{169
);172
img.src = path;173
});174
return;175
}170
}176
const dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);171
const dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);177
if (dualTint)172
if (dualTint)173
{ return dualTintedItemIconDataUrl(path, dualTint); }174
const tint = resolveItemTint(stack, def);175
if (tint && isPotionStack(stack))176
{ return potionIconDataUrl(stack.instance); }177
if (tint)178
{ return tintedItemIconDataUrl(path, tint); }179
return path;180
}181
182
/** Cheque paper with reserved goods icon centered at 50% scale. */183
export async function filledChequeIconDataUrl (chequeStack)184
{185
const goods = chequeReservedGoodsStack(chequeStack);186
const chequePath = itemAssetPathForStack(chequeStack);187
if (!goods?.itemId)188
{ return chequePath; }189
const goodsKey = JSON.stringify({190
itemId: goods.itemId,191
quantity: goods.quantity,192
instance: goods.instance193
});194
const cacheKey = `cheque|${goodsKey}`;195
if (urlCache.has(cacheKey))196
{ return urlCache.get(cacheKey); }197
198
const [chequeImg, goodsUrl] = await Promise.all([199
loadImage(chequePath),200
itemIconDataUrl(goods)201
]);202
const goodsImg = await loadImage(goodsUrl);203
const size = SPRITE_SIZE_PX;204
const canvas = document.createElement("canvas");205
canvas.width = size;206
canvas.height = size;207
const ctx = canvas.getContext("2d");208
ctx.imageSmoothingEnabled = false;209
ctx.clearRect(0, 0, size, size);210
ctx.drawImage(chequeImg, 0, 0, size, size);211
const half = size * 0.5;212
const ox = (size - half) / 2;213
const oy = (size - half) / 2;214
ctx.drawImage(goodsImg, 0, 0, goodsImg.width || size, goodsImg.height || size, ox, oy, half, half);215
const url = canvas.toDataURL("image/png");216
urlCache.set(cacheKey, url);217
return url;218
}219
220
/** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */221
export function applyItemIcon (img, stack, fallbackPath)222
{223
if (!img)224
{ return; }225
const path = fallbackPath || itemAssetPathForStack(stack);226
img.src = path;227
if (isFilledChequeStack(stack))178
{228
{179
dualTintedItemIconDataUrl(path, dualTint).then((url) =>229
filledChequeIconDataUrl(stack).then((url) =>180
{230
{181
img.src = url;231
img.src = url;182
}).catch(() =>232
}).catch(() =>@@ -185,15 +235,10 @@ export function applyItemIcon (img, stack, fallbackPath)185
});235
});186
return;236
return;187
}237
}188
const tint = resolveItemTint(stack, def);238
itemIconDataUrl(stack).then((url) =>189
if (!tint)190
{ return; }191
const work = isPotionStack(stack)192
? potionIconDataUrl(stack.instance)193
: tintedItemIconDataUrl(path, tint);194
work.then((url) =>195
{239
{196
img.src = url;240
if (url !== path)241
{ img.src = url; }197
}).catch(() =>242
}).catch(() =>198
{243
{199
img.src = path;244
img.src = path;@@ -6,6 +6,7 @@ import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRange
6
6
import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
7
7
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
8
8
import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";
9
import { chequeReservedGoodsStack, isFilledChequeStack } from "/shared/items/cheque.js";
9
10
import
10
11
{
11
12
resolveItemTint,
@@ -2066,13 +2067,14 @@ export class WorldView
2066
2067
item.displayName = payload.displayName;
2067
2068
item.sprite = spriteName;
2068
2069
item.instance = payload.instance ?? null;
2069
const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
2070
const stack = { itemId: payload.itemId, instance: payload.instance ?? null, quantity: payload.quantity };
2070
2071
const def = itemDefinition(payload.itemId);
2071
2072
item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
2072
2073
item.tintColor = item.dualTint ? null : resolveItemTint(stack, def);
2073
2074
if (item.object?.renderer && itemMaxCharges(def) != null)
2074
2075
{ item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); }
2075
2076
this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
2077
this.#syncGroundChequeOverlay(item, pivot);
2076
2078
this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
2077
2079
}
2078
2080
@@ -2081,10 +2083,56 @@ export class WorldView
2081
2083
const item = this.groundItems.get(groundItemId);
2082
2084
if (!item)
2083
2085
{ return; }
2086
item.chequeOverlay?.destroy();
2084
2087
item.object?.destroy();
2085
2088
this.groundItems.delete(groundItemId);
2086
2089
}
2087
2090
2091
#syncGroundChequeOverlay (item, pivot)
2092
{
2093
const stack = {
2094
itemId: item.itemId,
2095
instance: item.instance,
2096
quantity: item.quantity
2097
};
2098
const goods = isFilledChequeStack(stack) ? chequeReservedGoodsStack(stack) : null;
2099
if (!goods?.itemId)
2100
{
2101
item.chequeOverlay?.destroy();
2102
item.chequeOverlay = null;
2103
item.chequeOverlayTint = null;
2104
item.chequeOverlayDualTint = null;
2105
return;
2106
}
2107
const goodsPotion = goods.instance?.kind === "potion" ? goods.instance : null;
2108
const goodsSprite = goodsPotion
2109
? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, goodsPotion.fillLevel | 0 || 4))}`)
2110
: itemSpriteNameForStack(goods);
2111
const sprite = this.game.images[goodsSprite] ?? this.game.images[itemSpriteName(null)];
2112
if (!sprite)
2113
{
2114
item.chequeOverlay?.destroy();
2115
item.chequeOverlay = null;
2116
return;
2117
}
2118
if (!item.chequeOverlay || item.chequeOverlay.renderer?.sprite !== sprite)
2119
{
2120
item.chequeOverlay?.destroy();
2121
item.chequeOverlay = new GameObject(0, 0, sprite, SORT_BLOCK);
2122
this.scene.addObject(item.chequeOverlay);
2123
}
2124
const goodsDef = itemDefinition(goods.itemId);
2125
item.chequeOverlayDualTint = goodsDef?.iconTintFromTier
2126
? null
2127
: resolveItemDualTint(goods, goodsDef);
2128
item.chequeOverlayTint = item.chequeOverlayDualTint
2129
? null
2130
: resolveItemTint(goods, goodsDef);
2131
if (item.chequeOverlay?.renderer && itemMaxCharges(goodsDef) != null)
2132
{ item.chequeOverlay.renderer.setSubImage?.(chargeSpriteFrameIndex(goods)); }
2133
this.#placePivoted(item.chequeOverlay, pivot.x, pivot.y, pivot.y - 0.005, SORT_BLOCK, 0.5);
2134
}
2135
2088
2136
groundItemAtTile (tileX, tileY)
2089
2137
{
2090
2138
return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
@@ -2147,6 +2195,8 @@ export class WorldView
2147
2195
{
2148
2196
const pivot = tilePivot(item.tileX, item.tileY, size);
2149
2197
this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
2198
if (item.chequeOverlay)
2199
{ this.#placePivoted(item.chequeOverlay, pivot.x, pivot.y, pivot.y - 0.005, SORT_BLOCK, 0.5); }
2150
2200
}
2151
2201
this.#rebuildAllEdges();
2152
2202
this.#relayoutEditorSpawners();
@@ -3807,9 +3857,17 @@ export class WorldView
3807
3857
if (item?.dualTint)
3808
3858
{
3809
3859
this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
3860
}
3861
else
3862
{ this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null); }
3863
if (!item?.chequeOverlay)
3864
{ return; }
3865
if (item.chequeOverlayDualTint)
3866
{
3867
this.#syncDualTintLitSprite(item.chequeOverlay, darkness, item.chequeOverlayDualTint);
3810
3868
return;
3811
3869
}
3812
this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
3870
this.#syncLitSprite(item.chequeOverlay, darkness, 0, false, item.chequeOverlayTint ?? null);
3813
3871
}
3814
3872
3815
3873
#groundTypeAt (tileX, tileY)
@@ -6,6 +6,7 @@ import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRange6
import { smoothLitCorner } from "/shared/lighting/lightCorners.js";6
import { smoothLitCorner } from "/shared/lighting/lightCorners.js";7
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";7
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";8
import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";8
import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";9
import { chequeReservedGoodsStack, isFilledChequeStack } from "/shared/items/cheque.js";9
import10
import10
{11
{11
resolveItemTint,12
resolveItemTint,@@ -2066,13 +2067,14 @@ export class WorldView2066
item.displayName = payload.displayName;2067
item.displayName = payload.displayName;2067
item.sprite = spriteName;2068
item.sprite = spriteName;2068
item.instance = payload.instance ?? null;2069
item.instance = payload.instance ?? null;2069
const stack = { itemId: payload.itemId, instance: payload.instance ?? null };2070
const stack = { itemId: payload.itemId, instance: payload.instance ?? null, quantity: payload.quantity };2070
const def = itemDefinition(payload.itemId);2071
const def = itemDefinition(payload.itemId);2071
item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);2072
item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);2072
item.tintColor = item.dualTint ? null : resolveItemTint(stack, def);2073
item.tintColor = item.dualTint ? null : resolveItemTint(stack, def);2073
if (item.object?.renderer && itemMaxCharges(def) != null)2074
if (item.object?.renderer && itemMaxCharges(def) != null)2074
{ item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); }2075
{ item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); }2075
this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);2076
this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);2077
this.#syncGroundChequeOverlay(item, pivot);2076
this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);2078
this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);2077
}2079
}2078
2080
@@ -2081,10 +2083,56 @@ export class WorldView2081
const item = this.groundItems.get(groundItemId);2083
const item = this.groundItems.get(groundItemId);2082
if (!item)2084
if (!item)2083
{ return; }2085
{ return; }2086
item.chequeOverlay?.destroy();2084
item.object?.destroy();2087
item.object?.destroy();2085
this.groundItems.delete(groundItemId);2088
this.groundItems.delete(groundItemId);2086
}2089
}2087
2090
2091
#syncGroundChequeOverlay (item, pivot)2092
{2093
const stack = {2094
itemId: item.itemId,2095
instance: item.instance,2096
quantity: item.quantity2097
};2098
const goods = isFilledChequeStack(stack) ? chequeReservedGoodsStack(stack) : null;2099
if (!goods?.itemId)2100
{2101
item.chequeOverlay?.destroy();2102
item.chequeOverlay = null;2103
item.chequeOverlayTint = null;2104
item.chequeOverlayDualTint = null;2105
return;2106
}2107
const goodsPotion = goods.instance?.kind === "potion" ? goods.instance : null;2108
const goodsSprite = goodsPotion2109
? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, goodsPotion.fillLevel | 0 || 4))}`)2110
: itemSpriteNameForStack(goods);2111
const sprite = this.game.images[goodsSprite] ?? this.game.images[itemSpriteName(null)];2112
if (!sprite)2113
{2114
item.chequeOverlay?.destroy();2115
item.chequeOverlay = null;2116
return;2117
}2118
if (!item.chequeOverlay || item.chequeOverlay.renderer?.sprite !== sprite)2119
{2120
item.chequeOverlay?.destroy();2121
item.chequeOverlay = new GameObject(0, 0, sprite, SORT_BLOCK);2122
this.scene.addObject(item.chequeOverlay);2123
}2124
const goodsDef = itemDefinition(goods.itemId);2125
item.chequeOverlayDualTint = goodsDef?.iconTintFromTier2126
? null2127
: resolveItemDualTint(goods, goodsDef);2128
item.chequeOverlayTint = item.chequeOverlayDualTint2129
? null2130
: resolveItemTint(goods, goodsDef);2131
if (item.chequeOverlay?.renderer && itemMaxCharges(goodsDef) != null)2132
{ item.chequeOverlay.renderer.setSubImage?.(chargeSpriteFrameIndex(goods)); }2133
this.#placePivoted(item.chequeOverlay, pivot.x, pivot.y, pivot.y - 0.005, SORT_BLOCK, 0.5);2134
}2135
2088
groundItemAtTile (tileX, tileY)2136
groundItemAtTile (tileX, tileY)2089
{2137
{2090
return this.groundItemsAtTile(tileX, tileY)[0] ?? null;2138
return this.groundItemsAtTile(tileX, tileY)[0] ?? null;@@ -2147,6 +2195,8 @@ export class WorldView2147
{2195
{2148
const pivot = tilePivot(item.tileX, item.tileY, size);2196
const pivot = tilePivot(item.tileX, item.tileY, size);2149
this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);2197
this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);2198
if (item.chequeOverlay)2199
{ this.#placePivoted(item.chequeOverlay, pivot.x, pivot.y, pivot.y - 0.005, SORT_BLOCK, 0.5); }2150
}2200
}2151
this.#rebuildAllEdges();2201
this.#rebuildAllEdges();2152
this.#relayoutEditorSpawners();2202
this.#relayoutEditorSpawners();@@ -3807,9 +3857,17 @@ export class WorldView3807
if (item?.dualTint)3857
if (item?.dualTint)3808
{3858
{3809
this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);3859
this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);3860
}3861
else3862
{ this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null); }3863
if (!item?.chequeOverlay)3864
{ return; }3865
if (item.chequeOverlayDualTint)3866
{3867
this.#syncDualTintLitSprite(item.chequeOverlay, darkness, item.chequeOverlayDualTint);3810
return;3868
return;3811
}3869
}3812
this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);3870
this.#syncLitSprite(item.chequeOverlay, darkness, 0, false, item.chequeOverlayTint ?? null);3813
}3871
}3814
3872
3815
#groundTypeAt (tileX, tileY)3873
#groundTypeAt (tileX, tileY)@@ -26,6 +26,7 @@ import
26
26
stacksMatch,
27
27
fitStackQuantity
28
28
} from "../../../shared/items/inventory.js";
29
import { countIdenticalInSlots, chequeIsExpired } from "../../../shared/items/cheque.js";
29
30
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
30
31
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
31
32
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
@@ -860,7 +861,13 @@ function bankMove (world, sessionId, command, fromKey, toKey)
860
861
{
861
862
const slot = inventory.slots[command.slotIndex | 0];
862
863
if (slot?.itemId === ItemId.filledCheque)
863
{ return redeemCheque(world, sessionId, command); }
864
{
865
world.sweepExpiredCheques?.(command.characterId);
866
const fresh = inventory.slots[command.slotIndex | 0];
867
if (!fresh || fresh.itemId !== ItemId.filledCheque)
868
{ throw userError("That cheque has expired."); }
869
return redeemCheque(world, sessionId, command);
870
}
864
871
}
865
872
if (toKey === "vault")
866
873
{
@@ -949,6 +956,7 @@ function returnBlankCheques (world, sessionId, command)
949
956
function writeCheque (world, sessionId, command)
950
957
{
951
958
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
959
world.sweepExpiredCheques?.(command.characterId);
952
960
const inventory = ensureInventory(world.ecs, handle);
953
961
const vault = ensureVault(world.ecs, handle);
954
962
const slotIndex = command.slotIndex | 0;
@@ -962,7 +970,7 @@ function writeCheque (world, sessionId, command)
962
970
if (!def)
963
971
{ throw userError("Unknown item."); }
964
972
const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0);
965
const available = countItemInSlots(vault.slots, vaultSlot.itemId);
973
const available = countIdenticalInSlots(vault.slots, vaultSlot);
966
974
if (available < quantity)
967
975
{ throw userError("Not enough unreserved goods in the vault."); }
968
976
if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry))
@@ -971,7 +979,7 @@ function writeCheque (world, sessionId, command)
971
979
const pulled = takeMatchingFromSlots(vault.slots, {
972
980
itemId: vaultSlot.itemId,
973
981
quantity,
974
instance: def.uniqueInstance ? vaultSlot.instance : null
982
matchStack: vaultSlot
975
983
});
976
984
if (!pulled.ok)
977
985
{ throw userError("Not enough unreserved goods in the vault."); }
@@ -1019,6 +1027,7 @@ function writeCheque (world, sessionId, command)
1019
1027
function redeemCheque (world, sessionId, command)
1020
1028
{
1021
1029
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
1030
world.sweepExpiredCheques?.(command.characterId);
1022
1031
requireBank(world, handle);
1023
1032
const inventory = ensureInventory(world.ecs, handle);
1024
1033
const vault = ensureVault(world.ecs, handle);
@@ -1026,6 +1035,11 @@ function redeemCheque (world, sessionId, command)
1026
1035
const slot = inventory.slots[slotIndex];
1027
1036
if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque")
1028
1037
{ throw userError("Select a filled cheque."); }
1038
if (chequeIsExpired(slot))
1039
{
1040
world.expireFilledChequePaper?.(command.characterId, slotIndex);
1041
throw userError("That cheque has expired.");
1042
}
1029
1043
1030
1044
const chequeId = slot.instance.chequeId;
1031
1045
const issuerId = slot.instance.issuerCharacterId;
@@ -26,6 +26,7 @@ import26
stacksMatch,26
stacksMatch,27
fitStackQuantity27
fitStackQuantity28
} from "../../../shared/items/inventory.js";28
} from "../../../shared/items/inventory.js";29
import { countIdenticalInSlots, chequeIsExpired } from "../../../shared/items/cheque.js";29
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";30
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";30
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";31
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";31
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";32
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";@@ -860,7 +861,13 @@ function bankMove (world, sessionId, command, fromKey, toKey)860
{861
{861
const slot = inventory.slots[command.slotIndex | 0];862
const slot = inventory.slots[command.slotIndex | 0];862
if (slot?.itemId === ItemId.filledCheque)863
if (slot?.itemId === ItemId.filledCheque)863
{ return redeemCheque(world, sessionId, command); }864
{865
world.sweepExpiredCheques?.(command.characterId);866
const fresh = inventory.slots[command.slotIndex | 0];867
if (!fresh || fresh.itemId !== ItemId.filledCheque)868
{ throw userError("That cheque has expired."); }869
return redeemCheque(world, sessionId, command);870
}864
}871
}865
if (toKey === "vault")872
if (toKey === "vault")866
{873
{@@ -949,6 +956,7 @@ function returnBlankCheques (world, sessionId, command)949
function writeCheque (world, sessionId, command)956
function writeCheque (world, sessionId, command)950
{957
{951
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);958
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);959
world.sweepExpiredCheques?.(command.characterId);952
const inventory = ensureInventory(world.ecs, handle);960
const inventory = ensureInventory(world.ecs, handle);953
const vault = ensureVault(world.ecs, handle);961
const vault = ensureVault(world.ecs, handle);954
const slotIndex = command.slotIndex | 0;962
const slotIndex = command.slotIndex | 0;@@ -962,7 +970,7 @@ function writeCheque (world, sessionId, command)962
if (!def)970
if (!def)963
{ throw userError("Unknown item."); }971
{ throw userError("Unknown item."); }964
const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0);972
const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0);965
const available = countItemInSlots(vault.slots, vaultSlot.itemId);973
const available = countIdenticalInSlots(vault.slots, vaultSlot);966
if (available < quantity)974
if (available < quantity)967
{ throw userError("Not enough unreserved goods in the vault."); }975
{ throw userError("Not enough unreserved goods in the vault."); }968
if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry))976
if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry))@@ -971,7 +979,7 @@ function writeCheque (world, sessionId, command)971
const pulled = takeMatchingFromSlots(vault.slots, {979
const pulled = takeMatchingFromSlots(vault.slots, {972
itemId: vaultSlot.itemId,980
itemId: vaultSlot.itemId,973
quantity,981
quantity,974
instance: def.uniqueInstance ? vaultSlot.instance : null982
matchStack: vaultSlot975
});983
});976
if (!pulled.ok)984
if (!pulled.ok)977
{ throw userError("Not enough unreserved goods in the vault."); }985
{ throw userError("Not enough unreserved goods in the vault."); }@@ -1019,6 +1027,7 @@ function writeCheque (world, sessionId, command)1019
function redeemCheque (world, sessionId, command)1027
function redeemCheque (world, sessionId, command)1020
{1028
{1021
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);1029
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);1030
world.sweepExpiredCheques?.(command.characterId);1022
requireBank(world, handle);1031
requireBank(world, handle);1023
const inventory = ensureInventory(world.ecs, handle);1032
const inventory = ensureInventory(world.ecs, handle);1024
const vault = ensureVault(world.ecs, handle);1033
const vault = ensureVault(world.ecs, handle);@@ -1026,6 +1035,11 @@ function redeemCheque (world, sessionId, command)1026
const slot = inventory.slots[slotIndex];1035
const slot = inventory.slots[slotIndex];1027
if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque")1036
if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque")1028
{ throw userError("Select a filled cheque."); }1037
{ throw userError("Select a filled cheque."); }1038
if (chequeIsExpired(slot))1039
{1040
world.expireFilledChequePaper?.(command.characterId, slotIndex);1041
throw userError("That cheque has expired.");1042
}1029
1043
1030
const chequeId = slot.instance.chequeId;1044
const chequeId = slot.instance.chequeId;1031
const issuerId = slot.instance.issuerCharacterId;1045
const issuerId = slot.instance.issuerCharacterId;@@ -10,6 +10,7 @@ import {
10
10
shopOrigin
11
11
} from "../../../shared/items/origin.js";
12
12
import { isLetterStack } from "../../../shared/items/letters.js";
13
import { chequeIsExpired } from "../../../shared/items/cheque.js";
13
14
import {
14
15
addCoinsToSlots,
15
16
cloneStack,
@@ -673,6 +674,11 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde
673
674
{ throw userError("They will not buy that."); }
674
675
675
676
const isCheque = (slot.itemId | 0) === ItemId.filledCheque;
677
if (isCheque && chequeIsExpired(slot))
678
{
679
world.expireFilledChequePaper?.(characterId, slotIndex | 0);
680
throw userError("That cheque has expired.");
681
}
676
682
const isLetter = isLetterStack(slot);
677
683
const quote = resolveShopSellQuote(slot, {
678
684
lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),
@@ -10,6 +10,7 @@ import {10
shopOrigin10
shopOrigin11
} from "../../../shared/items/origin.js";11
} from "../../../shared/items/origin.js";12
import { isLetterStack } from "../../../shared/items/letters.js";12
import { isLetterStack } from "../../../shared/items/letters.js";13
import { chequeIsExpired } from "../../../shared/items/cheque.js";13
import {14
import {14
addCoinsToSlots,15
addCoinsToSlots,15
cloneStack,16
cloneStack,@@ -673,6 +674,11 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde673
{ throw userError("They will not buy that."); }674
{ throw userError("They will not buy that."); }674
675
675
const isCheque = (slot.itemId | 0) === ItemId.filledCheque;676
const isCheque = (slot.itemId | 0) === ItemId.filledCheque;677
if (isCheque && chequeIsExpired(slot))678
{679
world.expireFilledChequePaper?.(characterId, slotIndex | 0);680
throw userError("That cheque has expired.");681
}676
const isLetter = isLetterStack(slot);682
const isLetter = isLetterStack(slot);677
const quote = resolveShopSellQuote(slot, {683
const quote = resolveShopSellQuote(slot, {678
lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),684
lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),@@ -50,6 +50,7 @@ import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/st
50
50
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
51
51
import { BlockType } from "../../../shared/definitions/tiles.js";
52
52
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
53
import { chequeIsExpired, isFilledChequeStack } from "../../../shared/items/cheque.js";
53
54
import { seasonIdAt } from "../../../shared/world/season.js";
54
55
import { CourierService } from "../courier/service.js";
55
56
import { MarketService } from "../market/service.js";
@@ -123,6 +124,9 @@ export class Simulation
123
124
this.releaseChequeReservation(issuerId, chequeId, instance);
124
125
worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
125
126
worker.world.voidFilledCheque = (stack) => this.voidFilledCheque(stack);
127
worker.world.sweepExpiredCheques = (characterId) => this.sweepExpiredCheques(characterId);
128
worker.world.expireFilledChequePaper = (characterId, slotIndex) =>
129
this.expireFilledChequePaper(characterId, slotIndex);
126
130
}
127
131
this.courier = new CourierService({
128
132
stateDb: this.stateDb,
@@ -241,6 +245,11 @@ export class Simulation
241
245
this.tickIndex += 1;
242
246
if ((this.tickIndex % 1200) === 0)
243
247
{ this.worldDb.purgeExpiredDimensions(now); }
248
if ((this.tickIndex % 600) === 0)
249
{
250
for (const characterId of this.characterEntities.keys())
251
{ this.sweepExpiredCheques(characterId, { now }); }
252
}
244
253
const events = [];
245
254
const commands = this.commandQueue.splice(0);
246
255
for (const item of commands)
@@ -582,6 +591,7 @@ export class Simulation
582
591
...snap
583
592
});
584
593
}
594
this.sweepExpiredCheques(characterId);
585
595
return entityId;
586
596
}
587
597
@@ -3350,6 +3360,16 @@ export class Simulation
3350
3360
dim
3351
3361
))
3352
3362
{
3363
if (chequeIsExpired(item.stack, this.now))
3364
{
3365
this.voidFilledCheque(item.stack, { toast: true });
3366
item.stack = {
3367
itemId: ItemId.expiredCheque,
3368
quantity: 1,
3369
instance: null
3370
};
3371
this.stateDb.upsertGroundItem(item);
3372
}
3353
3373
if (item.expiresAt > this.now)
3354
3374
{
3355
3375
items.push(item);
@@ -3369,7 +3389,7 @@ export class Simulation
3369
3389
}
3370
3390
3371
3391
/** Cheque paper that no longer exists must free reserved vault goods. */
3372
voidFilledCheque (stack)
3392
voidFilledCheque (stack, { toast = true } = {})
3373
3393
{
3374
3394
if ((stack?.itemId | 0) !== ItemId.filledCheque || stack?.instance?.kind !== "filled-cheque")
3375
3395
{ return { ok: false }; }
@@ -3402,14 +3422,89 @@ export class Simulation
3402
3422
this.applyBag(onlineId, bag);
3403
3423
this.pushInventory(issuerId, bag);
3404
3424
}
3405
this.pendingPrivate.push({
3406
type: "toast",
3407
characterId: issuerId,
3408
message: "An uncashed cheque expired. Reserved goods returned to your vault."
3409
});
3425
if (toast)
3426
{
3427
this.pendingPrivate.push({
3428
type: "toast",
3429
characterId: issuerId,
3430
message: "An uncashed cheque expired. Reserved goods returned to your vault."
3431
});
3432
}
3410
3433
return { ok: true };
3411
3434
}
3412
3435
3436
/**
3437
* Convert an aged filled cheque in a character's bag into an expired cheque
3438
* and release its reservation back to the issuer.
3439
*/
3440
expireFilledChequePaper (characterId, slotIndex, { now = this.now } = {})
3441
{
3442
const cid = characterId | 0;
3443
const onlineId = this.characterEntities.get(cid);
3444
const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(cid);
3445
if (!bag?.inventory)
3446
{ return { ok: false }; }
3447
const index = slotIndex | 0;
3448
const stack = bag.inventory[index];
3449
if (!isFilledChequeStack(stack))
3450
{ return { ok: false }; }
3451
if (!chequeIsExpired(stack, now))
3452
{ return { ok: false, expired: false }; }
3453
bag.inventory[index] = {
3454
itemId: ItemId.expiredCheque,
3455
quantity: 1,
3456
instance: null,
3457
origins: []
3458
};
3459
this.stateDb.saveBag(cid, bag);
3460
if (onlineId)
3461
{
3462
this.applyBag(onlineId, bag);
3463
this.pushInventory(cid, bag);
3464
}
3465
this.voidFilledCheque(stack, { toast: true });
3466
return { ok: true, expired: true };
3467
}
3468
3469
/** Scan inventory (and convert) any filled cheques past their 30-day life. */
3470
sweepExpiredCheques (characterId, { now = this.now } = {})
3471
{
3472
const cid = characterId | 0;
3473
const onlineId = this.characterEntities.get(cid);
3474
let bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(cid);
3475
if (!bag?.inventory)
3476
{ return { ok: true, converted: 0 }; }
3477
const toRelease = [];
3478
for (let i = 0; i < bag.inventory.length; i++)
3479
{
3480
const stack = bag.inventory[i];
3481
if (!chequeIsExpired(stack, now))
3482
{ continue; }
3483
toRelease.push(stack);
3484
bag.inventory[i] = {
3485
itemId: ItemId.expiredCheque,
3486
quantity: 1,
3487
instance: null,
3488
origins: []
3489
};
3490
}
3491
if (!toRelease.length)
3492
{ return { ok: true, converted: 0 }; }
3493
this.stateDb.saveBag(cid, bag);
3494
if (onlineId)
3495
{
3496
this.applyBag(onlineId, bag);
3497
this.pushInventory(cid, bag);
3498
}
3499
let toasted = false;
3500
for (const stack of toRelease)
3501
{
3502
this.voidFilledCheque(stack, { toast: !toasted });
3503
toasted = true;
3504
}
3505
return { ok: true, converted: toRelease.length };
3506
}
3507
3413
3508
#destroyExpiredGroundItem (item)
3414
3509
{
3415
3510
if (item?.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque")
@@ -50,6 +50,7 @@ import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/st50
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";50
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";51
import { BlockType } from "../../../shared/definitions/tiles.js";51
import { BlockType } from "../../../shared/definitions/tiles.js";52
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";52
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";53
import { chequeIsExpired, isFilledChequeStack } from "../../../shared/items/cheque.js";53
import { seasonIdAt } from "../../../shared/world/season.js";54
import { seasonIdAt } from "../../../shared/world/season.js";54
import { CourierService } from "../courier/service.js";55
import { CourierService } from "../courier/service.js";55
import { MarketService } from "../market/service.js";56
import { MarketService } from "../market/service.js";@@ -123,6 +124,9 @@ export class Simulation123
this.releaseChequeReservation(issuerId, chequeId, instance);124
this.releaseChequeReservation(issuerId, chequeId, instance);124
worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);125
worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);125
worker.world.voidFilledCheque = (stack) => this.voidFilledCheque(stack);126
worker.world.voidFilledCheque = (stack) => this.voidFilledCheque(stack);127
worker.world.sweepExpiredCheques = (characterId) => this.sweepExpiredCheques(characterId);128
worker.world.expireFilledChequePaper = (characterId, slotIndex) =>129
this.expireFilledChequePaper(characterId, slotIndex);126
}130
}127
this.courier = new CourierService({131
this.courier = new CourierService({128
stateDb: this.stateDb,132
stateDb: this.stateDb,@@ -241,6 +245,11 @@ export class Simulation241
this.tickIndex += 1;245
this.tickIndex += 1;242
if ((this.tickIndex % 1200) === 0)246
if ((this.tickIndex % 1200) === 0)243
{ this.worldDb.purgeExpiredDimensions(now); }247
{ this.worldDb.purgeExpiredDimensions(now); }248
if ((this.tickIndex % 600) === 0)249
{250
for (const characterId of this.characterEntities.keys())251
{ this.sweepExpiredCheques(characterId, { now }); }252
}244
const events = [];253
const events = [];245
const commands = this.commandQueue.splice(0);254
const commands = this.commandQueue.splice(0);246
for (const item of commands)255
for (const item of commands)@@ -582,6 +591,7 @@ export class Simulation582
...snap591
...snap583
});592
});584
}593
}594
this.sweepExpiredCheques(characterId);585
return entityId;595
return entityId;586
}596
}587
597
@@ -3350,6 +3360,16 @@ export class Simulation3350
dim3360
dim3351
))3361
))3352
{3362
{3363
if (chequeIsExpired(item.stack, this.now))3364
{3365
this.voidFilledCheque(item.stack, { toast: true });3366
item.stack = {3367
itemId: ItemId.expiredCheque,3368
quantity: 1,3369
instance: null3370
};3371
this.stateDb.upsertGroundItem(item);3372
}3353
if (item.expiresAt > this.now)3373
if (item.expiresAt > this.now)3354
{3374
{3355
items.push(item);3375
items.push(item);@@ -3369,7 +3389,7 @@ export class Simulation3369
}3389
}3370
3390
3371
/** Cheque paper that no longer exists must free reserved vault goods. */3391
/** Cheque paper that no longer exists must free reserved vault goods. */3372
voidFilledCheque (stack)3392
voidFilledCheque (stack, { toast = true } = {})3373
{3393
{3374
if ((stack?.itemId | 0) !== ItemId.filledCheque || stack?.instance?.kind !== "filled-cheque")3394
if ((stack?.itemId | 0) !== ItemId.filledCheque || stack?.instance?.kind !== "filled-cheque")3375
{ return { ok: false }; }3395
{ return { ok: false }; }@@ -3402,14 +3422,89 @@ export class Simulation3402
this.applyBag(onlineId, bag);3422
this.applyBag(onlineId, bag);3403
this.pushInventory(issuerId, bag);3423
this.pushInventory(issuerId, bag);3404
}3424
}3405
this.pendingPrivate.push({3425
if (toast)3406
type: "toast",3426
{3407
characterId: issuerId,3427
this.pendingPrivate.push({3408
message: "An uncashed cheque expired. Reserved goods returned to your vault."3428
type: "toast",3409
});3429
characterId: issuerId,3430
message: "An uncashed cheque expired. Reserved goods returned to your vault."3431
});3432
}3410
return { ok: true };3433
return { ok: true };3411
}3434
}3412
3435
3436
/**3437
* Convert an aged filled cheque in a character's bag into an expired cheque3438
* and release its reservation back to the issuer.3439
*/3440
expireFilledChequePaper (characterId, slotIndex, { now = this.now } = {})3441
{3442
const cid = characterId | 0;3443
const onlineId = this.characterEntities.get(cid);3444
const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(cid);3445
if (!bag?.inventory)3446
{ return { ok: false }; }3447
const index = slotIndex | 0;3448
const stack = bag.inventory[index];3449
if (!isFilledChequeStack(stack))3450
{ return { ok: false }; }3451
if (!chequeIsExpired(stack, now))3452
{ return { ok: false, expired: false }; }3453
bag.inventory[index] = {3454
itemId: ItemId.expiredCheque,3455
quantity: 1,3456
instance: null,3457
origins: []3458
};3459
this.stateDb.saveBag(cid, bag);3460
if (onlineId)3461
{3462
this.applyBag(onlineId, bag);3463
this.pushInventory(cid, bag);3464
}3465
this.voidFilledCheque(stack, { toast: true });3466
return { ok: true, expired: true };3467
}3468
3469
/** Scan inventory (and convert) any filled cheques past their 30-day life. */3470
sweepExpiredCheques (characterId, { now = this.now } = {})3471
{3472
const cid = characterId | 0;3473
const onlineId = this.characterEntities.get(cid);3474
let bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(cid);3475
if (!bag?.inventory)3476
{ return { ok: true, converted: 0 }; }3477
const toRelease = [];3478
for (let i = 0; i < bag.inventory.length; i++)3479
{3480
const stack = bag.inventory[i];3481
if (!chequeIsExpired(stack, now))3482
{ continue; }3483
toRelease.push(stack);3484
bag.inventory[i] = {3485
itemId: ItemId.expiredCheque,3486
quantity: 1,3487
instance: null,3488
origins: []3489
};3490
}3491
if (!toRelease.length)3492
{ return { ok: true, converted: 0 }; }3493
this.stateDb.saveBag(cid, bag);3494
if (onlineId)3495
{3496
this.applyBag(onlineId, bag);3497
this.pushInventory(cid, bag);3498
}3499
let toasted = false;3500
for (const stack of toRelease)3501
{3502
this.voidFilledCheque(stack, { toast: !toasted });3503
toasted = true;3504
}3505
return { ok: true, converted: toRelease.length };3506
}3507
3413
#destroyExpiredGroundItem (item)3508
#destroyExpiredGroundItem (item)3414
{3509
{3415
if (item?.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque")3510
if (item?.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque")@@ -3,7 +3,9 @@ import assert from "node:assert/strict";
3
3
import { BlockType } from "../../shared/definitions/tiles.js";
4
4
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5
5
import { RangedItemId } from "../../shared/definitions/rangedItems.js";
6
import { FlowerColorId, flowerItemInstance } from "../../shared/definitions/dyes.js";
6
7
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
8
import { CHEQUE_LIFETIME_MS } from "../../shared/items/cheque.js";
7
9
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
8
10
import {
9
11
makeCharacter,
@@ -446,3 +448,141 @@ test("dropping a filled cheque keeps reservation; despawn returns goods to vault
446
448
finally
447
449
{ harness.close(); }
448
450
});
451
452
test("write cheque reserves only the selected flower colour stack", () =>
453
{
454
const harness = makeSimulation({ workerCount: 1 });
455
try
456
{
457
placeBank(harness.worldDb, 8, 8);
458
harness.simulation.reloadWorld();
459
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
460
const entityId = harness.simulation.spawnCharacter(1, character);
461
harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
462
harness.simulation.step();
463
464
const bagView = harness.simulation.bagOf(entityId);
465
bagView.inventory = emptySlots();
466
bagView.inventory[0] = { itemId: ItemId.blankCheque, quantity: 5 };
467
bagView.equipment = emptyEquipment();
468
bagView.vault = [
469
{ itemId: ItemId.flower, quantity: 5, instance: flowerItemInstance(FlowerColorId.red) },
470
{ itemId: ItemId.flower, quantity: 2, instance: flowerItemInstance(FlowerColorId.blue) }
471
];
472
bagView.vaultReserved = [];
473
harness.simulation.applyBag(entityId, bagView);
474
475
const blueIndex = 1;
476
harness.simulation.enqueue(1, {
477
type: "write-cheque",
478
characterId: character.character_id,
479
slotIndex: 0,
480
vaultSlotIndex: blueIndex,
481
quantity: 2
482
});
483
const result = harness.simulation.step();
484
assert.equal(result.events.some((event) => event.type === "command-error"), false);
485
486
const bag = harness.simulation.bagOf(entityId);
487
assert.equal((bag.vaultReserved ?? []).length, 1);
488
assert.equal(bag.vaultReserved[0].quantity, 2);
489
assert.equal(bag.vaultReserved[0].instance?.colorId, FlowerColorId.blue);
490
assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.red)?.quantity, 5);
491
assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.blue), undefined);
492
493
const cheque = bag.inventory.find((slot) => slot?.itemId === ItemId.filledCheque);
494
assert.equal(cheque?.instance?.reservedInstance?.colorId, FlowerColorId.blue);
495
assert.equal(cheque?.instance?.quantity, 2);
496
}
497
finally
498
{ harness.close(); }
499
});
500
501
test("write cheque rejects quantity beyond matching metadata stacks", () =>
502
{
503
const harness = makeSimulation({ workerCount: 1 });
504
try
505
{
506
placeBank(harness.worldDb, 8, 8);
507
harness.simulation.reloadWorld();
508
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
509
const entityId = harness.simulation.spawnCharacter(1, character);
510
harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
511
harness.simulation.step();
512
513
const bagView = harness.simulation.bagOf(entityId);
514
bagView.inventory = emptySlots();
515
bagView.inventory[0] = { itemId: ItemId.blankCheque, quantity: 5 };
516
bagView.equipment = emptyEquipment();
517
bagView.vault = [
518
{ itemId: ItemId.flower, quantity: 5, instance: flowerItemInstance(FlowerColorId.red) },
519
{ itemId: ItemId.flower, quantity: 2, instance: flowerItemInstance(FlowerColorId.blue) }
520
];
521
bagView.vaultReserved = [];
522
harness.simulation.applyBag(entityId, bagView);
523
524
harness.simulation.enqueue(1, {
525
type: "write-cheque",
526
characterId: character.character_id,
527
slotIndex: 0,
528
vaultSlotIndex: 1,
529
quantity: 3
530
});
531
const result = harness.simulation.step();
532
const error = result.events.find((event) => event.type === "command-error");
533
assert.ok(error);
534
assert.match(error.message, /Not enough/i);
535
const bag = harness.simulation.bagOf(entityId);
536
assert.equal((bag.vaultReserved ?? []).length, 0);
537
assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.blue)?.quantity, 2);
538
}
539
finally
540
{ harness.close(); }
541
});
542
543
test("filled cheque expires after 30 days into expired cheque and releases goods", () =>
544
{
545
const harness = makeSimulation({ workerCount: 1 });
546
try
547
{
548
placeBank(harness.worldDb, 8, 8);
549
harness.simulation.reloadWorld();
550
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
551
const entityId = harness.simulation.spawnCharacter(1, character);
552
harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
553
harness.simulation.step();
554
let bag = harness.simulation.bagOf(entityId);
555
const appleQty = countItem(bag.inventory, ItemId.apple);
556
harness.simulation.enqueue(1, {
557
type: "bank-deposit",
558
characterId: character.character_id,
559
slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple),
560
quantity: null
561
});
562
harness.simulation.step();
563
bag = harness.simulation.bagOf(entityId);
564
harness.simulation.enqueue(1, {
565
type: "write-cheque",
566
characterId: character.character_id,
567
slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque),
568
vaultSlotIndex: bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple),
569
quantity: 2
570
});
571
harness.simulation.step();
572
bag = harness.simulation.bagOf(entityId);
573
assert.equal((bag.vaultReserved ?? []).length, 1);
574
const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
575
assert.ok(chequeIndex >= 0);
576
577
bag.inventory[chequeIndex].instance.createdAt = harness.now() - CHEQUE_LIFETIME_MS - 1000;
578
harness.simulation.applyBag(entityId, bag);
579
580
harness.simulation.sweepExpiredCheques(character.character_id, { now: harness.now() });
581
bag = harness.simulation.bagOf(entityId);
582
assert.equal(bag.inventory[chequeIndex]?.itemId, ItemId.expiredCheque);
583
assert.equal((bag.vaultReserved ?? []).length, 0);
584
assert.equal(countItem(bag.vault, ItemId.apple), appleQty);
585
}
586
finally
587
{ harness.close(); }
588
});
@@ -3,7 +3,9 @@ import assert from "node:assert/strict";3
import { BlockType } from "../../shared/definitions/tiles.js";3
import { BlockType } from "../../shared/definitions/tiles.js";4
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";4
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";5
import { RangedItemId } from "../../shared/definitions/rangedItems.js";5
import { RangedItemId } from "../../shared/definitions/rangedItems.js";6
import { FlowerColorId, flowerItemInstance } from "../../shared/definitions/dyes.js";6
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";7
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";8
import { CHEQUE_LIFETIME_MS } from "../../shared/items/cheque.js";7
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";9
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";8
import {10
import {9
makeCharacter,11
makeCharacter,@@ -446,3 +448,141 @@ test("dropping a filled cheque keeps reservation; despawn returns goods to vault446
finally448
finally447
{ harness.close(); }449
{ harness.close(); }448
});450
});451
452
test("write cheque reserves only the selected flower colour stack", () =>453
{454
const harness = makeSimulation({ workerCount: 1 });455
try456
{457
placeBank(harness.worldDb, 8, 8);458
harness.simulation.reloadWorld();459
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });460
const entityId = harness.simulation.spawnCharacter(1, character);461
harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });462
harness.simulation.step();463
464
const bagView = harness.simulation.bagOf(entityId);465
bagView.inventory = emptySlots();466
bagView.inventory[0] = { itemId: ItemId.blankCheque, quantity: 5 };467
bagView.equipment = emptyEquipment();468
bagView.vault = [469
{ itemId: ItemId.flower, quantity: 5, instance: flowerItemInstance(FlowerColorId.red) },470
{ itemId: ItemId.flower, quantity: 2, instance: flowerItemInstance(FlowerColorId.blue) }471
];472
bagView.vaultReserved = [];473
harness.simulation.applyBag(entityId, bagView);474
475
const blueIndex = 1;476
harness.simulation.enqueue(1, {477
type: "write-cheque",478
characterId: character.character_id,479
slotIndex: 0,480
vaultSlotIndex: blueIndex,481
quantity: 2482
});483
const result = harness.simulation.step();484
assert.equal(result.events.some((event) => event.type === "command-error"), false);485
486
const bag = harness.simulation.bagOf(entityId);487
assert.equal((bag.vaultReserved ?? []).length, 1);488
assert.equal(bag.vaultReserved[0].quantity, 2);489
assert.equal(bag.vaultReserved[0].instance?.colorId, FlowerColorId.blue);490
assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.red)?.quantity, 5);491
assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.blue), undefined);492
493
const cheque = bag.inventory.find((slot) => slot?.itemId === ItemId.filledCheque);494
assert.equal(cheque?.instance?.reservedInstance?.colorId, FlowerColorId.blue);495
assert.equal(cheque?.instance?.quantity, 2);496
}497
finally498
{ harness.close(); }499
});500
501
test("write cheque rejects quantity beyond matching metadata stacks", () =>502
{503
const harness = makeSimulation({ workerCount: 1 });504
try505
{506
placeBank(harness.worldDb, 8, 8);507
harness.simulation.reloadWorld();508
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });509
const entityId = harness.simulation.spawnCharacter(1, character);510
harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });511
harness.simulation.step();512
513
const bagView = harness.simulation.bagOf(entityId);514
bagView.inventory = emptySlots();515
bagView.inventory[0] = { itemId: ItemId.blankCheque, quantity: 5 };516
bagView.equipment = emptyEquipment();517
bagView.vault = [518
{ itemId: ItemId.flower, quantity: 5, instance: flowerItemInstance(FlowerColorId.red) },519
{ itemId: ItemId.flower, quantity: 2, instance: flowerItemInstance(FlowerColorId.blue) }520
];521
bagView.vaultReserved = [];522
harness.simulation.applyBag(entityId, bagView);523
524
harness.simulation.enqueue(1, {525
type: "write-cheque",526
characterId: character.character_id,527
slotIndex: 0,528
vaultSlotIndex: 1,529
quantity: 3530
});531
const result = harness.simulation.step();532
const error = result.events.find((event) => event.type === "command-error");533
assert.ok(error);534
assert.match(error.message, /Not enough/i);535
const bag = harness.simulation.bagOf(entityId);536
assert.equal((bag.vaultReserved ?? []).length, 0);537
assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.blue)?.quantity, 2);538
}539
finally540
{ harness.close(); }541
});542
543
test("filled cheque expires after 30 days into expired cheque and releases goods", () =>544
{545
const harness = makeSimulation({ workerCount: 1 });546
try547
{548
placeBank(harness.worldDb, 8, 8);549
harness.simulation.reloadWorld();550
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });551
const entityId = harness.simulation.spawnCharacter(1, character);552
harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });553
harness.simulation.step();554
let bag = harness.simulation.bagOf(entityId);555
const appleQty = countItem(bag.inventory, ItemId.apple);556
harness.simulation.enqueue(1, {557
type: "bank-deposit",558
characterId: character.character_id,559
slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple),560
quantity: null561
});562
harness.simulation.step();563
bag = harness.simulation.bagOf(entityId);564
harness.simulation.enqueue(1, {565
type: "write-cheque",566
characterId: character.character_id,567
slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque),568
vaultSlotIndex: bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple),569
quantity: 2570
});571
harness.simulation.step();572
bag = harness.simulation.bagOf(entityId);573
assert.equal((bag.vaultReserved ?? []).length, 1);574
const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);575
assert.ok(chequeIndex >= 0);576
577
bag.inventory[chequeIndex].instance.createdAt = harness.now() - CHEQUE_LIFETIME_MS - 1000;578
harness.simulation.applyBag(entityId, bag);579
580
harness.simulation.sweepExpiredCheques(character.character_id, { now: harness.now() });581
bag = harness.simulation.bagOf(entityId);582
assert.equal(bag.inventory[chequeIndex]?.itemId, ItemId.expiredCheque);583
assert.equal((bag.vaultReserved ?? []).length, 0);584
assert.equal(countItem(bag.vault, ItemId.apple), appleQty);585
}586
finally587
{ harness.close(); }588
});