Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,22 @@ jobs:
cmake --install . --prefix stage
- name: Run tests
run: python3 -m pytest tests/ -v
- name: Check native binaries
# Nuitka's --include-data-dir silently drops executables and shared
# libraries, so they are listed explicitly; make sure they exist.
run: |
ls -l build/stage/native
test -x build/stage/native/terrain_gen
test -x build/stage/native/mob_ai
build/stage/native/terrain_gen --version | grep -q "pymc-worldgen 2"
- name: Build with Nuitka
run: |
pip install nuitka
python3 -m nuitka --standalone --onefile --assume-yes-for-downloads \
--include-data-file=world/blocks.json=world/blocks.json \
--include-data-dir=protocol/data=protocol/data \
--include-data-dir=world/data=world/data \
--include-data-dir=build/stage/native=native \
'--include-data-files=build/stage/native/*=native/' \
main.py -o pymc-server-linux-x86_64
- name: Upload Linux artifact
uses: actions/upload-artifact@v4
Expand Down Expand Up @@ -67,14 +75,22 @@ jobs:
cmake --install . --prefix stage
- name: Run tests
run: python3 -m pytest tests/ -v
- name: Check native binaries
# Nuitka's --include-data-dir silently drops executables and shared
# libraries, so they are listed explicitly; make sure they exist.
run: |
ls -l build/stage/native
test -x build/stage/native/terrain_gen
test -x build/stage/native/mob_ai
build/stage/native/terrain_gen --version | grep -q "pymc-worldgen 2"
- name: Build with Nuitka
run: |
pip install nuitka
python3 -m nuitka --standalone --onefile --assume-yes-for-downloads \
--include-data-file=world/blocks.json=world/blocks.json \
--include-data-dir=protocol/data=protocol/data \
--include-data-dir=world/data=world/data \
--include-data-dir=build/stage/native=native \
'--include-data-files=build/stage/native/*=native/' \
main.py -o pymc-server-macos-arm64
- name: Upload macOS artifact
uses: actions/upload-artifact@v4
Expand Down Expand Up @@ -118,6 +134,15 @@ jobs:
cmake --install . --config Release --prefix stage
- name: Run tests
run: python -m pytest tests/ -v
- name: Check native binaries
# Nuitka's --include-data-dir silently drops .exe/.dll files, so they
# are listed explicitly; make sure they exist.
shell: bash
run: |
ls -l build/stage/native
test -f build/stage/native/terrain_gen.exe
test -f build/stage/native/mob_ai.exe
build/stage/native/terrain_gen.exe --version | grep -q "pymc-worldgen 2"
- name: Build with Nuitka
# Nuitka on Windows defaults to MSVC. No --mingw64 flag, so it
# picks up the MSVC environment set up by ilammy/msvc-dev-cmd above.
Expand All @@ -127,7 +152,7 @@ jobs:
--include-data-file=world/blocks.json=world/blocks.json `
--include-data-dir=protocol/data=protocol/data `
--include-data-dir=world/data=world/data `
--include-data-dir=build/stage/native=native `
'--include-data-files=build/stage/native/*=native/' `
main.py -o pymc-server-windows-x86_64.exe
- name: Stage native binaries for separate download
# Copy the MSVC-built, statically-linked /MT .exe files so users
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,19 @@
- 世界出生点采用原版逻辑:按气候寻找陆地,再搜索周围安全地表。
- 新玩家在 `spawnRadius` 范围内随机选择安全地面,不会出生在水里、岩浆、树顶或方块里;老玩家回到下线位置(被埋住时才挪到附近安全处)。

### 合成与掉落
- 合成可用了:背包 2×2 合成格和工作台 3×3 都会实时显示产物,可点击取走、Shift 批量合成、数字键放入快捷栏、Q 丢出,关闭界面时合成格里的物品退回背包(满了就掉在地上)。
- 配方改用原版 1.21.1 完整数据(634 个有序 + 253 个无序配方,标签全部展开):任意木板都能做工作台、木棍等,可以混用不同木板;有序配方支持左右镜像;牛奶桶等合成后会留下空桶。数据由 `tools/gen_recipe_data.py` 生成。
- 物品栏点击改为原版的差异同步:只把客户端预测错的格子发回去,快速连续点击时不再出现物品闪烁、错位。
- 树叶掉落改为原版战利品表:树苗 5%(丛林 2.5%)、木棍 2%、橡树/深色橡树 0.5% 苹果,时运提高概率;用剪刀或精准采集才掉树叶本身。之前橡树叶 100% 掉树苗,其他树叶空手就掉树叶。

### 其他
- 修复远处区块迟迟不加载:区块编码改为批量操作(每个新区块从约 150 毫秒降到约 35 毫秒),并且由近到远分批生成、分批发送。视距 10 时外圈区块原来要等约 1 分钟才一次性出现,现在几秒内就从身边开始逐圈出现,约 18 秒全部加载完。
- 重生从 3 秒多降到约 0.1 秒:缓存已编码的区块和数据包,并且像原版一样先发送位置和血量、再推送区块。玩家进服也因此变快。
- 点击草、蕨、单层雪等可替换方块时,新方块直接替换它(原版行为)。
- 修复 Windows (MSVC) 下地形生成器无法编译的问题。
- 修复打包版(PyMC-windows.exe 等)不含 `terrain_gen`/`mob_ai`、只能退回到极慢的 Python 生成器的问题:Nuitka 的 `--include-data-dir` 会静默跳过 `.exe`/`.dll`/`.so`,现在改为显式打包,CI 打包前也会检查原生组件是否齐全。
- 准备出生区时 `stop` / Ctrl+C 会立即生效(不再等世界生成完);没有原生生成器时出生区只预生成 3x3,并逐区块显示进度。
- GitHub Actions:推送 `v*` tag 时自动构建三平台并发布正式版本。

### 已知限制
Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ PyMC 是一个用 Python 实现的 Minecraft Java 版 1.21.1 服务端原型,
- [x] Web 管理台、权限组、OP、封禁和白名单。
- [x] 单元测试覆盖原生地形、原版存档读写与迁移、玩家存档、原生 AI、种子解析和安全出生点。
- [x] **红石系统**:tick 引擎、电源/导线/火把/中继器/比较器/观察者/活塞、门与灯控制、TNT 起爆、音符盒、发射器/投掷器;红石时序为原版近似。
- [x] **合成**:背包 2×2 与工作台 3×3,原版 1.21.1 全部有序/无序配方(标签展开、镜像、合成剩余物),Shift 批量合成。
- [x] **物品栏系统**:`ItemStack`、玩家物品栏、协议序列化、左右键/Shift/数字键/拖拽/丢弃,以及方块容器交互与持久化;铁砧/附魔台等专业界面仍为简化。
- [x] **PYMC 原生扩展 API**:支持 Python Mod/Plugin 的发现、依赖排序、生命周期、事件和命令注册。Java Fabric/Forge Mod 不受支持;Bukkit/Paper `.jar` 插件通过可选 Java 桥接层提供 best-effort 兼容,详见 `MOD_COMPATIBILITY.md`。
- [x] **Web 管理台安全默认值**:默认只监听 `127.0.0.1`;由于当前没有内置认证,远程监听必须显式设置 `web-admin-allow-remote=true` 并部署外部访问控制。
Expand Down Expand Up @@ -225,6 +226,12 @@ g++ -O2 -std=c++17 -ffp-contract=off -pthread -o native/terrain_gen native/terra
python3 tools/gen_worldgen_data.py
```

