Skip to content

Commit

Permalink
building opt
Browse files Browse the repository at this point in the history
  • Loading branch information
ponderingdemocritus committed Dec 5, 2024
1 parent f64b391 commit 626849f
Show file tree
Hide file tree
Showing 13 changed files with 127 additions and 43 deletions.
3 changes: 2 additions & 1 deletion client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,13 @@
"lil-gui": "^0.19.2",
"lodash": "^4.17.21",
"lucide-react": "^0.365.0",
"next-themes": "^0.4.3",
"postprocessing": "^6.36.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-draggable": "^4.4.6",
"react-toastify": "^10.0.5",
"rxjs": "^7.8.1",
"sonner": "^1.7.0",
"tailwind-merge": "^2.2.2",
"three": "^0.166.0",
"three-csg": "^1.0.0",
Expand Down
7 changes: 4 additions & 3 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import "./index.css";
import { Toaster } from "./ui/components/Toaster";
import { TransactionNotification } from "./ui/components/TxEmit";
import { World } from "./ui/layouts/World";

function App({ backgroundImage }: { backgroundImage: string }) {
return (
<>
<ToastContainer style={{ zIndex: 1100 }} />
<Toaster />
<TransactionNotification />
<World backgroundImage={backgroundImage} />
</>
);
Expand Down
21 changes: 5 additions & 16 deletions client/src/dojo/createSystemCalls.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type * as SystemProps from "@bibliothecadao/eternum";
import { toast } from "react-toastify";
import { toast } from "sonner";
import { type SetupNetworkResult } from "./setupNetwork";

class PromiseQueue {
Expand Down Expand Up @@ -39,26 +39,15 @@ class PromiseQueue {
}
}

type SystemCallFunctions = ReturnType<typeof createSystemCalls>;
type SystemCallFunction = (...args: any[]) => any;
type WrappedSystemCalls = Record<string, SystemCallFunction>;

const withErrorHandling =
(fn: any) =>
async (...args: any[]) => {
try {
return await fn(...args);
} catch (error: any) {
toast(error.message);
}
};

export function createSystemCalls({ provider }: SetupNetworkResult) {
const promiseQueue = new PromiseQueue();

const withQueueing = <T extends (...args: any[]) => Promise<any>>(fn: T) => {
return async (...args: Parameters<T>): Promise<ReturnType<T>> => {
return await promiseQueue.enqueue(async () => await fn(...args));
return await promiseQueue.enqueue(async () => {
const result = await fn(...args);
return result;
});
};
};

Expand Down
14 changes: 11 additions & 3 deletions client/src/dojo/modelManager/TileManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,12 +252,15 @@ export class TileManager {
};

private _optimisticDestroy = (entityId: ID, col: number, row: number) => {
const currentBuilding = getComponentValue(this.setup.components.Building, getEntityIdFromKeys([BigInt(entityId)]));

const overrideId = uuid();
const realmPosition = getComponentValue(this.setup.components.Position, getEntityIdFromKeys([BigInt(entityId)]));
const { x: outercol, y: outerrow } = realmPosition || { x: 0, y: 0 };
const entity = getEntityIdFromKeys([outercol, outerrow, col, row].map((v) => BigInt(v)));

const currentBuilding = getComponentValue(this.setup.components.Building, entity);

console.log(currentBuilding);

this.setup.components.Building.addOverride(overrideId, {
entity,
value: {
Expand All @@ -277,12 +280,17 @@ export class TileManager {

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

const type = BuildingType[currentBuilding?.category as keyof typeof BuildingType];

this.setup.components.Population.addOverride(populationOverrideId, {
entity: realmEntityId,
value: {
population:
(getComponentValue(this.setup.components.Population, realmEntityId)?.population || 0) -
configManager.getBuildingPopConfig(currentBuilding?.category as unknown as BuildingType).population,
configManager.getBuildingPopConfig(type).population,
capacity:
(getComponentValue(this.setup.components.Population, realmEntityId)?.capacity || 0) -
configManager.getBuildingPopConfig(type).capacity,
},
});

Expand Down
7 changes: 3 additions & 4 deletions client/src/hooks/helpers/useRealm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
} from "@bibliothecadao/eternum";
import { useEntityQuery } from "@dojoengine/react";
import { type ComponentValue, type Entity, Has, HasValue, getComponentValue, runQuery } from "@dojoengine/recs";
import { useMemo } from "react";
import { shortString } from "starknet";
import realmIdsByOrder from "../../data/realmids_by_order.json";
import { unpackResources } from "../../ui/utils/packedData";
Expand Down Expand Up @@ -210,7 +209,7 @@ export function useGetRealm(realmEntityId: ID | undefined) {

const query = useEntityQuery([HasValue(Realm, { entity_id: realmEntityId })]);

const realm = useMemo((): any => {
const realm = (): any => {
if (realmEntityId !== undefined) {
const entityId = getEntityIdFromKeys([BigInt(realmEntityId)]);
const realm = getComponentValue(Realm, entityId);
Expand Down Expand Up @@ -240,10 +239,10 @@ export function useGetRealm(realmEntityId: ID | undefined) {
};
}
}
}, [realmEntityId, query]);
};

return {
realm,
realm: realm(),
};
}

Expand Down
27 changes: 27 additions & 0 deletions client/src/ui/components/Toaster.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { useTheme } from "next-themes";
import { Toaster as Sonner } from "sonner";

type ToasterProps = React.ComponentProps<typeof Sonner>;

const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme();

return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton: "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton: "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
);
};

export { Toaster };
32 changes: 32 additions & 0 deletions client/src/ui/components/TxEmit.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { useDojo } from "@/hooks/context/DojoContext";
import { useEffect } from "react";
import { toast } from "sonner";

export function TransactionNotification() {
const {
setup: {
network: { provider },
},
} = useDojo();
useEffect(() => {
const handleTransactionComplete = (receipt: any) => {
console.log("Transaction completed:", receipt);
toast("Transaction completed");
};

const handleTransactionFailed = (error: string) => {
console.error("Transaction failed:", error);
toast("Transaction failed");
};

provider.on("transactionComplete", handleTransactionComplete);
provider.on("transactionFailed", handleTransactionFailed);

return () => {
provider.off("transactionComplete", handleTransactionComplete);
provider.off("transactionFailed", handleTransactionFailed);
};
}, [provider]);

return null;
}
15 changes: 6 additions & 9 deletions client/src/ui/components/construction/SelectPreviewBuilding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ import clsx from "clsx";
import React, { useMemo, useState } from "react";
import { HintSection } from "../hints/HintModal";

// TODO: THIS IS TERRIBLE CODE, PLEASE REFACTOR

export const SelectPreviewBuildingMenu = ({ className, entityId }: { className?: string; entityId: number }) => {
const dojo = useDojo();

Expand Down Expand Up @@ -174,17 +172,16 @@ export const SelectPreviewBuildingMenu = ({ className, entityId }: { className?:
if (!buildingCosts) return;

const hasBalance = checkBalance(buildingCosts);

const hasEnoughPopulation = hasEnoughPopulationForBuilding(realm, building);
const canBuild =
BuildingType.WorkersHut == building
building === BuildingType.WorkersHut
? hasBalance
: hasBalance && realm?.hasCapacity && hasEnoughPopulation;

const isFarm = building === BuildingType["Farm"];
const isFishingVillage = building === BuildingType["FishingVillage"];
const isWorkersHut = building === BuildingType["WorkersHut"];
const isMarket = building === BuildingType["Market"];
const isFarm = building === BuildingType.Farm;
const isFishingVillage = building === BuildingType.FishingVillage;
const isWorkersHut = building === BuildingType.WorkersHut;
const isMarket = building === BuildingType.Market;

return (
<BuildingCard
Expand Down Expand Up @@ -287,7 +284,7 @@ export const SelectPreviewBuildingMenu = ({ className, entityId }: { className?:
),
},
],
[realm, entityId, realmResourceIds, selectedTab, previewBuilding, playResourceSound],
[realm, entityId, realmResourceIds, selectedTab, previewBuilding, playResourceSound, realm.population],
);

return (
Expand Down
28 changes: 27 additions & 1 deletion client/src/ui/modules/entity-details/BuildingEntityDetails.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { TileManager } from "@/dojo/modelManager/TileManager";
import { configManager } from "@/dojo/setup";
import { useDojo } from "@/hooks/context/DojoContext";
import { useEntities, useEntitiesUtils } from "@/hooks/helpers/useEntities";
import useUIStore from "@/hooks/store/useUIStore";
Expand All @@ -10,6 +11,7 @@ import Button from "@/ui/elements/Button";
import { getEntityIdFromKeys, ResourceIdToMiningType } from "@/ui/utils/utils";
import { BuildingType, ID, ResourcesIds, StructureType } from "@bibliothecadao/eternum";
import { useComponentValue } from "@dojoengine/react";
import { getComponentValue } from "@dojoengine/recs";
import { useCallback, useEffect, useMemo, useState } from "react";
import { LeftView } from "../navigation/LeftNavigationModule";
import { RealmDetails } from "./realm/RealmDetails";
Expand Down Expand Up @@ -106,6 +108,24 @@ export const BuildingEntityDetails = () => {
}
setLeftNavigationView(LeftView.None);
}, [selectedBuildingHex, buildingState]);

const canDestroyBuilding = useMemo(() => {
if (buildingState.buildingType !== BuildingType.WorkersHut) return true;

const realmId = getComponentValue(
dojo.setup.components.EntityOwner,
getEntityIdFromKeys([BigInt(structureEntityId)]),
);

const populationImpact = configManager.getBuildingPopConfig(buildingState.buildingType).capacity;

const population = getComponentValue(
dojo.setup.components.Population,
getEntityIdFromKeys([BigInt(realmId?.entity_owner_id || 0)]),
);
return (population?.capacity || 0) - (population?.population || 0) >= populationImpact;
}, [buildingState.buildingType, buildingState.ownerEntityId]);

return (
<div className="flex flex-col h-full">
{isCastleSelected ? (
Expand Down Expand Up @@ -141,7 +161,13 @@ export const BuildingEntityDetails = () => {
>
{isPaused ? "Resume" : "Pause"}
</Button>
<Button className="mb-4" onClick={handleDestroyBuilding} variant="danger" withoutSound>
<Button
disabled={!canDestroyBuilding}
className="mb-4"
onClick={handleDestroyBuilding}
variant="danger"
withoutSound
>
Destroy
</Button>
</div>
Expand Down
2 changes: 1 addition & 1 deletion client/src/ui/modules/settings/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { RangeInput } from "@/ui/elements/RangeInput";
import { addressToNumber, displayAddress } from "@/ui/utils/utils";
import { ContractAddress } from "@bibliothecadao/eternum";
import { useEffect, useRef, useState } from "react";
import { toast } from "react-toastify";
import { toast } from "sonner";

export const SettingsWindow = () => {
const {
Expand Down
2 changes: 2 additions & 0 deletions client/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export default defineConfig({
},
workbox: {
maximumFileSizeToCacheInBytes: 4000000,
clientsClaim: true,
skipWaiting: false,
},
manifest: {
name: "Eternum",
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 1 addition & 5 deletions sdk/packages/eternum/src/provider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -840,11 +840,7 @@ export class EternumProvider extends EnhancedDojoProvider {
public async create_building(props: SystemProps.CreateBuildingProps) {
const { entity_id, directions, building_category, produce_resource_type, signer } = props;
["62", "1", "0", "4", "1"];
console.log("Create Building Call Data:", {
contractAddress: getContractByName(this.manifest, `${NAMESPACE}-building_systems`),
entrypoint: "create",
calldata: CallData.compile([entity_id, directions, building_category, produce_resource_type]),
});

return this.executeAndCheckTransaction(signer, {
contractAddress: getContractByName(this.manifest, `${NAMESPACE}-building_systems`),
entrypoint: "create",
Expand Down

0 comments on commit 626849f

Please sign in to comment.