Compare commits

Author SHA1 Message Date
azykov@mail.ruandClaude Sonnet 5 9caa47a830 Allow overriding localStorage save key via ?game= query param
Defaults to 'incgame' when the query param is absent, preserving current behavior.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015ohELX137NFgWryS3BAY88
2026-09-04 13:59:14 +03:00
azykov@mail.ru 1553c48807 tick button can be held for ticks 2026-09-04 13:50:02 +03:00
azykov@mail.ru f56e79ee94 engine moved to a separate node.js module 2026-09-04 13:10:47 +03:00
azykov@mail.ru f4c1eedf62 behaviour refactoring. storage beahavior added 2026-09-03 12:31:23 +03:00
azykov@mail.ru 557d22517a display refactoring 2026-09-03 11:52:44 +03:00
azykov@mail.ru 51f9d44378 typo fix 2026-09-03 11:14:47 +03:00
azykov@mail.ru 52ec3ec7de classes refactoring, converter input pull amount fix 2026-09-03 11:12:49 +03:00
azykov@mail.ru 4f0ae5452f project structure refactoring 2026-09-03 10:39:29 +03:00
azykov@mail.ru 4b4ab88918 converter work on demand 2026-09-03 10:24:51 +03:00
azykov@mail.ru b14b60858c converter now has cycleLength. storage save load fix 2026-09-01 09:52:52 +03:00
22 changed files with 679 additions and 891 deletions
+1
View File
@@ -0,0 +1 @@
{"sessionId":"d232f3c1-b7d4-4616-b6d5-259dc502a2e7","pid":83268,"procStart":"134326544516295730","acquiredAt":1788511492089}
+233 -31
View File
@@ -1,43 +1,245 @@
# Граф ресурсов — тиковая симуляция (Vite + React + TypeScript)
# Resource Graph Engine — документация движка
## Запуск
Этот файл описывает **логику симуляции** (пакет `src/engine`, `src/types`, `src/utils`), а не конкретную игру. Он написан как справочник для разработки НА БАЗЕ этого движка (в том числе с помощью Claude) — здесь зафиксированы точные контракты, инварианты и неочевидные архитектурные решения, которые нужно знать, чтобы не сломать существующую логику при добавлении нового контента.
```bash
npm install
npm run dev
Слой представления (`src/components`, `src/ui`, `App.tsx`) — это ОДНА конкретная демо-визуализация (React + SVG + автолэйаут ELK). Движок от неё не зависит: `Game`/`Behaviour`/сериализация не импортируют ничего из React/DOM. Полностью описан отдельным разделом в конце.
## Ключевые понятия
| Термин | Где определён | Смысл |
|---|---|---|
| `Resource` | `src/types/resource.ts` | Строковый union-тип названий ресурсов (`'tree' \| 'wood' \| 'stone'` на момент написания). Добавление нового ресурса — это просто расширение union'а. |
| `Unit` | `src/types/unit.ts` | Узел мира: `{ id, name, behaviour }`. `id` — идентификатор *слота в мире* (для UI/сохранения расположения), `name` — отображаемое имя. |
| `Behaviour` | `src/engine/behaviours/base.ts` | Абстрактный класс — фактическая симулируемая сущность. **У `Behaviour` есть СВОЙ `id`, отдельный от `Unit.id`.** Связи (`inputLinks`) ссылаются на `Behaviour.id`, а не на `Unit.id`. |
| `Game` | `src/engine/game.ts` | Контейнер: `time: Decimal` + `nodes: Unit[]`, метод `tick(deltaTime)` — единственная точка входа симуляции. |
Важный нюанс, который легко перепутать: в `prefabs/game.ts` узел с `Unit.id = 'sawmill'` содержит `Behaviour` с `id: 'sawmill.1'`; связи других узлов указывают `target: 'sawmill.1'` (id поведения), не `'sawmill'`.
Все числа в симуляции — `Decimal` из [`break_eternity.js`](https://github.com/Patashu/break_eternity.js) (для больших чисел инкремental-игр), а не `number`. Публичные API принимают `DecimalSource = Decimal | number | string`. Только шаг тика (`deltaTime` в `Game.tick`/`Behaviour.tick`) — обычный `number`.
## Модель поведения (`Behaviour`)
```ts
abstract class Behaviour {
readonly id: string;
readonly kind: string; // 'converter' | 'storage' | ...
readonly inputLinks: BehaviourLink[]; // BehaviourLink = { target: string, resource: Resource }
abstract get inputs(): Resource[]; // какие ресурсы принимает (для сокетов/UI)
abstract get outputs(): Resource[]; // какие ресурсы отдаёт (для сокетов/UI)
abstract take(resource, amount): Decimal; // публичный: забрать (ограничено наличием)
protected abstract give(resource, amount): void; // защищённый: положить (без ограничений)
abstract getStorage(): Partial<Resources>; // снимок текущих запасов
abstract reset(): void; // обнулить запасы (не связи/id)
abstract tick(
deltaTime: number,
resolve: (id: string) => Behaviour | undefined,
fairShare: (sourceId: string, resource: Resource) => Decimal,
): void;
}
```
Откроется адрес вида `http://localhost:5173`.
**`take()` — единственный публичный способ отобрать ресурс.** Всегда возвращает `min(amount, реально_доступное)`, никогда не уходит в минус. `give()` защищённый — положить ресурс в поведение может только оно само (изнутри `tick()`, после `take()` у источника). Это значит: **толкать (push) ресурс в чужое поведение нельзя** — можно только объявить связь (`inputLinks`) и на своём тике *вытягивать (pull)* у источника.
## Сборка
### Односвязность входа (важное ограничение)
```bash
npm run build # tsc -b && vite build -> dist/
npm run preview # локальный просмотр собранного dist/
`inputLinks` — плоский список `{target, resource}`. Оба текущих поведения ищут связь через `inputLinks.find(l => l.resource === X)` — **берётся первая** подходящая по ресурсу связь. Следствие: **один вход поведения может брать один и тот же ресурс только из ОДНОГО источника.** Если нужно смешивать один и тот же ресурс из нескольких источников в одном поведении — текущий код этого не поддерживает, нужно расширять `find` на что-то вроде списка/суммирования. Fan-*out* (один источник → много потребителей одного ресурса) поддерживается полностью, см. ниже.
### Порядок связи `resource`
`BehaviourLink.resource` используется дважды одним и тем же значением: и как ключ в собственных `inputRates`/`acceptsResources` этого поведения, и как аргумент `source.take(link.resource, ...)`. **Переименования ресурса через связь нет** — если A принимает `wood` от B, у B тоже должно быть `wood` (не `plank`, не что-то ещё).
## Тик игры (`Game.tick(deltaTime)`)
```ts
tick(deltaTime: number) {
time += deltaTime;
// 1. Топологический порядок: источник тикает раньше потребителя.
for (const behaviour of orderByDependency(nodes)) {
behaviour.tick(deltaTime, resolve, fairShare);
snapshots[behaviour.id] = behaviour.getStorage(); // фиксируем "после этого тика"
}
}
```
## Структура
1. **Топологическая сортировка** (`src/utils/behaviourSort.ts`, DFS по `inputLinks`) гарантирует, что производитель тикает раньше своего потребителя — благодаря этому ресурс, произведённый в этом тике, может быть **потреблён по всей цепочке в тот же самый тик**, а не с задержкой в один тик.
- **Циклические связи**: если граф содержит цикл (A тянет у B, B тянет у A), DFS обрывает цикл в первом же уже-посещённом узле и просто использует порядок обхода как есть — без ошибки, но без гарантии полной синхронности: одно из рёбер цикла всегда будет видеть состояние источника с *предыдущего* тика, а не текущего. На практике для DAG (обычный ресурсный граф без циклов) это не проявляется.
- `src/engine.ts` — ядро симуляции: типы (`SimNode`, `SimEdge`, `Behavior`,
`Topology`, `Buffers`), функция `tick()` (один детерминированный тик) и
`resetBuffers()`. Модуль не зависит от React/DOM — логика переносима на
другой стек (Rust/C#/GDScript) по этой же спецификации.
- `src/storage.ts` — чтение/запись localStorage (`incsim.topology.v1`,
`incsim.buffers.v1`, `incsim.tickcount.v1`).
- `src/App.tsx` — состояние приложения (topology/buffers/tickCount/selected),
все обработчики мутаций, эффекты персистентности.
- `src/components/` — `Topbar`, `WorldCanvas` (холст с узлами и SVG-связями),
`NodeCard` (перетаскиваемая карточка узла), `EdgeLines` (SVG-стрелки),
`Sidebar`, `NodeEditor`, `EdgeEditor`, `RecipeEditor`.
2. **`resolve(id)`** — поиск `Behaviour` по его `id` (не `Unit.id`!) среди всех узлов игры.
## Модель
3. **Честное разделение (`fairShare`)** решает проблему конкуренции: если несколько поведений связаны с одним и тем же (`source`, `resource`), при заборе ресурса "кто первый в порядке тика — тот и съел всё" было бы недетерминированным-по-смыслу (хотя технически воспроизводимым) багом. Вместо этого:
- Перед началом тика подсчитывается **`claimantCounts`** — сколько *разных* поведений ссылаются на каждую пару (`target`, `resource`). Это статическая информация (связи не меняются после создания), пересчитывается заново каждый тик, но не может измениться в рамках одной игры без ручного редактирования `inputLinks`.
- После того как поведение отработало свой `tick()`, его текущий запас (`getStorage()`) сохраняется в `snapshots` — этот снимок **фиксирован до конца тика**, даже когда несколько потребителей после этого будут его "есть".
- `fairShare(sourceId, resource)` возвращает:
- `Decimal.dInf` (без ограничения), если претендент один или ни одного;
- `snapshot[resource] / claimantCount`, если претендентов несколько.
- Каждый потребитель обязан ограничивать свой запрос к источнику через `min(желаемое, fairShare(...))`, ПЕРЕД вызовом `source.take(...)`.
- **Это буквальное равное деление, не max-min fairness.** Если один потребитель хочет меньше своей доли — остаток НЕ перераспределяется другим в этот же тик, а просто остаётся у источника до следующего. Пример (один источник даёт 10, два потребителя хотят 10 и 3): первый получит ровно 5 (свою долю), второй — все свои 3; 2 единицы останутся у источника.
- **Реализация нового `Behaviour` обязана сама вызывать `fairShare` и ограничивать запрос** — это не гарантируется автоматически на уровне `take()`.
- **Storage** — пассивный буфер с ёмкостью.
- **Converter** — единственный активный узел: раз в `period` тиков атомарно
списывает `inputs` и начисляет `outputs` в собственном буфере.
`source`/`consumer` — его частные случаи с пустым списком входов/выходов.
- **Edge** — перенос ресурса между буферами узлов; конкуренция при
fan-in/fan-out разрешается по `priority` (выше — раньше), порядок
обработки узлов/рёбер фиксирован — тик полностью детерминирован.
## `Converter` (`src/engine/behaviours/converter.ts`)
Reset обнуляет буферы и таймеры конвертеров, настройки узлов/связей не трогает.
Узел с рецептом: раз в `cycleLength` секунд (по игровому времени, не по количеству тиков) атомарно списывает `inputRates` и начисляет `outputRates` в собственный буфер (`storage`).
Поля: `cycleTime: Decimal` (прогресс внутри текущего цикла, мутируется), `cycleLength: Decimal`, `inputRates: Partial<Resources>`, `outputRates: Partial<Resources>` (оба — ставки *за один цикл*, не в секунду).
### Алгоритм `tick(deltaTime, resolve, fairShare)`
```
idealCycleTime = cycleTime + deltaTime
reserveCycles = ceil(idealCycleTime / cycleLength) // сколько циклов "хочется" покрыть запасом наперёд
newCycleTime = idealCycleTime
для каждого (resource, rate) из inputRates (rate != 0):
target = rate * reserveCycles // сколько нужно НАКОПИТЬ, чтобы не тормозить
shortfall = max(0, target - storage[resource])
если shortfall > 0 И есть связь на resource:
source = resolve(link.target)
request = min(shortfall, fairShare(link.target, link.resource))
give(resource, source.take(link.resource, request)) // забираем ОДНИМ куском, не по чуть-чуть
// прогресс не может опережать САМЫЙ дефицитный ингредиент:
newCycleTime = min(newCycleTime, storage[resource] * cycleLength / rate)
cycleTime = newCycleTime
affordableCycles = floor(cycleTime / cycleLength)
если affordableCycles > 0:
списать affordableCycles * inputRates[*] из storage
начислить affordableCycles * outputRates[*] в storage
cycleTime -= affordableCycles * cycleLength
```
Три свойства, которые важно понимать при отладке/расширении:
1. **"Забрать всё сразу, а не по чуть-чуть".** `reserveCycles` округляется ВВЕРХ (`ceil`), а не пропорционально прошедшей доле цикла. Это специально: как только у источника появляется достаточно ресурса, конвертер выгребает его одним рывком (весь нужный на текущий+грядущий циклы объём), а не тянет дробно по мере хода времени. Визуально в UI это выглядит так, будто буфер конвертера "телепортируется" с 0 сразу на полную ставку в момент, когда источник произвёл ресурс.
2. **`cycleTime` не может "врать".** Прогресс `newCycleTime` ограничивается снизу для КАЖДОГО входного ресурса формулой `have * cycleLength / rate` — то есть таймер физически не может показывать больше прогресса, чем оправдано самым дефицитным ингредиентом. Если ресурсов не хватает, `cycleTime` просто перестаёт расти (стоит на месте) до следующего тика, когда источник, возможно, произведёт ещё. **Никакого "долга" не копится**: если конвертер голодал 50 тиков подряд, при появлении ресурса он не обработает мгновенно 50 циклов — `cycleTime` всё это время не рос, а как только ресурс появился, продвинется ровно настолько, насколько хватит того, что реально забрано.
3. **Один вызов `tick()` может закрыть НЕСКОЛЬКО циклов сразу**, если `deltaTime` большой (например, при офлайн-прогрессе одним большим тиком) и ресурсов хватает — `affordableCycles` не ограничен единицей. Это специально сделано так, чтобы `game.tick(1000)` (один большой шаг) и 10 000×`game.tick(0.1)` (много маленьких) давали **математически тот же результат** (с точностью до погрешности накопления `number` при многократном сложении `deltaTime`, см. раздел "Подводные камни"). Из этого следует практическая рекомендация: **офлайн-прогресс лучше считать одним большим `tick()`**, а не циклом из множества маленьких — так быстрее (не зависит от числа "прошедших" циклов) и точнее.
Пустые `inputRates`/`outputRates` — нормальный случай: чистый источник (пустые входы) или чистый потребитель/поглотитель (пустые выходы).
## `Storage` (`src/engine/behaviours/storage.ts`)
Пассивный буфер **без собственной скорости**: и приём, и выдача ресурса ограничены только противоположной стороной.
Поля: `capacity: Decimal | undefined` (лимит, **на каждый ресурс отдельно**, не общий на всё хранилище), `acceptsResources: Resource[]` (какие ресурсы вообще может держать), `items: Partial<Resources>`.
### Алгоритм `tick(deltaTime, resolve, fairShare)`
`deltaTime` не используется — скорость не зависит от времени.
```
для каждого resource из acceptsResources:
если нет связи на этот resource — пропустить
source = resolve(link.target)
room = capacity ? max(0, capacity - items[resource]) : Infinity
request = min(room, fairShare(link.target, link.resource))
give(resource, source.take(link.resource, request))
```
То есть на каждом тике `Storage` пытается забрать у источника **столько, сколько есть места** (или сколько источник готов дать — что меньше), одним куском, без ограничения по скорости. С другой стороны, любой узел, который свяжется со `Storage` как со своим источником, вызовет `storage.take()`, которое отдаст **сколько попросят, ограничено только фактическим наличием** — тоже без собственного лимита скорости `Storage`.
`capacity` не задан (`undefined`) → ёмкость бесконечна для всех принимаемых ресурсов.
## Данные и сериализация (`src/types/serialization.ts`, `src/engine/saveLoad.ts`)
```ts
type SerializedGame = {
time: DecimalSource;
nodes: SerializedNode[]; // { id, name, behaviour }
}
type SerializedBehaviour = {
id: string;
inputLinks: { pins: { target: string, resource: Resource }[] };
} & (SerializedConverter | SerializedStorage);
type SerializedConverter = {
kind: 'converter';
cycleTime?: DecimalSource; // по умолчанию 0
storage?: Partial<Record<Resource, DecimalSource>>; // по умолчанию {}
rules: {
cycleLength: DecimalSource;
inputRates?: Partial<Record<Resource, DecimalSource>>;
outputRates?: Partial<Record<Resource, DecimalSource>>;
}
}
type SerializedStorage = {
kind: 'storage';
capacity?: DecimalSource; // по умолчанию бесконечность
acceptsResources: Resource[];
items: Partial<Record<Resource, DecimalSource>>;
}
```
Пример из `src/prefabs/game.ts` (полный рабочий граф — лес → лесопилка → два склада, второй склад забирает камень с той же связи, что и первый, демонстрируя `fairShare`):
```ts
{
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' }, // делит 'stone' с shop2 через fairShare
] },
acceptsResources: ['wood', 'stone'],
items: {},
},
},
```
API верхнего уровня: `serializeBehaviour`/`deserializeBehaviour` (диспетчер по `kind`), `serialize`/`deserialize` (весь `Game`), `serializeToString`/`deserializeFromString` (JSON), `save`/`load` (localStorage, ключ `` `${saveParams.path}_incgane` `` — `saveParams.path` можно менять, чтобы держать несколько независимых сохранений/слотов).
`Game.reset()` обнуляет `time` и вызывает `reset()` у каждого поведения (обнуляет только запасы — `cycleTime`, связи, ставки и id не трогает). `Game.clone()` — неглубокая копия с новым `Object.create`, нужна исключительно чтобы React увидел изменение ссылки после мутирующего `tick()`/`reset()`.
## Как расширять движок
### Добавить новый ресурс
1. Добавить строку в union `Resource` (`src/types/resource.ts`).
2. Добавить запись в `ResourceDescriptions` (`src/ui/resource.ts`) — `label`/`color`/`icon` для UI. Это **не часть движка**, но без неё UI упадёт при попытке отрисовать сокет/буфер с новым ресурсом (обращение по ключу без проверки).
### Добавить новый тип `Behaviour`
1. Отнаследоваться от `Behaviour` (`src/engine/behaviours/base.ts`), реализовать все абстрактные члены: `inputs`, `outputs`, `take`, `give`, `getStorage`, `reset`, `tick`.
2. В `tick()` — если поведение вообще что-то тянет через `inputLinks`, обязательно ограничивать запрос через переданный `fairShare(sourceId, resource)` (см. `Converter`/`Storage` как образец), иначе честное деление между несколькими потребителями не будет работать для этого нового типа.
3. Добавить новый `kind`-литерал в тип `SerializedBehaviour` (объединение в `src/types/serialization.ts`) и обработать его в обоих `switch` в `src/engine/saveLoad.ts` (`serializeBehaviour` и `deserializeBehaviour`) — если забыть один из двух, поведение либо не сохранится, либо не восстановится при загрузке, без ошибки компиляции (проверьте оба места вручную).
4. Если нужна собственная визуализация внутри карточки (как `ConverterCardInfo` для прогресс-бара конвертера) — расширить `BehaviourCard.tsx` условием по `behaviour.kind`, аналогично существующему `behaviour.kind === 'converter' && <ConverterCardInfo .../>`.
## Подводные камни
- **`Decimal` не бесконечно точен для обычных чисел.** Для величин масштаба `layer === 0` (не гипер-больших чисел) `break_eternity.js` внутри использует обычный JS `double` — привычные артефакты вроде `0.1 + 0.1 + 0.1 !== 0.3` воспроизводятся и здесь. Смена `number` → `Decimal`/строка это не лечит. Для отображения использовать `.toStringWithDecimalPlaces(n)`, а не сырой `.toString()`.
- **Много маленьких тиков ≠ побитово один большой тик**, только математически эквивалентны — расхождение исключительно из-за многократного накопления `deltaTime` (см. выше), не из-за самого алгоритма `Converter`/`Storage`. Для офлайн-прогресса предпочитать один большой `tick(суммарное_время)`.
- **`fairShare` не защищает от общего перерасхода**, если реализация нового `Behaviour` игнорирует его и вызывает `take()` напрямую без ограничения — на это нет проверки времени компиляции.
- **Порядок узлов в `nodes` влияет на результат только в графах с циклами** (см. раздел про топосортировку); для обычного ациклического графа результат от порядка не зависит.
- Тип `Resources = Record<Resource, Decimal>` (не `Partial`), но фактически везде в рантайме используется как `Partial<Resources>` — обращение по ключу может вернуть `undefined`, поэтому по всему движку принят паттерн `storage[resource] ?? Decimal.dZero`.
## Слой представления (не часть движка, но идёт в комплекте)
- `src/ui/graph.ts` — раскладка графа на плоскости через `elkjs` (слоистый layout, направление `LEFT`), асинхронно (`build2dNodes`).
- `src/ui/resource.ts` — `ResourceDescriptions`: цвет/иконка/подпись на ресурс, для сокетов и буферов.
- `src/components/GameCanvas.tsx` — измеряет реальные центры карточек/сокетов через DOM (`getBoundingClientRect`) после раскладки, чтобы линии связей (`LinkLine.tsx`) рисовались точно между сокетами, а не между условными координатами узла.
- `src/components/BehaviourCard.tsx` — карточка узла: сокеты, буферы (`getDisplayInfo().storages`), для конвертера — прогресс-бар (`ConverterCardInfo.tsx`, использует `cycleTime.div(cycleLength)`), плюс отладочный YAML-дамп `info.raw`.
- `src/App.tsx` — хранит единственный `Game` в `useState`, персистит в localStorage при каждом изменении, `handleTick` вызывает `game.tick(1/10)` + `setGame(game.clone())` (тик размером `0.1` игровой секунды на клик).
Ничего в `src/engine`/`src/types`/`src/utils` не импортирует из `src/components`/`src/ui`/React — движок можно использовать (или перенести под другой рендер) без этого слоя.
+35 -3
View File
@@ -1,17 +1,19 @@
{
"name": "resource-graph-sim",
"name": "@incgame/resource-graph-sim",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "resource-graph-sim",
"name": "@incgame/resource-graph-sim",
"version": "0.1.0",
"dependencies": {
"@incgame/engine": "file:../engine",
"break_eternity.js": "^2.1.3",
"elkjs": "^0.12.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
"react-dom": "^18.3.1",
"yaml": "^2.9.0"
},
"devDependencies": {
"@types/react": "^18.3.12",
@@ -21,6 +23,17 @@
"vite": "^5.4.10"
}
},
"../engine": {
"name": "@incgame/engine",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"break_eternity.js": "^2.1.3"
},
"devDependencies": {
"typescript": "^5.6.3"
}
},
"node_modules/@babel/code-frame": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
@@ -694,6 +707,10 @@
"node": ">=12"
}
},
"node_modules/@incgame/engine": {
"resolved": "../engine",
"link": true
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -1759,6 +1776,21 @@
"integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
"dev": true,
"license": "ISC"
},
"node_modules/yaml": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
"integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
},
"engines": {
"node": ">= 14.6"
},
"funding": {
"url": "https://github.com/sponsors/eemeli"
}
}
}
}
+4 -2
View File
@@ -1,5 +1,5 @@
{
"name": "resource-graph-sim",
"name": "@incgame/resource-graph-sim",
"private": true,
"version": "0.1.0",
"type": "module",
@@ -12,7 +12,9 @@
"break_eternity.js": "^2.1.3",
"elkjs": "^0.12.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
"react-dom": "^18.3.1",
"yaml": "^2.9.0",
"@incgame/engine": "file:../engine"
},
"devDependencies": {
"@types/react": "^18.3.12",
+3 -3
View File
@@ -1,9 +1,9 @@
import { useEffect, useState } from 'react';
import Topbar from './components/Topbar';
import { GameCanvas } from './components/GameCanvas';
import { Game } from './types';
import { deserialize, load, save } from './engine/saveLoad';
import { load, save } from './saveLoad';
import { defaultGame } from './prefabs/game';
import { Game, deserializeGame } from '@incgame/engine';
export type Selection = { kind: 'node'; id: string } | null;
@@ -37,7 +37,7 @@ export default function App() {
if (!ok)
return;
setGame(deserialize(defaultGame()));
setGame(deserializeGame(defaultGame()));
}
// function handleAddNode(kind: NodeKind) {
@@ -1,65 +1,67 @@
import { forwardRef } from 'react';
import { Game, Resource } from '../types';
import { Node2D } from '../ui/graph';
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;
node2d: Node2D;
position: GraphNode['position'];
behaviour: Behaviour,
selected: boolean;
onSelect: () => void;
onSocketRef?: (type: 'input' | 'output', index: number, el: HTMLDivElement | null) => void;
}
const NodeCard = forwardRef<HTMLDivElement, Props>(function NodeCard({ node2d, selected, onSelect, onSocketRef }, ref) {
const node = node2d.node;
export const BehaviourCard = forwardRef<HTMLDivElement, Props>(function NodeCard({ position, behaviour, selected, onSelect, onSocketRef }, ref) {
function handleClick() {
onSelect();
}
const info = node.behaviour.getDisplayInfo();
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--${node.behaviour.kind}${selected ? ' is-selected' : ''}`}
style={{ left: node2d.position.x, top: node2d.position.y }}
className={`node node--${behaviour.kind}${selected ? ' is-selected' : ''}`}
style={{ left: position.x, top: position.y }}
onClick={handleClick}
>
<div className="node__sockets node__sockets--input">
<div className="unit__sockets unit__sockets--input">
{
inputSockets.map((socket) => (
<div
key={`input.${socket.index}`}
ref={(el) => onSocketRef?.('input', socket.index, el)}
className="node__socket"
className="unit__socket"
style={{ background: ResourceDescriptions[socket.resource].color }}
title={`${ResourceDescriptions[socket.resource].label} (вход)`}
/>
))
}
</div>
<div className="node__sockets node__sockets--output">
<div className="unit__sockets unit__sockets--output">
{
outputSockets.map((socket) => (
<div
key={`output.${socket.index}`}
ref={(el) => onSocketRef?.('output', socket.index, el)}
className="node__socket"
className="unit__socket"
style={{ background: ResourceDescriptions[socket.resource].color }}
title={`${ResourceDescriptions[socket.resource].label} (выход)`}
/>
))
}
</div>
<div className="node__id">#{node.id}</div>
<div className="node__title">{node.name}</div>
<div className="node__kind">{node.behaviour.kind}</div>
<div className="unit__id">#{behaviour.id}</div>
<div className="unit__kind">{behaviour.kind}</div>
{
Object.entries(info.storages).map(([name, storage]) => (
<div className="node__resources" key={name}>
<div className="unit__resources" key={name}>
<div>{name}</div>
{
Object.entries(storage)
@@ -68,14 +70,13 @@ const NodeCard = forwardRef<HTMLDivElement, Props>(function NodeCard({ node2d, s
</div>
))
}
<div className="node__links">
{
info.links.map((link) => <div key={`${link.target}/${link.resource}`}>→{link.target}/{link.resource}</div>)
}
</div>
<div className="node__debug" style={{fontSize: '50%', whiteSpace: 'pre'}}>{JSON.stringify(info, undefined, 4)}</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>
);
});
export default NodeCard;
+14
View File
@@ -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>
</>
}
+32 -31
View File
@@ -1,9 +1,9 @@
import type { Selection } from '../App';
import NodeCard from './NodeCard';
import { Game } from '../types';
import { build2dNodes, Node2D } from '../ui/graph';
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;
@@ -35,7 +35,7 @@ export const GameCanvas = function ({
return () => observer.disconnect();
}, []);
const [nodes2d, setNodes2d] = useState<Node2D[]>([]);
const [graphNodes, setNodes2d] = useState<GraphNode[]>([]);
useEffect(() => {
let cancelled = false;
@@ -61,70 +61,71 @@ export const GameCanvas = function ({
const nextCenters: Record<string, { x: number, y: number }> = {};
const nextSocketCenters: Record<string, { x: number, y: number }> = {};
for (const node2d of nodes2d) {
const el = nodeElsRef.current.get(node2d.id);
if (el) nextCenters[node2d.id] = centerOf(el);
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 node2d.node.behaviour.getDisplayInfo().sockets) {
const socketKey = `${node2d.id}.${socket.type}.${socket.index}`;
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);
}, [nodes2d]);
}, [graphNodes]);
function withCenter(node2d: Node2D): Node2D {
const center = centers[node2d.id];
return center ? { ...node2d, position: center } : node2d;
function withCenter(graphNode: GraphNode): GraphNode {
const center = centers[graphNode.entity.id];
return center ? { ...graphNode, position: center } : graphNode;
}
function withSocket(node2d: Node2D, type: 'input' | 'output', resource: string): Node2D {
const socket = node2d.node.behaviour.getDisplayInfo().sockets
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[`${node2d.id}.${type}.${socket.index}`];
return center ? { ...node2d, position: center } : withCenter(node2d);
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}>
{
nodes2d.map((node2d) =>
node2d.node.behaviour.getDisplayInfo().links.map((link, idx) => {
const target = nodes2d.find((n2d) => n2d.id === link.target);
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={`${node2d.id}.${idx}`}
from={{ node: withSocket(node2d, 'input', link.resource), resource: link.resource }}
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 }}
/>
);
}))
}
{
nodes2d.map((node2d) => (
<NodeCard
graphNodes.map((graphNode) => (
<BehaviourCard
ref={(el) => {
if (el)
nodeElsRef.current.set(node2d.id, el);
nodeElsRef.current.set(graphNode.entity.id, el);
else
nodeElsRef.current.delete(node2d.id);
nodeElsRef.current.delete(graphNode.entity.id);
}}
onSocketRef={(type, index, el) => {
const socketKey = `${node2d.id}.${type}.${index}`;
const socketKey = `${graphNode.entity.id}.${type}.${index}`;
if (el)
socketElsRef.current.set(socketKey, el);
else
socketElsRef.current.delete(socketKey);
}}
game={game}
key={node2d.id}
node2d={node2d}
selected={selected?.kind === 'node' && selected.id === node2d.id}
onSelect={() => onSelectNode(node2d.id)}
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>
+7 -7
View File
@@ -1,17 +1,17 @@
import { Game, Resource } from "../types";
import { Node2D } from "../ui/graph";
import { Game, Resource } from "@incgame/engine";
import { GraphNode } from "../ui/graph";
type Props = {
game: Game,
from: { node: Node2D, resource: Resource },
to: { node: Node2D, resource: Resource },
from: { node: GraphNode, resource: Resource },
to: { node: GraphNode, resource: Resource },
}
export const LinkLine = function ({ from, to }: Props) {
const markerId = `node-line-arrow-${from.node.id}-${to.node.id}`.replace(/[^a-zA-Z0-9_-]/g, '_');
const markerId = `node-line-arrow-${from.node.entity.id}-${to.node.entity.id}`.replace(/[^a-zA-Z0-9_-]/g, '_');
const fromSocket = from.node.node.behaviour.getDisplayInfo().sockets.find((s) => s.type === 'input' && s.resource == from.resource);
const toSocket = to.node.node.behaviour.getDisplayInfo().sockets.find((s) => s.type === 'output' && s.resource == to.resource);
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;
-111
View File
@@ -1,111 +0,0 @@
import type { ChangeEvent } from 'react';
import type { Topology, SimNode, SimEdge, NodeKind, Behavior } from '../engine';
import type { Selection } from '../App';
import NodeEditor from './NodeEditor';
import EdgeEditor from './EdgeEditor';
import { Game, SerializedNodeBehaviour } from '../types';
const BEHAVIOR_DEFAULTS: SerializedNodeBehaviour[] = [
{
kind: 'converter',
inputs: [],
outputs: [],
},
];
interface Props {
game: Game;
selected: Selection;
onSelectNode: (id: string) => void;
onSelectEdge: (id: string) => void;
onAddNode: (kind: NodeKind) => void;
onAddEdge: () => void;
onRemoveNode: (id: string) => void;
onRemoveEdge: (id: string) => void;
onUpdateNode: (id: string, patch: Partial<SimNode>) => void;
onUpdateNodeBehavior: (id: string, behavior: Behavior) => void;
onUpdateEdge: (id: string, patch: Partial<SimEdge>) => void;
}
export default function Sidebar(props: Props) {
const { game: topology, selected } = props;
const selectedNode = selected?.kind === 'node' ? topology.nodes.find((n) => n.id === selected.id) : undefined;
const selectedEdge = selected?.kind === 'edge' ? topology.edges.find((e) => e.id === selected.id) : undefined;
function handleAddNodeChange(e: ChangeEvent<HTMLSelectElement>) {
const kind = e.target.value as NodeKind | '';
if (kind) props.onAddNode(kind);
e.target.value = '';
}
return (
<div className="sidebar">
<div className="sidebar__section">
<h4>Узлы</h4>
<ul className="sidebar__list">
{topology.nodes.map((n) => (
<li
key={n.id}
className={selected?.kind === 'node' && selected.id === n.id ? 'is-active' : ''}
onClick={() => props.onSelectNode(n.id)}
>
{n.label} ({n.id})
</li>
))}
</ul>
<select value="" onChange={handleAddNodeChange}>
<option value="">+ добавить узел…</option>
<option value="source">Источник</option>
<option value="storage">Склад</option>
<option value="converter">Конвертер</option>
<option value="consumer">Потребитель</option>
</select>
</div>
<div className="sidebar__section">
<h4>Связи</h4>
<ul className="sidebar__list">
{topology.edges.map((e) => (
<li
key={e.id}
className={selected?.kind === 'edge' && selected.id === e.id ? 'is-active' : ''}
onClick={() => props.onSelectEdge(e.id)}
>
{e.from} → {e.to} [{e.resource}]
</li>
))}
</ul>
<button className="btn btn--ghost" style={{ marginTop: 8 }} onClick={props.onAddEdge}>
+ добавить связь
</button>
</div>
<div className="sidebar__section sidebar__section--grow">
<h4>Редактор</h4>
<div id="sidebar-content">
{!selected && (
<p className="hint">
Выберите узел или связь в списке слева либо кликните по объекту на схеме.
</p>
)}
{selectedNode && (
<NodeEditor
node={selectedNode}
onUpdate={(patch) => props.onUpdateNode(selectedNode.id, patch)}
onUpdateBehavior={(b) => props.onUpdateNodeBehavior(selectedNode.id, b)}
onRemove={() => props.onRemoveNode(selectedNode.id)}
/>
)}
{selectedEdge && (
<EdgeEditor
edge={selectedEdge}
nodes={topology.nodes}
onUpdate={(patch) => props.onUpdateEdge(selectedEdge.id, patch)}
onRemove={() => props.onRemoveEdge(selectedEdge.id)}
/>
)}
</div>
</div>
</div>
);
}
+48 -1
View File
@@ -1,4 +1,6 @@
import type Decimal from 'break_eternity.js';
import { useEffect, useRef } from 'react';
import type { PointerEvent } from 'react';
interface Props {
time: Decimal;
@@ -7,7 +9,47 @@ interface Props {
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">
@@ -24,7 +66,12 @@ export default function Topbar({ time, onTick, onReset, onInitialize }: Props) {
<button className="btn" onClick={onReset}>
Reset
</button>
<button className="btn btn--primary" onClick={onTick}>
<button
className="btn btn--primary"
onPointerDown={startHolding}
onPointerUp={stopHolding}
onPointerCancel={stopHolding}
>
Tick ▶
</button>
</div>
-242
View File
@@ -1,242 +0,0 @@
// for Claude: ignore this file
/**
* engine.ts — ядро симуляции.
*
* - Storage — пассивный буфер с ёмкостью, сам ничего не делает.
* - Converter — единственный активный узел: раз в `period` тиков атомарно
* списывает `inputs` и начисляет `outputs` в СВОИХ ЖЕ буферах.
* source / consumer — частные случаи converter с пустым списком
* входов или выходов соответственно.
* - Edge (транспорт) — переносит ресурс между буферами двух узлов.
* Порядок обработки рёбер фиксирован (priority desc, id asc) —
* разрешает конкуренцию при fan-in/fan-out детерминированно.
*
* Модуль не содержит DOM/React-зависимостей — чистые данные и функции,
* поэтому логику легко перенести на другой язык/платформу по этой же
* спецификации (см. обсуждение — Rust/C#/GDScript как нативные цели).
*/
export type ResourceType = 'wood' | 'iron' | 'stone' | 'gold' | 'knowledge';
export interface ResourceMeta {
id: ResourceType;
label: string;
color: string;
icon: string;
}
export const RESOURCES: ResourceMeta[] = [
{ id: 'wood', label: 'Дерево', color: '#b98249', icon: '🌲' },
{ id: 'iron', label: 'Железо', color: '#9aa7b0', icon: '⛓' },
{ id: 'stone', label: 'Камень', color: '#8a8a8a', icon: '🪨' },
{ id: 'gold', label: 'Золото', color: '#d9b64e', icon: '💰' },
{ id: 'knowledge', label: 'Знание', color: '#7d8bf0', icon: '📖' },
];
export type NodeKind = 'source' | 'storage' | 'converter' | 'consumer';
export interface RecipeLine {
resource: ResourceType;
amount: number;
}
export type Behavior =
| { kind: 'storage' }
| { kind: 'source'; resource: ResourceType; rate: number }
| { kind: 'consumer'; resource: ResourceType; rate: number }
| {
kind: 'converter';
period: number;
timer: number;
inputs: RecipeLine[];
outputs: RecipeLine[];
};
export interface SimNode {
label: string;
x: number;
y: number;
actor: Actor;
}
export type Actor = {
id: string;
behavior: Behavior;
}
export interface SimEdge {
id: string;
from: string;
to: string;
resource: ResourceType;
rate: number;
priority: number;
}
export interface Topology {
nextId: number;
nodes: SimNode[];
edges: SimEdge[];
}
/** buffers[nodeId][resource] = amount */
export type Buffers = Record<string, Partial<Record<ResourceType, number>>>;
export const NODE_W = 150;
export const NODE_H = 74;
export function kindLabel(kind: NodeKind): string {
return { source: 'Источник', storage: 'Склад', converter: 'Конвертер', consumer: 'Потребитель' }[kind];
}
/** Глубокая копия чисто-JSON-данных (topology/buffers сериализуемы, structuredClone не требуется). */
export function cloneJSON<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
function getBuf(buffers: Buffers, nodeId: string, r: ResourceType): number {
return buffers[nodeId]?.[r] ?? 0;
}
function setBuf(buffers: Buffers, nodeId: string, r: ResourceType, v: number): void {
if (!buffers[nodeId]) buffers[nodeId] = {};
buffers[nodeId][r] = v;
}
function capOf(node: SimNode): number {
return node.capacity === null || node.capacity === undefined ? Infinity : node.capacity;
}
/**
* Выполняет ровно один детерминированный тик (мутирует topology.*.timer и buffers).
* Порядок фаз фиксирован и не зависит от порядка вставки узлов/рёбер в массивах.
*/
export function tick(topology: Topology, buffers: Buffers): void {
const nodesById = new Map(topology.nodes.map((n) => [n.id, n]));
const sortedNodes = [...topology.nodes].sort((a, b) => a.id.localeCompare(b.id));
// Фаза 1: источники — генерация "из ничего" в собственный буфер.
for (const node of sortedNodes) {
if (node.behavior.kind === 'source') {
const { resource, rate } = node.behavior;
const cur = getBuf(buffers, node.id, resource);
setBuf(buffers, node.id, resource, Math.min(capOf(node), cur + rate));
}
}
// Фаза 2: конвертеры. Blocking: при нехватке сырья таймер не сбрасывается,
// попытка повторяется каждый следующий тик.
for (const node of sortedNodes) {
if (node.behavior.kind === 'converter') {
const b = node.behavior;
b.timer += 1;
if (b.timer >= b.period) {
const canRun = b.inputs.every((line) => getBuf(buffers, node.id, line.resource) >= line.amount);
if (canRun) {
for (const line of b.inputs) {
setBuf(buffers, node.id, line.resource, getBuf(buffers, node.id, line.resource) - line.amount);
}
for (const line of b.outputs) {
const next = getBuf(buffers, node.id, line.resource) + line.amount;
setBuf(buffers, node.id, line.resource, Math.min(capOf(node), next));
}
b.timer = 0;
}
}
}
}
// Фаза 3: транспорт по рёбрам, порядок (priority desc, id asc).
const sortedEdges = [...topology.edges].sort(
(a, b) => b.priority - a.priority || a.id.localeCompare(b.id)
);
for (const edge of sortedEdges) {
const fromNode = nodesById.get(edge.from);
const toNode = nodesById.get(edge.to);
if (!fromNode || !toNode) continue;
const available = getBuf(buffers, edge.from, edge.resource);
const freeSpace = capOf(toNode) - getBuf(buffers, edge.to, edge.resource);
const amount = Math.max(0, Math.min(edge.rate, available, freeSpace));
if (amount > 0) {
setBuf(buffers, edge.from, edge.resource, available - amount);
setBuf(buffers, edge.to, edge.resource, getBuf(buffers, edge.to, edge.resource) + amount);
}
}
// Фаза 4: потребители — безвозвратное поглощение.
for (const node of sortedNodes) {
if (node.behavior.kind === 'consumer') {
const { resource, rate } = node.behavior;
const cur = getBuf(buffers, node.id, resource);
const amount = Math.min(cur, rate);
setBuf(buffers, node.id, resource, cur - amount);
}
}
}
/** Обнуляет все буферы и таймеры конвертеров. Настройки узлов/связей не трогает. */
export function resetBuffers(topology: Topology): Buffers {
const buffers: Buffers = {};
for (const node of topology.nodes) {
buffers[node.id] = {};
if (node.behavior.kind === 'converter') node.behavior.timer = 0;
}
return buffers;
}
export function defaultTopology(): Topology {
return {
nextId: 100,
nodes: [
{ id: 'src-wood', label: 'Лесопилка', x: 40, y: 40, capacity: null,
behavior: { kind: 'source', resource: 'wood', rate: 5 } },
{ id: 'src-stone', label: 'Каменоломня', x: 40, y: 180, capacity: null,
behavior: { kind: 'source', resource: 'stone', rate: 3 } },
{ id: 'src-iron', label: 'Рудник', x: 40, y: 320, capacity: null,
behavior: { kind: 'source', resource: 'iron', rate: 2 } },
{ id: 'store-wood', label: 'Склад дерева', x: 300, y: 40, capacity: 100,
behavior: { kind: 'storage' } },
{ id: 'store-stone', label: 'Склад камня', x: 300, y: 180, capacity: 100,
behavior: { kind: 'storage' } },
{ id: 'store-iron', label: 'Склад железа', x: 300, y: 320, capacity: 100,
behavior: { kind: 'storage' } },
{ id: 'conv-craft', label: 'Мастерская', x: 560, y: 110, capacity: 50,
behavior: { kind: 'converter', period: 2, timer: 0,
inputs: [{ resource: 'wood', amount: 3 }, { resource: 'stone', amount: 2 }],
outputs: [{ resource: 'gold', amount: 1 }] } },
{ id: 'conv-forge', label: 'Кузница', x: 560, y: 320, capacity: 50,
behavior: { kind: 'converter', period: 2, timer: 0,
inputs: [{ resource: 'iron', amount: 2 }, { resource: 'wood', amount: 1 }],
outputs: [{ resource: 'gold', amount: 2 }] } },
{ id: 'vault', label: 'Хранилище золота', x: 820, y: 210, capacity: 200,
behavior: { kind: 'storage' } },
{ id: 'conv-research', label: 'Лаборатория', x: 1060, y: 210, capacity: 30,
behavior: { kind: 'converter', period: 3, timer: 0,
inputs: [{ resource: 'gold', amount: 5 }],
outputs: [{ resource: 'knowledge', amount: 1 }] } },
{ id: 'store-knowledge', label: 'Архив знаний', x: 1300, y: 210, capacity: null,
behavior: { kind: 'storage' } },
],
edges: [
{ id: 'e1', from: 'src-wood', to: 'store-wood', resource: 'wood', rate: 5, priority: 0 },
{ id: 'e2', from: 'src-stone', to: 'store-stone', resource: 'stone', rate: 3, priority: 0 },
{ id: 'e3', from: 'src-iron', to: 'store-iron', resource: 'iron', rate: 2, priority: 0 },
{ id: 'e4', from: 'store-wood', to: 'conv-craft', resource: 'wood', rate: 3, priority: 1 },
{ id: 'e5', from: 'store-stone', to: 'conv-craft', resource: 'stone', rate: 2, priority: 1 },
{ id: 'e6', from: 'store-wood', to: 'conv-forge', resource: 'wood', rate: 1, priority: 0 },
{ id: 'e7', from: 'store-iron', to: 'conv-forge', resource: 'iron', rate: 2, priority: 1 },
{ id: 'e8', from: 'conv-craft', to: 'vault', resource: 'gold', rate: 5, priority: 0 },
{ id: 'e9', from: 'conv-forge', to: 'vault', resource: 'gold', rate: 5, priority: 0 },
{ id: 'e10', from: 'vault', to: 'conv-research', resource: 'gold', rate: 5, priority: 0 },
{ id: 'e11', from: 'conv-research', to: 'store-knowledge', resource: 'knowledge', rate: 5, priority: 0 },
],
};
}
-150
View File
@@ -1,150 +0,0 @@
import Decimal, { DecimalSource } from "break_eternity.js";
import { Resource, Resources, SerializedConverter, SerializedNodeBehaviour as SerializedBehaviour, SerializedNodeBehaviour } from "../../types";
export type BehaviourResourcePin = {
resource: Resource;
}
export type BehaviourSocket = {
type: 'input' | 'output';
index: number; // within its type
resource: Resource;
}
export type BehaviourLink = {
target: Behaviour['id'],
resource: Resource;
}
export type BehaviourInput = BehaviourResourcePin & {
link: BehaviourLink;
}
export type BehaviourInputs = {
pins: BehaviourInput[];
}
export type BehaviourOutput = BehaviourResourcePin & {
}
export type BehaviourOutputs = {
pins: BehaviourOutput[];
}
export type BehaviourDisplayInfo = {
storages: Record<string, Resources>;
sockets: BehaviourSocket[];
links: BehaviourLink[];
}
export abstract class Behaviour {
public readonly id: string;
public readonly kind: string;
public readonly inputs: BehaviourInputs;
public readonly outputs: BehaviourOutputs;
protected readonly storage: Partial<Resources> = {};
constructor(source: SerializedBehaviour) {
this.id = source.id;
this.kind = source.kind;
this.outputs = {
pins: source.outputs.pins.map((output) => ({
resource: output.resource,
})),
}
this.inputs = {
pins: source.inputs.pins.map((input) => ({
resource: input.resource,
link: input.link,
})),
}
}
public reset() {
for (const res of Object.keys(this.storage))
delete (this.storage[res as Resource]);
}
abstract getDisplayInfo(): BehaviourDisplayInfo;
/** Withdraws up to `amount` of `resource` from this behaviour's storage, returning how much was actually taken. */
public take(resource: Resource, amount: DecimalSource): Decimal {
const available = this.storage[resource] ?? Decimal.dZero;
const taken = available.min(amount);
this.storage[resource] = available.sub(taken);
return taken;
}
protected give(resource: Resource, amount: DecimalSource): void {
this.storage[resource] = (this.storage[resource] ?? Decimal.dZero).add(amount);
}
abstract produce(deltaTime: number): void;
abstract pull(deltaTime: number, resolve: (id: string) => Behaviour | undefined): void;
}
export class Converter extends Behaviour {
public readonly inputRates: Partial<Resources>;
public readonly outputRates: Partial<Resources>;
constructor(source: SerializedNodeBehaviour & SerializedConverter) {
if (source.kind !== 'converter')
throw new Error('Invalid source');
super(source);
this.inputRates = {};
for (const pin of source.inputs.pins)
this.inputRates[pin.resource] = new Decimal(pin.rate);
this.outputRates = {};
for (const pin of source.outputs.pins)
this.outputRates[pin.resource] = new Decimal(pin.rate);
}
/** Fills this converter's own storage from its outputs' production rates. */
public produce(deltaTime: number): void {
for (const output of this.outputs.pins)
this.give(output.resource, (this.outputRates[output.resource] ?? Decimal.dZero).mul(deltaTime));
}
/** Pulls resources into this converter's storage from whatever each input pin is linked to. */
public pull(deltaTime: number, resolve: (id: string) => Behaviour | undefined): void {
for (const input of this.inputs.pins) {
const source = resolve(input.link.target);
if (!source)
continue;
const rate = this.inputRates[input.resource] ?? Decimal.dZero;
const taken = source.take(input.link.resource, rate.mul(deltaTime));
this.give(input.resource, taken);
}
}
public getDisplayInfo(): BehaviourDisplayInfo {
return {
storages: { 'Буфер': { ...this.storage } as Resources },
links: this.inputs.pins.map((input) => input.link),
sockets: [
...this.inputs.pins.map((input, index) => ({
type: 'input',
index,
resource: input.resource,
} satisfies BehaviourSocket)),
...this.outputs.pins.map((output, index) => ({
type: 'output',
index,
resource: output.resource,
} satisfies BehaviourSocket)),
],
}
}
}
// export class Storage extends Behaviour {
// public static type: string = 'storage';
// }
export const behaviours = {
'converter': Converter,
// 'storage': ,
} satisfies Record<string, { new(source: never): Behaviour }>;
View File
-80
View File
@@ -1,80 +0,0 @@
import { defaultGame } from "../prefabs/game";
import { Game, SerializedGame, SerializedNodeBehaviour } from "../types";
import { Behaviour, behaviours, Converter } from "./functions";
export function serializeBehaviour(behaviour: Behaviour): SerializedNodeBehaviour {
switch (behaviour.kind) {
case 'converter': {
const converter = behaviour as Converter;
return {
id: converter.id,
kind: 'converter',
inputs: {
pins: converter.inputs.pins.map((pin) => ({
...pin,
rate: converter.inputRates[pin.resource] ?? 0,
})),
},
outputs: {
pins: converter.outputs.pins.map((pin) => ({
...pin,
rate: converter.outputRates[pin.resource] ?? 0,
})),
},
};
}
default:
throw new Error('Unknown behaviour');
}
}
export function deserializeBehaviour(value: SerializedNodeBehaviour): Behaviour {
switch (value.kind) {
case 'converter':
return new (behaviours.converter)(value);
default:
throw new Error('Unknown behaviour');
}
}
export function serialize(game: Game): SerializedGame {
return {
time: game.time,
nodes: game.nodes.map((node) => ({
id: node.id,
name: node.name,
behaviour: serializeBehaviour(node.behaviour),
})),
};
}
export function deserialize(value: SerializedGame): Game {
return new Game(value);
}
export function serializeToString(game: Game): string {
return JSON.stringify(serialize(game));
}
export function deserializeFromString(value: string): Game {
return deserialize(JSON.parse(value));
}
const KEY_GAME = 'incgane';
export function save(game: Game) {
localStorage.setItem(KEY_GAME, serializeToString(game));
}
export function load(): Game {
try {
const raw = localStorage.getItem(KEY_GAME);
if (raw)
return deserializeFromString(raw);
} catch (e) {
console.warn('Не удалось прочитать игру из localStorage', e);
}
const fresh = deserialize(defaultGame());
save(fresh);
return fresh;
}
+161 -53
View File
@@ -1,5 +1,3 @@
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap');
:root {
--bg: #201f1c;
--panel: #29271f;
@@ -18,14 +16,19 @@
--display: 'Space Grotesk', ui-sans-serif, sans-serif;
}
* { box-sizing: border-box; }
* {
box-sizing: border-box;
}
html, body, #root {
html,
body,
#root {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--ink);
font-family: var(--mono);
font-size: 10pt;
}
#app {
@@ -49,7 +52,7 @@ html, body, #root {
.topbar__title {
font-family: var(--display);
font-weight: 700;
font-size: 15px;
font-size: 150%;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--ink);
@@ -62,7 +65,6 @@ html, body, #root {
display: block;
font-family: var(--mono);
font-weight: 400;
font-size: 10px;
letter-spacing: 0.04em;
color: var(--ink-dim);
text-transform: none;
@@ -71,23 +73,23 @@ html, body, #root {
.tick-counter {
font-family: var(--mono);
font-size: 12px;
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);
font-size: 14px;
}
.spacer { flex: 1; }
.spacer {
flex: 1;
}
.btn {
font-family: var(--mono);
font-size: 12px;
font-weight: 500;
letter-spacing: 0.03em;
border: 1px solid var(--line);
@@ -98,9 +100,19 @@ html, body, #root {
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: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);
@@ -108,7 +120,10 @@ html, body, #root {
color: #201f1c;
font-weight: 600;
}
.btn--primary:hover { border-color: #f0c169; }
.btn--primary:hover {
border-color: #f0c169;
}
.btn--danger {
background: transparent;
@@ -117,7 +132,10 @@ html, body, #root {
margin-top: 14px;
width: 100%;
}
.btn--danger:hover { background: rgba(193, 90, 78, 0.12); }
.btn--danger:hover {
background: rgba(193, 90, 78, 0.12);
}
.btn--ghost {
background: transparent;
@@ -129,12 +147,10 @@ html, body, #root {
.btn--icon {
padding: 4px 8px;
font-size: 11px;
}
select {
font-family: var(--mono);
font-size: 12px;
background: var(--panel-2);
color: var(--ink);
border: 1px solid var(--line);
@@ -169,14 +185,18 @@ select {
height: 900px;
}
#world > svg {
#world>svg {
position: absolute;
top: 0; left: 0;
top: 0;
left: 0;
width: 1600px;
height: 900px;
pointer-events: none;
}
#world > svg line { pointer-events: stroke; }
#world>svg line {
pointer-events: stroke;
}
.node {
position: absolute;
@@ -184,54 +204,68 @@ select {
border: 1px solid var(--line);
border-left: 4px solid var(--accent-storage);
border-radius: 4px;
padding: 8px 10px;
padding: 0.25em 0.5em;
cursor: grab;
user-select: none;
box-shadow: 0 2px 6px rgba(0,0,0,0.35);
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: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); }
.node--source {
border-left-color: var(--accent-source);
}
.node__id {
.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;
font-size: 10px;
color: var(--ink);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.node__title {
.unit__title {
font-family: var(--display);
font-weight: 600;
font-size: 12.5px;
font-size: 125%;
color: var(--ink);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.node__kind {
font-size: 9px;
.unit__kind {
letter-spacing: 0.05em;
text-transform: uppercase;
color: var(--ink-dim);
margin: 2px 0 6px;
}
.node__resources {
font-size: 11px;
.unit__resources {
background: #171613;
border: 1px solid var(--line);
border-radius: 3px;
@@ -240,8 +274,7 @@ select {
white-space: nowrap;
}
.node__links {
font-size: 11px;
.unit__links {
background: #171613;
border: 1px solid var(--line);
border-radius: 3px;
@@ -250,7 +283,38 @@ select {
white-space: nowrap;
}
.node__sockets {
.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;
@@ -260,10 +324,16 @@ select {
justify-content: center;
gap: 6px;
}
.node__sockets--input { left: -5px; }
.node__sockets--output { right: -5px; }
.node__socket {
.unit__sockets--input {
left: -5px;
}
.unit__sockets--output {
right: -5px;
}
.unit__socket {
width: 10px;
height: 10px;
border-radius: 50%;
@@ -287,6 +357,7 @@ select {
padding: 14px 16px;
border-bottom: 1px solid var(--line);
}
.sidebar__section--grow {
flex: 1;
border-bottom: none;
@@ -308,6 +379,7 @@ select {
max-height: 140px;
overflow-y: auto;
}
.sidebar__list li {
padding: 6px 8px;
font-size: 11.5px;
@@ -318,8 +390,16 @@ select {
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__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;
@@ -349,7 +429,9 @@ select {
font-size: 11px;
color: var(--ink-dim);
}
.field input, .field select {
.field input,
.field select {
font-family: var(--mono);
font-size: 12px;
background: var(--panel-2);
@@ -359,13 +441,21 @@ select {
padding: 7px 9px;
width: 100%;
}
.field input:focus-visible, .field select:focus-visible {
.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%; }
.coord-row {
display: flex;
gap: 8px;
}
.coord-row input {
width: 50%;
}
.recipe-box {
border: 1px solid var(--line);
@@ -374,6 +464,7 @@ select {
margin-bottom: 12px;
background: var(--panel-2);
}
.recipe-box__title {
font-size: 10.5px;
text-transform: uppercase;
@@ -381,15 +472,32 @@ select {
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; }
.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;
}
+44 -38
View File
@@ -1,4 +1,4 @@
import { SerializedGame } from "../types";
import { SerializedGame } from "@incgame/engine";
export const defaultGame: () => SerializedGame = () => ({
time: 0,
@@ -9,21 +9,11 @@ export const defaultGame: () => SerializedGame = () => ({
behaviour: {
id: 'forest.1',
kind: 'converter',
inputs: {
pins: [],
},
outputs: {
pins: [
{
resource: 'wood',
rate: 1,
},
{
resource: 'stone',
rate: 0.1,
},
],
},
inputLinks: { pins: [] },
rules: {
cycleLength: 1,
outputRates: { tree: 1, stone: 0.1 },
}
},
},
{
@@ -32,43 +22,59 @@ export const defaultGame: () => SerializedGame = () => ({
behaviour: {
id: 'sawmill.1',
kind: 'converter',
inputs: {
inputLinks: {
pins: [
{
resource: 'wood',
rate: 0.5,
link: { target: 'forest.1', resource: 'wood' },
resource: 'tree',
target: 'forest.1',
},
]
},
outputs: {
pins: [
{
resource: 'plank',
rate: 1,
},
],
rules: {
cycleLength: 1.8,
inputRates: { tree: 1 },
outputRates: { wood: 2 },
},
},
},
{
id: 'burner',
name: 'Магазин досок',
id: 'shop',
name: 'Магазин',
behaviour: {
id: 'burner.1',
kind: 'converter',
inputs: {
id: 'shop.1',
kind: 'storage',
inputLinks: {
pins: [
{
resource: 'plank',
rate: 1,
link: { target: 'sawmill.1', resource: 'plank' },
resource: 'wood',
target: 'sawmill.1',
},
],
{
resource: 'stone',
target: 'forest.1',
}
]
},
outputs: {
pins: [],
acceptsResources: ['wood', 'stone'],
items: {},
},
},
{
id: 'shop2',
name: 'Магазин 2',
behaviour: {
id: 'shop.2',
kind: 'storage',
inputLinks: {
pins: [
{
resource: 'stone',
target: 'forest.1',
}
]
},
acceptsResources: ['stone'],
items: {},
},
},
],
+30
View File
@@ -0,0 +1,30 @@
import { defaultGame } from "./prefabs/game";
import { Game, serializeGameToString, deserializeGame, deserializeGameFromString } from '@incgame/engine';
export const saveParams = {
path: 'default',
}
const DEFAULT_KEY_GAME = 'incgame';
function getKeyGame(): string {
const params = new URLSearchParams(window.location.search);
return params.get('game') || DEFAULT_KEY_GAME;
}
export function save(game: Game) {
localStorage.setItem(`${saveParams.path}_${getKeyGame()}`, serializeGameToString(game));
}
export function load(): Game {
try {
const raw = localStorage.getItem(`${saveParams.path}_${getKeyGame()}`);
if (raw)
return deserializeGameFromString(raw);
} catch (e) {
console.warn('Не удалось прочитать игру из localStorage', e);
}
const fresh = deserializeGame(defaultGame());
save(fresh);
return fresh;
}
-96
View File
@@ -1,96 +0,0 @@
import Decimal, { DecimalSource } from "break_eternity.js";
import { Behaviour } from "../engine/functions";
import { deserializeBehaviour } from "../engine/saveLoad";
export type Resource = 'wood' | 'plank' | 'stone';
export type Resources = Record<Resource, Decimal>;
export type Node = {
id: string;
name: string;
behaviour: Behaviour;
}
export class Game {
public time: Decimal;
public readonly nodes: Node[];
constructor(source: SerializedGame) {
this.time = new Decimal(source.time);
this.nodes = source.nodes.map((node) => ({
id: node.id,
name: node.name,
behaviour: deserializeBehaviour(node.behaviour),
}));
}
public tick(deltaTime: number) {
this.time = this.time.add(deltaTime);
const behavioursById = new Map(this.nodes.map((node) => [node.behaviour.id, node.behaviour]));
for (const node of this.nodes)
node.behaviour.produce(deltaTime);
for (const node of this.nodes)
node.behaviour.pull(deltaTime, (id) => behavioursById.get(id));
}
public reset() {
this.time = Decimal.dZero;
for (const node of this.nodes)
node.behaviour.reset();
}
/** Shallow copy with a new identity, so React sees a change after in-place mutations like `tick`. */
public clone(): Game {
return Object.assign(Object.create(Game.prototype), this);
}
}
export type SerializedConverterInput = {
resource: Resource;
rate: DecimalSource;
link: {
target: SerializedNodeBehaviour['id'],
resource: Resource,
}
}
export type SerializedConverterOutput = {
resource: Resource;
rate: DecimalSource;
}
export type SerializedConverterInputs = {
pins: SerializedConverterInput[];
}
export type SerializedConverterOutputs = {
pins: SerializedConverterOutput[];
}
export type SerializedConverter = {
kind: 'converter';
}
export type SerializedStorage = {
kind: 'storage',
}
export type SerializedNodeBehaviour = {
id: string;
inputs: SerializedConverterInputs;
outputs: SerializedConverterOutputs;
} & (SerializedConverter | SerializedStorage);
export type SerializedNode = {
id: Node['id'],
name: Node['name'],
behaviour: SerializedNodeBehaviour,
}
export type SerializedGame = {
time: DecimalSource;
nodes: SerializedNode[];
}
+16 -16
View File
@@ -1,35 +1,35 @@
import ELK, { ElkNode } from "elkjs/lib/elk.bundled.js";
import { Node } from "../types";
import { Unit, Behaviour } from "@incgame/engine";
const elk = new ELK();
const NODE_WIDTH = 100;
const NODE_HEIGHT = 90;
const UNIT_WIDTH = 200;
const NODE_HEIGHT = 150;
export type Node2D = {
id: Node['id'];
export type GraphNode = {
position: { x: number, y: number };
node: Node;
kind: 'behaviour';
entity: Behaviour;
}
export async function build2dNodes(nodes: Node[], area: { width: number, height: number, padding: number }): Promise<Node2D[]> {
const nodesById = new Map(nodes.map((node) => [node.behaviour.id, node]));
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": "60",
"elk.spacing.nodeNode": "100",
"elk.layered.spacing.nodeNodeBetweenLayers": "100",
},
children: nodes.map((node) => ({
id: node.behaviour.id,
width: NODE_WIDTH,
children: units.map((unit) => ({
id: unit.behaviour.id,
width: UNIT_WIDTH,
height: NODE_HEIGHT,
})),
edges: nodes.flatMap((node) =>
node.behaviour.getDisplayInfo().links.map((link, idx) => ({
edges: units.flatMap((node) =>
node.behaviour.inputLinks.map((link, idx) => ({
id: `${node.behaviour.id}->${link.target}.${idx}`,
sources: [node.behaviour.id],
targets: [link.target],
@@ -40,11 +40,11 @@ export async function build2dNodes(nodes: Node[], area: { width: number, height:
const layout = await elk.layout(graph);
return (layout.children ?? []).map((child) => ({
id: child.id,
position: {
x: (child.x ?? 0) + area.padding,
y: (child.y ?? 0) + area.padding,
},
node: nodesById.get(child.id)!,
kind: 'behaviour',
entity: entitiesById.get(child.id)!,
}));
}
+3 -3
View File
@@ -1,4 +1,4 @@
import { Resource } from "../types";
import { Resource } from "@incgame/engine";
export type ResourceDescription = {
id: Resource;
@@ -8,8 +8,8 @@ export type ResourceDescription = {
}
export const ResourceDescriptions: Record<ResourceDescription['id'], ResourceDescription> = {
wood: { id: 'wood', label: 'Дерево', color: '#b98249', icon: '🌲' },
plank: { id: 'plank', label: 'Доска', color: '#c9c209', icon: 'P' },
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: '💰' },
+23
View File
@@ -1,6 +1,29 @@
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
const rootDir = path.dirname(fileURLToPath(import.meta.url));
const engineDir = path.resolve(rootDir, '../engine');
export default defineConfig({
plugins: [react()],
resolve: {
// Follow the node_modules symlink to the real sibling directory, so Vite's dev server
// watches and transforms the actual engine source files (not a frozen pre-bundled copy).
preserveSymlinks: false,
},
optimizeDeps: {
// Treat @incgame/engine as first-party source, not a vendor dependency to pre-bundle once
// and cache — otherwise edits to the engine package wouldn't trigger HMR until a full
// dev-server restart.
exclude: ['@incgame/engine'],
},
server: {
fs: {
// The engine package lives outside this project's root (a sibling directory reached
// through a node_modules symlink); allow Vite to serve/watch files from there too.
allow: [rootDir, engineDir],
},
},
});