Skip to content

Commit

Permalink
Merge branch 'next' of https://github.com/BibliothecaDAO/eternum into…
Browse files Browse the repository at this point in the history
… next
  • Loading branch information
credence0x committed Dec 14, 2024
2 parents 50753b5 + f5b372a commit c57642b
Show file tree
Hide file tree
Showing 22 changed files with 526 additions and 417 deletions.
4 changes: 2 additions & 2 deletions client/.env.preview
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ VITE_PUBLIC_MASTER_PRIVATE_KEY=0x075362a844768f31c8058ce31aec3dd7751686440b4f220
VITE_PUBLIC_WORLD_ADDRESS="0x00fd85ef42eaed3b90d02d2cdc7417d6cae189ff4ba876aa5608551afbf1fb47"
VITE_PUBLIC_ACCOUNT_CLASS_HASH="0x07dc7899aa655b0aae51eadff6d801a58e97dd99cf4666ee59e704249e51adf2"
VITE_PUBLIC_FEE_TOKEN_ADDRESS=0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7
VITE_PUBLIC_TORII=https://api.cartridge.gg/x/sepolia-rc-17/torii
VITE_PUBLIC_TORII=https://api.cartridge.gg/x/sepolia-rc-18/torii
VITE_PUBLIC_NODE_URL=https://api.cartridge.gg/x/starknet/sepolia
VITE_PUBLIC_DEV=false
VITE_PUBLIC_GAME_VERSION="v1.0.0-rc7"
VITE_PUBLIC_SHOW_FPS=false
VITE_PUBLIC_GRAPHICS_DEV=false
VITE_PUBLIC_TORII_RELAY=/dns4/api.cartridge.gg/tcp/443/x-parity-wss/%2Fx%2Fsepolia-rc-17%2Ftorii%2Fwss
VITE_PUBLIC_TORII_RELAY=/dns4/api.cartridge.gg/tcp/443/x-parity-wss/%2Fx%2Fsepolia-rc-18%2Ftorii%2Fwss
VITE_SEASON_PASS_ADDRESS=0x23cc88996a5f9c7bcb559fdcffc257c0f75abe60f2a7e5d5cd343f8a95967f7
VITE_REALMS_ADDRESS=0x3205f47bd6f0b5e9cd5c79fcae19e12523a024709776d0a9e8b375adf63468d
VITE_LORDS_ADDRESS=0x0342ad5cc14002c005a5cedcfce2bd3af98d5e7fb79e9bf949b3a91cf145d72e
Expand Down
23 changes: 13 additions & 10 deletions client/src/dojo/modelManager/ConfigManager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { divideByPrecision } from "@/ui/utils/utils";
import {
ADMIN_BANK_ENTITY_ID,
BUILDING_CATEGORY_POPULATION_CONFIG_ID,
Expand Down Expand Up @@ -78,7 +77,7 @@ export class ClientConfigManager {

// if (productionInput) {
// const resource = productionInput.input_resource_type;
// const amount = divideByPrecision(Number(productionInput.input_resource_amount));
// const amount = this.divideByPrecision(Number(productionInput.input_resource_amount));
// inputs.push({ resource, amount });
// }
// }
Expand Down Expand Up @@ -108,7 +107,7 @@ export class ClientConfigManager {

this.resourceOutput[Number(resourceType)] = {
resource: Number(resourceType) as ResourcesIds,
amount: divideByPrecision(Number(productionConfig?.amount)),
amount: this.divideByPrecision(Number(productionConfig?.amount)),
};
}
}
Expand Down Expand Up @@ -156,7 +155,7 @@ export class ClientConfigManager {
// );
// if (resource) {
// const resourceId = resource.resource_type;
// const amount = divideByPrecision(Number(resource.resource_amount));
// const amount = this.divideByPrecision(Number(resource.resource_amount));
// resources.push({ resource: resourceId, amount });
// }
// }
Expand Down Expand Up @@ -254,7 +253,7 @@ export class ClientConfigManager {
);

return {
amount: divideByPrecision(Number(hyperstructureResourceConfig?.min_amount) ?? 0),
amount: this.divideByPrecision(Number(hyperstructureResourceConfig?.min_amount) ?? 0),
resource: ResourcesIds.AncientFragment,
};
}
Expand Down Expand Up @@ -293,7 +292,7 @@ export class ClientConfigManager {
return this.getValueOrDefault(() => {
const exploreConfig = getComponentValue(this.components.MapConfig, getEntityIdFromKeys([WORLD_CONFIG_ID]));

return divideByPrecision(Number(exploreConfig?.reward_resource_amount ?? 0));
return this.divideByPrecision(Number(exploreConfig?.reward_resource_amount ?? 0));
}, 0);
}

Expand All @@ -309,7 +308,7 @@ export class ClientConfigManager {
crossbowmanStrength: troopConfig?.crossbowman_strength ?? 0,
advantagePercent: troopConfig?.advantage_percent ?? 0,
disadvantagePercent: troopConfig?.disadvantage_percent ?? 0,
maxTroopCount: divideByPrecision(troopConfig?.max_troop_count ?? 0),
maxTroopCount: this.divideByPrecision(troopConfig?.max_troop_count ?? 0),
pillageHealthDivisor: troopConfig?.pillage_health_divisor ?? 0,
baseArmyNumberForStructure: troopConfig?.army_free_per_structure ?? 0,
armyExtraPerMilitaryBuilding: troopConfig?.army_extra_per_building ?? 0,
Expand Down Expand Up @@ -414,7 +413,7 @@ export class ClientConfigManager {
const bankConfig = getComponentValue(this.components.BankConfig, getEntityIdFromKeys([WORLD_CONFIG_ID]));

return {
lordsCost: divideByPrecision(Number(bankConfig?.lords_cost)),
lordsCost: this.divideByPrecision(Number(bankConfig?.lords_cost)),
lpFeesNumerator: Number(bankConfig?.lp_fee_num ?? 0),
lpFeesDenominator: Number(bankConfig?.lp_fee_denom ?? 0),
};
Expand Down Expand Up @@ -557,11 +556,11 @@ export class ClientConfigManager {
const maxAmount = Number(hyperstructureResourceConfig.max_amount);

if (minAmount === maxAmount) {
return divideByPrecision(minAmount);
return this.divideByPrecision(minAmount);
}

const additionalAmount = Number(randomness % BigInt(maxAmount - minAmount));
return divideByPrecision(minAmount + Number(additionalAmount));
return this.divideByPrecision(minAmount + Number(additionalAmount));
}

getBasePopulationCapacity(): number {
Expand Down Expand Up @@ -626,6 +625,10 @@ export class ClientConfigManager {
return EternumGlobalConfig.resources.resourcePrecision;
}

divideByPrecision(value: number) {
return value / EternumGlobalConfig.resources.resourcePrecision;
}

getResourceMultiplier() {
return EternumGlobalConfig.resources.resourceMultiplier;
}
Expand Down
36 changes: 17 additions & 19 deletions client/src/dojo/modelManager/TileManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,38 +208,36 @@ export class TileManager {

const populationOverrideId = uuid();

const realmEntityId = getEntityIdFromKeys([BigInt(entityId)]);
const realmEntity = getEntityIdFromKeys([BigInt(entityId)]);

this.setup.components.Population.addOverride(populationOverrideId, {
entity: realmEntityId,
entity: realmEntity,
value: {
population:
(getComponentValue(this.setup.components.Population, realmEntityId)?.population || 0) +
(getComponentValue(this.setup.components.Population, realmEntity)?.population || 0) +
configManager.getBuildingPopConfig(buildingType).population,
capacity:
(getComponentValue(this.setup.components.Population, realmEntityId)?.capacity || 0) +
(getComponentValue(this.setup.components.Population, realmEntity)?.capacity || 0) +
configManager.getBuildingPopConfig(buildingType).capacity,
},
});
const quantityOverrideId = uuid();
if (buildingType === BuildingType.Storehouse) {
const storehouseQuantity =
getComponentValue(
this.setup.components.BuildingQuantityv2,
getEntityIdFromKeys([BigInt(entityId), BigInt(buildingType)]),
)?.value || 0;

this.setup.components.BuildingQuantityv2.addOverride(quantityOverrideId, {
entity: realmEntityId,
value: {
value: storehouseQuantity + 1,
},
});
}

const buildingQuantityEntity = getEntityIdFromKeys([BigInt(entityId), BigInt(buildingType)]);

const storehouseQuantity =
getComponentValue(this.setup.components.BuildingQuantityv2, buildingQuantityEntity)?.value || 0;

this.setup.components.BuildingQuantityv2.addOverride(quantityOverrideId, {
entity: buildingQuantityEntity,
value: {
value: storehouseQuantity + 1,
},
});

const resourceChange = configManager.buildingCosts[buildingType];
resourceChange.forEach((resource) => {
this._overrideResource(realmEntityId, resource.resource, -BigInt(resource.amount));
this._overrideResource(realmEntity, resource.resource, -BigInt(resource.amount));
});

return { overrideId, populationOverrideId, quantityOverrideId };
Expand Down
6 changes: 3 additions & 3 deletions client/src/dojo/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export const addToSubscription = async <S extends Schema>(
...positionClause,
},
components,
10_000,
30_000,
false,
));

Expand All @@ -87,7 +87,7 @@ export const addToSubscription = async <S extends Schema>(
},
},
components,
20_000,
30_000,
false,
);
};
Expand All @@ -106,7 +106,7 @@ export const addMarketSubscription = async <S extends Schema>(
},
},
components,
50_000,
30_000,
false,
);
};
115 changes: 70 additions & 45 deletions client/src/three/scenes/Worldmap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ export default class WorldmapScene extends HexagonScene {

dojo: SetupResult;

private fetchedChunks: Set<string> = new Set();

constructor(
dojoContext: SetupResult,
raycaster: Raycaster,
Expand Down Expand Up @@ -379,6 +381,7 @@ export default class WorldmapScene extends HexagonScene {
useUIStore.getState().setLeftNavigationView(LeftView.None);

this.armyManager.addLabelsToScene();
this.clearTileEntityCache();
}

onSwitchOff() {
Expand Down Expand Up @@ -670,53 +673,71 @@ export default class WorldmapScene extends HexagonScene {
const { width } = this.renderChunkSize;
const range = width / 2;

const sub = await getEntities(
this.dojo.network.toriiClient,
{
Composite: {
operator: "And",
clauses: [
{
Member: {
model: "s0_eternum-Tile",
member: "col",
operator: "Gte",
value: { Primitive: { U32: startCol - range } },
},
},
{
Member: {
model: "s0_eternum-Tile",
member: "col",
operator: "Lte",
value: { Primitive: { U32: startCol + range } },
},
},
{
Member: {
model: "s0_eternum-Tile",
member: "row",
operator: "Gte",
value: { Primitive: { U32: startRow - range } },
},
},
// Create a unique key for this chunk range
const chunkKey = `${startCol - range},${startCol + range},${startRow - range},${startRow + range}`;

console.log(chunkKey);

// Skip if we've already fetched this chunk
if (this.fetchedChunks.has(chunkKey)) {
console.log("Already fetched");
return;
}

// Add to fetched chunks before the query to prevent concurrent duplicate requests
this.fetchedChunks.add(chunkKey);

try {
await getEntities(
this.dojo.network.toriiClient,
{
Member: {
model: "s0_eternum-Tile",
member: "row",
operator: "Lte",
value: { Primitive: { U32: startRow + range } },
},
Composite: {
operator: "And",
clauses: [
{
Member: {
model: "s0_eternum-Tile",
member: "col",
operator: "Gte",
value: { Primitive: { U32: startCol - range } },
},
},
{
Member: {
model: "s0_eternum-Tile",
member: "col",
operator: "Lte",
value: { Primitive: { U32: startCol + range } },
},
},
{
Member: {
model: "s0_eternum-Tile",
member: "row",
operator: "Gte",
value: { Primitive: { U32: startRow - range } },
},
},
{
Member: {
model: "s0_eternum-Tile",
member: "row",
operator: "Lte",
value: { Primitive: { U32: startRow + range } },
},
},
],
},
},
],
},
},
this.dojo.network.contractComponents as any,
1000,
false,
);

console.log(sub);
this.dojo.network.contractComponents as any,
1000,
false,
);
} catch (error) {
// If there's an error, remove the chunk from cached set so it can be retried
this.fetchedChunks.delete(chunkKey);
console.error('Error fetching tile entities:', error);
}
}

private getExploredHexesForCurrentChunk() {
Expand Down Expand Up @@ -823,4 +844,8 @@ export default class WorldmapScene extends HexagonScene {
this.minimap.update();
}
}

public clearTileEntityCache() {
this.fetchedChunks.clear();
}
}
40 changes: 26 additions & 14 deletions client/src/ui/components/entities/Entity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ type EntityProps = {
arrival: ArrivalInfo;
} & React.HTMLAttributes<HTMLDivElement>;

const CACHE_KEY = "inventory-resources-sync";
const CACHE_DURATION = 2 * 60 * 1000; // 2 minutes in milliseconds

export const EntityArrival = ({ arrival, ...props }: EntityProps) => {
const dojo = useDojo();

Expand All @@ -50,23 +53,32 @@ export const EntityArrival = ({ arrival, ...props }: EntityProps) => {

useEffect(() => {
if (entityResources.length === 0) {
const cacheKey = `${CACHE_KEY}-${arrival.entityId}`;
const cachedTime = localStorage.getItem(cacheKey);
const now = Date.now();

if (cachedTime && now - parseInt(cachedTime) < CACHE_DURATION) {
return;
}

setIsSyncing(true);
const fetch = async () => {
try {
await addToSubscription(
dojo.network.toriiClient,
dojo.network.contractComponents as any,
arrival.entityId.toString(),
);
} catch (error) {
console.error("Fetch failed", error);
} finally {
setIsSyncing(false);
try {
await addToSubscription(
dojo.network.toriiClient,
dojo.network.contractComponents as any,
arrival.entityId.toString(),
);
localStorage.setItem(cacheKey, now.toString());
} catch (error) {
console.error("Fetch failed", error);
} finally {
setIsSyncing(false);
}
};
fetch();
}
};
fetch();
}
}, [arrival.entityId, dojo.network.toriiClient, dojo.network.contractComponents, entityResources.length]);
}, [arrival.entityId, dojo.network.toriiClient, dojo.network.contractComponents, entityResources.length]);

const army = useMemo(() => getArmy(arrival.entityId), [arrival.entityId, entity.resources]);

Expand Down
Loading

0 comments on commit c57642b

Please sign in to comment.