Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor hooks #2642

Merged
merged 17 commits into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 32 additions & 57 deletions client/apps/game/src/hooks/helpers/use-battle-events.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,41 @@
import { useDojo } from "@/hooks/context/dojo-context";
import { BattleSide, ID } from "@bibliothecadao/eternum";
import { useEntityQuery } from "@dojoengine/react";
import { getComponentValue, HasValue } from "@dojoengine/recs";
import { Component, getComponentValue, HasValue } from "@dojoengine/recs";
import { useMemo } from "react";

export const useBattleStart = (battleEntityId: ID) => {
const {
setup: {
components: {
events: { BattleStartData },
},
},
} = useDojo();

const battleStartDataEntityIds = useEntityQuery(
const useBattleEventData = (
eventComponent: Component,
battleEntityId: ID,
sideFilter?: { key: string; side: BattleSide },
) => {
const eventEntityIds = useEntityQuery(
[
HasValue(BattleStartData, {
HasValue(eventComponent, {
battle_entity_id: battleEntityId,
...(sideFilter ? { [sideFilter.key]: BattleSide[sideFilter.side] } : {}),
}),
],
{
updateOnValueChange: false,
},
);

const battleStartData = useMemo(() => {
return battleStartDataEntityIds.map((entityId) => {
const battleStartData = getComponentValue(BattleStartData, entityId);
return battleStartData;
});
}, [battleStartDataEntityIds]);
return useMemo(() => {
return eventEntityIds.map((entityId) => getComponentValue(eventComponent, entityId));
}, [eventEntityIds]);
};

export const useBattleStart = (battleEntityId: ID) => {
const {
setup: {
components: {
events: { BattleStartData },
},
},
} = useDojo();

return battleStartData;
return useBattleEventData(BattleStartData, battleEntityId);
};

export const useBattleJoin = (battleEntityId: ID, joinerSide?: BattleSide) => {
Expand All @@ -43,27 +47,13 @@ export const useBattleJoin = (battleEntityId: ID, joinerSide?: BattleSide) => {
},
} = useDojo();

const battleStartDataEntityIds = useEntityQuery(
[
HasValue(BattleJoinData, {
battle_entity_id: battleEntityId,
...(joinerSide ? { joiner_side: BattleSide[joinerSide] } : {}),
}),
],
{
updateOnValueChange: false,
},
return useBattleEventData(
BattleJoinData,
battleEntityId,
joinerSide ? { key: "joiner_side", side: joinerSide } : undefined,
);

const battleStartData = useMemo(() => {
return battleStartDataEntityIds.map((entityId) => {
const battleJoinData = getComponentValue(BattleJoinData, entityId);
return battleJoinData;
});
}, [battleStartDataEntityIds]);

return battleStartData;
};

export const useBattleLeave = (battleEntityId: ID, leaverSide?: BattleSide) => {
const {
setup: {
Expand All @@ -73,24 +63,9 @@ export const useBattleLeave = (battleEntityId: ID, leaverSide?: BattleSide) => {
},
} = useDojo();

const battleLeaveDataEntityIds = useEntityQuery(
[
HasValue(BattleLeaveData, {
battle_entity_id: battleEntityId,
...(leaverSide ? { leaver_side: BattleSide[leaverSide] } : {}),
}),
],
{
updateOnValueChange: false,
},
return useBattleEventData(
BattleLeaveData,
battleEntityId,
leaverSide ? { key: "leaver_side", side: leaverSide } : undefined,
);

const battleLeaveData = useMemo(() => {
return battleLeaveDataEntityIds.map((entityId) => {
const battleLeaveData = getComponentValue(BattleLeaveData, entityId);
return battleLeaveData;
});
}, [battleLeaveDataEntityIds]);

return battleLeaveData;
};
8 changes: 4 additions & 4 deletions client/apps/game/src/hooks/helpers/use-battles.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { useDojo } from "@/hooks/context/dojo-context";
import { useEntities } from "@/hooks/helpers/use-entities";
import { BattleManager, ID, Position } from "@bibliothecadao/eternum";
import { BattleManager, ContractAddress, ID, Position } from "@bibliothecadao/eternum";
import { useComponentValue, useEntityQuery } from "@dojoengine/react";
import { Has, HasValue, NotValue, getComponentValue, runQuery } from "@dojoengine/recs";
import { getEntityIdFromKeys } from "@dojoengine/utils";
import { useMemo } from "react";
import { usePlayerRealms } from "./use-entities";

export const useBattleManager = (battleEntityId: ID) => {
const dojo = useDojo();
Expand Down Expand Up @@ -40,13 +40,13 @@ export const useBattlesAtPosition = ({ x, y }: Position) => {

export const usePlayerBattles = () => {
const {
account: { account },
setup: {
components: { Army, EntityOwner },
},
} = useDojo();

const { playerRealms } = useEntities();
const realms = playerRealms();
const realms = usePlayerRealms(ContractAddress(account.address));

const battleEntityIds = useMemo(() => {
// Get all armies in battle owned by player's realms
Expand Down
58 changes: 36 additions & 22 deletions client/apps/game/src/hooks/helpers/use-buildings.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,24 @@
import { configManager } from "@/dojo/setup";
import { useDojo } from "@/hooks/context/dojo-context";
import { ResourceIdToMiningType } from "@/ui/utils/utils";
import { BuildingType, ResourceCost, ResourcesIds } from "@bibliothecadao/eternum";
import { getComponentValue, Has, HasValue, runQuery } from "@dojoengine/recs";
import { getEntityIdFromKeys, ResourceIdToMiningType } from "@/ui/utils/utils";
import { Building, BuildingType, ID, ResourcesIds } from "@bibliothecadao/eternum";
import { useEntityQuery } from "@dojoengine/react";
import { getComponentValue, Has, HasValue } from "@dojoengine/recs";
import { useMemo } from "react";

export interface Building {
name: string;
category: string;
paused: boolean;
produced: ResourceCost;
consumed: ResourceCost[];
bonusPercent: number;
innerCol: number;
innerRow: number;
}

export const useBuildings = () => {
export const useBuildings = (outerCol: number, outerRow: number) => {
const {
setup: {
components: { Building },
},
} = useDojo();

const getBuildings = (outerCol: number, outerRow: number): Building[] => {
const buildingEntities = runQuery([
Has(Building),
HasValue(Building, { outer_col: outerCol, outer_row: outerRow }),
]);
const buildingEntities = useEntityQuery([
Has(Building),
HasValue(Building, { outer_col: outerCol, outer_row: outerRow }),
]);

const buildings = useMemo(() => {
return Array.from(buildingEntities)
.map((entity) => {
const building = getComponentValue(Building, entity);
Expand Down Expand Up @@ -60,7 +51,30 @@ export const useBuildings = () => {
};
})
.filter((building) => building != null);
};
}, [buildingEntities]);

return buildings as Building[];
};

export const useBuildingQuantities = (structureEntityId: ID | undefined) => {
const {
setup: {
components: { BuildingQuantityv2 },
},
} = useDojo();
const entityUpdate = useEntityQuery([HasValue(BuildingQuantityv2, { entity_id: structureEntityId || 0 })]);

const getBuildingQuantity = (buildingType: BuildingType) =>
getComponentValue(BuildingQuantityv2, getEntityIdFromKeys([BigInt(structureEntityId || 0), BigInt(buildingType)]))
?.value || 0;
bob0005 marked this conversation as resolved.
Show resolved Hide resolved

return { getBuildings };
return useMemo(
() => ({
food: getBuildingQuantity(BuildingType.Farm) + getBuildingQuantity(BuildingType.FishingVillage),
resource: getBuildingQuantity(BuildingType.Resource),
workersHut: getBuildingQuantity(BuildingType.WorkersHut),
markets: getBuildingQuantity(BuildingType.Market),
}),
[structureEntityId, entityUpdate],
);
};
96 changes: 9 additions & 87 deletions client/apps/game/src/hooks/helpers/use-contributions.tsx
Original file line number Diff line number Diff line change
@@ -1,98 +1,20 @@
import { configManager } from "@/dojo/setup";
import { useDojo } from "@/hooks/context/dojo-context";
import { divideByPrecision } from "@/ui/utils/utils";
import { ClientComponents, ContractAddress, ID, Resource } from "@bibliothecadao/eternum";
import { ClientComponents, ContractAddress, ID } from "@bibliothecadao/eternum";
import { useEntityQuery } from "@dojoengine/react";
import { ComponentValue, HasValue, getComponentValue, runQuery } from "@dojoengine/recs";
import { useCallback } from "react";
import { ComponentValue, HasValue, getComponentValue } from "@dojoengine/recs";

export const useContributions = () => {
export const usePlayerContributions = (playerAddress: ContractAddress, hyperstructureEntityId: ID) => {
const {
setup: {
components: { Contribution },
},
} = useDojo();

const getContributions = (hyperstructureEntityId: ID) => {
const contributionsToHyperstructure = Array.from(
runQuery([HasValue(Contribution, { hyperstructure_entity_id: hyperstructureEntityId })]),
).map((id) => getComponentValue(Contribution, id));
const contributionsToHyperstructure = useEntityQuery([
HasValue(Contribution, { hyperstructure_entity_id: hyperstructureEntityId, player_address: playerAddress }),
])
.map((id) => getComponentValue(Contribution, id))
.filter((x): x is ComponentValue<ClientComponents["Contribution"]["schema"]> => x !== undefined);

return contributionsToHyperstructure as ComponentValue<ClientComponents["Contribution"]["schema"]>[];
};

const useContributionsByPlayerAddress = (playerAddress: ContractAddress, hyperstructureEntityId: ID) => {
const contributionsToHyperstructure = useEntityQuery([
HasValue(Contribution, { hyperstructure_entity_id: hyperstructureEntityId, player_address: playerAddress }),
])
.map((id) => getComponentValue(Contribution, id))
.filter((x): x is ComponentValue<ClientComponents["Contribution"]["schema"]> => x !== undefined);

return contributionsToHyperstructure;
};

const getContributionsTotalPercentage = (hyperstructureId: number, contributions: Resource[]) => {
const totalPlayerContribution = divideByPrecision(
contributions.reduce((acc, { amount, resourceId }) => {
return acc + amount * configManager.getResourceRarity(resourceId);
}, 0),
);

const totalHyperstructureContribution = configManager.getHyperstructureTotalContributableAmount(hyperstructureId);

return totalPlayerContribution / totalHyperstructureContribution;
};

return {
getContributions,
useContributionsByPlayerAddress,
getContributionsTotalPercentage,
};
};

export const useGetHyperstructuresWithContributionsFromPlayer = () => {
const {
account: { account },
setup: {
components: { Contribution },
},
} = useDojo();

const getContributions = useCallback(() => {
const entityIds = runQuery([HasValue(Contribution, { player_address: ContractAddress(account.address) })]);
const hyperstructureEntityIds = Array.from(entityIds).map(
(entityId) => getComponentValue(Contribution, entityId)?.hyperstructure_entity_id ?? 0,
);
return new Set(hyperstructureEntityIds);
}, [account.address]);

return getContributions;
};

export const useGetUnregisteredContributions = () => {
const {
account: { account },
setup: {
components: { LeaderboardRegisterContribution },
},
} = useDojo();
const getContributions = useGetHyperstructuresWithContributionsFromPlayer();

const getUnregisteredContributions = useCallback(() => {
const registeredContributionsEntities = runQuery([
HasValue(LeaderboardRegisterContribution, { address: ContractAddress(account.address) }),
]);
const registeredContributions = Array.from(registeredContributionsEntities)
.map((entityId) => getComponentValue(LeaderboardRegisterContribution, entityId)?.hyperstructure_entity_id)
.filter((x): x is number => x !== undefined);
console.log("registeredContributions", registeredContributions);
const hyperstructuresContributedTo = Array.from(getContributions());
console.log("hyperstructuresContributedTo", hyperstructuresContributedTo);
return hyperstructuresContributedTo.filter(
(hyperstructureEntityId) =>
!registeredContributions.some((contribution) => contribution === hyperstructureEntityId),
);
}, [getContributions]);

return getUnregisteredContributions;
return contributionsToHyperstructure;
};
Loading
Loading