合成配方 `world/data/recipes.json` 同样由 `tools/gen_recipe_data.py` 从原版 1.21.1 数据生成(已附带):

```bash
python3 tools/gen_recipe_data.py
```

生物群系参数查找树取自 [cubiomes](https://github.com/Cubitect/cubiomes) (MIT 许可) 的 `btree20` 表;worldgen JSON 来自 [misode/mcmeta](https://github.com/misode/mcmeta) 的 `1.21.1-data-json`。

### CI/CD
Expand Down
6 changes: 3 additions & 3 deletions build.bat
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ echo.
--include-package=world ^
--include-module=config ^
--include-data-dir=native=native ^
--include-data-files=native/terrain_gen.exe=terrain_gen.exe ^
--include-data-files=native/mob_ai.exe=mob_ai.exe ^
--include-data-files=native/terrain_gen.exe=native/terrain_gen.exe ^
--include-data-files=native/mob_ai.exe=native/mob_ai.exe ^
--include-data-files=world/blocks.json=world/blocks.json ^
--include-data-dir=protocol/data=protocol/data ^
--include-data-dir=world/data=world/data ^
Expand All @@ -118,7 +118,7 @@ echo.
--windows-console-mode=force ^
--company-name=PyMC ^
--product-name="PyMC Minecraft Server" ^
--file-version=1.0.0 ^
--file-version=1.2.0 ^
--product-version=1.21.1 ^
--file-description="PyMC - Python Minecraft 1.21.1 服务端" ^
main.py
Expand Down
37 changes: 35 additions & 2 deletions handlers/play/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ async def handle_play(conn: Connection, packet_id: int, payload: bytes,
from handlers.play.players import broadcast_player_equipment
await broadcast_player_equipment(server, conn)
elif name == "close_container":
_handle_close_container(conn, payload)
await _handle_close_container(conn, payload, server)
elif name == "interact":
await _handle_interact(conn, payload, server)
elif name == "set_creative_mode_slot":
Expand Down Expand Up @@ -421,12 +421,15 @@ async def _handle_click_container(conn: Connection, payload: bytes, server):
await handle_container_click(conn, payload, server, _player_window_slot_to_inventory)


def _handle_close_container(conn: Connection, payload: bytes):
async def _handle_close_container(conn: Connection, payload: bytes, server=None):
"""Handle Close Container packet (0x0D)."""
from protocol.data_types import read_varint
offset = 0
window_id, offset = read_varint(payload, offset)

if window_id == 0 or getattr(conn, '_open_container_type', None) == 'crafting':
await return_crafting_grid(conn, server, window_id)

if getattr(conn, '_open_window_id', None) != window_id:
return

Expand All @@ -440,6 +443,36 @@ def _handle_close_container(conn: Connection, payload: bytes):
conn._open_container_type = None


async def return_crafting_grid(conn: Connection, server, window_id: int):
"""Closing a crafting grid hands its items back (dropped when the inventory is full)."""
inv = getattr(conn, 'inventory_obj', None)
if inv is None:
return
from world.crafting_window import return_grid_items
from world.inventory_interactions import _drop_stack
from world.inventory import send_inventory_sync
leftovers = []

def give(stack):
left = inv.add_item(stack)
if left > 0:
extra = stack.copy()
extra.count = left
leftovers.append(extra)

if window_id != 0 and getattr(conn, '_crafting_grid', None) is None:
return
if window_id == 0 and not any(inv.slots[i] for i in (41, 42, 43, 44)):
inv.slots[45] = None
return
return_grid_items(conn, window_id, give)
if window_id != 0:
conn._crafting_grid = None
for stack in leftovers:
await _drop_stack(conn, server, stack, stack.count)
await send_inventory_sync(conn)


async def _handle_respawn(conn: Connection, server):
"""Handle player respawn after death (Client Command: Perform Respawn)."""
from handlers.play.join import respawn_player
Expand Down
6 changes: 4 additions & 2 deletions handlers/play/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,8 +332,10 @@ async def _handle_block_dig(conn: Connection, payload: bytes, server):
if inv is not None:
tool_item = inv.get_held_item_from_slot(conn.selected_hotbar_slot)

# Use the new block drops system
drops = get_block_drops(block_name, tool_item)
# Vanilla block loot table (uses the broken block's state, e.g. crop age)
from world.chunk_io import STATE_ID_TO_BLOCK
state_props = STATE_ID_TO_BLOCK.get(current, (block_name, {}))[1]
drops = get_block_drops(block_name, tool_item, state_props)

if drops:
for drop in drops:
Expand Down
78 changes: 59 additions & 19 deletions handlers/play/chunks.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,22 +354,65 @@ async def _send_chunk_results_streamed(conn: Connection, chunk_results,
await asyncio.sleep(0)


PROGRESSIVE_BATCH_SIZE = 32


async def _load_and_send_progressively(conn: Connection, server, chunk_coords,
still_wanted=None) -> int:
"""
Generate/load and send chunks in small batches, nearest first, so the
client fills in its view ring by ring instead of waiting for the whole
view distance. ``still_wanted()`` returning False stops early (the player
moved on). Returns how many chunks were sent.
"""
loop = asyncio.get_running_loop()
batches = [
chunk_coords[index:index + PROGRESSIVE_BATCH_SIZE]
for index in range(0, len(chunk_coords), PROGRESSIVE_BATCH_SIZE)
]

def _start(batch):
batch = [coord for coord in batch if coord not in conn.loaded_chunks]
if not batch:
return None
return loop.run_in_executor(None, lambda: server.generate_chunk_results(batch)[0])

sent = 0
pending = _start(batches[0]) if batches else None
for next_index in range(1, len(batches) + 1):
current, pending = pending, None
if not conn.alive or (still_wanted is not None and not still_wanted()):
if current is not None:
await current # let the worker finish its writes before returning
break
# pipeline: the next batch is generated while this one is sent
if next_index < len(batches):
pending = _start(batches[next_index])
if current is None:
continue
results = await current
if not conn.alive:
break
await _send_chunk_results_streamed(conn, results)
conn.loaded_chunks.update((cx, cz) for cx, cz, *_ in results)
sent += len(results)
if pending is not None:
await pending
return sent


async def _send_deferred_chunks(conn: Connection, server, chunk_coords, total_count: int):
"""后台发送出生点外圈区块。"""
"""后台发送出生点外圈区块 (由近到远分批生成并发送)。"""
if not conn.alive or not chunk_coords:
return

loop = asyncio.get_event_loop()
start = time.time()

def _generate_deferred():
return server.generate_chunk_results(chunk_coords)[0]

chunk_results = await loop.run_in_executor(None, _generate_deferred)
await _send_chunk_results_streamed(conn, chunk_results)
conn.loaded_chunks.update((cx, cz) for cx, cz, *_ in chunk_results)
center = conn.chunk_center
sent = await _load_and_send_progressively(
conn, server, list(chunk_coords),
still_wanted=lambda: conn.chunk_center == center)
logger.debug(
f"已向 {conn.username} 补发远距离区块 {len(chunk_results)} 个 "
f"已向 {conn.username} 补发远距离区块 {sent} 个 "
f"(总计 {total_count} 个, 用时 {time.time() - start:.1f}s)"
)

Expand Down Expand Up @@ -417,25 +460,22 @@ async def _stream_chunks_around_player(conn: Connection, server):
if not missing_coords:
continue

loop = asyncio.get_event_loop()
start = time.time()
logger.debug(
f"玩家 {conn.username} 进入新区块中心 {center_cx},{center_cz},"
f"正在补发 {len(missing_coords)} 个新区块..."
)

def _generate_missing():
return server.generate_chunk_results(missing_coords)[0]

chunk_results = await loop.run_in_executor(None, _generate_missing)
current = (center_cx, center_cz)
sent = await _load_and_send_progressively(
conn, server, missing_coords,
# moved into another chunk: stop and re-plan around the new center
still_wanted=lambda: (math.floor(conn.x) >> 4, math.floor(conn.z) >> 4) == current)
if not conn.alive:
return

await _send_chunk_results_streamed(conn, chunk_results)
conn.loaded_chunks.update((cx, cz) for cx, cz, *_ in chunk_results)

logger.debug(
f"已向 {conn.username} 动态补发新区块 {len(chunk_results)} 个 "
f"已向 {conn.username} 动态补发新区块 {sent} 个 "
f"(中心={center_cx},{center_cz}, 用时 {time.time() - start:.1f}s)"
)

Expand Down
Loading
Loading