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

New positions #1678

Merged
merged 29 commits into from
Oct 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
46421a2
start new realm position
aymericdelab Sep 16, 2024
8232bcf
Merge branch 'main' of https://github.com/BibliothecaDAO/eternum into…
aymericdelab Sep 17, 2024
6000ab5
new realm positions contract
aymericdelab Sep 17, 2024
b0d83af
new realm position client
aymericdelab Sep 19, 2024
d1aa023
Merge branch 'main' of https://github.com/BibliothecaDAO/eternum into…
aymericdelab Sep 19, 2024
5b66da0
fix tests
aymericdelab Sep 19, 2024
9c2e7b1
fix tests
aymericdelab Sep 19, 2024
9f55392
prettier
aymericdelab Sep 19, 2024
2079c51
fix tests
aymericdelab Sep 19, 2024
6a0d106
fmt
aymericdelab Sep 19, 2024
54607d2
fix test
aymericdelab Sep 19, 2024
e16e6e3
closer realms together
aymericdelab Sep 19, 2024
0a798f6
fix tests
aymericdelab Sep 19, 2024
fe729ca
fix tests
aymericdelab Sep 19, 2024
2cd1312
fix tests
aymericdelab Sep 19, 2024
ca55b1e
add mint realm function
aymericdelab Sep 19, 2024
1dddfbd
normalized position check
aymericdelab Sep 19, 2024
388847c
fix tests
aymericdelab Sep 20, 2024
0320428
fix test
aymericdelab Sep 20, 2024
6b0cb11
radius in precision 100
aymericdelab Sep 20, 2024
43b5283
new position config
aymericdelab Sep 20, 2024
1c28a98
inverse with row < 0
aymericdelab Sep 20, 2024
3cb1859
fix positions
aymericdelab Oct 7, 2024
cc64230
Merge branch 'rc' into new-positions
aymericdelab Oct 7, 2024
8068e25
fix config
aymericdelab Oct 7, 2024
727055a
fix config issue
aymericdelab Oct 7, 2024
f6b9e5f
merge conflict
ponderingdemocritus Oct 7, 2024
c72d0d0
fix types
ponderingdemocritus Oct 7, 2024
5dd5141
prettier
ponderingdemocritus Oct 7, 2024
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
18,002 changes: 0 additions & 18,002 deletions client/src/data/geodata/hex/realmHexPositions.json

This file was deleted.

15 changes: 4 additions & 11 deletions client/src/dojo/modelManager/ArmyMovementManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ import {
CapacityConfigCategory,
ContractAddress,
EternumGlobalConfig,
NEIGHBOR_OFFSETS_EVEN,
NEIGHBOR_OFFSETS_ODD,
ID,
ResourcesIds,
getDirectionBetweenAdjacentHexes,
getNeighborHexes,
type ID,
} from "@bibliothecadao/eternum";
import { getComponentValue, type ComponentValue, type Entity } from "@dojoengine/recs";
import { uuid } from "@latticexyz/utils";
Expand Down Expand Up @@ -270,18 +269,12 @@ export class ArmyMovementManager {

const startPos = { col: path[0].col, row: path[0].row };
const endPos = { col: path[1].col, row: path[1].row };
const neighborOffsets = startPos.row % 2 === 0 ? NEIGHBOR_OFFSETS_EVEN : NEIGHBOR_OFFSETS_ODD;

for (const offset of neighborOffsets) {
if (startPos.col + offset.i === endPos.col && startPos.row + offset.j === endPos.row) {
return offset.direction;
}
}
return getDirectionBetweenAdjacentHexes(startPos, endPos);
};

