multirepo

This commit is contained in:
azykov@mail.ru
2026-09-04 13:54:54 +03:00
parent 1553c48807
commit 5b2452aa50
41 changed files with 544 additions and 2 deletions
+147
View File
@@ -0,0 +1,147 @@
import { useEffect, useState } from 'react';
import Topbar from './components/Topbar';
import { GameCanvas } from './components/GameCanvas';
import { load, save } from './saveLoad';
import { defaultGame } from './prefabs/game';
import { Game, deserializeGame } from '@incgame/engine';
export type Selection = { kind: 'node'; id: string } | null;
export default function App() {
const [game, setGame] = useState<Game>(() => load());
const [selected, setSelected] = useState<Selection>(null);
useEffect(() => save(game), [game]);
// useEffect(() => saveTickCount(tickCount), [tickCount]);
function handleTick() {
game.tick(1.0 / 10);
setGame(game.clone());
}
function handleReset() {
const ok = window.confirm(
'Обнулить все значения и таймеры? Настройки узлов и связей не изменятся.'
);
if (!ok)
return;
game.reset();
setGame(game.clone());
}
function handleInitialize() {
const ok = window.confirm(
'Удалить все объекты и начать игру с начала?'
);
if (!ok)
return;
setGame(deserializeGame(defaultGame()));
}
// function handleAddNode(kind: NodeKind) {
// const idNum = game.nextId + 1;
// const id = `${kind}-${idNum}`;
// const node: SimNode = {
// id,
// label: kindLabel(kind),
// x: 60 + (game.nodes.length * 25) % 600,
// y: 60 + (game.nodes.length * 47) % 400,
// capacity: kind === 'storage' ? 100 : null,
// behavior: BEHAVIOR_DEFAULTS[kind],
// };
// setGame((prev) => ({ ...prev, nextId: idNum, nodes: [...prev.nodes, node] }));
// setBuffers((prev) => ({ ...prev, [id]: {} }));
// setSelected({ kind: 'node', id });
// }
// function handleRemoveNode(id: string) {
// setGame((prev) => ({
// ...prev,
// nodes: prev.nodes.filter((n) => n.id !== id),
// edges: prev.edges.filter((e) => e.from !== id && e.to !== id),
// }));
// setBuffers((prev) => {
// const next = { ...prev };
// delete next[id];
// return next;
// });
// setSelected((s) => (s && s.id === id ? null : s));
// }
// function handleAddEdge() {
// if (game.nodes.length < 2) return;
// const idNum = game.nextId + 1;
// const id = `e-${idNum}`;
// const edge: SimEdge = {
// id,
// from: game.nodes[0].id,
// to: game.nodes[1].id,
// resource: 'wood',
// rate: 1,
// priority: 0,
// };
// setGame((prev) => ({ ...prev, nextId: idNum, edges: [...prev.edges, edge] }));
// setSelected({ kind: 'edge', id });
// }
// function handleRemoveEdge(id: string) {
// setGame((prev) => ({ ...prev, edges: prev.edges.filter((e) => e.id !== id) }));
// setSelected((s) => (s && s.id === id ? null : s));
// }
// function handleUpdateNode(id: string, patch: Partial<SimNode>) {
// setGame((prev) => ({
// ...prev,
// nodes: prev.nodes.map((n) => (n.id === id ? { ...n, ...patch } : n)),
// }));
// }
// function handleUpdateNodeBehavior(id: string, behavior: Behavior) {
// handleUpdateNode(id, { behavior });
// }
// function handleUpdateEdge(id: string, patch: Partial<SimEdge>) {
// setGame((prev) => ({
// ...prev,
// edges: prev.edges.map((e) => (e.id === id ? { ...e, ...patch } : e)),
// }));
// }
// function handleDragNode(id: string, x: number, y: number) {
// handleUpdateNode(id, { x, y });
// }
return (
<div id="app">
<Topbar
time={game.time}
onTick={handleTick}
onReset={handleReset}
onInitialize={handleInitialize}
/>
<div className="main">
<GameCanvas
game={game}
selected={selected}
onSelectNode={(id) => setSelected({ kind: 'node', id })}
/>
{/* <Sidebar
game={game}
selected={selected}
onSelectNode={(id) => setSelected({ kind: 'node', id })}
onSelectEdge={(id) => setSelected({ kind: 'edge', id })}
onAddNode={handleAddNode}
onAddEdge={handleAddEdge}
onRemoveNode={handleRemoveNode}
onRemoveEdge={handleRemoveEdge}
onUpdateNode={handleUpdateNode}
onUpdateNodeBehavior={handleUpdateNodeBehavior}
onUpdateEdge={handleUpdateEdge}
/> */}
</div>
</div>
);
}
@@ -0,0 +1,82 @@
import { forwardRef } from 'react';
import { GraphNode } from '../ui/graph';
import { ResourceDescriptions } from '../ui/resource';
import { ConverterCardInfo } from './ConverterCardInfo';
import { Game, Behaviour, Converter, Resource } from '@incgame/engine';
import * as yaml from 'yaml';
interface Props {
game: Game;
position: GraphNode['position'];
behaviour: Behaviour,
selected: boolean;
onSelect: () => void;
onSocketRef?: (type: 'input' | 'output', index: number, el: HTMLDivElement | null) => void;
}
export const BehaviourCard = forwardRef<HTMLDivElement, Props>(function NodeCard({ position, behaviour, selected, onSelect, onSocketRef }, ref) {
function handleClick() {
onSelect();
}
const info = behaviour.getDisplayInfo();
const inputSockets = info.sockets.filter((s) => s.type === 'input');
const outputSockets = info.sockets.filter((s) => s.type === 'output');
return (
<div
ref={ref}
className={`node node--${behaviour.kind}${selected ? ' is-selected' : ''}`}
style={{ left: position.x, top: position.y }}
onClick={handleClick}
>
<div className="unit__sockets unit__sockets--input">
{
inputSockets.map((socket) => (
<div
key={`input.${socket.index}`}
ref={(el) => onSocketRef?.('input', socket.index, el)}
className="unit__socket"
style={{ background: ResourceDescriptions[socket.resource].color }}
title={`${ResourceDescriptions[socket.resource].label} (вход)`}
/>
))
}
</div>
<div className="unit__sockets unit__sockets--output">
{
outputSockets.map((socket) => (
<div
key={`output.${socket.index}`}
ref={(el) => onSocketRef?.('output', socket.index, el)}
className="unit__socket"
style={{ background: ResourceDescriptions[socket.resource].color }}
title={`${ResourceDescriptions[socket.resource].label} (выход)`}
/>
))
}
</div>
<div className="unit__id">#{behaviour.id}</div>
<div className="unit__kind">{behaviour.kind}</div>
{
Object.entries(info.storages).map(([name, storage]) => (
<div className="unit__resources" key={name}>
<div>{name}</div>
{
Object.entries(storage)
.map(([rt, v]) => `${ResourceDescriptions[rt as Resource].icon}${v.toStringWithDecimalPlaces(4)}`).join(' ')
}
</div>
))
}
{/* <div className="unit__links">
{info.links.map((link) => <div key={`${link.target}/${link.resource}`}>→{link.target}/{link.resource}</div>)}
</div> */}
{
behaviour.kind === 'converter' && <ConverterCardInfo converter={behaviour as Converter} />
}
<div className="unit__debug" style={{ fontSize: '75%', whiteSpace: 'pre' }}>{yaml.stringify(info.raw, undefined, 4)}</div>
</div>
);
});
@@ -0,0 +1,14 @@
import { Converter } from "@incgame/engine";
type Props = {
converter: Converter;
}
export const ConverterCardInfo = function ({ converter }: Props) {
return <>
<div className="unit__converter__progress">
<div className="unit__converter__progress_bar" style={{ width: `${converter.cycleTime.div(converter.cycleLength).mul(100).toFixed(2)}%` }} />
<div className="unit__converter__progress_info">{converter.cycleTime.toFixed(4)} of {converter.cycleLength.toFixed(4)}</div>
</div>
</>
}
@@ -0,0 +1,134 @@
import type { Selection } from '../App';
import { BehaviourCard } from './BehaviourCard';
import { build2dNodes, GraphNode } from '../ui/graph';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { LinkLine } from './LinkLine';
import { Game } from '@incgame/engine';
interface Props {
game: Game;
selected: Selection;
onSelectNode: (id: string) => void;
}
export const GameCanvas = function ({
game,
selected,
onSelectNode,
}: Props) {
const canvasRef = useRef<HTMLDivElement>(null);
const nodeElsRef = useRef<Map<string, HTMLDivElement>>(new Map());
const socketElsRef = useRef<Map<string, HTMLDivElement>>(new Map());
const [size, setSize] = useState({ width: 0, height: 0 });
const [centers, setCenters] = useState<Record<string, { x: number, y: number }>>({});
const [socketCenters, setSocketCenters] = useState<Record<string, { x: number, y: number }>>({});
useEffect(() => {
const el = canvasRef.current;
if (!el) return;
const observer = new ResizeObserver(([entry]) => {
const { width, height } = entry.contentRect;
setSize({ width, height });
});
observer.observe(el);
return () => observer.disconnect();
}, []);
const [graphNodes, setNodes2d] = useState<GraphNode[]>([]);
useEffect(() => {
let cancelled = false;
build2dNodes(game.nodes, { width: size.width, height: size.height, padding: 40 })
.then((result) => {
if (!cancelled) setNodes2d(result);
});
return () => { cancelled = true; };
}, [game.nodes, size.width, size.height]);
useLayoutEffect(() => {
const worldEl = canvasRef.current;
if (!worldEl) return;
const worldRect = worldEl.getBoundingClientRect();
function centerOf(el: HTMLDivElement) {
const rect = el.getBoundingClientRect();
return {
x: rect.left - worldRect.left + rect.width / 2,
y: rect.top - worldRect.top + rect.height / 2,
};
}
const nextCenters: Record<string, { x: number, y: number }> = {};
const nextSocketCenters: Record<string, { x: number, y: number }> = {};
for (const graphNode of graphNodes) {
const el = nodeElsRef.current.get(graphNode.entity.id);
if (el) nextCenters[graphNode.entity.id] = centerOf(el);
for (const socket of graphNode.entity.getDisplayInfo().sockets) {
const socketKey = `${graphNode.entity.id}.${socket.type}.${socket.index}`;
const socketEl = socketElsRef.current.get(socketKey);
if (socketEl) nextSocketCenters[socketKey] = centerOf(socketEl);
}
}
setCenters(nextCenters);
setSocketCenters(nextSocketCenters);
}, [graphNodes]);
function withCenter(graphNode: GraphNode): GraphNode {
const center = centers[graphNode.entity.id];
return center ? { ...graphNode, position: center } : graphNode;
}
function withSocket(graphNode: GraphNode, type: 'input' | 'output', resource: string): GraphNode {
const socket = graphNode.entity.getDisplayInfo().sockets
.find((s) => s.type === type && s.resource === resource);
const center = socket && socketCenters[`${graphNode.entity.id}.${type}.${socket.index}`];
return center ? { ...graphNode, position: center } : withCenter(graphNode);
}
return (
<div className="world-wrap">
<div id="world" ref={canvasRef}>
{
graphNodes.map((graphNode) =>
graphNode.entity.inputLinks.map((link, idx) => {
const target = graphNodes.find((gn) => gn.entity.id === link.target);
return target && (
<LinkLine
game={game}
key={`${graphNode.entity.id}.${idx}`}
from={{ node: withSocket(graphNode, 'input', link.resource), resource: link.resource }}
to={{ node: withSocket(target, 'output', link.resource), resource: link.resource }}
/>
);
}))
}
{
graphNodes.map((graphNode) => (
<BehaviourCard
ref={(el) => {
if (el)
nodeElsRef.current.set(graphNode.entity.id, el);
else
nodeElsRef.current.delete(graphNode.entity.id);
}}
onSocketRef={(type, index, el) => {
const socketKey = `${graphNode.entity.id}.${type}.${index}`;
if (el)
socketElsRef.current.set(socketKey, el);
else
socketElsRef.current.delete(socketKey);
}}
game={game}
key={graphNode.entity.id}
position={graphNode.position}
behaviour={graphNode.entity}
selected={selected?.kind === 'node' && selected.id === graphNode.entity.id}
onSelect={() => onSelectNode(graphNode.entity.id)}
/>
))}
</div>
</div>
);
}
@@ -0,0 +1,45 @@
import { Game, Resource } from "@incgame/engine";
import { GraphNode } from "../ui/graph";
type Props = {
game: Game,
from: { node: GraphNode, resource: Resource },
to: { node: GraphNode, resource: Resource },
}
export const LinkLine = function ({ from, to }: Props) {
const markerId = `node-line-arrow-${from.node.entity.id}-${to.node.entity.id}`.replace(/[^a-zA-Z0-9_-]/g, '_');
const fromSocket = from.node.entity.getDisplayInfo().sockets.find((s) => s.type === 'input' && s.resource == from.resource);
const toSocket = to.node.entity.getDisplayInfo().sockets.find((s) => s.type === 'output' && s.resource == to.resource);
if (!fromSocket || !toSocket)
return null;
return (
<svg>
<defs>
<marker
id={markerId}
viewBox="0 0 10 10"
refX="9"
refY="5"
markerWidth="6"
markerHeight="6"
orient="auto-start-reverse"
>
<path d="M0,0 L10,5 L0,10 z" fill="white" />
</marker>
</defs>
<line
x1={from.node.position.x}
y1={from.node.position.y}
x2={to.node.position.x}
y2={to.node.position.y}
stroke="white"
strokeWidth={2}
markerStart={`url(#${markerId})`}
/>
</svg>
);
};
@@ -0,0 +1,79 @@
import type Decimal from 'break_eternity.js';
import { useEffect, useRef } from 'react';
import type { PointerEvent } from 'react';
interface Props {
time: Decimal;
onTick: () => void;
onReset: () => void;
onInitialize: () => void;
}
const HOLD_TICK_INTERVAL_MS = 1000;
const MIN_TICK_INTERVAL_MS = 50;
export default function Topbar({ time, onTick, onReset, onInitialize }: Props) {
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Mutable, not React state: doTick reschedules itself via setTimeout, so it must always read
// and write the CURRENT speed directly — a value captured in a render's closure (e.g. via
// useState) would stay frozen for the lifetime of that closure, since nothing ever forces
// doTick to be re-created from a fresh render while a hold is in progress.
const speedRef = useRef(HOLD_TICK_INTERVAL_MS);
function stopHolding() {
if (timeoutRef.current !== null) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
speedRef.current = HOLD_TICK_INTERVAL_MS;
}
function doTick() {
onTick();
speedRef.current = Math.max(MIN_TICK_INTERVAL_MS, Math.pow(speedRef.current, 0.97));
timeoutRef.current = setTimeout(doTick, speedRef.current);
}
function startHolding(e: PointerEvent<HTMLButtonElement>) {
if (e.button !== 0)
return;
e.currentTarget.setPointerCapture(e.pointerId);
stopHolding();
doTick();
}
useEffect(() => {
window.addEventListener('blur', stopHolding);
return () => {
window.removeEventListener('blur', stopHolding);
stopHolding();
};
}, []);
return (
<div className="topbar">
<h1 className="topbar__title">
Граф ресурсов
<span>детерминированная тиковая симуляция</span>
</h1>
<div className="tick-counter">
Время <b>{time.toStringWithDecimalPlaces(4)}</b>
</div>
<div className="spacer" />
<button className="btn" onClick={onInitialize}>
Initialize
</button>
<button className="btn" onClick={onReset}>
Reset
</button>
<button
className="btn btn--primary"
onPointerDown={startHolding}
onPointerUp={stopHolding}
onPointerCancel={stopHolding}
>
Tick ▶
</button>
</div>
);
}
+503
View File
@@ -0,0 +1,503 @@
:root {
--bg: #201f1c;
--panel: #29271f;
--panel-2: #322f26;
--line: #4a4536;
--grid-line: rgba(196, 178, 138, 0.08);
--ink: #e9e2d2;
--ink-dim: #a89f8a;
--accent-source: #7fae6a;
--accent-storage: #a89f8a;
--accent-converter: #d9a441;
--accent-consumer: #c15a4e;
--edge-color: #8a8a8a;
--danger: #c15a4e;
--mono: 'IBM Plex Mono', ui-monospace, monospace;
--display: 'Space Grotesk', ui-sans-serif, sans-serif;
}
* {
box-sizing: border-box;
}
html,
body,
#root {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--ink);
font-family: var(--mono);
font-size: 10pt;
}
#app {
display: flex;
flex-direction: column;
height: 100vh;
}
/* ---------------------------------------------------------- top bar --- */
.topbar {
display: flex;
align-items: center;
gap: 20px;
padding: 12px 20px;
background: var(--panel);
border-bottom: 1px solid var(--line);
flex-shrink: 0;
}
.topbar__title {
font-family: var(--display);
font-weight: 700;
font-size: 150%;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--ink);
margin: 0;
border-right: 1px solid var(--line);
padding-right: 16px;
}
.topbar__title span {
display: block;
font-family: var(--mono);
font-weight: 400;
letter-spacing: 0.04em;
color: var(--ink-dim);
text-transform: none;
margin-top: 2px;
}
.tick-counter {
font-family: var(--mono);
color: var(--ink-dim);
background: var(--panel-2);
border: 1px solid var(--line);
padding: 6px 12px;
border-radius: 3px;
}
.tick-counter b {
color: var(--accent-converter);
}
.spacer {
flex: 1;
}
.btn {
font-family: var(--mono);
font-weight: 500;
letter-spacing: 0.03em;
border: 1px solid var(--line);
background: var(--panel-2);
color: var(--ink);
padding: 9px 16px;
border-radius: 3px;
cursor: pointer;
transition: border-color 0.12s, transform 0.05s;
}
.btn:hover {
border-color: var(--ink-dim);
}
.btn:active {
transform: translateY(1px);
}
.btn:focus-visible {
outline: 2px solid var(--accent-converter);
outline-offset: 2px;
}
.btn--primary {
background: var(--accent-converter);
border-color: var(--accent-converter);
color: #201f1c;
font-weight: 600;
}
.btn--primary:hover {
border-color: #f0c169;
}
.btn--danger {
background: transparent;
border-color: var(--danger);
color: var(--danger);
margin-top: 14px;
width: 100%;
}
.btn--danger:hover {
background: rgba(193, 90, 78, 0.12);
}
.btn--ghost {
background: transparent;
border-style: dashed;
color: var(--ink-dim);
width: 100%;
margin-top: 4px;
}
.btn--icon {
padding: 4px 8px;
}
select {
font-family: var(--mono);
background: var(--panel-2);
color: var(--ink);
border: 1px solid var(--line);
border-radius: 3px;
padding: 8px 10px;
}
/* --------------------------------------------------------------- main --- */
.main {
flex: 1;
display: flex;
min-height: 0;
}
/* ------------------------------------------------------------- world --- */
.world-wrap {
flex: 1;
overflow: auto;
position: relative;
background-color: var(--bg);
background-image:
linear-gradient(var(--grid-line) 1px, transparent 1px),
linear-gradient(90deg, var(--grid-line) 1px, transparent 1px);
background-size: 24px 24px;
}
#world {
position: relative;
width: 1600px;
height: 900px;
}
#world>svg {
position: absolute;
top: 0;
left: 0;
width: 1600px;
height: 900px;
pointer-events: none;
}
#world>svg line {
pointer-events: stroke;
}
.node {
position: absolute;
background: var(--panel);
border: 1px solid var(--line);
border-left: 4px solid var(--accent-storage);
border-radius: 4px;
padding: 0.25em 0.5em;
cursor: grab;
user-select: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.35);
touch-action: none;
display: flex;
flex-direction: column;
gap: 0.25em;
}
.node:active {
cursor: grabbing;
}
.node.is-selected {
border-left-width: 4px;
outline: 1.5px dashed var(--ink);
outline-offset: 3px;
}
.node--source {
border-left-color: var(--accent-source);
}
.node--storage {
border-left-color: var(--accent-storage);
}
.node--converter {
border-left-color: var(--accent-converter);
}
.node--consumer {
border-left-color: var(--accent-consumer);
}
.unit__id {
font-family: var(--display);
font-weight: 200;
color: var(--ink);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.unit__title {
font-family: var(--display);
font-weight: 600;
font-size: 125%;
color: var(--ink);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.unit__kind {
letter-spacing: 0.05em;
text-transform: uppercase;
color: var(--ink-dim);
}
.unit__resources {
background: #171613;
border: 1px solid var(--line);
border-radius: 3px;
padding: 4px 6px;
letter-spacing: 0.02em;
white-space: nowrap;
}
.unit__links {
background: #171613;
border: 1px solid var(--line);
border-radius: 3px;
padding: 4px 6px;
letter-spacing: 0.02em;
white-space: nowrap;
}
.unit__converter__progress {
font-size: 75%;
background: #171613;
border: 1px solid var(--line);
border-radius: 3px;
padding: 1px 6px;
letter-spacing: 0.02em;
white-space: nowrap;
position: relative;
overflow: hidden;
min-height: 10px;
display: flex;
align-items: center;
justify-content: center;
}
.unit__converter__progress_bar {
position: absolute;
inset: 0;
z-index: 1;
background: linear-gradient(90deg, var(--accent-converter), #f0c169);
opacity: 0.3;
transition: width 0.15s ease-out;
}
.unit__converter__progress_info {
position: relative;
z-index: 2;
color: var(--ink);
}
.unit__sockets {
position: absolute;
top: 0;
bottom: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
}
.unit__sockets--input {
left: -5px;
}
.unit__sockets--output {
right: -5px;
}
.unit__socket {
width: 10px;
height: 10px;
border-radius: 50%;
border: 1.5px solid var(--panel);
box-shadow: 0 0 0 1px var(--edge-color);
}
/* ------------------------------------------------------------ sidebar --- */
.sidebar {
width: 340px;
flex-shrink: 0;
background: var(--panel);
border-left: 1px solid var(--line);
display: flex;
flex-direction: column;
overflow-y: auto;
}
.sidebar__section {
padding: 14px 16px;
border-bottom: 1px solid var(--line);
}
.sidebar__section--grow {
flex: 1;
border-bottom: none;
}
.sidebar__section h4 {
font-family: var(--display);
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--ink-dim);
margin: 0 0 8px;
}
.sidebar__list {
list-style: none;
margin: 0;
padding: 0;
max-height: 140px;
overflow-y: auto;
}
.sidebar__list li {
padding: 6px 8px;
font-size: 11.5px;
border-radius: 3px;
cursor: pointer;
color: var(--ink-dim);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.sidebar__list li:hover {
background: var(--panel-2);
color: var(--ink);
}
.sidebar__list li.is-active {
background: var(--panel-2);
color: var(--accent-converter);
}
#sidebar-content {
padding: 16px 0 0;
flex: 1;
overflow-y: auto;
}
#sidebar-content h3 {
font-family: var(--display);
font-size: 13px;
color: var(--ink);
margin: 0 0 14px;
word-break: break-all;
}
.hint {
color: var(--ink-dim);
font-size: 11.5px;
line-height: 1.5;
}
.field {
display: flex;
flex-direction: column;
gap: 5px;
margin-bottom: 12px;
font-size: 11px;
color: var(--ink-dim);
}
.field input,
.field select {
font-family: var(--mono);
font-size: 12px;
background: var(--panel-2);
color: var(--ink);
border: 1px solid var(--line);
border-radius: 3px;
padding: 7px 9px;
width: 100%;
}
.field input:focus-visible,
.field select:focus-visible {
outline: 2px solid var(--accent-converter);
outline-offset: 1px;
}
.coord-row {
display: flex;
gap: 8px;
}
.coord-row input {
width: 50%;
}
.recipe-box {
border: 1px solid var(--line);
border-radius: 4px;
padding: 10px;
margin-bottom: 12px;
background: var(--panel-2);
}
.recipe-box__title {
font-size: 10.5px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--ink-dim);
margin-bottom: 8px;
}
.recipe-row {
display: flex;
gap: 6px;
margin-bottom: 6px;
align-items: center;
}
.recipe-row select {
flex: 1.4;
}
.recipe-row input {
flex: 1;
}
::-webkit-scrollbar {
width: 9px;
height: 9px;
}
::-webkit-scrollbar-track {
background: var(--bg);
}
::-webkit-scrollbar-thumb {
background: var(--line);
border-radius: 5px;
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
+81
View File
@@ -0,0 +1,81 @@
import { SerializedGame } from "@incgame/engine";
export const defaultGame: () => SerializedGame = () => ({
time: 0,
nodes: [
{
id: 'forest',
name: 'Лес',
behaviour: {
id: 'forest.1',
kind: 'converter',
inputLinks: { pins: [] },
rules: {
cycleLength: 1,
outputRates: { tree: 1, stone: 0.1 },
}
},
},
{
id: 'sawmill',
name: 'Лесопилка',
behaviour: {
id: 'sawmill.1',
kind: 'converter',
inputLinks: {
pins: [
{
resource: 'tree',
target: 'forest.1',
},
]
},
rules: {
cycleLength: 1.8,
inputRates: { tree: 1 },
outputRates: { wood: 2 },
},
},
},
{
id: 'shop',
name: 'Магазин',
behaviour: {
id: 'shop.1',
kind: 'storage',
inputLinks: {
pins: [
{
resource: 'wood',
target: 'sawmill.1',
},
{
resource: 'stone',
target: 'forest.1',
}
]
},
acceptsResources: ['wood', 'stone'],
items: {},
},
},
{
id: 'shop2',
name: 'Магазин 2',
behaviour: {
id: 'shop.2',
kind: 'storage',
inputLinks: {
pins: [
{
resource: 'stone',
target: 'forest.1',
}
]
},
acceptsResources: ['stone'],
items: {},
},
},
],
});
+25
View File
@@ -0,0 +1,25 @@
import { defaultGame } from "./prefabs/game";
import { Game, serializeGameToString, deserializeGame, deserializeGameFromString } from '@incgame/engine';
export const saveParams = {
path: 'default',
}
const KEY_GAME = 'incgame';
export function save(game: Game) {
localStorage.setItem(`${saveParams.path}_${KEY_GAME}`, serializeGameToString(game));
}
export function load(): Game {
try {
const raw = localStorage.getItem(`${saveParams.path}_${KEY_GAME}`);
if (raw)
return deserializeGameFromString(raw);
} catch (e) {
console.warn('Не удалось прочитать игру из localStorage', e);
}
const fresh = deserializeGame(defaultGame());
save(fresh);
return fresh;
}
+50
View File
@@ -0,0 +1,50 @@
import ELK, { ElkNode } from "elkjs/lib/elk.bundled.js";
import { Unit, Behaviour } from "@incgame/engine";
const elk = new ELK();
const UNIT_WIDTH = 200;
const NODE_HEIGHT = 150;
export type GraphNode = {
position: { x: number, y: number };
kind: 'behaviour';
entity: Behaviour;
}
export async function build2dNodes(units: Unit[], area: { width: number, height: number, padding: number }): Promise<GraphNode[]> {
const entitiesById = new Map(units.map((unit) => [unit.behaviour.id, unit.behaviour]));
const graph: ElkNode = {
id: "root",
layoutOptions: {
"elk.algorithm": "layered",
"elk.direction": "LEFT",
"elk.spacing.nodeNode": "100",
"elk.layered.spacing.nodeNodeBetweenLayers": "100",
},
children: units.map((unit) => ({
id: unit.behaviour.id,
width: UNIT_WIDTH,
height: NODE_HEIGHT,
})),
edges: units.flatMap((node) =>
node.behaviour.inputLinks.map((link, idx) => ({
id: `${node.behaviour.id}->${link.target}.${idx}`,
sources: [node.behaviour.id],
targets: [link.target],
}))
),
};
const layout = await elk.layout(graph);
return (layout.children ?? []).map((child) => ({
position: {
x: (child.x ?? 0) + area.padding,
y: (child.y ?? 0) + area.padding,
},
kind: 'behaviour',
entity: entitiesById.get(child.id)!,
}));
}
+17
View File
@@ -0,0 +1,17 @@
import { Resource } from "@incgame/engine";
export type ResourceDescription = {
id: Resource;
label: string;
color: string;
icon: string;
}
export const ResourceDescriptions: Record<ResourceDescription['id'], ResourceDescription> = {
tree: { id: 'tree', label: 'Дерево', color: '#b98249', icon: '🌲' },
wood: { id: 'wood', label: 'Бревно', color: '#c9c209', icon: '🪵' },
// iron: { id: 'iron', label: 'Железо', color: '#9aa7b0', icon: '⛓' },
stone: { id: 'stone', label: 'Камень', color: '#8a8a8a', icon: '🪨' },
// gold: { id: 'gold', label: 'Золото', color: '#d9b64e', icon: '💰' },
// knowledge: { id: 'knowledge', label: 'Знание', color: '#7d8bf0', icon: '📖' },
};