diff --git a/app/react/components/devtools/entities.jsx b/app/react/components/devtools/entities.jsx new file mode 100644 index 0000000..8c88248 --- /dev/null +++ b/app/react/components/devtools/entities.jsx @@ -0,0 +1,172 @@ +import {Map} from 'immutable'; +import {useCallback, useEffect, useState} from 'react'; + +import {useClient} from '@/react/context/client.js'; +import {useEcs, useEcsTick} from '@/react/context/ecs.js'; + +import styles from './entities.module.css'; + +const entityJsonPaths = Object.keys(import.meta.glob('%/**/*.entity.json')); + +function entityLabel(entity) { + let label = `${entity.id}`; + const {Player, Position} = entity; + if (1 === entity.id) { + label = 'Master'; + } + if (Player) { + label += `: Player (${Player.id})`; + } + if (Position) { + label += `: [${Position.x.toFixed(2)}, ${Position.y.toFixed(2)}]` + } + return label; +} + +function Entities({eventsChannel}) { + const client = useClient(); + const ecsRef = useEcs(); + const [activeEntity, setActiveEntity] = useState(1); + const [creatingEntityPath, setCreatingEntityPath] = useState(entityJsonPaths[0]); + const [entities, setEntities] = useState(Map()); + const onEcsTick = useCallback((payload, ecs) => { + setEntities((entities) => { + return entities.withMutations((entities) => { + if (0 === entities.size) { + for (const id in ecs.$$entities) { + const entity = ecs.get(id); + entities.set(id, entityLabel(entity)); + } + return; + } + for (const id in payload) { + const update = payload[id]; + if (false === update) { + entities.delete(id); + } + else { + const entity = ecs.get(id); + entities.set(id, entityLabel(entity)); + } + } + }); + }); + }, []); + useEcsTick(onEcsTick); + useEffect(() => { + if (!ecsRef.current) { + return; + } + const master = ecsRef.current.get(1); + if (!master) { + return; + } + const {TileLayers} = master; + const {size, tileSize} = TileLayers.layer(0); + function onClick({x, y}, {shiftKey}) { + const at = { + x: shiftKey ? Math.floor(x / tileSize.x) * tileSize.x + (tileSize.x / 2) : x, + y: shiftKey ? Math.floor(y / tileSize.y) * tileSize.y + (tileSize.y / 2) : y, + }; + if (at.x < 0 || at.y < 0 || at.x >= size.x || at.y >= size.y) { + return; + } + const entity = ecsRef.current.get(activeEntity); + if (!entity.Position) { + return; + } + client.send({ + type: 'AdminAction', + payload: { + type: 'moveEntity', + value: { + id: activeEntity, + at, + }, + }, + }); + } + eventsChannel.addListener('click', onClick); + return () => { + eventsChannel.removeListener('click', onClick); + }; + }, [activeEntity, client, ecsRef, eventsChannel]); + const options = []; + for (const [id, label] of entities.entries()) { + options.push( + ); + } + return ( +