private readonly _exploreHex = async (path: HexPosition[], currentArmiesTick: number) => {
const direction = this._findDirection(path);
if (direction === undefined) return;
if (direction === undefined || direction === null) return;

const overrideId = this._optimisticExplore(path[1].col, path[1].row, currentArmiesTick);

Expand Down
17 changes: 8 additions & 9 deletions client/src/dojo/modelManager/TileManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ import { BUILDINGS_CENTER } from "@/three/scenes/constants";
import { HexPosition } from "@/types";
import { FELT_CENTER } from "@/ui/config";
import { getEntityIdFromKeys } from "@/ui/utils/utils";
import { BuildingType, Direction, getNeighborHexes, ID, StructureType } from "@bibliothecadao/eternum";
import {
BuildingType,
Direction,
getDirectionBetweenAdjacentHexes,
getNeighborHexes,
ID,
StructureType,
} from "@bibliothecadao/eternum";
import { getComponentValue, Has, HasValue, NotValue, runQuery } from "@dojoengine/recs";
import { uuid } from "@latticexyz/utils";
import { CairoOption, CairoOptionVariant } from "starknet";
Expand Down Expand Up @@ -272,14 +279,6 @@ export class TileManager {
};
}

function getDirectionBetweenAdjacentHexes(
from: { col: number; row: number },
to: { col: number; row: number },
): Direction | null {
const neighbors = getNeighborHexes(from.col, from.row);
return neighbors.find((n) => n.col === to.col && n.row === to.row)?.direction ?? null;
}

