docs: present Shacraft Core and its documentation in English

This commit is contained in:
Emil
2026-09-14 17:58:30 +03:00
parent b6ba064339
commit 26748912c6
18 changed files with 643 additions and 620 deletions
+39 -39
View File
@@ -1,77 +1,77 @@
# Interchange MVP: Java 26.2 и Sponge v3
# Interchange MVP: Java 26.2 and Sponge v3
`shacraft-compat` — отдельная Rust-библиотека и автономная CLI. Она действительно переносит состояния блоков в `WorldStore`: браузер, Control API и MCP редактируют импортированные данные, а экспорт читает текущие секции. Исходный мир хранится отдельно на диске с SHA-256. Возврат оригинала без изменений является отдельным проверенным режимом.
`shacraft-compat` is a separate Rust library and standalone CLI. It transfers block states into `WorldStore`: the browser, Control API, and MCP edit the imported data, and export reads the current sections. The source world is preserved separately on disk with SHA-256 hashes. Returning the unchanged original is a separate, verified mode.
Целевая версия: **Minecraft Java 26.2, DataVersion 4903**. Библиотека не запускает JVM. Java 25 нужна только воспроизводимой проверке и генератору собственных тестовых сохранений.
Target version: **Minecraft Java 26.2, DataVersion 4903**. The library does not launch a JVM. Java 25 is needed only for reproducible verification and the generator of original test saves.
## Команды
## Commands
Команды выполняются из корня репозитория. Все выходные пути должны отсутствовать. Каждый экспорт публикует **каталог**, даже экспорт одной постройки: в нём находятся `world.schem` и `conversion-report.json`. Если исходный мир уже содержит файл с этим именем, новый отчёт получает числовой суффикс; исходный файл сохраняется.
Run these commands from the repository root. All output paths must be absent. Every export publishes a **directory**, including exports of a single build: it contains `world.schem` and `conversion-report.json`. If the source world already contains a file with that report name, the new report receives a numeric suffix; the original file is preserved.
```bash
cargo build --release -p shacraft-compat -p shacraft-server
# Импорт остановленной копии Java-мира в новый native store.
# Import a copy of a stopped Java world into a new native store.
target/release/shacraft-compat import-anvil /path/to/java-world data/imported
# Открыть импорт в браузере через сервер; в списке миров выбрать main.
# Open the import in the browser through the server; select main in the world list.
target/release/shacraft-server --data data/imported --listen 127.0.0.1:4000
# После остановки сервера: все импортированные измерения вместе.
# After stopping the server: export all imported dimensions together.
target/release/shacraft-compat export-anvil data/imported artifacts/return-exact
target/release/shacraft-compat export-anvil data/imported artifacts/return-edited --mode best-effort
# Новый мир Shacraft: полноценный каталог сохранения Java 26.2.
# New Shacraft world: a complete Java 26.2 save directory.
target/release/shacraft-compat export-anvil data artifacts/new-java-world --world lobby --mode best-effort
# Sponge v3; Offset переносится в координаты native мира.
# Sponge v3; Offset is applied to native world coordinates.
target/release/shacraft-compat import-schem /path/to/build.schem data/build --world main
target/release/shacraft-compat export-schem data/build artifacts/build-edited --mode best-effort
# Экспорт ограниченного объёма нового native мира; границы включительные.
# Export a bounded volume from a new native world; bounds are inclusive.
target/release/shacraft-compat export-schem data artifacts/build --world lobby --min=-16,-1,-16 --max=16,15,16
```
CLI печатает отчёт JSON в stdout, ошибки — JSON в stderr и ненулевой exit code. Конвертация выполняется offline: `WorldStore` удерживает ту же блокировку единственного писателя, что сервер, поэтому параллельное редактирование не смешивает ревизии в одном экспорте. Сам исходный Java-мир должен быть остановленной копией: изменения размера/времени файла во время копирования обнаруживаются, но это не заменяет согласованный backup работающего Minecraft.
The CLI prints a JSON report to stdout; errors produce JSON on stderr and a nonzero exit code. Conversion runs offline: `WorldStore` holds the same single-writer lock as the server, preventing concurrent edits from mixing revisions within one export. The source Java world must itself be a copy of a stopped world: changes to file size/timestamps during copying are detected, but this does not replace a consistent backup of a running Minecraft instance.
## Что реализовано
## Implemented features
- Big-endian NBT: все 12 payload-типов, числовые разрядности, float/double bit patterns, signed arrays, Java modified UTF-8/CESU-8, Unicode, тип элемента пустого списка и неизвестные compound-поля. Duplicate compound keys, невозможные длины, превышение глубины и лишние распакованные байты отклоняются.
- Anvil: `level.dat`, обычные измерения, `dimensions/<namespace>/<path>`, секционные палитры `Name`/`Properties`, современные непересекающие 64-битную границу индексы, отрицательные координаты, единообразные секции, биомы. Чтение gzip, zlib, raw и LZ4Block с checksum, включая внешние `c.x.z.mcc`. Запись zlib и внешний payload для chunk более 255 секторов.
- Исходные `entities`, `block_entities`, POI, биомы, inventories, playerdata, datapacks, неизвестные поля и произвольные обычные файлы сохраняются на диске. Отдельные entity region-файлы действительно читаются для серверного представления, а не только копируются.
- Sponge v3: `Blocks`, sparse palette indices и varints, block entities, сущности, полный 3D-контейнер биомов, размеры, Offset, Metadata и неизвестные теги. Контейнер `Schematic` вложен в корневой NBT compound согласно спецификации.
- Новый Anvil-мир использует собственный маленький шаблон сохранения, созданный public API Java 26.2. В 26.2 параметры генерации и game rules находятся в `data/minecraft/world_gen_settings.dat` и `game_rules.dat`; экспорт включает эти файлы. Генератор — пустой flat overworld, creative, три стандартных измерения, биом plains в новых секциях, высота редактируемого экспорта −64…319.
- Big-endian NBT: all 12 payload types, numeric widths, float/double bit patterns, signed arrays, Java modified UTF-8/CESU-8, Unicode, the element type of an empty list, and unknown compound fields. Duplicate compound keys, impossible lengths, excessive depth, and trailing decompressed bytes are rejected.
- Anvil: `level.dat`, standard dimensions, `dimensions/<namespace>/<path>`, section palettes using `Name`/`Properties`, modern indices that do not cross 64-bit boundaries, negative coordinates, uniform sections, and biomes. Reads gzip, zlib, raw, and LZ4Block with checksum, including external `c.x.z.mcc` files. Writes zlib and an external payload for chunks larger than 255 sectors.
- Original `entities`, `block_entities`, POI, biomes, inventories, playerdata, datapacks, unknown fields, and arbitrary regular files are preserved on disk. Separate entity region files are parsed for the server representation, not merely copied.
- Sponge v3: `Blocks`, sparse palette indices and varints, block entities, entities, the full 3D biome container, dimensions, Offset, Metadata, and unknown tags. The `Schematic` container is nested in the root NBT compound as specified.
- New Anvil worlds use a small original save template created through the public Java 26.2 API. In 26.2, generation settings and game rules reside in `data/minecraft/world_gen_settings.dat` and `game_rules.dat`; export includes these files. Generation uses an empty flat overworld, creative mode, three standard dimensions, the plains biome in new sections, and an editable export height of −64…319.
## Сущности между MCP и файлами мира
## Entities between MCP and world files
Импорт создаёт совместимый `server.sqlite3`, таблица `metadata(id,json)`. До 4 096 сущностей становятся доступны через сервер и MCP с исходными UUID, типом, координатами и поворотом. Остальные сущности, неподходящие координаты и неподдерживаемые записи остаются в оригинале и отмечаются `preserved`; они не превращаются в пропавшие данные.
Import creates a compatible `server.sqlite3` with the table `metadata(id,json)`. Up to 4,096 entities become available through the server and MCP with their original UUIDs, types, coordinates, and rotations. Remaining entities, unsuitable coordinates, and unsupported records stay in the original and are marked `preserved`; the data is not discarded.
Исходный типизированный NBT каждой редактируемой сущности находится в `compat/entities/<uuid>.nbt`; его хеш закреплён в provenance. `compat/native-entities.json` содержит исходное серверное представление. Экспорт отдельно сравнивает fingerprint сущностей и ревизии блоков, поэтому перемещение сущности без правки блоков также отклоняет `exact`.
Each editable entity's original typed NBT is stored in `compat/entities/<uuid>.nbt`; its hash is pinned in the provenance record. `compat/native-entities.json` contains the original server representation. Export compares entity fingerprints and block revisions separately, so moving an entity without editing blocks also causes `exact` to refuse the export.
`best-effort` применяет создание, удаление и перемещение сущностей между chunks/regions и измерениями, а также yaw в радианах из серверного API. Явно поддерживаются свойства `Health`, `CustomName`, `NoGravity`, `Invisible`, `Invulnerable`, `Glowing`, `Silent`, `CustomNameVisible` с соответствующими числовыми/строковыми/логическими типами. Прочие свойства JSON сохраняются в `shacraft-native-entities*.json` и получают `entity_property_unmapped`; они не выдаются за vanilla NBT. Оригинальный NBT сохраняет остальные поля. AI, passengers, leash и связанные UUID не симулируются и не получают обещания точной семантики после перемещения.
`best-effort` applies entity creation, deletion, and movement between chunks/regions and dimensions, as well as yaw in radians from the server API. The properties `Health`, `CustomName`, `NoGravity`, `Invisible`, `Invulnerable`, `Glowing`, `Silent`, and `CustomNameVisible` are explicitly supported with their corresponding numeric/string/boolean types. Other JSON properties are preserved in `shacraft-native-entities*.json` and reported as `entity_property_unmapped`; they are not presented as vanilla NBT. The original NBT retains its other fields. AI, passengers, leashes, and linked UUIDs are not simulated, and their exact semantics after movement are not guaranteed.
## Exact и best-effort
## Exact and best-effort
`exact` использует DataVersion 4903 и тот же формат, что источник. Пока **любая новая ревизия блоков или изменённое серверное представление сущностей** консервативно запрещает точный возврат исходного мира/постройки. Это касается даже отменённой правки, восстановившей те же блоки: ревизия не возвращается назад. Без правок все исходные файлы побайтно идентичны после проверки SHA-256.
`exact` uses DataVersion 4903 and the same format as the source. Currently, **any new block revision or changed server entity representation** conservatively prevents an exact return of the original world/build. This includes an undone edit that restored the same blocks: revisions do not go backward. With no edits, all source files remain byte-identical after SHA-256 verification.
Для нового native мира `exact` поддерживает представимый Sponge v3. Создание нового Anvil-окружения и межформатное преобразование требуют `best-effort`, поскольку свет и производные данные нуждаются в восстановлении Minecraft. Режим не содержит скрытых замен блоков. Неизвестный namespace остаётся в палитре и получает `unsupported`: целевому Minecraft нужен соответствующий мод, иначе он может заменить неизвестный блок воздухом.
For a new native world, `exact` supports representable Sponge v3 data. Creating a new Anvil environment and converting between formats require `best-effort`, because lighting and derived data need rebuilding by Minecraft. This mode makes no hidden block substitutions. Unknown namespaces remain in the palette and are marked `unsupported`: the target Minecraft installation needs the corresponding mod, or it may replace an unknown block with air.
В изменённых Anvil chunks экспорт обновляет палитры/блоки, удаляет сохранённые light arrays и heightmaps, устанавливает `isLightOn=false`, удаляет устаревшие block entities и scheduled ticks непосредственно в изменённых координатах, инвалидирует POI record изменённого chunk. Все эти действия перечислены в отчёте, оригиналы находятся в `shacraft-source-sidecar*`. Это проверенный профиль сериализации и инвалидации; прохождение полной игровой симуляции света/POI не заявляется.
In edited Anvil chunks, export updates palettes/blocks, removes saved light arrays and heightmaps, sets `isLightOn=false`, removes stale block entities and scheduled ticks at the edited coordinates, and invalidates the edited chunk's POI record. The report lists all these actions, and originals remain in `shacraft-source-sidecar*`. This is a verified serialization and invalidation profile; a complete in-game lighting/POI simulation pass is not claimed.
При экспорте между `.schem` и Anvil переносится блоковая модель и явный entity bridge. Биомная сетка, block entities и произвольные metadata разных форматов пока архивируются без преобразования и получают `cross_format_opaque_data`. Оригинал находится рядом с результатом. Неподдерживаемые версии не мигрируют через DataFixer: `exact` отказывает, а `best-effort` сохраняет исходный DataVersion и диагностирует непроверенную схему.
Conversion between `.schem` and Anvil transfers the block model and uses the explicit entity bridge. Biome grids, block entities, and arbitrary metadata from different formats are currently archived without translation and reported as `cross_format_opaque_data`. The original is retained alongside the result. Unsupported versions are not migrated through DataFixer: `exact` refuses them, while `best-effort` preserves the source DataVersion and reports the unverified schema.
## Ограничения ресурсов и публикация
## Resource limits and publication
- Не более 16 MiB распакованного NBT на chunk/постройку, глубина 64, до 1 000 000 NBT nodes. Это лимиты входных данных, не обещание 16 MiB RSS: Rust-структуры и строки занимают дополнительную память.
- Sponge: максимум 262 144 вокселя; Anvil обрабатывается по одному chunk, экспортная очередь координат находится на диске, страницы секций — не более 4 096 ключей. Кэш ядра конвертера — 32 секции плюс ограниченный SQLite cache.
- Entity bridge: 4 096 записей, до 16 KiB properties на сущность, ограничение сериализованного metadata 8 MiB (импортируемый entity subset ограничен 6 MiB с запасом для настроек сервера). Избыточные исходные сущности сохраняются без загрузки всех записей в серверную RAM.
- До 1 000 подробных issue в отчёте; `omitted_issues` явно считает оставшиеся события. До 256 импортированных измерений, 1 000 000 файлов, 8 GiB на исходный файл и 1 TiB суммарного источника. Symlinks, специальные файлы, выход из каталога, вложенный в исходный мир destination и повреждённые region headers отклоняются.
- Импорт строит весь новый native store, metadata и provenance в соседнем временном каталоге. Экспорт тоже использует staging. Файлы и каталоги синхронизируются, публикация — Linux `renameat2(RENAME_NOREPLACE)` и fsync родителя. Конвертер никогда не перезаписывает существующий destination и не меняет исходный Java-мир.
- При штатной ошибке staging удаляется; после SIGKILL может остаться непубликованный `.shacraft-convert-*`. Повторный импорт безопасно начинается заново. Возобновление с последнего chunk после аварии ещё не реализовано. Нужен запас диска: исходный архив плюс native DB, а изменённый экспорт сохраняет ещё одну полную копию исходника.
- At most 16 MiB of decompressed NBT per chunk/build, depth 64, and up to 1,000,000 NBT nodes. These are input limits, not a promise of 16 MiB RSS: Rust structures and strings require additional memory.
- Sponge: at most 262,144 voxels. Anvil processes one chunk at a time, keeps the export coordinate queue on disk, and pages section keys in batches of at most 4,096. The converter's core cache holds 32 sections, plus a bounded SQLite cache.
- Entity bridge: 4,096 records, up to 16 KiB of properties per entity, and an 8 MiB serialized metadata limit. The imported entity subset is limited to 6 MiB to leave room for server settings. Excess source entities are preserved without loading all records into server RAM.
- At most 1,000 detailed issues in the report; `omitted_issues` explicitly counts the remaining events. Limits: 256 imported dimensions, 1,000,000 files, 8 GiB per source file, and 1 TiB for the complete source. Symlinks, special files, directory escapes, a destination nested inside the source world, and corrupt region headers are rejected.
- Import builds the complete new native store, metadata, and provenance in an adjacent temporary directory. Export also uses staging. Files and directories are synchronized; publication uses Linux `renameat2(RENAME_NOREPLACE)` and fsync of the parent directory. The converter never overwrites an existing destination or changes the source Java world.
- On an ordinary error, staging is removed; SIGKILL can leave an unpublished `.shacraft-convert-*` directory. Retrying an import safely starts over. Resuming from the last chunk after a crash is not yet implemented. Allow enough disk space for the source archive plus the native DB; an edited export retains another complete copy of the source.
`.schem` v2, legacy `.schematic`, vanilla structure `.nbt`, произвольные повороты/миграции версий и полная ванильная симуляция не включены в этот профиль. Они не распознаются как v3 по расширению файла.
`.schem` v2, legacy `.schematic`, vanilla structure `.nbt`, arbitrary rotations/version migrations, and complete vanilla simulation are outside this profile. They are not treated as v3 based on the filename extension.
## Воспроизводимая проверка
## Reproducible verification
```bash
cargo test -p shacraft-compat
@@ -81,8 +81,8 @@ artifacts/compat-venv/bin/pip install nbtlib==2.0.4
artifacts/compat-venv/bin/python scripts/compat_verify.py
```
Для последней команды нужен pinned JAR/JDK из `scripts/catalog_generate.py`; альтернативный JDK передаётся `--java-bin /path/to/jdk25/bin`. Скрипт проверяет SHA-1 JAR, компилирует `compat_java.java`, проверяет оригинальный, изменённый и новый Rust-экспорт через **официальные `NbtIo`, `RegionFile`, `SerializableChunkData`, `PrimaryLevelData`, `WorldGenSettings`**. Независимый `nbtlib 2.0.4` сравнивает типизированные Sponge-теги. Результат и Java logs сохраняются в `artifacts/compat-verification-*/verification.json`.
The last command needs the pinned JAR/JDK from `scripts/catalog_generate.py`; pass an alternative JDK with `--java-bin /path/to/jdk25/bin`. The script checks the JAR's SHA-1, compiles `compat_java.java`, and validates original, edited, and new Rust exports through the **official `NbtIo`, `RegionFile`, `SerializableChunkData`, `PrimaryLevelData`, and `WorldGenSettings`**. Independent `nbtlib 2.0.4` checks compare typed Sponge tags. Results and Java logs are saved under `artifacts/compat-verification-*/verification.json`.
Проверка 14 сентября 2026: 17 Rust-тестов и clippy прошли; Java прочитал exact 1 chunk / 3 блока, edited 2 chunks / 3 блока, new 2 chunks / 2 блока. Плюс тесты всех четырёх compression modes, внешнего большого chunk, границ палитр, отрицательных координат, entities move/create/remove, отказа exact после entity edits, checksum и no-overwrite. Java-проверка использует codecs, **не запускает сервер, не принимает EULA и не является игровым плейтестом**.
Verification on September 14, 2026: 17 Rust tests and clippy passed; Java read exact 1 chunk / 3 blocks, edited 2 chunks / 3 blocks, and new 2 chunks / 2 blocks. Checks also cover all four compression modes, a large external chunk, palette boundaries, negative coordinates, entity move/create/remove, refusal of exact after entity edits, checksum validation, and no-overwrite behavior. Java verification uses codecs **without launching the Minecraft game/server or accepting its server startup prompt; it is not an in-game playtest**.
Первичные источники: [Sponge v3 specification](https://github.com/SpongePowered/Schematic-Specification/blob/master/versions/schematic-3.md), [WorldEdit AnvilChunk18](https://github.com/EngineHub/WorldEdit/blob/dca10737fe81bd81bb6a096e1801cc2d94f1793b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk18.java), [lz4-java block stream](https://github.com/lz4/lz4-java/blob/master/src/java/net/jpountz/lz4/LZ4BlockInputStream.java). Runtime реализация написана самостоятельно; код Minecraft и оригинальные игровые ресурсы не включены.
Primary sources: [Sponge v3 specification](https://github.com/SpongePowered/Schematic-Specification/blob/master/versions/schematic-3.md), [WorldEdit AnvilChunk18](https://github.com/EngineHub/WorldEdit/blob/dca10737fe81bd81bb6a096e1801cc2d94f1793b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk18.java), [lz4-java block stream](https://github.com/lz4/lz4-java/blob/master/src/java/net/jpountz/lz4/LZ4BlockInputStream.java). The runtime implementation is original; Minecraft code and original game assets are not included.