function getDirectionsArray(start: [number, number], end: [number, number]): Direction[] {
const [startCol, startRow] = start;
const [endCol, endRow] = end;
Expand Down
6 changes: 3 additions & 3 deletions client/src/hooks/helpers/useEntities.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type ClientComponents } from "@/dojo/createClientComponents";
import { getRealmNameById } from "@/ui/utils/realms";
import { divideByPrecision, getEntityIdFromKeys, getPosition } from "@/ui/utils/utils";
import { divideByPrecision, getEntityIdFromKeys } from "@/ui/utils/utils";
import {
CAPACITY_CONFIG_CATEGORY_STRING_MAP,
ContractAddress,
Expand Down Expand Up @@ -85,7 +85,7 @@ export const useEntities = () => {
const realm = getComponentValue(Realm, id);
return {
...realm,
position: getPosition(realm!.realm_id),
position: getComponentValue(Position, id),
name: getRealmNameById(realm!.realm_id),
owner: getComponentValue(Owner, id),
} as RealmWithPosition;
Expand All @@ -97,7 +97,7 @@ export const useEntities = () => {
const realm = getComponentValue(Realm, id);
return {
...realm,
position: getPosition(realm!.realm_id),
position: getComponentValue(Position, id),
name: getRealmNameById(realm!.realm_id),
owner: getComponentValue(Owner, id),
} as RealmWithPosition;
Expand Down
11 changes: 2 additions & 9 deletions client/src/hooks/helpers/useRealm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { shortString } from "starknet";
import realmIdsByOrder from "../../data/realmids_by_order.json";
import { unpackResources } from "../../ui/utils/packedData";
import { getRealmNameById } from "../../ui/utils/realms";
import { getEntityIdFromKeys, getPosition } from "../../ui/utils/utils";
import { getEntityIdFromKeys } from "../../ui/utils/utils";
import { useDojo } from "../context/DojoContext";
import useUIStore from "../store/useUIStore";

Expand Down Expand Up @@ -92,14 +92,7 @@ export function useRealm() {
nextRealmIdFromOrder = orderRealmIds[latestIndex + 1];
}

const position = getPosition(nextRealmIdFromOrder);

// check if there is a structure on position, if no structure we can keep this realm Id
if (Array.from(runQuery([HasValue(Position, { x: position.x, y: position.y }), Has(Structure)])).length === 0) {
return nextRealmIdFromOrder;
} else {
latestRealmIdFromOrder = nextRealmIdFromOrder;
}
return nextRealmIdFromOrder;
}

throw new Error(`Could not find an unoccupied realm ID for order ${orderName} after ${maxIterations} attempts`);
Expand Down
9 changes: 5 additions & 4 deletions client/src/hooks/helpers/useStructures.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ export const getStructureByEntityId = (entityId: ID) => {
export function useStructuresFromPosition({ position }: { position: Position }) {
const {
setup: {
components: { Realm, Owner },
components: { Realm, Owner, Position },
},
} = useDojo();

Expand All @@ -191,21 +191,22 @@ export function useStructuresFromPosition({ position }: { position: Position })
() =>
allRealms.map((entityId) => {
const realm = getComponentValue(Realm, entityId);
if (realm) {
const realmPosition = getComponentValue(Position, entityId);
if (realm && realmPosition) {
const realmData = getRealm(realm.realm_id);
if (!realmData) return undefined;
const name = realmData.name;
const owner = getComponentValue(Owner, entityId);
const resources = unpackResources(BigInt(realm.resource_types_packed), realm.resource_types_count);

const distanceFromPosition = calculateDistance(position, realmData.position) ?? 0;
const distanceFromPosition = calculateDistance(position, realmPosition) ?? 0;

const timeToTravel = Math.floor(((distanceFromPosition / EternumGlobalConfig.speed.donkey) * 3600) / 60 / 60);

return {
...realm,
name,
position: realmData.position,
position: realmPosition,
owner: owner?.address,
resources,
distanceFromPosition,
Expand Down
6 changes: 3 additions & 3 deletions client/src/three/scenes/Worldmap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { FELT_CENTER } from "@/ui/config";
import { UNDEFINED_STRUCTURE_ENTITY_ID } from "@/ui/constants";
import { View } from "@/ui/modules/navigation/LeftNavigationModule";
import { getWorldPositionForHex } from "@/ui/utils/utils";
import { BiomeType, ID, NEIGHBOR_OFFSETS_EVEN, NEIGHBOR_OFFSETS_ODD } from "@bibliothecadao/eternum";
import { BiomeType, getNeighborOffsets, ID } from "@bibliothecadao/eternum";
import { throttle } from "lodash";
import { MapControls } from "three/examples/jsm/controls/MapControls";
import { SceneManager } from "../SceneManager";
Expand Down Expand Up @@ -335,7 +335,7 @@ export default class WorldmapScene extends HexagonScene {
this.interactiveHexManager.addHex({ col, row });

// Add border hexes for newly explored hex
const neighborOffsets = row % 2 === 0 ? NEIGHBOR_OFFSETS_EVEN : NEIGHBOR_OFFSETS_ODD;
const neighborOffsets = getNeighborOffsets(row);

neighborOffsets.forEach(({ i, j }) => {
const neighborCol = col + i;
Expand Down Expand Up @@ -426,7 +426,7 @@ export default class WorldmapScene extends HexagonScene {
}

if (!isExplored) {
const neighborOffsets = globalRow % 2 === 0 ? NEIGHBOR_OFFSETS_EVEN : NEIGHBOR_OFFSETS_ODD;
const neighborOffsets = getNeighborOffsets(globalRow);
const isBorder = neighborOffsets.some(({ i, j }) => {
const neighborCol = globalCol + i;
const neighborRow = globalRow + j;
Expand Down
5 changes: 4 additions & 1 deletion client/src/types/Position.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ export class Position {
constructor({ x, y }: { x: number; y: number }) {
this.x = x;
this.y = y;
this.normalized = x < FELT_CENTER && y < FELT_CENTER;
// if outide of square 1_000_000 x 1_000_000 around the center, it's already normalized
const squareSize = 1_000_000;
const halfSquareSize = squareSize / 2;
this.normalized = Math.abs(x - FELT_CENTER) > halfSquareSize || Math.abs(y - FELT_CENTER) > halfSquareSize;
}

public getContract() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useState } from "react";
import Button from "../../../elements/Button";

import { MAX_REALMS } from "@/ui/constants";
import { getPosition, toValidAscii } from "@/ui/utils/utils";
import { toValidAscii } from "@/ui/utils/utils";
import { getOrderName, orders } from "@bibliothecadao/eternum";
import clsx from "clsx";
import { shortString } from "starknet";
Expand Down Expand Up @@ -45,7 +45,6 @@ const SettleRealmComponent = () => {

const realmNameInAscii = toValidAscii(realm.name);

const position = getPosition(new_realm_id);
calldata.push({
realm_name: shortString.encodeShortString(realmNameInAscii),
realm_id: Number(realm.realmId),
Expand All @@ -57,7 +56,6 @@ const SettleRealmComponent = () => {
rivers: realm.rivers,
harbors: realm.harbors,
cities: realm.cities,
position,
});
}

Expand Down
5 changes: 3 additions & 2 deletions client/src/ui/config.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { ResourceMiningTypes } from "@/types";
import { BuildingType } from "@bibliothecadao/eternum";
import { BuildingType, FELT_CENTER } from "@bibliothecadao/eternum";

export { FELT_CENTER };

export const FELT_CENTER = 2147483646;
export const IS_LOW_GRAPHICS_ENABLED = localStorage.getItem("LOW_GRAPHICS_FLAG") === "true";

const BUILD_IMAGES_PREFIX = "/images/buildings/construction/";
Expand Down
6 changes: 0 additions & 6 deletions client/src/ui/utils/realms.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@ import {
orders,
RealmInterface,
} from "@bibliothecadao/eternum";
import realmsHexPositions from "../../data/geodata/hex/realmHexPositions.json";
import realmsJson from "../../data/geodata/realms.json";
import realmsOrdersJson from "../../data/geodata/realms_raw.json";
import { packResources } from "./packedData";
import { getPosition } from "./utils";

interface Attribute {
trait_type: string;
Expand Down Expand Up @@ -61,8 +58,6 @@ export function getRealm(realmId: ID): RealmInterface | undefined {
const orderName = orderAttribute ? orderAttribute.value.split(" ").pop() || "" : "";
const order = orders.find(({ orderName: name }) => name === orderName)?.orderId || 0;

const position = getPosition(realmId);

return {
realmId,
name: getRealmNameById(realmId),
Expand All @@ -74,7 +69,6 @@ export function getRealm(realmId: ID): RealmInterface | undefined {
regions,
wonder,
order,
position,
};
}

Expand Down
13 changes: 4 additions & 9 deletions client/src/ui/utils/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
} from "@bibliothecadao/eternum";
import { getEntityIdFromKeys } from "@dojoengine/utils";
import * as THREE from "three";
import { default as realmsHexPositions } from "../../data/geodata/hex/realmHexPositions.json";
import { type SortInterface } from "../elements/SortButton";

export { getEntityIdFromKeys };
Expand Down Expand Up @@ -49,12 +48,6 @@ export function divideByPrecision(value: number): number {
return value / EternumGlobalConfig.resources.resourcePrecision;
}

export function getPosition(realm_id: ID): { x: number; y: number } {
const realmPositions = realmsHexPositions as Record<number, Array<{ col: number; row: number }>>;
const position = realmPositions[Number(realm_id)][0];
return { x: position.col, y: position.row };
}

export function addressToNumber(address: string) {
// Convert the address to a big integer
let numericValue = ContractAddress(address);
Expand Down Expand Up @@ -109,7 +102,8 @@ export const getWorldPositionForHex = (hexCoords: HexPosition, flat: boolean = t

const col = hexCoords.col;
const row = hexCoords.row;
const x = col * horizDist - ((row % 2) * horizDist) / 2;
const rowOffset = ((row % 2) * Math.sign(row) * horizDist) / 2;
const x = col * horizDist - rowOffset;
const z = row * vertDist;
const y = flat ? 0 : pseudoRandom(x, z) * 2;
return new THREE.Vector3(x, y, z);
Expand All @@ -124,7 +118,8 @@ export const getHexForWorldPosition = (worldPosition: { x: number; y: number; z:

const row = Math.round(worldPosition.z / vertDist);
// hexception offsets hack
const col = Math.round((worldPosition.x + ((row % 2) * horizDist) / 2) / horizDist);
const rowOffset = ((row % 2) * Math.sign(row) * horizDist) / 2;
const col = Math.round((worldPosition.x + rowOffset) / horizDist);

return {
col,
Expand Down
10 changes: 6 additions & 4 deletions config/bank/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { config } from "..";
import { EternumConfig } from "@bibliothecadao/eternum";
import devManifest from "../../contracts/manifests/dev/deployment/manifest.json";
import productionManifest from "../../contracts/manifests/prod/deployment/manifest.json";

import { EternumProvider, ResourcesIds } from "@bibliothecadao/eternum";
import { EternumProvider, FELT_CENTER, ResourcesIds } from "@bibliothecadao/eternum";
import { Account } from "starknet";

if (
Expand All @@ -16,6 +16,8 @@ if (
const VITE_PUBLIC_MASTER_ADDRESS = process.env.VITE_PUBLIC_MASTER_ADDRESS;
const VITE_PUBLIC_MASTER_PRIVATE_KEY = process.env.VITE_PUBLIC_MASTER_PRIVATE_KEY;

// default config
const config = new EternumConfig();
const manifest = process.env.VITE_PUBLIC_DEV === "true" ? devManifest : productionManifest;
// Bug in bun we have to use http://127.0.0.1:5050/
const nodeUrl = process.env.VITE_PUBLIC_DEV === "true" ? "http://127.0.0.1:5050/" : process.env.VITE_PUBLIC_NODE_URL;
Expand All @@ -28,8 +30,8 @@ const ADMIN_BANK_ENTITY_ID = 999999998n;
const LORDS_LIQUIDITY_PER_RESOURCE = 250000;

// Banks
const COORD_X = 2147483899;
const COORD_Y = 2147483801;
const COORD_X = FELT_CENTER;
const COORD_Y = FELT_CENTER;

export const createAdminBank = async () => {
const tx = await provider.create_admin_bank({
Expand Down
2 changes: 2 additions & 0 deletions contracts/scripts/system_models.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"CONFIG_SYSTEMS": [
"SettlementConfig",
"ProductionInput",
"CapacityConfig",
"SpeedConfig",
Expand Down Expand Up @@ -31,6 +32,7 @@
"DEV_RESOURCE_SYSTEMS": ["Resource", "OwnedResourcesTracker", "Production"],
"DEV_BANK_SYSTEMS": ["Tile", "Position", "Owner", "Bank", "Structure", "StructureCount", "CapacityCategory"],
"REALM_SYSTEMS": [
"SettlementConfig",
"Owner",
"Realm",
"Position",
Expand Down
33 changes: 33 additions & 0 deletions contracts/scripts/testing/mint_realms.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#!/bin/bash

commands=()

# Function to show usage
usage() {
echo "Usage: $0"
exit 1
}

create_realms() {
local num_realms=$1
for ((i=1; i<=$num_realms; i++)); do
commands+=("sozo execute --account-address $DOJO_ACCOUNT_ADDRESS --calldata 0x1,1,0x20309,3,5,5,5,5,1,1 $REALM_SYSTEMS create && sleep 0.1")
done
}

world="$SOZO_WORLD"

source ./scripts/env_variables.sh dev

source ./scripts/contracts.sh

read -p "Enter the number of realms you want to mint: " num_realms
create_realms "$num_realms"

for cmd in "${commands[@]}"; do
echo "Executing command: $cmd"
output=$(eval "$cmd")
echo "Output:"
echo "$output"
echo "--------------------------------------"
done
7 changes: 4 additions & 3 deletions contracts/src/constants.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const HYPERSTRUCTURE_LEVELING_START_TIER: u64 = 0;
const REALM_LEVELING_START_TIER: u64 = 1;

// max realms per user
const MAX_REALMS_PER_ADDRESS: u8 = 5;
const MAX_REALMS_PER_ADDRESS: u16 = 8_000;

// resource precision
const RESOURCE_PRECISION: u128 = 1_000;
Expand Down Expand Up @@ -305,8 +305,9 @@ fn split_resources_and_probs() -> (Span<u8>, Span<u128>) {


// DISCUSS: instead of using constants for entity_type, store the entity_type in the storage
// DISCUSS: register each new entity_type to the system by creating an entity containing the config components
// Using DONKEY_ENTITY_TYPE I can look up the speed and capacity of that entity when creating it
// DISCUSS: register each new entity_type to the system by creating an entity containing the config
// components Using DONKEY_ENTITY_TYPE I can look up the speed and capacity of that entity when
// creating it
const DONKEY_ENTITY_TYPE: u32 = 256;
const REALM_ENTITY_TYPE: u32 = 257;
const ARMY_ENTITY_TYPE: u32 = 258;
Expand Down
Loading
Loading