diff --git a/.gitignore b/.gitignore
index 5465697..028faf9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -200,3 +200,10 @@ games/
vcpkg_installed/
.cache/
conan/
+
+# Local build output and test scratch
+dist/
+_test/
+
+# Music (converted from your own FLAC files with tools/convert-music.ps1)
+data/music/*.ogg
diff --git a/CMakeLists.txt b/CMakeLists.txt
index b978db0..df8b711 100755
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -8,6 +8,7 @@ set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
set(CMAKE_POLICY_VERSION_MINIMUM 3.10)
include(cmake/EnumOption.cmake)
+include(cmake/LuaJIT.cmake)
if(EMSCRIPTEN)
# When configuring web builds with "emcmake cmake -B build -S .", set PLATFORM to Web by default
@@ -99,6 +100,16 @@ else()
)
endif()
+if(NOT ${PLATFORM} MATCHES "Web")
+ # single file OGG Vorbis decoder used by the music player
+ CPMAddPackage(
+ NAME "stb"
+ GIT_REPOSITORY "https://github.com/nothings/stb.git"
+ GIT_TAG "a7d4c2175630e1ea5b6f8dd00ab96fed0b97b96d"
+ DOWNLOAD_ONLY YES
+ )
+endif()
+
CPMAddPackage(
NAME "openal"
GIT_REPOSITORY "https://github.com/kcat/openal-soft.git"
@@ -196,6 +207,7 @@ file(GLOB SERVER_SOURCES
"src/world/level/biome/Biome.cpp"
"src/world/level/biome/BiomeSource.cpp"
+ "src/world/level/chunk/ChunkCache.cpp"
"src/world/level/chunk/LevelChunk.cpp"
"src/world/level/dimension/Dimension.cpp"
@@ -217,6 +229,7 @@ file(GLOB SERVER_SOURCES
"src/world/phys/HitResult.cpp"
"src/commands/*.cpp"
+ "src/lua/*.cpp"
)
file(GLOB CLIENT_SOURCES
@@ -302,10 +315,11 @@ file(GLOB CLIENT_SOURCES
"src/main.cpp"
"src/commands/*.cpp"
+ "src/lua/*.cpp"
)
if (${PLATFORM} STREQUAL "Desktop")
- list(APPEND CLIENT_SOURCES glad/src/glad.c)
+ list(APPEND CLIENT_SOURCES glad/src/glad.c "${stb_SOURCE_DIR}/stb_vorbis.c")
endif()
# Server
@@ -318,7 +332,13 @@ target_include_directories("${PROJECT_NAME}-server" PUBLIC
"project/lib_projects/raknet/jni/RaknetSources"
)
-target_link_libraries("${PROJECT_NAME}-server" ${CMAKE_THREAD_LIBS_INIT} ${EXTRA_LIBS})
+target_link_libraries("${PROJECT_NAME}-server" ${CMAKE_THREAD_LIBS_INIT} ${EXTRA_LIBS} luajit)
+
+# Lua API (prelude) and bundled mods are shipped next to the executables
+add_custom_command(TARGET "${PROJECT_NAME}-server" POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/lua" "$/lua"
+ COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/mods" "$/mods"
+)
add_executable(${PROJECT_NAME} ${CLIENT_SOURCES})
@@ -333,6 +353,7 @@ target_include_directories(${PROJECT_NAME} PUBLIC
"${CMAKE_SOURCE_DIR}/src"
"${openal_SOURCE_DIR}/include"
"${glfw_SOURCE_DIR}/include"
+ "${stb_SOURCE_DIR}"
"lib/include"
)
@@ -381,7 +402,7 @@ endif()
# Client
target_compile_definitions(${PROJECT_NAME} PUBLIC "OPENGL_ES" "NO_EGL" ${PLATFORM})
-target_link_libraries(${PROJECT_NAME} zlib ${PNG_LIB} OpenAL::OpenAL glfw ${EXTRA_LIBS})
+target_link_libraries(${PROJECT_NAME} zlib ${PNG_LIB} OpenAL::OpenAL glfw ${EXTRA_LIBS} luajit)
if (OpenSSL_FOUND)
target_link_libraries(${PROJECT_NAME} OpenSSL::SSL OpenSSL::Crypto)
@@ -402,6 +423,8 @@ if(NOT ${PLATFORM} MATCHES "Web")
TARGET ${PROJECT_NAME}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/data" $/data
+ COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/lua" $/lua
+ COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/mods" $/mods
)
else()
add_custom_command(
diff --git a/README.md b/README.md
index 094ec25..9b2fc0c 100644
--- a/README.md
+++ b/README.md
@@ -24,6 +24,25 @@ This project aims to preserve and improve this early version of Minecraft PE.
+
+# This fork: infinite world, Lua mods, WorldEdit, skins, music
+
+- **Infinite world** - chunks are generated, saved (region files `r...dat`, old `chunks.dat` worlds still load) and unloaded around the players. Dedicated server: `view-distance=` in `server.properties` (the old `world-size` is ignored). Multiplayer protocol version is now 10.
+- **Lua mods (LuaJIT)** - drop mods into `mods/`, see [mods/README.md](mods/README.md) for the API (events, commands, world/player access, scheduler).
+- **WorldEdit** - [mods/worldedit](mods/worldedit) is a port of EngineHub's WorldEdit command set to that API (`//wand`, `//set`, `//sphere`, `//copy`, `//paste`, `/undo`, brushes, ...).
+- **Skins** - `data/images/skins/*.png` (64x32 or 64x64). `/skin list`, `/skin ` in the chat console; other players see the skin you pick. Drop a `.png` there to override the skin of that player.
+- **Music** - the `.ogg` files in `data/music` are played in random order (volume: Music slider). Use `tools/convert-music.ps1` to convert your own FLAC/MP3 files.
+
+## Windows build (client + server)
+
+```powershell
+.\package-windows.ps1 # needs Visual Studio 2022 (C++) and CMake
+```
+
+Result: `dist\MinecraftPE-win64` (client) and `dist\MinecraftPE-server-win64` (dedicated server, `start-server.bat`).
+The script limits the compiler parallelism because OpenAL Soft needs a lot of memory (`-Jobs 2` for small machines), and
+trusts the dependency checkouts for git ("dubious ownership" on drives that do not store file owners).
+
# Build
## CMake
diff --git a/cmake/LuaJIT.cmake b/cmake/LuaJIT.cmake
new file mode 100644
index 0000000..5d1f4c0
--- /dev/null
+++ b/cmake/LuaJIT.cmake
@@ -0,0 +1,70 @@
+# Builds LuaJIT (static) from source and exposes it as the imported target "luajit".
+#
+# * MSVC: runs LuaJIT's own msvcbuild.bat inside the matching Visual Studio environment
+# * others: runs LuaJIT's Makefile (make / mingw32-make)
+
+CPMAddPackage(
+ NAME "luajit"
+ GIT_REPOSITORY "https://github.com/LuaJIT/LuaJIT.git"
+ GIT_TAG "dd3b24369ddfaa83c78cd6fdd91d157c8968ec8d"
+ DOWNLOAD_ONLY YES
+)
+
+set(LUAJIT_SRC "${luajit_SOURCE_DIR}/src")
+
+if (MSVC)
+ set(LUAJIT_LIB "${LUAJIT_SRC}/lua51.lib")
+
+ # /VC/Tools/MSVC//bin/Hostx64/x64/cl.exe -> /VC/Auxiliary/Build/vcvarsall.bat
+ get_filename_component(_cl_dir "${CMAKE_C_COMPILER}" DIRECTORY)
+ get_filename_component(_vc_root "${_cl_dir}/../../../../../.." ABSOLUTE)
+ set(_vcvars "${_vc_root}/Auxiliary/Build/vcvarsall.bat")
+ if (NOT EXISTS "${_vcvars}")
+ message(FATAL_ERROR "vcvarsall.bat not found at ${_vcvars}")
+ endif()
+
+ if (CMAKE_SIZEOF_VOID_P EQUAL 8)
+ set(_vcarch x64)
+ else()
+ set(_vcarch x86)
+ endif()
+
+ file(TO_NATIVE_PATH "${_vcvars}" _vcvars_native)
+ file(TO_NATIVE_PATH "${LUAJIT_SRC}" _src_native)
+ file(TO_NATIVE_PATH "${CMAKE_BINARY_DIR}/build_luajit.bat" _bat_native)
+
+ # LuaJIT needs the Visual Studio command line environment, so run it from a batch file
+ # (msvcbuild.bat runs the tools it just built by bare name, which needs the current directory in the search path)
+ set(_bat "@echo off\r\nset NoDefaultCurrentDirectoryInExePath=\r\n")
+ string(APPEND _bat "call \"${_vcvars_native}\" ${_vcarch} || exit /b 1\r\n")
+ string(APPEND _bat "cd /d \"${_src_native}\" || exit /b 1\r\n")
+ string(APPEND _bat "call .\\msvcbuild.bat static || exit /b 1\r\n")
+ file(WRITE "${CMAKE_BINARY_DIR}/build_luajit.bat" "${_bat}")
+
+ add_custom_command(
+ OUTPUT "${LUAJIT_LIB}"
+ COMMAND cmd /c "${_bat_native}"
+ WORKING_DIRECTORY "${LUAJIT_SRC}"
+ COMMENT "Building LuaJIT"
+ VERBATIM
+ )
+else()
+ set(LUAJIT_LIB "${LUAJIT_SRC}/libluajit.a")
+ find_program(_make NAMES make gmake mingw32-make REQUIRED)
+ add_custom_command(
+ OUTPUT "${LUAJIT_LIB}"
+ COMMAND "${_make}" BUILDMODE=static
+ WORKING_DIRECTORY "${LUAJIT_SRC}"
+ COMMENT "Building LuaJIT"
+ VERBATIM
+ )
+endif()
+
+add_custom_target(luajit_build DEPENDS "${LUAJIT_LIB}")
+
+add_library(luajit STATIC IMPORTED GLOBAL)
+set_target_properties(luajit PROPERTIES
+ IMPORTED_LOCATION "${LUAJIT_LIB}"
+ INTERFACE_INCLUDE_DIRECTORIES "${LUAJIT_SRC}"
+)
+add_dependencies(luajit luajit_build)
diff --git a/data/images/skins/blonde.png b/data/images/skins/blonde.png
new file mode 100644
index 0000000..aef7319
Binary files /dev/null and b/data/images/skins/blonde.png differ
diff --git a/data/images/skins/green.png b/data/images/skins/green.png
new file mode 100644
index 0000000..7a9b1fe
Binary files /dev/null and b/data/images/skins/green.png differ
diff --git a/data/images/skins/ninja.png b/data/images/skins/ninja.png
new file mode 100644
index 0000000..9976e3a
Binary files /dev/null and b/data/images/skins/ninja.png differ
diff --git a/data/images/skins/orange.png b/data/images/skins/orange.png
new file mode 100644
index 0000000..8f9ab49
Binary files /dev/null and b/data/images/skins/orange.png differ
diff --git a/data/images/skins/pink.png b/data/images/skins/pink.png
new file mode 100644
index 0000000..9df5556
Binary files /dev/null and b/data/images/skins/pink.png differ
diff --git a/data/images/skins/purple.png b/data/images/skins/purple.png
new file mode 100644
index 0000000..e068bc2
Binary files /dev/null and b/data/images/skins/purple.png differ
diff --git a/data/images/skins/red.png b/data/images/skins/red.png
new file mode 100644
index 0000000..adde5ca
Binary files /dev/null and b/data/images/skins/red.png differ
diff --git a/data/images/skins/snow.png b/data/images/skins/snow.png
new file mode 100644
index 0000000..1a5b305
Binary files /dev/null and b/data/images/skins/snow.png differ
diff --git a/data/images/skins/steve.png b/data/images/skins/steve.png
new file mode 100644
index 0000000..555fb11
Binary files /dev/null and b/data/images/skins/steve.png differ
diff --git a/data/images/skins/yellow.png b/data/images/skins/yellow.png
new file mode 100644
index 0000000..66692d9
Binary files /dev/null and b/data/images/skins/yellow.png differ
diff --git a/lua/prelude.lua b/lua/prelude.lua
new file mode 100644
index 0000000..fb6483c
--- /dev/null
+++ b/lua/prelude.lua
@@ -0,0 +1,404 @@
+-- ============================================================================
+-- MinecraftPE Lua API (LuaJIT)
+-- This file is loaded by the game before any mod. It builds the friendly
+-- `mc` API on top of the native primitives (mc._*) that the game provides.
+-- Documentation: mods/README.md
+-- ============================================================================
+
+local mc = mc
+mc.VERSION = "1.0"
+
+local floor, max, min = math.floor, math.max, math.min
+
+-- ---------------------------------------------------------------- utilities
+mc.util = {}
+
+function mc.util.split(s, sep)
+ local out = {}
+ sep = sep or "%s+"
+ for piece in string.gmatch(s, "([^" .. (sep == "%s+" and "%s" or sep) .. "]+)") do
+ out[#out + 1] = piece
+ end
+ return out
+end
+
+function mc.util.copy(t)
+ local c = {}
+ for k, v in pairs(t) do c[k] = v end
+ return c
+end
+
+local function serialize(v, indent)
+ local t = type(v)
+ if t == "number" or t == "boolean" then return tostring(v) end
+ if t == "string" then return string.format("%q", v) end
+ if t == "table" then
+ local parts = {}
+ for k, val in pairs(v) do
+ parts[#parts + 1] = "[" .. serialize(k) .. "]=" .. serialize(val)
+ end
+ return "{" .. table.concat(parts, ",") .. "}"
+ end
+ return "nil"
+end
+
+--- Saves a plain Lua table (numbers, strings, booleans, tables) to a file.
+function mc.save_table(path, tbl)
+ local f, err = io.open(path, "w")
+ if not f then return false, err end
+ f:write("return ", serialize(tbl))
+ f:close()
+ return true
+end
+
+--- Loads a table written by mc.save_table, or returns `default`.
+function mc.load_table(path, default)
+ local chunk = loadfile(path)
+ if not chunk then return default end
+ setfenv(chunk, {})
+ local ok, res = pcall(chunk)
+ if ok then return res end
+ return default
+end
+
+function mc.log(...)
+ local parts = {}
+ for i = 1, select("#", ...) do parts[i] = tostring((select(i, ...))) end
+ mc._log(table.concat(parts, " "))
+end
+
+-- ------------------------------------------------------------------ blocks
+local BLOCKS = {
+ [0] = "air", [1] = "stone", [2] = "grass", [3] = "dirt", [4] = "cobblestone", [5] = "planks",
+ [6] = "sapling", [7] = "bedrock", [8] = "flowing_water", [9] = "water", [10] = "flowing_lava",
+ [11] = "lava", [12] = "sand", [13] = "gravel", [14] = "gold_ore", [15] = "iron_ore",
+ [16] = "coal_ore", [17] = "log", [18] = "leaves", [20] = "glass", [21] = "lapis_ore",
+ [22] = "lapis_block", [24] = "sandstone", [26] = "bed", [30] = "cobweb", [31] = "tallgrass",
+ [35] = "wool", [37] = "dandelion", [38] = "rose", [39] = "brown_mushroom", [40] = "red_mushroom",
+ [41] = "gold_block", [42] = "iron_block", [43] = "double_slab", [44] = "slab", [45] = "bricks",
+ [46] = "tnt", [47] = "bookshelf", [48] = "mossy_cobblestone", [49] = "obsidian", [50] = "torch",
+ [51] = "fire", [53] = "oak_stairs", [54] = "chest", [56] = "diamond_ore", [57] = "diamond_block",
+ [58] = "crafting_table", [59] = "wheat", [60] = "farmland", [61] = "furnace", [62] = "lit_furnace",
+ [63] = "sign", [64] = "wooden_door", [65] = "ladder", [67] = "stone_stairs", [68] = "wall_sign",
+ [71] = "iron_door", [73] = "redstone_ore", [74] = "lit_redstone_ore", [78] = "snow_layer",
+ [79] = "ice", [80] = "snow", [81] = "cactus", [82] = "clay", [83] = "reeds", [85] = "fence",
+ [86] = "pumpkin", [87] = "netherrack", [89] = "glowstone", [91] = "jack_o_lantern",
+ [96] = "trapdoor", [98] = "stonebrick", [102] = "glass_pane", [103] = "melon", [105] = "melon_stem",
+ [107] = "fence_gate", [108] = "brick_stairs", [109] = "stonebrick_stairs", [112] = "nether_brick",
+ [114] = "nether_brick_stairs", [128] = "sandstone_stairs", [129] = "emerald_ore",
+ [133] = "emerald_block", [155] = "quartz_block", [156] = "quartz_stairs", [245] = "stonecutter",
+ [246] = "glowing_obsidian", [247] = "nether_reactor",
+}
+
+local ALIASES = {
+ rock = 1, smooth_stone = 1, grass_block = 2, cobble = 4, wood = 5, wood_planks = 5, oak_planks = 5,
+ planks = 5, sapling = 6, adminium = 7, bed_rock = 7, water = 9, still_water = 9, stationary_water = 9,
+ lava = 11, still_lava = 11, stationary_lava = 11, flowing_water = 8, flowing_lava = 10,
+ gold = 14, iron = 15, coal = 16, trunk = 17, tree = 17, wood_log = 17, oak_log = 17, leaf = 18,
+ leaves = 18, lapis = 21, sandstone = 24, web = 30, grass_plant = 31, cloth = 35, flower = 37,
+ yellow_flower = 37, red_flower = 38, goldblock = 41, ironblock = 42, brick = 45, bricks = 45,
+ mossy = 48, mossy_cobble = 48, moss = 48, obsidian = 49, torch = 50, fire = 51, chest = 54,
+ diamond = 56, workbench = 58, crafting = 58, table = 58, furnace = 61, ladder = 65, ice = 79,
+ snowblock = 80, snow_block = 80, cactus = 81, clay = 82, sugarcane = 83, fence = 85, glowstone = 89,
+ lightstone = 89, netherrack = 87, hell = 87, stonebricks = 98, stone_brick = 98, stone_bricks = 98,
+ melon = 103, quartz = 155, door = 64, iron_door = 71, tnt = 46, bookshelf = 47, books = 47,
+ glass = 20, sand = 12, gravel = 13, dirt = 3, stone = 1, grass = 2, bedrock = 7,
+ pane = 102, trap_door = 96, pumpkin = 86, lantern = 91, stair = 53, stairs = 53, double_step = 43,
+ step = 44, half_slab = 44, slab = 44, double_slab = 43, farmland = 60, soil = 60,
+}
+
+local WOOL = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray",
+ "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" }
+local WOOL_DATA = {}
+for i, name in ipairs(WOOL) do
+ WOOL_DATA[name] = i - 1
+ ALIASES[name .. "_wool"] = { 35, i - 1 }
+end
+
+local NAME_TO_ID = {}
+for id, name in pairs(BLOCKS) do NAME_TO_ID[name] = id end
+
+mc.block = { ids = NAME_TO_ID, names = BLOCKS }
+
+--- Name of a block id ("stone"), or the number as a string.
+function mc.block.name(id)
+ return BLOCKS[id] or tostring(id)
+end
+
+--- Parses "stone", "35:14", "red_wool", "log:1" -> id, data (data is nil when not given)
+function mc.block.parse(text)
+ text = string.lower(text)
+ local nameOrId, data = string.match(text, "^([%w_]+):(%d+)$")
+ if nameOrId then data = tonumber(data) else nameOrId = text end
+ local id = tonumber(nameOrId)
+ if not id then
+ local alias = ALIASES[nameOrId]
+ if type(alias) == "table" then
+ id, data = alias[1], data or alias[2]
+ else
+ id = alias or NAME_TO_ID[nameOrId]
+ end
+ end
+ if not id or id < 0 or id > 255 then return nil end
+ return id, data
+end
+
+-- Blocks that are not solid ground (used by e.g. //green, //naturalize, //ascend)
+mc.block.AIR = 0
+
+-- ------------------------------------------------------------------- items
+mc.item = {
+ stick = 280, compass = 345, wooden_axe = 271, wooden_pickaxe = 270, wooden_shovel = 269,
+ wooden_sword = 268, stone_axe = 275, iron_axe = 258, diamond_axe = 279, flint_and_steel = 259,
+ apple = 260, bow = 261, arrow = 262, coal = 263, diamond = 264, iron_ingot = 265, gold_ingot = 266,
+ bucket = 325, water_bucket = 326, lava_bucket = 327, clock = 347, paper = 339, book = 340,
+}
+
+mc.mob = { chicken = 10, cow = 11, pig = 12, sheep = 13, zombie = 32, creeper = 33,
+ skeleton = 34, spider = 35, pig_zombie = 36 }
+
+-- ------------------------------------------------------------------ players
+local Player = {}
+Player.__index = Player
+local playerCache = {}
+
+local function getPlayer(id)
+ if not id then return nil end
+ local p = playerCache[id]
+ if not p then
+ local name = mc._pname(id)
+ if not name then return nil end
+ p = setmetatable({ id = id, name = name, data = {} }, Player)
+ playerCache[id] = p
+ end
+ return p
+end
+mc._player = getPlayer
+
+function Player:__tostring() return "Player(" .. self.name .. ")" end
+
+--- Feet position: x, y, z
+function Player:pos() local x, y, z = mc._ppos(self.id); return x, y, z end
+--- Block the feet are in
+function Player:block_pos()
+ local x, y, z = mc._ppos(self.id)
+ return floor(x), floor(y), floor(z)
+end
+--- yaw, pitch in degrees
+function Player:look() local _, _, _, yaw, pitch = mc._ppos(self.id); return yaw, pitch end
+--- Horizontal facing as 0..3 (south, west, north, east) and its unit vector
+function Player:facing()
+ local yaw = self:look()
+ local dir = floor(((yaw % 360) + 45) / 90) % 4
+ local vec = { [0] = { 0, 1 }, [1] = { -1, 0 }, [2] = { 0, -1 }, [3] = { 1, 0 } }
+ return dir, vec[dir][1], vec[dir][2]
+end
+function Player:teleport(x, y, z, yaw, pitch) mc._pteleport(self.id, x, y, z, yaw, pitch) end
+function Player:say(...)
+ local parts = {}
+ for i = 1, select("#", ...) do parts[i] = tostring((select(i, ...))) end
+ local text = table.concat(parts, " ")
+ for line in string.gmatch(text .. "\n", "(.-)\n") do
+ if line ~= "" then mc._pmsg(self.id, line) end
+ end
+end
+function Player:is_op() return mc._pop(self.id) end
+--- id, data, count of the held item (0,0,0 when empty)
+function Player:held() return mc._pheld(self.id) end
+function Player:give(id, count, data) mc._pgive(self.id, id, count or 1, data or 0) end
+--- 0 = survival, 1 = creative
+function Player:gamemode() return mc._pgamemode() end
+--- x, y, z, face of the block the player is looking at, or nil
+function Player:target(distance) return mc._ptrace(self.id, distance or 128) end
+function Player:is_online() return mc._pname(self.id) ~= nil end
+
+mc.Player = Player
+
+function mc.players()
+ local list = {}
+ for i, id in ipairs(mc._players()) do list[i] = getPlayer(id) end
+ return list
+end
+
+function mc.player(name)
+ name = string.lower(name)
+ for _, id in ipairs(mc._players()) do
+ local p = getPlayer(id)
+ if p and string.lower(p.name) == name then return p end
+ end
+ return nil
+end
+
+function mc.broadcast(text) mc._broadcast(text) end
+
+-- -------------------------------------------------------------------- world
+mc.world = {}
+local W = mc.world
+
+W.get_block = mc._get_block
+W.set_block = mc._set_block
+--- Re-sends/relights everything written with silent set_block calls
+W.flush = mc._flush
+W.is_loaded = mc._loaded
+W.ensure_loaded = mc._ensure
+W.seed = mc._seed
+W.explode = mc._explode
+W.spawn_mob = mc._spawn_mob
+W.drop_item = mc._drop_item
+W.butcher = mc._butcher
+W.height = mc._solid_height
+W.get_time = mc._get_time
+W.set_time = mc._set_time
+
+-- ---------------------------------------------------------------- scheduler
+local tasks, nextTask, tickCount = {}, 1, 0
+mc.tick_count = 0
+
+function mc.after(ticks, fn)
+ local id = nextTask; nextTask = nextTask + 1
+ tasks[id] = { at = tickCount + max(1, ticks), fn = fn }
+ return id
+end
+
+function mc.every(ticks, fn)
+ local id = nextTask; nextTask = nextTask + 1
+ tasks[id] = { at = tickCount + max(1, ticks), fn = fn, period = max(1, ticks) }
+ return id
+end
+
+function mc.cancel(id) tasks[id] = nil end
+
+-- ------------------------------------------------------------------- events
+local handlers = {}
+
+--- mc.on("block_break", function(player, x, y, z, tile) return false end)
+--- Events: start, stop, tick, join, leave, chat, block_break, use_item
+--- Returning false from a cancellable event (chat, block_break, use_item) cancels it.
+function mc.on(event, fn)
+ handlers[event] = handlers[event] or {}
+ table.insert(handlers[event], fn)
+end
+
+local function report(modName, err)
+ mc._log("error in handler: " .. tostring(err))
+end
+
+function mc._fire(event, pid, ...)
+ local list = handlers[event]
+ if not list then return true end
+ local first = pid
+ if pid ~= nil then first = getPlayer(pid) end
+ local result = true
+ for i = 1, #list do
+ local ok, res = xpcall(list[i], debug.traceback, first, ...)
+ if not ok then
+ report(nil, res)
+ elseif res == false then
+ result = false
+ end
+ end
+ if event == "leave" and pid then playerCache[pid] = nil end
+ return result
+end
+
+function mc._tick()
+ tickCount = tickCount + 1
+ mc.tick_count = tickCount
+ for id, task in pairs(tasks) do
+ if task.at <= tickCount then
+ if task.period then task.at = tickCount + task.period else tasks[id] = nil end
+ local ok, err = xpcall(task.fn, debug.traceback)
+ if not ok then report(nil, err) end
+ end
+ end
+ if handlers.tick then mc._fire("tick") end
+end
+
+-- ----------------------------------------------------------------- commands
+local commands = {}
+
+--- mc.command("home", { description = "...", usage = "/home", op = false }, function(ctx) ... end)
+--- Names are what the player types after the first slash, so WorldEdit's "//set" is "/set".
+function mc.command(name, opts, fn)
+ if type(opts) == "function" then fn, opts = opts, {} end
+ commands[string.lower(name)] = { fn = fn, opts = opts or {}, name = name }
+end
+
+function mc._command_names()
+ local names = {}
+ for name in pairs(commands) do names[#names + 1] = name end
+ table.sort(names)
+ return names
+end
+
+function mc._run_command(pid, name, args)
+ local cmd = commands[string.lower(name)]
+ if not cmd then return false end
+ local player = getPlayer(pid)
+ if cmd.opts.op and not player:is_op() then
+ return true, "You are not allowed to use this command."
+ end
+ local replies = {}
+ local ctx = {
+ player = player, args = args, name = name,
+ reply = function(_, ...) player:say(...) end,
+ }
+ setmetatable(ctx, { __index = function(_, k) return nil end })
+ local ok, res = xpcall(cmd.fn, debug.traceback, ctx)
+ if not ok then
+ mc._log("command /" .. name .. " failed: " .. tostring(res))
+ return true, "Command failed: " .. tostring(res):match("^[^\n]*")
+ end
+ if type(res) == "string" then return true, res end
+ return true
+end
+
+-- ------------------------------------------------------------------- mods
+mc.mods = {}
+
+local function listDir(dir)
+ return mc._listdir and mc._listdir(dir) or {}
+end
+
+local function loadMod(name, dir, file)
+ local env = setmetatable({}, { __index = _G })
+ env.MOD = { name = name, dir = dir }
+ env.require = function(m)
+ local path = dir .. "/" .. m:gsub("%.", "/") .. ".lua"
+ local chunk = loadfile(path)
+ if chunk then
+ setfenv(chunk, env)
+ return chunk()
+ end
+ return require(m)
+ end
+ local chunk, err = loadfile(file)
+ if not chunk then
+ mc._log("cannot load mod '" .. name .. "': " .. tostring(err))
+ return
+ end
+ setfenv(chunk, env)
+ local ok, res = xpcall(chunk, debug.traceback)
+ if not ok then
+ mc._log("mod '" .. name .. "' failed: " .. tostring(res))
+ return
+ end
+ mc.mods[name] = env.MOD
+ mc._log("loaded mod '" .. name .. "'")
+end
+
+function mc._load_mods()
+ local entries = listDir("mods")
+ table.sort(entries, function(a, b) return a.name < b.name end)
+ for _, e in ipairs(entries) do
+ if e.dir then
+ local main = "mods/" .. e.name .. "/main.lua"
+ local f = io.open(main, "r")
+ if f then f:close(); loadMod(e.name, "mods/" .. e.name, main) end
+ elseif e.name:match("%.lua$") then
+ loadMod((e.name:gsub("%.lua$", "")), "mods", "mods/" .. e.name)
+ end
+ end
+ mc._fire("start")
+ for _, id in ipairs(mc._players()) do mc._fire("join", id) end
+end
diff --git a/mods/README.md b/mods/README.md
new file mode 100644
index 0000000..a083123
--- /dev/null
+++ b/mods/README.md
@@ -0,0 +1,120 @@
+# Lua mods (LuaJIT)
+
+The game embeds **LuaJIT 2.1**. Mods run on the machine that hosts the world:
+the dedicated server (`MinecraftPE-server.exe`), a single player world, or a
+client that hosts a LAN game. A client that only joins a server runs no mods.
+
+```
+mods/
+ my_mod/
+ main.lua <- loaded at startup (alphabetical order)
+ other.lua <- require("other")
+ tiny.lua <- a single file mod works too
+```
+
+Every mod runs in its own environment (`MOD.name`, `MOD.dir` describe it), so
+globals do not leak between mods. `require("x")` loads `mods//x.lua` first.
+The full Lua 5.1 standard library, `io`, `os`, `bit` and `ffi` are available –
+mods are trusted code, only install mods you trust.
+
+## Events
+
+```lua
+mc.on("start", function() end) -- all mods loaded, world is up
+mc.on("stop", function() end)
+mc.on("tick", function() end) -- 20 times per second
+mc.on("join", function(player) end)
+mc.on("leave", function(player) end)
+mc.on("chat", function(player, message) end) -- return false to cancel
+mc.on("block_break", function(player, x, y, z, tile) end)-- return false to cancel
+mc.on("use_item", function(player, x, y, z, face, itemId, itemData) end) -- right click on a block, false cancels
+```
+
+## Commands
+
+```lua
+mc.command("home", { description = "Go home", op = false }, function(ctx)
+ ctx.player:teleport(0, 70, 0)
+ return "Welcome home!" -- a returned string is sent to the player
+end)
+```
+
+`ctx` has `player`, `args` (array of strings) and `name`. Names are what is typed
+after the first slash: `mc.command("/set", ...)` is `//set` in game. `op = true`
+restricts the command to operators (`ops.txt`).
+
+## Players
+
+`mc.players()`, `mc.player("name")`, `mc.broadcast(text)`
+
+| method | |
+|---|---|
+| `p.name`, `p.id`, `p.data` | `data` is a free table for your mod |
+| `p:pos()` → x, y, z | feet position |
+| `p:block_pos()` → x, y, z | integer block of the feet |
+| `p:look()` → yaw, pitch | |
+| `p:facing()` → 0..3, dx, dz | south, west, north, east |
+| `p:teleport(x, y, z [, yaw, pitch])` | |
+| `p:say(text)` | private message |
+| `p:is_op()` | |
+| `p:held()` → id, data, count | |
+| `p:give(id [, count [, data]])` | |
+| `p:target([distance])` → x, y, z, face | block in the crosshair |
+| `p:gamemode()` | 0 survival, 1 creative |
+
+## World
+
+```lua
+mc.world.get_block(x, y, z) -- id, data
+mc.world.set_block(x, y, z, id, data) -- normal change (updates neighbours, notifies clients)
+mc.world.set_block(x, y, z, id, data, true) -- "silent": no updates; call mc.world.flush() afterwards
+mc.world.flush() -- relight + resend every chunk touched by silent writes
+mc.world.height(x, z) -- highest solid block, -1 if none
+mc.world.is_loaded(x, z) -- block coordinates
+mc.world.ensure_loaded(x, z, radiusInChunks)
+mc.world.spawn_mob(mc.mob.pig, x, y, z) -- returns entity id
+mc.world.drop_item(id, count, data, x, y, z)
+mc.world.explode(x, y, z, radius)
+mc.world.butcher(x, y, z, radius, includeFriendly) -- radius 0 = everywhere, returns count
+mc.world.get_time() / set_time(t) / seed()
+```
+
+The world is infinite: chunks around players are generated, saved and unloaded
+on demand. Use `ensure_loaded` before touching far-away coordinates.
+
+## Names and ids
+
+`mc.block.parse("stone")`, `mc.block.parse("35:14")`, `mc.block.parse("red_wool")` → id, data
+`mc.block.name(id)`, `mc.item.wooden_axe`, `mc.mob.zombie`, …
+
+## Scheduler and utilities
+
+```lua
+local id = mc.after(40, function() ... end) -- ticks
+mc.every(20, function() ... end)
+mc.cancel(id)
+mc.log("text")
+mc.save_table("mods/data/x.lua", tbl) / mc.load_table(path, default)
+```
+
+# Bundled mods
+
+* **worldedit** – a port of EngineHub's WorldEdit command set (see below).
+* **hello** – the smallest possible example.
+
+## WorldEdit
+
+Give yourself the wand with `//wand` (a wooden axe): left click = position 1,
+right click = position 2. Operators only. Implemented commands:
+
+`//wand //pos1 //pos2 //hpos1 //hpos2 //chunk //sel //expand //contract //shift //outset //inset //trim //size //count //distr`
+`//set //replace //overlay //center //naturalize //walls //faces //hollow //smooth //move //stack //line`
+`//sphere //hsphere //cyl //hcyl //cone //pyramid //hpyramid`
+`//copy //cut //paste //rotate //flip /clearclipboard /schematic save|load|list|delete`
+`/undo /redo /clearhistory //fill //fillr //drain /fixwater /fixlava /removeabove /removebelow /removenear /replacenear`
+`/snow /thaw /green /extinguish /butcher //limit /toggleplace /we`
+`/unstuck /ascend /descend /ceil /thru /jumpto /up`
+`/tool (repl, info, farwand, navwand, selwand, deltree, floodfill, none) /brush (sphere, cylinder, set, smooth, raise, lower, gravity, extinguish, butcher) /mask /material /range /size // /sp`
+
+Patterns: `stone`, `35:14`, `red_wool`, `50%stone,50%dirt`. Masks: `stone,dirt`, `!air`,
+`#existing`, `#solid`. Flags work like in the original (`//sphere -h stone 5`).
diff --git a/mods/hello.lua b/mods/hello.lua
new file mode 100644
index 0000000..1f4a9bb
--- /dev/null
+++ b/mods/hello.lua
@@ -0,0 +1,22 @@
+-- The smallest mod: greets players and adds /hello and /where.
+
+mc.on("join", function(player)
+ player:say("Welcome, " .. player.name .. "! Lua mods are running on this world.")
+end)
+
+mc.command("hello", { description = "Say hello" }, function(ctx)
+ return "Hello, " .. ctx.player.name .. "!"
+end)
+
+mc.command("where", { description = "Show your coordinates" }, function(ctx)
+ local x, y, z = ctx.player:block_pos()
+ return string.format("You are at %d, %d, %d", x, y, z)
+end)
+
+mc.command("tp", { description = "Teleport: /tp ", usage = "/tp ", op = true }, function(ctx)
+ local x, y, z = tonumber(ctx.args[1]), tonumber(ctx.args[2]), tonumber(ctx.args[3])
+ if not (x and y and z) then return "Usage: /tp (y = 0 puts you on the ground)" end
+ if y <= 0 then mc.world.ensure_loaded(x, z, 1); y = mc.world.height(math.floor(x), math.floor(z)) + 1 end
+ ctx.player:teleport(x + 0.5, y, z + 0.5)
+ return string.format("Teleported to %d, %d, %d", x, y, z)
+end)
diff --git a/mods/worldedit/lib.lua b/mods/worldedit/lib.lua
new file mode 100644
index 0000000..3d6ecce
--- /dev/null
+++ b/mods/worldedit/lib.lua
@@ -0,0 +1,450 @@
+-- WorldEdit for MinecraftPE: core library
+-- (edit sessions, patterns, masks, region helpers, shapes, history)
+
+local L = {}
+
+local floor, ceil, abs, min, max, sqrt = math.floor, math.ceil, math.abs, math.min, math.max, math.sqrt
+local get_block, set_block = mc.world.get_block, mc.world.set_block
+
+L.DEFAULT_LIMIT = 5000000
+
+-- =========================================================== player sessions
+local sessions = {}
+
+function L.session(player)
+ local s = sessions[player.name]
+ if not s then
+ s = {
+ pos1 = nil, pos2 = nil,
+ clipboard = nil,
+ undo = {}, redo = {},
+ limit = L.DEFAULT_LIMIT,
+ tools = {}, -- item id -> { type = "repl"/"info"/"brush"/..., ... }
+ superpick = nil, -- nil | "single" | "area" | "recursive"
+ superpick_range = 3,
+ brush_size = 5, brush_mask = nil, brush_material = nil, brush_range = 200,
+ selector = "cuboid",
+ }
+ sessions[player.name] = s
+ end
+ return s
+end
+
+-- ================================================================== helpers
+function L.region(s)
+ if not s.pos1 or not s.pos2 then return nil end
+ local a, b = s.pos1, s.pos2
+ return {
+ x0 = min(a[1], b[1]), y0 = min(a[2], b[2]), z0 = min(a[3], b[3]),
+ x1 = max(a[1], b[1]), y1 = max(a[2], b[2]), z1 = max(a[3], b[3]),
+ }
+end
+
+function L.volume(r)
+ return (r.x1 - r.x0 + 1) * (r.y1 - r.y0 + 1) * (r.z1 - r.z0 + 1)
+end
+
+local function clampY(y) return max(0, min(127, y)) end
+L.clampY = clampY
+
+--- Loads every chunk the region touches.
+function L.load_region(r)
+ for cx = floor(r.x0 / 16), floor(r.x1 / 16) do
+ for cz = floor(r.z0 / 16), floor(r.z1 / 16) do
+ mc.world.ensure_loaded(cx * 16 + 8, cz * 16 + 8, 0)
+ end
+ end
+end
+
+local DIRS = {
+ up = { 0, 1, 0 }, u = { 0, 1, 0 }, down = { 0, -1, 0 }, d = { 0, -1, 0 },
+ north = { 0, 0, -1 }, n = { 0, 0, -1 }, south = { 0, 0, 1 }, s = { 0, 0, 1 },
+ east = { 1, 0, 0 }, e = { 1, 0, 0 }, west = { -1, 0, 0 }, w = { -1, 0, 0 },
+}
+
+--- Direction word -> unit vector. "me"/nil = where the player looks (incl. up/down)
+function L.direction(player, word)
+ word = word and string.lower(word)
+ if word and DIRS[word] then return DIRS[word] end
+ local yaw, pitch = player:look()
+ if pitch < -50 then return DIRS.up end
+ if pitch > 50 then return DIRS.down end
+ local _, dx, dz = player:facing()
+ return { dx, 0, dz }
+end
+
+--- Splits "-abc foo 5 -p 2" into flags and positional arguments.
+--- `valued` is a set of flags that take a value: { p = true }
+function L.parse(args, valued)
+ local flags, pos = {}, {}
+ local i = 1
+ while i <= #args do
+ local a = args[i]
+ if a:match("^%-%a+$") and not tonumber(a) then
+ for ch in a:sub(2):gmatch(".") do
+ if valued and valued[ch] then
+ i = i + 1
+ flags[ch] = args[i]
+ else
+ flags[ch] = true
+ end
+ end
+ else
+ pos[#pos + 1] = a
+ end
+ i = i + 1
+ end
+ return flags, pos
+end
+
+-- ================================================================== patterns
+-- "stone" "5%stone,5%dirt:1,air" "35:14"
+function L.pattern(text)
+ if not text or text == "" then return nil, "No pattern given." end
+ local entries, total = {}, 0
+ for part in text:gmatch("[^,]+") do
+ local weight, spec = part:match("^([%d%.]+)%%(.+)$")
+ weight = tonumber(weight) or 1
+ spec = spec or part
+ local id, data = mc.block.parse(spec)
+ if not id then return nil, "Unknown block: " .. spec end
+ entries[#entries + 1] = { id = id, data = data, w = weight }
+ total = total + weight
+ end
+ if #entries == 1 then
+ local e = entries[1]
+ return function() return e.id, e.data end, entries[1]
+ end
+ return function()
+ local r = math.random() * total
+ for _, e in ipairs(entries) do
+ r = r - e.w
+ if r <= 0 then return e.id, e.data end
+ end
+ local e = entries[#entries]
+ return e.id, e.data
+ end
+end
+
+-- masks: "stone" "stone,dirt" "!air" "#existing" "#solid"
+function L.mask(text)
+ if not text or text == "" then return nil end
+ local negate = false
+ if text:sub(1, 1) == "!" then negate = true; text = text:sub(2) end
+ local test
+ if text == "#existing" then
+ test = function(id) return id ~= 0 end
+ elseif text == "#solid" then
+ test = function(id) return id ~= 0 and id ~= 8 and id ~= 9 and id ~= 10 and id ~= 11 end
+ elseif text == "#air" then
+ test = function(id) return id == 0 end
+ else
+ local set = {}
+ for part in text:gmatch("[^,]+") do
+ local id, data = mc.block.parse(part)
+ if not id then return nil, "Unknown block: " .. part end
+ set[#set + 1] = { id, data }
+ end
+ test = function(id, data)
+ for _, e in ipairs(set) do
+ if e[1] == id and (e[2] == nil or e[2] == data) then return true end
+ end
+ return false
+ end
+ end
+ if negate then return function(id, data) return not test(id, data) end end
+ return test
+end
+
+-- ============================================================== edit sessions
+local Edit = {}
+Edit.__index = Edit
+
+function L.new_edit(session)
+ return setmetatable({ s = session, entries = {}, index = {}, count = 0, limit = session.limit }, Edit)
+end
+
+local OFFSET = 1000000
+
+--- Sets a block (recording the old one for undo). Returns true when something changed.
+function Edit:set(x, y, z, id, data)
+ if y < 0 or y > 127 then return false end
+ data = data or 0
+ local oid, od = get_block(x, y, z)
+ if oid == id and od == data then return false end
+ if self.limit >= 0 and self.count >= self.limit then
+ self.overflow = true
+ return false
+ end
+ if not self.bx then self.bx, self.bz = x, z end
+ local key = ((x - self.bx + OFFSET) * 4000000 + (z - self.bz + OFFSET)) * 128 + y
+ local e = self.index[key]
+ if not e then
+ e = { x, y, z, oid, od, id, data }
+ self.index[key] = e
+ self.entries[#self.entries + 1] = e
+ else
+ e[6], e[7] = id, data
+ end
+ self.count = self.count + 1
+ set_block(x, y, z, id, data, true)
+ return true
+end
+
+function Edit:get(x, y, z)
+ return get_block(x, y, z)
+end
+
+--- Writes the pattern into the block
+function Edit:place(x, y, z, pattern)
+ local id, data = pattern()
+ return self:set(x, y, z, id, data)
+end
+
+--- Finishes the edit: relights/resends the touched chunks and stores it in the history
+function Edit:commit()
+ mc.world.flush()
+ if #self.entries > 0 then
+ local undo = self.s.undo
+ undo[#undo + 1] = self.entries
+ if #undo > 40 then table.remove(undo, 1) end
+ self.s.redo = {}
+ end
+ return #self.entries
+end
+
+local function apply_history(entries, reverse)
+ local changed = 0
+ if reverse then
+ for i = #entries, 1, -1 do
+ local e = entries[i]
+ set_block(e[1], e[2], e[3], e[4], e[5], true)
+ changed = changed + 1
+ end
+ else
+ for i = 1, #entries do
+ local e = entries[i]
+ set_block(e[1], e[2], e[3], e[6], e[7], true)
+ changed = changed + 1
+ end
+ end
+ mc.world.flush()
+ return changed
+end
+
+function L.undo(s)
+ local e = table.remove(s.undo)
+ if not e then return nil end
+ s.redo[#s.redo + 1] = e
+ return apply_history(e, true)
+end
+
+function L.redo(s)
+ local e = table.remove(s.redo)
+ if not e then return nil end
+ s.undo[#s.undo + 1] = e
+ return apply_history(e, false)
+end
+
+-- ============================================================ region iteration
+function L.each(r, fn)
+ for x = r.x0, r.x1 do
+ for z = r.z0, r.z1 do
+ for y = r.y0, r.y1 do
+ fn(x, y, z)
+ end
+ end
+ end
+end
+
+function L.walls_and_faces(r, edit, pattern, floorAndCeil)
+ L.each(r, function(x, y, z)
+ local wall = x == r.x0 or x == r.x1 or z == r.z0 or z == r.z1
+ local cap = y == r.y0 or y == r.y1
+ if wall or (floorAndCeil and cap) then edit:place(x, y, z, pattern) end
+ end)
+end
+
+-- ================================================================== shapes
+local function lsq(x, y, z) return x * x + y * y + z * z end
+
+--- WorldEdit's ellipsoid. (cx,cy,cz) is the centre block.
+function L.sphere(edit, cx, cy, cz, pattern, rx, ry, rz, filled)
+ rx, ry, rz = rx + 0.5, ry + 0.5, rz + 0.5
+ local irx, iry, irz = 1 / rx, 1 / ry, 1 / rz
+ local crx, cry, crz = ceil(rx), ceil(ry), ceil(rz)
+ local nextXn = 0
+ for x = 0, crx do
+ local xn = nextXn
+ nextXn = (x + 1) * irx
+ local nextYn = 0
+ for y = 0, cry do
+ local yn = nextYn
+ nextYn = (y + 1) * iry
+ local nextZn = 0
+ for z = 0, crz do
+ local zn = nextZn
+ nextZn = (z + 1) * irz
+ if lsq(xn, yn, zn) > 1 then break end
+ local skip = false
+ if not filled then
+ if lsq(nextXn, yn, zn) <= 1 and lsq(xn, nextYn, zn) <= 1 and lsq(xn, yn, nextZn) <= 1 then
+ skip = true
+ end
+ end
+ if not skip then
+ for sx = -1, 1, 2 do
+ for sy = -1, 1, 2 do
+ for sz = -1, 1, 2 do
+ if (x ~= 0 or sx == 1) and (y ~= 0 or sy == 1) and (z ~= 0 or sz == 1) then
+ edit:place(cx + sx * x, cy + sy * y, cz + sz * z, pattern)
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+end
+
+function L.cylinder(edit, cx, cy, cz, pattern, rx, rz, height, filled)
+ rx, rz = rx + 0.5, rz + 0.5
+ if height == 0 then return end
+ local irx, irz = 1 / rx, 1 / rz
+ local crx, crz = ceil(rx), ceil(rz)
+ local ys, ye = cy, cy + height - 1
+ if height < 0 then ys, ye = cy + height + 1, cy end
+ local nextXn = 0
+ for x = 0, crx do
+ local xn = nextXn
+ nextXn = (x + 1) * irx
+ local nextZn = 0
+ for z = 0, crz do
+ local zn = nextZn
+ nextZn = (z + 1) * irz
+ if lsq(xn, 0, zn) > 1 then break end
+ local skip = false
+ if not filled then
+ if lsq(nextXn, 0, zn) <= 1 and lsq(xn, 0, nextZn) <= 1 then skip = true end
+ end
+ if not skip then
+ for sx = -1, 1, 2 do
+ for sz = -1, 1, 2 do
+ if (x ~= 0 or sx == 1) and (z ~= 0 or sz == 1) then
+ for y = ys, ye do
+ edit:place(cx + sx * x, y, cz + sz * z, pattern)
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+end
+
+function L.cone(edit, cx, cy, cz, pattern, rx, rz, height, filled)
+ for h = 0, height - 1 do
+ local f = 1 - h / height
+ L.cylinder(edit, cx, cy + h, cz, pattern, max(0, rx * f), max(0, rz * f), 1, filled)
+ end
+end
+
+function L.pyramid(edit, cx, cy, cz, pattern, size, filled)
+ local height = size
+ for y = 0, height do
+ size = size - 1
+ for x = 0, size do
+ for z = 0, size do
+ if (filled and z <= size and x <= size) or z == size or x == size then
+ edit:place(cx + x, cy + y, cz + z, pattern)
+ edit:place(cx - x, cy + y, cz + z, pattern)
+ edit:place(cx + x, cy + y, cz - z, pattern)
+ edit:place(cx - x, cy + y, cz - z, pattern)
+ end
+ end
+ end
+ end
+end
+
+--- Line through block space; thickness > 0 puts a sphere of that radius on every point.
+function L.line(edit, a, b, pattern, radius, filled)
+ local dx, dy, dz = b[1] - a[1], b[2] - a[2], b[3] - a[3]
+ local steps = max(abs(dx), abs(dy), abs(dz))
+ local seen = {}
+ for i = 0, steps do
+ local t = steps == 0 and 0 or i / steps
+ local x = floor(a[1] + dx * t + 0.5)
+ local y = floor(a[2] + dy * t + 0.5)
+ local z = floor(a[3] + dz * t + 0.5)
+ if radius and radius > 0 then
+ L.sphere(edit, x, y, z, pattern, radius, radius, radius, filled ~= false)
+ else
+ edit:place(x, y, z, pattern)
+ end
+ end
+end
+
+-- ============================================================== block helpers
+local function is_air(id) return id == 0 end
+local LIQUID = { [8] = true, [9] = true, [10] = true, [11] = true }
+function L.is_liquid(id) return LIQUID[id] == true end
+function L.is_air(id) return is_air(id) end
+
+--- Top block (y) that is not air within [y0, y1] for the column, or nil
+function L.top_existing(x, z, y0, y1)
+ for y = y1, y0, -1 do
+ if get_block(x, y, z) ~= 0 then return y end
+ end
+ return nil
+end
+
+--- Top solid (non liquid/plant) block y in the column
+local PLANTS = { [6] = true, [31] = true, [37] = true, [38] = true, [39] = true, [40] = true, [50] = true,
+ [51] = true, [59] = true, [83] = true, [78] = true, [81] = false, [18] = false }
+function L.top_ground(x, z, y0, y1)
+ for y = y1, y0, -1 do
+ local id = get_block(x, y, z)
+ if id ~= 0 and not LIQUID[id] and not PLANTS[id] and id ~= 17 and id ~= 18 then return y end
+ end
+ return nil
+end
+
+-- ======================================================== rotation of block data
+-- data values that point in a direction, rotated 90 degrees clockwise (y axis)
+local ROT = {
+ stairs = { [0] = 2, [1] = 3, [2] = 1, [3] = 0 }, -- east,west,south,north
+ torch = { [1] = 3, [2] = 4, [3] = 2, [4] = 1 },
+ ladder = { [2] = 5, [3] = 4, [4] = 2, [5] = 3 }, -- chest, furnace, ladder, signs
+ door = { [0] = 1, [1] = 2, [2] = 3, [3] = 0 },
+ trapdoor = { [0] = 3, [1] = 2, [2] = 0, [3] = 1 },
+}
+local KIND = {
+ [53] = "stairs", [67] = "stairs", [108] = "stairs", [109] = "stairs", [114] = "stairs", [128] = "stairs",
+ [156] = "stairs",
+ [50] = "torch", [75] = "torch", [76] = "torch",
+ [65] = "ladder", [54] = "ladder", [61] = "ladder", [62] = "ladder", [68] = "ladder", [86] = "ladder",
+ [91] = "ladder",
+ [64] = "door", [71] = "door", [107] = "door",
+ [96] = "trapdoor",
+}
+
+function L.rotate_data(id, data, turns)
+ local kind = KIND[id]
+ if not kind then return data end
+ local map = ROT[kind]
+ turns = turns % 4
+ for _ = 1, turns do
+ local flags, d = 0, data
+ if kind == "stairs" then
+ flags = bit.band(d, 4); d = bit.band(d, 3)
+ elseif kind == "door" or kind == "trapdoor" then
+ flags = bit.band(d, bit.bnot(3)); d = bit.band(d, 3)
+ end
+ d = map[d] or d
+ data = bit.bor(d, flags)
+ end
+ return data
+end
+
+return L
diff --git a/mods/worldedit/main.lua b/mods/worldedit/main.lua
new file mode 100644
index 0000000..6d8ca1d
--- /dev/null
+++ b/mods/worldedit/main.lua
@@ -0,0 +1,1574 @@
+-- WorldEdit for MinecraftPE, written against the Lua mod API (see ../README.md).
+-- Command names, arguments, flags and behaviour follow EngineHub's WorldEdit
+-- (https://worldedit.enginehub.org/en/latest/commands/). Everything is typed
+-- with the usual double slash: "//wand", "//set stone", "/undo", ...
+
+local W = require("lib")
+
+local floor, ceil, abs, min, max = math.floor, math.ceil, math.abs, math.min, math.max
+local get_block = mc.world.get_block
+
+local WAND = mc.item.wooden_axe
+local NAVWAND = mc.item.compass
+local PICKAXES = { [270] = true, [274] = true, [257] = true, [278] = true, [285] = true }
+
+-- ----------------------------------------------------------------- helpers
+-- Names starting with "/" are typed with two slashes (//set). Commands that WorldEdit also
+-- offers with a single slash (/undo, /tool, ...) are registered under both spellings.
+local SINGLE = {}
+for name in ("unstuck ! ascend asc descend desc ceil thru jumpto j up toggleeditwand undo redo clearhistory "
+ .. "tool none mask material mat range superpickaxe pickaxe sp brush br fixlava fixwater removeabove "
+ .. "removebelow removenear replacenear snow thaw green extinguish ex ext butcher toggleplace schematic "
+ .. "schem clearclipboard ;"):gmatch("%S+") do SINGLE[name] = true end
+
+local function reg(names, desc, fn)
+ if type(names) == "string" then names = { names } end
+ for _, n in ipairs(names) do
+ mc.command(n, { description = desc, op = true }, fn)
+ local bare = n:match("^/(.+)$")
+ if bare and SINGLE[bare] then
+ mc.command(bare, { description = desc, op = true }, fn)
+ end
+ end
+end
+
+local function fmt(p) return string.format("(%d, %d, %d)", p[1], p[2], p[3]) end
+
+local function say(ctx, ...) ctx.player:say(...) end
+
+local function selection(ctx)
+ local s = W.session(ctx.player)
+ local r = W.region(s)
+ if not r then
+ say(ctx, "Make a region selection first (//wand, //pos1, //pos2).")
+ return s, nil
+ end
+ return s, r
+end
+
+local function describe_pos(s, which, p)
+ local msg = string.format("Position %d set to %s", which, fmt(p))
+ local r = W.region(s)
+ if r then msg = msg .. " (" .. W.volume(r) .. " blocks)" end
+ return msg .. "."
+end
+
+local function set_pos(player, which, p)
+ local s = W.session(player)
+ s[which == 1 and "pos1" or "pos2"] = p
+ player:say(describe_pos(s, which, p))
+end
+
+--- Runs `fn(edit)` as one undoable edit and reports the number of changed blocks.
+local function edit_session(ctx, fn, noun)
+ local s = W.session(ctx.player)
+ local edit = W.new_edit(s)
+ local ok, err = pcall(fn, edit, s)
+ local n = edit:commit()
+ if not ok then
+ say(ctx, "Error: " .. tostring(err))
+ return n
+ end
+ if edit.overflow then say(ctx, "Block change limit reached (" .. s.limit .. "), use //limit.") end
+ say(ctx, n .. " " .. (noun or "blocks") .. " changed.")
+ return n
+end
+
+local function pattern_or_err(ctx, text)
+ local p, err = W.pattern(text)
+ if not p then say(ctx, err) end
+ return p
+end
+
+local function num(text, default)
+ local n = tonumber(text)
+ return n or default
+end
+
+local function player_block(ctx) return ctx.player:block_pos() end
+
+local function radii(text)
+ local list = {}
+ for part in tostring(text):gmatch("[^,]+") do list[#list + 1] = tonumber(part) end
+ return list
+end
+
+-- ----------------------------------------------------------------- help
+local help_lines = {
+ "Navigation: /unstuck /ascend /descend /ceil /thru /jumpto /up",
+ "Selection: //wand //pos1 //pos2 //hpos1 //hpos2 //chunk //sel //expand //contract //shift //outset //inset //size //count //distr",
+ "Region: //set //replace //overlay //center //naturalize //walls //faces //smooth //move //stack //hollow //line",
+ "Generation: //sphere //hsphere //cyl //hcyl //cone //pyramid //hpyramid",
+ "Clipboard: //copy //cut //paste //rotate //flip /clearclipboard /schematic",
+ "History: /undo /redo /clearhistory",
+ "Tools: /tool /brush /mask /material /range /size // (super pickaxe)",
+ "Utility: //fill //fillr //drain /fixlava /fixwater /removeabove /removebelow /removenear /replacenear",
+ " /snow /thaw /green /extinguish /butcher //limit /toggleplace /we",
+}
+reg({ "/help" }, "Shows the WorldEdit commands", function(ctx)
+ for _, l in ipairs(help_lines) do say(ctx, l) end
+end)
+
+reg({ "we", "worldedit" }, "WorldEdit information", function(ctx)
+ local sub = ctx.args[1]
+ if sub == "version" or sub == "ver" or not sub then
+ say(ctx, "WorldEdit (MinecraftPE Lua port) 1.0, based on the EngineHub WorldEdit command set.")
+ else
+ say(ctx, "Usage: /we version")
+ end
+end)
+
+reg("/limit", "Sets the block change limit", function(ctx)
+ local s = W.session(ctx.player)
+ if ctx.args[1] then s.limit = tonumber(ctx.args[1]) or s.limit end
+ say(ctx, "Block change limit: " .. (s.limit < 0 and "unlimited" or s.limit))
+end)
+
+-- ------------------------------------------------------------- navigation
+local function free(x, y, z)
+ local id = get_block(x, y, z)
+ return id == 0 or id == 50 or id == 31 or id == 37 or id == 38 or id == 78 or id == 6
+end
+
+local function standable(x, y, z)
+ return not free(x, y - 1, z) and not W.is_liquid(get_block(x, y - 1, z)) and free(x, y, z) and free(x, y + 1, z)
+end
+
+reg({ "/unstuck", "/!" }, "Escape from being stuck inside a block", function(ctx)
+ local x, y, z = player_block(ctx)
+ for dy = 0, 127 - y do
+ if free(x, y + dy, z) and free(x, y + dy + 1, z) then
+ ctx.player:teleport(x + 0.5, y + dy, z + 0.5)
+ return "There you go!"
+ end
+ end
+ return "Nowhere to go."
+end)
+
+local function levels_arg(ctx) return max(1, floor(num(ctx.args[1], 1))) end
+
+reg({ "/ascend", "/asc" }, "Go up a floor", function(ctx)
+ local x, y, z = player_block(ctx)
+ local levels, found = levels_arg(ctx), 0
+ local cy, last = y, nil
+ for yy = y + 1, 126 do
+ if standable(x, yy, z) and not standable(x, yy - 1, z) and (not free(x, yy - 1, z) or yy > cy + 1) then
+ found = found + 1
+ last = yy
+ if found >= levels then break end
+ end
+ end
+ if not last then return "No free spot above you found." end
+ ctx.player:teleport(x + 0.5, last, z + 0.5)
+ return "Ascended " .. found .. " level" .. (found > 1 and "s" or "") .. "."
+end)
+
+reg({ "/descend", "/desc" }, "Go down a floor", function(ctx)
+ local x, y, z = player_block(ctx)
+ local levels, found, last = levels_arg(ctx), 0, nil
+ for yy = y - 1, 1, -1 do
+ if standable(x, yy, z) then
+ found = found + 1
+ last = yy
+ if found >= levels then break end
+ end
+ end
+ if not last then return "No free spot below you found." end
+ ctx.player:teleport(x + 0.5, last, z + 0.5)
+ return "Descended " .. found .. " level" .. (found > 1 and "s" or "") .. "."
+end)
+
+reg("/ceil", "Go to the ceiling", function(ctx)
+ local flags, pos = W.parse(ctx.args)
+ local clearance = max(0, floor(num(pos[1], 0)))
+ local x, y, z = player_block(ctx)
+ for yy = 126, y + 1, -1 do
+ if not free(x, yy + 1, z) and free(x, yy, z) and free(x, yy - 1, z) then
+ local ty = yy - 1 - clearance
+ if ty > y then
+ ctx.player:teleport(x + 0.5, ty, z + 0.5)
+ if flags.g then mc.world.set_block(x, ty - 1, z, 20, 0) end
+ return "Whoosh!"
+ end
+ end
+ end
+ return "No free spot above you found."
+end)
+
+reg("/thru", "Pass through walls", function(ctx)
+ local x, y, z = ctx.player:pos()
+ local dir, dx, dz = ctx.player:facing()
+ local yaw, pitch = ctx.player:look()
+ local vy = pitch > 50 and -1 or (pitch < -50 and 1 or 0)
+ if vy ~= 0 then dx, dz = 0, 0 end
+ local bx, by, bz = floor(x), floor(y), floor(z)
+ local inWall = false
+ for i = 1, 100 do
+ local cx, cy, cz = bx + dx * i, by + vy * i, bz + dz * i
+ if not free(cx, cy, cz) or not free(cx, cy + 1, cz) then inWall = true
+ elseif inWall and free(cx, cy, cz) and free(cx, cy + 1, cz) then
+ ctx.player:teleport(cx + 0.5, cy, cz + 0.5)
+ return "Whoosh!"
+ end
+ end
+ return "No free spot ahead of you found."
+end)
+
+reg({ "/jumpto", "/j" }, "Teleport to the targeted location", function(ctx)
+ local x, y, z = ctx.player:target(300)
+ if not x then return "No block in sight!" end
+ ctx.player:teleport(x + 0.5, y + 1, z + 0.5)
+ return "Poof!"
+end)
+
+reg("/up", "Go upwards some distance", function(ctx)
+ local flags, pos = W.parse(ctx.args)
+ local dist = floor(num(pos[1], 0))
+ if dist <= 0 then return "Usage: /up " end
+ local x, y, z = player_block(ctx)
+ local ty = min(126, y + dist)
+ ctx.player:teleport(x + 0.5, ty, z + 0.5)
+ mc.world.set_block(x, ty - 1, z, 20, 0)
+ return "Whoosh!"
+end)
+
+-- --------------------------------------------------------------- selection
+reg("/wand", "Gives the wand item", function(ctx)
+ local flags = W.parse(ctx.args)
+ if flags.n then
+ ctx.player:give(NAVWAND, 1)
+ return "Navigation wand given (left click: /jumpto, right click: /thru)."
+ end
+ ctx.player:give(WAND, 1)
+ return "Left click: select pos #1; Right click: select pos #2"
+end)
+
+reg("/toggleeditwand", "Toggles the wand function", function(ctx)
+ local s = W.session(ctx.player)
+ s.wand_off = not s.wand_off
+ return "Edit wand " .. (s.wand_off and "disabled." or "enabled.")
+end)
+
+local function parse_coords(text)
+ if not text then return nil end
+ local c = {}
+ for n in text:gmatch("[^,]+") do c[#c + 1] = tonumber(n) end
+ if #c == 3 then return { floor(c[1]), floor(c[2]), floor(c[3]) } end
+end
+
+local function pos_cmd(which)
+ return function(ctx)
+ local p = parse_coords(ctx.args[1])
+ if not p then
+ local x, y, z = player_block(ctx)
+ p = { x, y, z }
+ end
+ set_pos(ctx.player, which, p)
+ end
+end
+reg("/pos1", "Set position 1", pos_cmd(1))
+reg("/pos2", "Set position 2", pos_cmd(2))
+
+reg("/pos", "Set positions", function(ctx)
+ local x, y, z = player_block(ctx)
+ set_pos(ctx.player, 1, { x, y, z })
+end)
+
+local function hpos_cmd(which)
+ return function(ctx)
+ local x, y, z = ctx.player:target(300)
+ if not x then return "No block in sight!" end
+ set_pos(ctx.player, which, { x, y, z })
+ end
+end
+reg("/hpos1", "Set position 1 to targeted block", hpos_cmd(1))
+reg("/hpos2", "Set position 2 to targeted block", hpos_cmd(2))
+
+reg("/chunk", "Select the chunk you are in", function(ctx)
+ local flags, pos = W.parse(ctx.args)
+ local s = W.session(ctx.player)
+ local x, _, z = player_block(ctx)
+ local cx, cz = floor(x / 16), floor(z / 16)
+ if pos[1] then
+ local c = radii(pos[1])
+ if c[1] and c[2] then
+ if flags.c then cx, cz = c[1], c[2] else cx, cz = floor(c[1] / 16), floor(c[2] / 16) end
+ end
+ end
+ s.pos1 = { cx * 16, 0, cz * 16 }
+ s.pos2 = { cx * 16 + 15, 127, cz * 16 + 15 }
+ return "Chunk selected: (" .. cx .. ", " .. cz .. ")"
+end)
+
+local function sel_apply(s, fn)
+ local r = W.region(s)
+ fn(r)
+ s.pos1 = { r.x0, r.y0, r.z0 }
+ s.pos2 = { r.x1, r.y1, r.z1 }
+ return r
+end
+
+local function move_edge(r, dir, amount)
+ if dir[1] > 0 then r.x1 = r.x1 + amount elseif dir[1] < 0 then r.x0 = r.x0 - amount end
+ if dir[2] > 0 then r.y1 = r.y1 + amount elseif dir[2] < 0 then r.y0 = r.y0 - amount end
+ if dir[3] > 0 then r.z1 = r.z1 + amount elseif dir[3] < 0 then r.z0 = r.z0 - amount end
+ r.y0, r.y1 = max(0, r.y0), min(127, r.y1)
+end
+
+reg("/expand", "Expand the selection area", function(ctx)
+ local s, r = selection(ctx)
+ if not r then return end
+ if ctx.args[1] == "vert" or ctx.args[1] == "vertical" then
+ s.pos1[2], s.pos2[2] = 0, 127
+ return "Region expanded vertically."
+ end
+ local amount = floor(num(ctx.args[1], 0))
+ local rev, dirWord = nil, ctx.args[2]
+ if tonumber(ctx.args[2]) then rev = floor(tonumber(ctx.args[2])); dirWord = ctx.args[3] end
+ local dir = W.direction(ctx.player, dirWord)
+ local before = W.volume(r)
+ sel_apply(s, function(r2)
+ move_edge(r2, dir, amount)
+ if rev then move_edge(r2, { -dir[1], -dir[2], -dir[3] }, rev) end
+ end)
+ return "Region expanded " .. (W.volume(W.region(s)) - before) .. " blocks."
+end)
+
+reg("/contract", "Contract the selection area", function(ctx)
+ local s, r = selection(ctx)
+ if not r then return end
+ local amount = floor(num(ctx.args[1], 0))
+ local rev, dirWord = nil, ctx.args[2]
+ if tonumber(ctx.args[2]) then rev = floor(tonumber(ctx.args[2])); dirWord = ctx.args[3] end
+ local dir = W.direction(ctx.player, dirWord)
+ local before = W.volume(r)
+ sel_apply(s, function(r2)
+ -- contracting moves the far edge in the direction towards the opposite one
+ move_edge(r2, dir, -amount)
+ if rev then move_edge(r2, { -dir[1], -dir[2], -dir[3] }, -rev) end
+ end)
+ return "Region contracted " .. (before - W.volume(W.region(s))) .. " blocks."
+end)
+
+reg("/shift", "Shift the selection area", function(ctx)
+ local s, r = selection(ctx)
+ if not r then return end
+ local amount = floor(num(ctx.args[1], 0))
+ local dir = W.direction(ctx.player, ctx.args[2])
+ for _, p in ipairs({ s.pos1, s.pos2 }) do
+ p[1], p[2], p[3] = p[1] + dir[1] * amount, p[2] + dir[2] * amount, p[3] + dir[3] * amount
+ end
+ return "Region shifted."
+end)
+
+local function outset_inset(sign)
+ return function(ctx)
+ local s, r = selection(ctx)
+ if not r then return end
+ local flags, pos = W.parse(ctx.args)
+ local a = floor(num(pos[1], 0)) * sign
+ sel_apply(s, function(r2)
+ if not flags.v then r2.x0, r2.x1, r2.z0, r2.z1 = r2.x0 - a, r2.x1 + a, r2.z0 - a, r2.z1 + a end
+ if not flags.h then r2.y0, r2.y1 = max(0, r2.y0 - a), min(127, r2.y1 + a) end
+ end)
+ return "Region " .. (sign > 0 and "outset." or "inset.")
+ end
+end
+reg("/outset", "Outset the selection area", outset_inset(1))
+reg("/inset", "Inset the selection area", outset_inset(-1))
+
+reg({ "/sel", "/;", "/desel", "/deselect" }, "Choose a region selector", function(ctx)
+ local s = W.session(ctx.player)
+ if not ctx.args[1] or ctx.args[1] == "clear" or ctx.name == "/desel" or ctx.name == "/deselect" then
+ s.pos1, s.pos2 = nil, nil
+ return "Selection cleared."
+ end
+ if ctx.args[1] == "cuboid" then return "Cuboid: left click for point 1, right click for point 2" end
+ return "Only the cuboid selector is available."
+end)
+
+reg("/size", "Get information about the selection", function(ctx)
+ local flags = W.parse(ctx.args)
+ local s = W.session(ctx.player)
+ if flags.c then
+ local c = s.clipboard
+ if not c then return "Your clipboard is empty. Use //copy first." end
+ return string.format("Size: %d x %d x %d\nBlocks: %d", c.w, c.h, c.l, c.w * c.h * c.l)
+ end
+ local _, r = selection(ctx)
+ if not r then return end
+ say(ctx, "Type: cuboid")
+ say(ctx, "Position 1: " .. fmt(s.pos1))
+ say(ctx, "Position 2: " .. fmt(s.pos2))
+ say(ctx, string.format("Size: %d x %d x %d", r.x1 - r.x0 + 1, r.y1 - r.y0 + 1, r.z1 - r.z0 + 1))
+ say(ctx, "Number of blocks: " .. W.volume(r))
+end)
+
+reg("/count", "Counts the number of blocks matching a mask", function(ctx)
+ local _, r = selection(ctx)
+ if not r then return end
+ local mask, err = W.mask(ctx.args[1])
+ if not mask then return err or "Usage: //count " end
+ W.load_region(r)
+ local n = 0
+ W.each(r, function(x, y, z)
+ local id, d = get_block(x, y, z)
+ if mask(id, d) then n = n + 1 end
+ end)
+ return "Counted: " .. n
+end)
+
+reg("/distr", "Get the distribution of blocks in the selection", function(ctx)
+ local flags = W.parse(ctx.args)
+ local _, r = selection(ctx)
+ if not r then return end
+ W.load_region(r)
+ local counts, total = {}, 0
+ W.each(r, function(x, y, z)
+ local id, d = get_block(x, y, z)
+ local key = flags.d and (id * 16 + d) or id
+ counts[key] = (counts[key] or 0) + 1
+ total = total + 1
+ end)
+ local list = {}
+ for k, v in pairs(counts) do list[#list + 1] = { k, v } end
+ table.sort(list, function(a, b) return a[2] > b[2] end)
+ say(ctx, "# total blocks: " .. total)
+ for i = 1, min(#list, 12) do
+ local k = list[i][1]
+ local name = flags.d and (mc.block.name(floor(k / 16)) .. ":" .. (k % 16)) or mc.block.name(k)
+ say(ctx, string.format("%-7d (%.3f%%) %s", list[i][2], list[i][2] * 100 / total, name))
+ end
+end)
+
+reg("/trim", "Shrink the selection to the blocks matching a mask", function(ctx)
+ local s, r = selection(ctx)
+ if not r then return end
+ local mask = W.mask(ctx.args[1] or "#existing")
+ local nx0, ny0, nz0, nx1, ny1, nz1 = 1e9, 1e9, 1e9, -1e9, -1e9, -1e9
+ W.each(r, function(x, y, z)
+ local id, d = get_block(x, y, z)
+ if mask(id, d) then
+ nx0, ny0, nz0 = min(nx0, x), min(ny0, y), min(nz0, z)
+ nx1, ny1, nz1 = max(nx1, x), max(ny1, y), max(nz1, z)
+ end
+ end)
+ if nx0 == 1e9 then return "No blocks match." end
+ s.pos1, s.pos2 = { nx0, ny0, nz0 }, { nx1, ny1, nz1 }
+ return "Region trimmed."
+end)
+
+-- ----------------------------------------------------------------- region
+reg("/set", "Set all the blocks inside the selection to a pattern", function(ctx)
+ local _, r = selection(ctx)
+ if not r then return end
+ local pattern = pattern_or_err(ctx, ctx.args[1])
+ if not pattern then return end
+ W.load_region(r)
+ edit_session(ctx, function(e) W.each(r, function(x, y, z) e:place(x, y, z, pattern) end) end)
+end)
+
+reg({ "/replace", "/re", "/rep" }, "Replace all blocks in the selection with another", function(ctx)
+ local _, r = selection(ctx)
+ if not r then return end
+ local from, to = ctx.args[1], ctx.args[2]
+ if not to then from, to = "#existing", ctx.args[1] end
+ local mask, err = W.mask(from)
+ if not mask then return err or "Usage: //replace [from] " end
+ local pattern = pattern_or_err(ctx, to)
+ if not pattern then return end
+ W.load_region(r)
+ edit_session(ctx, function(e)
+ W.each(r, function(x, y, z)
+ local id, d = get_block(x, y, z)
+ if mask(id, d) then e:place(x, y, z, pattern) end
+ end)
+ end)
+end)
+
+reg("/overlay", "Set a block on top of blocks in the region", function(ctx)
+ local _, r = selection(ctx)
+ if not r then return end
+ local pattern = pattern_or_err(ctx, ctx.args[1])
+ if not pattern then return end
+ W.load_region(r)
+ edit_session(ctx, function(e)
+ for x = r.x0, r.x1 do
+ for z = r.z0, r.z1 do
+ local top = W.top_existing(x, z, r.y0, r.y1)
+ if top and top < 127 then e:place(x, top + 1, z, pattern) end
+ end
+ end
+ end)
+end)
+
+reg({ "/center", "/middle" }, "Set the center block(s)", function(ctx)
+ local _, r = selection(ctx)
+ if not r then return end
+ local pattern = pattern_or_err(ctx, ctx.args[1])
+ if not pattern then return end
+ edit_session(ctx, function(e)
+ local cx0, cx1 = floor((r.x0 + r.x1) / 2), ceil((r.x0 + r.x1) / 2)
+ local cy0, cy1 = floor((r.y0 + r.y1) / 2), ceil((r.y0 + r.y1) / 2)
+ local cz0, cz1 = floor((r.z0 + r.z1) / 2), ceil((r.z0 + r.z1) / 2)
+ for x = cx0, cx1 do for y = cy0, cy1 do for z = cz0, cz1 do e:place(x, y, z, pattern) end end end
+ end)
+end)
+
+reg("/naturalize", "3 layers of dirt on top then rock below", function(ctx)
+ local _, r = selection(ctx)
+ if not r then return end
+ W.load_region(r)
+ edit_session(ctx, function(e)
+ for x = r.x0, r.x1 do
+ for z = r.z0, r.z1 do
+ local depth = 0
+ for y = r.y1, r.y0, -1 do
+ local id = get_block(x, y, z)
+ if id ~= 0 and not W.is_liquid(id) then
+ if depth == 0 then e:set(x, y, z, 2, 0)
+ elseif depth <= 3 then e:set(x, y, z, 3, 0)
+ else e:set(x, y, z, 1, 0) end
+ depth = depth + 1
+ else
+ depth = 0
+ end
+ end
+ end
+ end
+ end)
+end)
+
+reg("/walls", "Build the four sides of the selection", function(ctx)
+ local _, r = selection(ctx)
+ if not r then return end
+ local pattern = pattern_or_err(ctx, ctx.args[1])
+ if not pattern then return end
+ W.load_region(r)
+ edit_session(ctx, function(e) W.walls_and_faces(r, e, pattern, false) end)
+end)
+
+reg({ "/faces", "/outline" }, "Build the walls, ceiling, and floor of a selection", function(ctx)
+ local _, r = selection(ctx)
+ if not r then return end
+ local pattern = pattern_or_err(ctx, ctx.args[1])
+ if not pattern then return end
+ W.load_region(r)
+ edit_session(ctx, function(e) W.walls_and_faces(r, e, pattern, true) end)
+end)
+
+reg("/hollow", "Hollows out the object contained in this selection", function(ctx)
+ local _, r = selection(ctx)
+ if not r then return end
+ local flags, pos = W.parse(ctx.args)
+ local thickness = max(1, floor(num(pos[1], 1)))
+ local fill = pattern_or_err(ctx, pos[2] or "air")
+ if not fill then return end
+ W.load_region(r)
+ local function inside(x, y, z) return x >= r.x0 and x <= r.x1 and y >= r.y0 and y <= r.y1 and z >= r.z0 and z <= r.z1 end
+ local N = { { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } }
+ local keep, frontier = {}, {}
+ local function key(x, y, z) return (x - r.x0) + (z - r.z0) * 4096 + (y * 16777216) end
+ W.each(r, function(x, y, z)
+ if get_block(x, y, z) ~= 0 then
+ for _, n in ipairs(N) do
+ local nx, ny, nz = x + n[1], y + n[2], z + n[3]
+ if not inside(nx, ny, nz) or get_block(nx, ny, nz) == 0 then
+ keep[key(x, y, z)] = true
+ frontier[#frontier + 1] = { x, y, z }
+ break
+ end
+ end
+ end
+ end)
+ for _ = 2, thickness do
+ local nextFrontier = {}
+ for _, p in ipairs(frontier) do
+ for _, n in ipairs(N) do
+ local nx, ny, nz = p[1] + n[1], p[2] + n[2], p[3] + n[3]
+ if inside(nx, ny, nz) and get_block(nx, ny, nz) ~= 0 and not keep[key(nx, ny, nz)] then
+ keep[key(nx, ny, nz)] = true
+ nextFrontier[#nextFrontier + 1] = { nx, ny, nz }
+ end
+ end
+ end
+ frontier = nextFrontier
+ end
+ edit_session(ctx, function(e)
+ W.each(r, function(x, y, z)
+ if get_block(x, y, z) ~= 0 and not keep[key(x, y, z)] then e:place(x, y, z, fill) end
+ end)
+ end)
+end)
+
+-- Gaussian terrain smoothing, like the WorldEdit height map filter (5x5 kernel)
+local KERNEL, KSUM = {}, 0
+for dx = -2, 2 do
+ for dz = -2, 2 do
+ local w = math.exp(-(dx * dx + dz * dz) / 2)
+ KERNEL[#KERNEL + 1] = { dx, dz, w }
+ KSUM = KSUM + w
+ end
+end
+
+local function smooth_region(e, r, iterations, mask)
+ local w, l = r.x1 - r.x0 + 1, r.z1 - r.z0 + 1
+ local function heights()
+ local h, types = {}, {}
+ for x = r.x0, r.x1 do
+ for z = r.z0, r.z1 do
+ local top
+ for y = r.y1, r.y0, -1 do
+ local id, d = get_block(x, y, z)
+ if id ~= 0 and not W.is_liquid(id) and (not mask or mask(id, d)) then top = y; types[#types + 1] = nil; break end
+ end
+ h[(x - r.x0) * l + (z - r.z0)] = top or (r.y0 - 1)
+ end
+ end
+ return h
+ end
+ for _ = 1, iterations do
+ local h = heights()
+ local newH = {}
+ for x = 0, w - 1 do
+ for z = 0, l - 1 do
+ local sum, wsum = 0, 0
+ for _, k in ipairs(KERNEL) do
+ local nx, nz = x + k[1], z + k[2]
+ if nx >= 0 and nx < w and nz >= 0 and nz < l then
+ sum = sum + h[nx * l + nz] * k[3]
+ wsum = wsum + k[3]
+ end
+ end
+ newH[x * l + z] = floor(sum / wsum + 0.5)
+ end
+ end
+ for x = 0, w - 1 do
+ for z = 0, l - 1 do
+ local wx, wz = r.x0 + x, r.z0 + z
+ local oh, nh = h[x * l + z], newH[x * l + z]
+ if nh > oh then
+ local id, d = get_block(wx, max(oh, r.y0), wz)
+ if oh < r.y0 then id, d = 3, 0 end
+ for y = oh + 1, min(nh, r.y1) do e:set(wx, y, wz, id, d) end
+ elseif nh < oh then
+ for y = nh + 1, oh do e:set(wx, y, wz, 0, 0) end
+ end
+ end
+ end
+ end
+end
+
+reg("/smooth", "Smooth the elevation in the selection", function(ctx)
+ local _, r = selection(ctx)
+ if not r then return end
+ local iterations = max(1, floor(num(ctx.args[1], 1)))
+ local mask = ctx.args[2] and W.mask(ctx.args[2])
+ W.load_region(r)
+ edit_session(ctx, function(e) smooth_region(e, r, iterations, mask) end)
+end)
+
+-- ------------------------------------------------------- move / stack
+local function read_region(r, skipAir)
+ local blocks = {}
+ local n = 0
+ for x = r.x0, r.x1 do
+ for y = r.y0, r.y1 do
+ for z = r.z0, r.z1 do
+ local id, d = get_block(x, y, z)
+ if not (skipAir and id == 0) then
+ n = n + 1
+ blocks[n] = { x - r.x0, y - r.y0, z - r.z0, id, d }
+ end
+ end
+ end
+ end
+ return blocks
+end
+
+reg("/move", "Move the contents of the selection", function(ctx)
+ local s, r = selection(ctx)
+ if not r then return end
+ local flags, pos = W.parse(ctx.args, { m = true })
+ local count = max(1, floor(num(pos[1], 1)))
+ local dir = W.direction(ctx.player, pos[2])
+ local replace = pattern_or_err(ctx, pos[3] or "air")
+ if not replace then return end
+ local mask = flags.m and W.mask(flags.m)
+ local dx, dy, dz = dir[1] * count, dir[2] * count, dir[3] * count
+ local target = { x0 = r.x0 + dx, x1 = r.x1 + dx, y0 = r.y0 + dy, y1 = r.y1 + dy, z0 = r.z0 + dz, z1 = r.z1 + dz }
+ W.load_region(r); W.load_region(target)
+ local blocks = read_region(r, flags.a)
+ edit_session(ctx, function(e)
+ for _, b in ipairs(blocks) do
+ if not mask or mask(b[4], b[5]) then e:place(r.x0 + b[1], r.y0 + b[2], r.z0 + b[3], replace) end
+ end
+ for _, b in ipairs(blocks) do
+ if not mask or mask(b[4], b[5]) then e:set(target.x0 + b[1], target.y0 + b[2], target.z0 + b[3], b[4], b[5]) end
+ end
+ end)
+ if flags.s then
+ s.pos1 = { target.x0, target.y0, target.z0 }
+ s.pos2 = { target.x1, target.y1, target.z1 }
+ end
+end)
+
+reg("/stack", "Repeat the contents of the selection", function(ctx)
+ local s, r = selection(ctx)
+ if not r then return end
+ local flags, pos = W.parse(ctx.args, { m = true })
+ local count = max(1, floor(num(pos[1], 1)))
+ local dir = W.direction(ctx.player, pos[2])
+ local sx = (r.x1 - r.x0 + 1) * dir[1]
+ local sy = (r.y1 - r.y0 + 1) * dir[2]
+ local sz = (r.z1 - r.z0 + 1) * dir[3]
+ local mask = flags.m and W.mask(flags.m)
+ W.load_region(r)
+ local blocks = read_region(r, flags.a)
+ edit_session(ctx, function(e)
+ for i = 1, count do
+ W.load_region({ x0 = r.x0 + sx * i, x1 = r.x1 + sx * i, z0 = r.z0 + sz * i, z1 = r.z1 + sz * i, y0 = 0, y1 = 0 })
+ for _, b in ipairs(blocks) do
+ if not mask or mask(b[4], b[5]) then
+ e:set(r.x0 + b[1] + sx * i, r.y0 + b[2] + sy * i, r.z0 + b[3] + sz * i, b[4], b[5])
+ end
+ end
+ end
+ end)
+ if flags.s then
+ s.pos2 = { r.x1 + sx * count, r.y1 + sy * count, r.z1 + sz * count }
+ end
+end)
+
+-- ------------------------------------------------------------- generation
+local function gen_origin(ctx, flags, raise)
+ local x, y, z = player_block(ctx)
+ if flags.r then y = y + raise end
+ return x, y, z
+end
+
+local function sphere_cmd(hollowDefault)
+ return function(ctx)
+ local flags, pos = W.parse(ctx.args)
+ local pattern = pattern_or_err(ctx, pos[1])
+ if not pattern then return end
+ local rad = radii(pos[2] or "")
+ if not rad[1] then return "Usage: //sphere [-hr] " end
+ local rx, ry, rz = rad[1], rad[2] or rad[1], rad[3] or rad[1]
+ local x, y, z = gen_origin(ctx, flags, ry)
+ local filled = not (flags.h or hollowDefault)
+ W.load_region({ x0 = x - rx, x1 = x + rx, z0 = z - rz, z1 = z + rz, y0 = 0, y1 = 0 })
+ edit_session(ctx, function(e) W.sphere(e, x, y, z, pattern, rx, ry, rz, filled) end)
+ end
+end
+reg("/sphere", "Generate a filled sphere", sphere_cmd(false))
+reg("/hsphere", "Generate a hollow sphere", sphere_cmd(true))
+
+local function cyl_cmd(hollowDefault)
+ return function(ctx)
+ local flags, pos = W.parse(ctx.args)
+ local pattern = pattern_or_err(ctx, pos[1])
+ if not pattern then return end
+ local rad = radii(pos[2] or "")
+ if not rad[1] then return "Usage: //cyl [-h] [height]" end
+ local rx, rz = rad[1], rad[2] or rad[1]
+ local height = floor(num(pos[3], 1))
+ local x, y, z = player_block(ctx)
+ W.load_region({ x0 = x - rx, x1 = x + rx, z0 = z - rz, z1 = z + rz, y0 = 0, y1 = 0 })
+ edit_session(ctx, function(e) W.cylinder(e, x, y, z, pattern, rx, rz, height, not (flags.h or hollowDefault)) end)
+ end
+end
+reg("/cyl", "Generate a cylinder", cyl_cmd(false))
+reg("/hcyl", "Generate a hollow cylinder", cyl_cmd(true))
+
+reg("/cone", "Generate a cone", function(ctx)
+ local flags, pos = W.parse(ctx.args)
+ local pattern = pattern_or_err(ctx, pos[1])
+ if not pattern then return end
+ local rad = radii(pos[2] or "")
+ if not rad[1] then return "Usage: //cone [-h] [height]" end
+ local rx, rz = rad[1], rad[2] or rad[1]
+ local height = floor(num(pos[3], 1))
+ local x, y, z = player_block(ctx)
+ W.load_region({ x0 = x - rx, x1 = x + rx, z0 = z - rz, z1 = z + rz, y0 = 0, y1 = 0 })
+ edit_session(ctx, function(e) W.cone(e, x, y, z, pattern, rx, rz, height, not flags.h) end)
+end)
+
+local function pyramid_cmd(hollowDefault)
+ return function(ctx)
+ local flags, pos = W.parse(ctx.args)
+ local pattern = pattern_or_err(ctx, pos[1])
+ if not pattern then return end
+ local size = floor(num(pos[2], 0))
+ if size < 1 then return "Usage: //pyramid [-h] " end
+ local x, y, z = player_block(ctx)
+ W.load_region({ x0 = x - size, x1 = x + size, z0 = z - size, z1 = z + size, y0 = 0, y1 = 0 })
+ edit_session(ctx, function(e) W.pyramid(e, x, y, z, pattern, size, not (flags.h or hollowDefault)) end)
+ end
+end
+reg("/pyramid", "Generate a filled pyramid", pyramid_cmd(false))
+reg("/hpyramid", "Generate a hollow pyramid", pyramid_cmd(true))
+
+reg("/line", "Draws a line segment between the cuboid selection corners", function(ctx)
+ local s, r = selection(ctx)
+ if not r then return end
+ local flags, pos = W.parse(ctx.args)
+ local pattern = pattern_or_err(ctx, pos[1])
+ if not pattern then return end
+ local thickness = floor(num(pos[2], 0))
+ W.load_region(r)
+ edit_session(ctx, function(e) W.line(e, s.pos1, s.pos2, pattern, thickness, not flags.h) end)
+end)
+
+-- -------------------------------------------------------------- clipboard
+local function take_clipboard(ctx, r, flags, cut, leave)
+ local s = W.session(ctx.player)
+ local px, py, pz = player_block(ctx)
+ W.load_region(r)
+ local mask = flags.m and W.mask(flags.m)
+ local blocks = {}
+ local n = 0
+ for x = r.x0, r.x1 do
+ for y = r.y0, r.y1 do
+ for z = r.z0, r.z1 do
+ local id, d = get_block(x, y, z)
+ if not mask or mask(id, d) then
+ n = n + 1
+ blocks[n] = { x - r.x0, y - r.y0, z - r.z0, id, d }
+ end
+ end
+ end
+ end
+ s.clipboard = {
+ w = r.x1 - r.x0 + 1, h = r.y1 - r.y0 + 1, l = r.z1 - r.z0 + 1,
+ ox = r.x0 - px, oy = r.y0 - py, oz = r.z0 - pz, -- offset from copy position to min corner
+ wx = r.x0, wy = r.y0, wz = r.z0, -- original world position
+ blocks = blocks,
+ }
+ say(ctx, n .. " block(s) were copied.")
+ if cut then
+ edit_session(ctx, function(e)
+ for _, b in ipairs(blocks) do e:place(r.x0 + b[1], r.y0 + b[2], r.z0 + b[3], leave) end
+ end)
+ end
+end
+
+reg("/copy", "Copy the selection to the clipboard", function(ctx)
+ local flags = W.parse(ctx.args, { m = true })
+ local _, r = selection(ctx)
+ if r then take_clipboard(ctx, r, flags, false) end
+end)
+
+reg("/cut", "Cut the selection to the clipboard", function(ctx)
+ local flags, pos = W.parse(ctx.args, { m = true })
+ local _, r = selection(ctx)
+ if not r then return end
+ local leave = pattern_or_err(ctx, pos[1] or "air")
+ if leave then take_clipboard(ctx, r, flags, true, leave) end
+end)
+
+reg("/paste", "Paste the clipboard's contents", function(ctx)
+ local flags = W.parse(ctx.args, { m = true })
+ local s = W.session(ctx.player)
+ local c = s.clipboard
+ if not c then return "Your clipboard is empty. Use //copy first." end
+ local px, py, pz = player_block(ctx)
+ local bx, by, bz
+ if flags.o then bx, by, bz = c.wx, c.wy, c.wz else bx, by, bz = px + c.ox, py + c.oy, pz + c.oz end
+ local mask = flags.m and W.mask(flags.m)
+ W.load_region({ x0 = bx, x1 = bx + c.w, z0 = bz, z1 = bz + c.l, y0 = 0, y1 = 0 })
+ if not flags.n then
+ edit_session(ctx, function(e)
+ for _, b in ipairs(c.blocks) do
+ if not (flags.a and b[4] == 0) and (not mask or mask(b[4], b[5])) then
+ e:set(bx + b[1], by + b[2], bz + b[3], b[4], b[5])
+ end
+ end
+ end)
+ end
+ if flags.s or flags.n then
+ s.pos1 = { bx, by, bz }
+ s.pos2 = { bx + c.w - 1, by + c.h - 1, bz + c.l - 1 }
+ end
+end)
+
+local function transform_clipboard(c, fn, newW, newH, newL, ox, oy, oz)
+ local out = {}
+ for i, b in ipairs(c.blocks) do out[i] = fn(b) end
+ c.blocks = out
+ c.w, c.h, c.l = newW or c.w, newH or c.h, newL or c.l
+ if ox then c.ox, c.oy, c.oz = ox, oy, oz end
+end
+
+reg("/rotate", "Rotate the contents of the clipboard", function(ctx)
+ local s = W.session(ctx.player)
+ local c = s.clipboard
+ if not c then return "Your clipboard is empty. Use //copy first." end
+ local deg = floor(num(ctx.args[1], 0))
+ if deg % 90 ~= 0 then return "Angles must be multiples of 90 degrees." end
+ local turns = (deg / 90) % 4
+ for _ = 1, turns do
+ -- 90 degrees clockwise around y: (x, z) -> (l - 1 - z, x)
+ local w, l = c.w, c.l
+ transform_clipboard(c, function(b)
+ return { l - 1 - b[3], b[2], b[1], b[4], W.rotate_data(b[4], b[5], 1) }
+ end, l, c.h, w, -(c.oz + l - 1), c.oy, c.ox)
+ end
+ return "The clipboard copy has been rotated."
+end)
+
+reg({ "/flip", "/mirror" }, "Flip the contents of the clipboard", function(ctx)
+ local s = W.session(ctx.player)
+ local c = s.clipboard
+ if not c then return "Your clipboard is empty. Use //copy first." end
+ local dir = W.direction(ctx.player, ctx.args[1])
+ local w, h, l = c.w, c.h, c.l
+ transform_clipboard(c, function(b)
+ local x, y, z = b[1], b[2], b[3]
+ if dir[1] ~= 0 then x = w - 1 - x end
+ if dir[2] ~= 0 then y = h - 1 - y end
+ if dir[3] ~= 0 then z = l - 1 - z end
+ return { x, y, z, b[4], b[5] }
+ end)
+ if dir[1] ~= 0 then c.ox = -(c.ox + w - 1) end
+ if dir[2] ~= 0 then c.oy = -(c.oy + h - 1) end
+ if dir[3] ~= 0 then c.oz = -(c.oz + l - 1) end
+ return "The clipboard copy has been flipped."
+end)
+
+reg("/clearclipboard", "Clear your clipboard", function(ctx)
+ W.session(ctx.player).clipboard = nil
+ return "Clipboard cleared."
+end)
+
+-- schematics are stored as Lua tables in schematics/.schem
+reg({ "/schematic", "/schem" }, "Schematic commands for saving/loading areas", function(ctx)
+ local sub = ctx.args[1]
+ local s = W.session(ctx.player)
+ mc._mkdir("schematics")
+ local function path(name) return "schematics/" .. name:gsub("[^%w_%-]", "_") .. ".schem" end
+ if sub == "save" then
+ local name = ctx.args[#ctx.args]
+ if not s.clipboard or not name or name == "save" then return "Usage: /schematic save (copy something first)" end
+ local ok, err = mc.save_table(path(name), s.clipboard)
+ return ok and ("Clipboard saved as " .. name .. ".") or ("Could not save: " .. tostring(err))
+ elseif sub == "load" then
+ local name = ctx.args[#ctx.args]
+ local data = name and mc.load_table(path(name))
+ if not data then return "Schematic not found." end
+ s.clipboard = data
+ return "Schematic " .. name .. " loaded. Paste it with //paste"
+ elseif sub == "list" or sub == "all" or sub == "ls" then
+ local names = {}
+ for _, e in ipairs(mc._listdir("schematics")) do
+ local n = e.name:match("^(.+)%.schem$")
+ if n then names[#names + 1] = n end
+ end
+ table.sort(names)
+ return "Available schematics: " .. (#names > 0 and table.concat(names, ", ") or "(none)")
+ elseif sub == "delete" or sub == "d" then
+ local name = ctx.args[2]
+ if not name then return "Usage: /schematic delete " end
+ os.remove(path(name))
+ return "Deleted " .. name .. "."
+ elseif sub == "formats" then
+ return "Available formats: mcpe-lua (default)"
+ end
+ return "Usage: /schematic "
+end)
+
+-- ---------------------------------------------------------------- history
+reg({ "/undo" }, "Undo your last action", function(ctx)
+ local times = max(1, floor(num(ctx.args[1], 1)))
+ local s = W.session(ctx.player)
+ local done = 0
+ for _ = 1, times do
+ if not W.undo(s) then break end
+ done = done + 1
+ end
+ if done == 0 then return "Nothing left to undo." end
+ return "Undo successful."
+end)
+
+reg({ "/redo" }, "Redo your last undone action", function(ctx)
+ local times = max(1, floor(num(ctx.args[1], 1)))
+ local s = W.session(ctx.player)
+ local done = 0
+ for _ = 1, times do
+ if not W.redo(s) then break end
+ done = done + 1
+ end
+ if done == 0 then return "Nothing left to redo." end
+ return "Redo successful."
+end)
+
+reg("/clearhistory", "Clear your history", function(ctx)
+ local s = W.session(ctx.player)
+ s.undo, s.redo = {}, {}
+ return "History cleared."
+end)
+
+-- ------------------------------------------------------------------ utility
+local function flood_fill(ctx, recursive)
+ local flags, pos = W.parse(ctx.args)
+ local pattern = pattern_or_err(ctx, pos[1])
+ if not pattern then return end
+ local radius = floor(num(pos[2], 0))
+ if radius < 1 then return "Usage: //fill [depth]" end
+ local depth = floor(num(pos[3], 1 / 0))
+ local ox, oy, oz = player_block(ctx)
+ W.load_region({ x0 = ox - radius, x1 = ox + radius, z0 = oz - radius, z1 = oz + radius, y0 = 0, y1 = 0 })
+ edit_session(ctx, function(e)
+ local seen = {}
+ local queue, head = {}, 1
+ local function push(x, y, z)
+ local k = (x * 4096 + z) * 256 + y
+ if seen[k] then return end
+ if (x - ox) ^ 2 + (z - oz) ^ 2 > radius * radius then return end
+ if y > oy or y < oy - depth + 1 or y < 0 then return end
+ if get_block(x, y, z) ~= 0 then return end
+ seen[k] = true
+ queue[#queue + 1] = { x, y, z }
+ end
+ push(ox, oy, oz)
+ if recursive then push(ox, oy - 1, oz) end
+ while head <= #queue do
+ local p = queue[head]; head = head + 1
+ e:place(p[1], p[2], p[3], pattern)
+ push(p[1] + 1, p[2], p[3]); push(p[1] - 1, p[2], p[3])
+ push(p[1], p[2], p[3] + 1); push(p[1], p[2], p[3] - 1)
+ if recursive then push(p[1], p[2] - 1, p[3]) end
+ end
+ end)
+end
+reg("/fill", "Fill a hole", function(ctx) flood_fill(ctx, false) end)
+reg("/fillr", "Fill a hole recursively", function(ctx) flood_fill(ctx, true) end)
+
+reg("/drain", "Drain a pool", function(ctx)
+ local flags, pos = W.parse(ctx.args)
+ local radius = floor(num(pos[1], 0))
+ if radius < 1 then return "Usage: //drain [-w] " end
+ local ox, oy, oz = player_block(ctx)
+ W.load_region({ x0 = ox - radius, x1 = ox + radius, z0 = oz - radius, z1 = oz + radius, y0 = 0, y1 = 0 })
+ edit_session(ctx, function(e)
+ local seen, queue, head = {}, {}, 1
+ local function push(x, y, z)
+ if y < 0 or y > 127 then return end
+ local k = (x * 4096 + z) * 256 + y
+ if seen[k] or (x - ox) ^ 2 + (y - oy) ^ 2 + (z - oz) ^ 2 > radius * radius then return end
+ if not W.is_liquid(get_block(x, y, z)) then return end
+ seen[k] = true
+ queue[#queue + 1] = { x, y, z }
+ end
+ for dx = -1, 1 do for dy = -1, 2 do for dz = -1, 1 do push(ox + dx, oy + dy, oz + dz) end end end
+ while head <= #queue do
+ local p = queue[head]; head = head + 1
+ e:set(p[1], p[2], p[3], 0, 0)
+ push(p[1] + 1, p[2], p[3]); push(p[1] - 1, p[2], p[3])
+ push(p[1], p[2] + 1, p[3]); push(p[1], p[2] - 1, p[3])
+ push(p[1], p[2], p[3] + 1); push(p[1], p[2], p[3] - 1)
+ end
+ end)
+end)
+
+local function near_sphere(ctx, radius, fn)
+ local ox, oy, oz = player_block(ctx)
+ W.load_region({ x0 = ox - radius, x1 = ox + radius, z0 = oz - radius, z1 = oz + radius, y0 = 0, y1 = 0 })
+ for x = ox - radius, ox + radius do
+ for y = max(0, oy - radius), min(127, oy + radius) do
+ for z = oz - radius, oz + radius do
+ if (x - ox) ^ 2 + (y - oy) ^ 2 + (z - oz) ^ 2 <= radius * radius then fn(x, y, z) end
+ end
+ end
+ end
+end
+
+reg("/fixwater", "Level nearby water", function(ctx)
+ local radius = floor(num(ctx.args[1], 0))
+ if radius < 1 then return "Usage: /fixwater " end
+ edit_session(ctx, function(e)
+ near_sphere(ctx, radius, function(x, y, z)
+ local id = get_block(x, y, z)
+ if id == 8 then e:set(x, y, z, 9, 0) end
+ end)
+ end)
+end)
+
+reg("/fixlava", "Level nearby lava", function(ctx)
+ local radius = floor(num(ctx.args[1], 0))
+ if radius < 1 then return "Usage: /fixlava " end
+ edit_session(ctx, function(e)
+ near_sphere(ctx, radius, function(x, y, z)
+ local id = get_block(x, y, z)
+ if id == 10 then e:set(x, y, z, 11, 0) end
+ end)
+ end)
+end)
+
+local function column_remove(ctx, dirY)
+ local size = max(1, floor(num(ctx.args[1], 1)))
+ local height = floor(num(ctx.args[2], 127))
+ local ox, oy, oz = player_block(ctx)
+ W.load_region({ x0 = ox - size, x1 = ox + size, z0 = oz - size, z1 = oz + size, y0 = 0, y1 = 0 })
+ edit_session(ctx, function(e)
+ local y0, y1
+ if dirY > 0 then y0, y1 = oy + 2, min(127, oy + 1 + height) else y0, y1 = max(0, oy - height), oy - 1 end
+ for x = ox - size, ox + size do
+ for z = oz - size, oz + size do
+ for y = y0, y1 do e:set(x, y, z, 0, 0) end
+ end
+ end
+ end)
+end
+reg("/removeabove", "Remove blocks above your head", function(ctx) column_remove(ctx, 1) end)
+reg("/removebelow", "Remove blocks below you", function(ctx) column_remove(ctx, -1) end)
+
+reg("/removenear", "Remove blocks near you", function(ctx)
+ local mask, err = W.mask(ctx.args[1])
+ if not mask then return err or "Usage: /removenear [size]" end
+ local size = floor(num(ctx.args[2], 50))
+ edit_session(ctx, function(e)
+ near_sphere(ctx, size, function(x, y, z)
+ local id, d = get_block(x, y, z)
+ if mask(id, d) then e:set(x, y, z, 0, 0) end
+ end)
+ end)
+end)
+
+reg("/replacenear", "Replace nearby blocks", function(ctx)
+ local size = floor(num(ctx.args[1], 0))
+ if size < 1 then return "Usage: /replacenear [from] " end
+ local from, to = ctx.args[2], ctx.args[3]
+ if not to then from, to = "#existing", ctx.args[2] end
+ local mask = W.mask(from)
+ local pattern = pattern_or_err(ctx, to)
+ if not mask or not pattern then return end
+ edit_session(ctx, function(e)
+ near_sphere(ctx, size, function(x, y, z)
+ local id, d = get_block(x, y, z)
+ if mask(id, d) then e:place(x, y, z, pattern) end
+ end)
+ end)
+end)
+
+reg("/snow", "Simulates snow", function(ctx)
+ local flags, pos = W.parse(ctx.args)
+ local size = max(1, floor(num(pos[1], 10)))
+ local ox, _, oz = player_block(ctx)
+ W.load_region({ x0 = ox - size, x1 = ox + size, z0 = oz - size, z1 = oz + size, y0 = 0, y1 = 0 })
+ edit_session(ctx, function(e)
+ for x = ox - size, ox + size do
+ for z = oz - size, oz + size do
+ if (x - ox) ^ 2 + (z - oz) ^ 2 <= size * size then
+ local top = W.top_existing(x, z, 0, 127)
+ if top and top < 127 then
+ local id = get_block(x, top, z)
+ if id == 9 or id == 8 then e:set(x, top, z, 79, 0)
+ elseif id ~= 78 and id ~= 80 and id ~= 79 then e:set(x, top + 1, z, 78, 0) end
+ end
+ end
+ end
+ end
+ end)
+end)
+
+reg("/thaw", "Thaws the area", function(ctx)
+ local size = max(1, floor(num(ctx.args[1], 10)))
+ edit_session(ctx, function(e)
+ near_sphere(ctx, size, function(x, y, z)
+ local id = get_block(x, y, z)
+ if id == 78 then e:set(x, y, z, 0, 0) elseif id == 79 then e:set(x, y, z, 9, 0) end
+ end)
+ end)
+end)
+
+reg("/green", "Converts dirt to grass blocks", function(ctx)
+ local size = max(1, floor(num(ctx.args[1], 10)))
+ local ox, _, oz = player_block(ctx)
+ W.load_region({ x0 = ox - size, x1 = ox + size, z0 = oz - size, z1 = oz + size, y0 = 0, y1 = 0 })
+ edit_session(ctx, function(e)
+ for x = ox - size, ox + size do
+ for z = oz - size, oz + size do
+ if (x - ox) ^ 2 + (z - oz) ^ 2 <= size * size then
+ local top = W.top_existing(x, z, 0, 127)
+ if top and get_block(x, top, z) == 3 then e:set(x, top, z, 2, 0) end
+ end
+ end
+ end
+ end)
+end)
+
+reg({ "/extinguish", "/ex", "/ext" }, "Extinguish nearby fire", function(ctx)
+ local size = floor(num(ctx.args[1], 40))
+ edit_session(ctx, function(e)
+ near_sphere(ctx, size, function(x, y, z)
+ if get_block(x, y, z) == 51 then e:set(x, y, z, 0, 0) end
+ end)
+ end)
+end)
+
+reg("/butcher", "Kill all or nearby mobs", function(ctx)
+ local flags, pos = W.parse(ctx.args)
+ local radius = floor(num(pos[1], 0))
+ local x, y, z = ctx.player:pos()
+ local n = mc.world.butcher(x, y, z, radius > 0 and radius or 0, flags.f or flags.a)
+ return "Killed " .. n .. " mobs" .. (radius > 0 and (" in a radius of " .. radius) or "") .. "."
+end)
+
+reg("/toggleplace", "Switch between your position and pos1 for placement", function(ctx)
+ local s = W.session(ctx.player)
+ s.place_at_pos1 = not s.place_at_pos1
+ return "Now placing at " .. (s.place_at_pos1 and "pos #1." or "the block you stand in.")
+end)
+
+-- ------------------------------------------------------------------- tools
+local function held_id(player) local id = player:held(); return id end
+
+reg("/tool", "Bind a tool to the item in your hand", function(ctx)
+ local s = W.session(ctx.player)
+ local item = held_id(ctx.player)
+ if item == 0 then return "Hold an item to bind the tool to." end
+ local sub = ctx.args[1]
+ if sub == "none" or sub == "unbind" then
+ s.tools[item] = nil
+ return "Tool unbound from your current item."
+ elseif sub == "repl" then
+ local p = pattern_or_err(ctx, ctx.args[2])
+ if not p then return end
+ s.tools[item] = { type = "repl", pattern = p }
+ return "Block replacer tool bound to " .. mc.block.name(item) .. "."
+ elseif sub == "info" then
+ s.tools[item] = { type = "info" }
+ return "Block info tool bound."
+ elseif sub == "farwand" then
+ s.tools[item] = { type = "farwand" }
+ return "Far wand tool bound."
+ elseif sub == "navwand" then
+ s.tools[item] = { type = "nav" }
+ return "Navigation wand bound."
+ elseif sub == "selwand" then
+ s.tools[item] = { type = "wand" }
+ return "Selection wand bound."
+ elseif sub == "deltree" then
+ s.tools[item] = { type = "deltree" }
+ return "Floating tree remover bound."
+ elseif sub == "floodfill" or sub == "flood" then
+ local p = pattern_or_err(ctx, ctx.args[2])
+ if not p then return end
+ s.tools[item] = { type = "flood", pattern = p, range = floor(num(ctx.args[3], 5)) }
+ return "Block flood fill tool bound."
+ end
+ return "Usage: /tool "
+end)
+
+reg("/none", "Unbind the tool of your item", function(ctx)
+ local s = W.session(ctx.player)
+ s.tools[held_id(ctx.player)] = nil
+ return "Tool unbound from your current item."
+end)
+
+reg("/mask", "Set the brush mask", function(ctx)
+ local s = W.session(ctx.player)
+ if not ctx.args[1] then s.brush_mask = nil; return "Brush mask disabled." end
+ local m, err = W.mask(ctx.args[1])
+ if not m then return err end
+ s.brush_mask = m
+ return "Brush mask set."
+end)
+
+reg({ "/material", "/mat" }, "Set the brush material", function(ctx)
+ local s = W.session(ctx.player)
+ local p = pattern_or_err(ctx, ctx.args[1])
+ if not p then return end
+ s.brush_material = p
+ return "Brush material set."
+end)
+
+reg("/range", "Set the brush range", function(ctx)
+ local s = W.session(ctx.player)
+ s.brush_range = floor(num(ctx.args[1], 200))
+ return "Brush range set."
+end)
+
+reg("size", "Set the brush size", function(ctx)
+ local s = W.session(ctx.player)
+ s.brush_size = max(1, min(20, floor(num(ctx.args[1], 5))))
+ return "Brush size set to " .. s.brush_size .. "."
+end)
+
+reg({ "/superpickaxe", "/pickaxe", "/sp" }, "Select super pickaxe mode", function(ctx)
+ local s = W.session(ctx.player)
+ local mode = ctx.args[1]
+ if mode == "single" or mode == "area" or mode == "recursive" or mode == "recur" then
+ s.superpick = (mode == "recur") and "recursive" or mode
+ s.superpick_range = floor(num(ctx.args[2], 3))
+ return "Mode changed. Left click with a pickaxe. // to disable."
+ end
+ return "Usage: /sp [range]"
+end)
+
+reg({ "/", ",", "/," }, "Toggle the super pickaxe pickaxe function", function(ctx)
+ local s = W.session(ctx.player)
+ if s.superpick then s.superpick = nil; return "Super pick axe disabled." end
+ s.superpick = "single"
+ return "Super pick axe enabled."
+end)
+
+-- brushes
+local BRUSHES = { sphere = true, cylinder = true, cyl = true, set = true, smooth = true, gravity = true,
+ extinguish = true, ex = true, raise = true, lower = true, butcher = true, kill = true }
+
+reg({ "/brush", "/br" }, "Brush tool", function(ctx)
+ local s = W.session(ctx.player)
+ local item = held_id(ctx.player)
+ if item == 0 then return "Hold an item to bind the brush to." end
+ local flags, pos = W.parse(ctx.args)
+ local kind = pos[1]
+ if kind == "none" or kind == "unbind" then
+ s.tools[item] = nil
+ return "Brush unbound from your current item."
+ end
+ if kind == "s" then kind = "sphere" elseif kind == "c" then kind = "cylinder" elseif kind == "cyl" then kind = "cylinder"
+ elseif kind == "ex" then kind = "extinguish" elseif kind == "kill" then kind = "butcher" end
+ if not kind or not BRUSHES[kind] then
+ return "Usage: /brush ..."
+ end
+ local brush = { type = "brush", kind = kind, hollow = flags.h }
+ local i = 2
+ if kind == "sphere" or kind == "cylinder" then
+ brush.pattern = pattern_or_err(ctx, pos[i]); if not brush.pattern then return end
+ brush.radius = floor(num(pos[i + 1], 2))
+ if kind == "cylinder" then brush.height = floor(num(pos[i + 2], 1)) end
+ elseif kind == "set" then
+ brush.pattern = pattern_or_err(ctx, pos[i + 2] or pos[i]); if not brush.pattern then return end
+ brush.radius = floor(num(pos[i + 1], 2))
+ else
+ brush.radius = floor(num(pos[i], 2))
+ brush.iterations = floor(num(pos[i + 1], 4))
+ end
+ s.tools[item] = brush
+ return "Brush '" .. kind .. "' bound to your current item."
+end)
+
+local function use_brush(player, s, brush, x, y, z)
+ if brush.kind == "extinguish" then
+ local e = W.new_edit(s)
+ for dx = -brush.radius, brush.radius do for dy = -brush.radius, brush.radius do for dz = -brush.radius, brush.radius do
+ if get_block(x + dx, y + dy, z + dz) == 51 then e:set(x + dx, y + dy, z + dz, 0, 0) end
+ end end end
+ e:commit()
+ return
+ elseif brush.kind == "butcher" then
+ mc.world.butcher(x, y, z, brush.radius, false)
+ return
+ end
+ local edit = W.new_edit(s)
+ local mask = s.brush_mask
+ local r = brush.radius
+ W.load_region({ x0 = x - r, x1 = x + r, z0 = z - r, z1 = z + r, y0 = 0, y1 = 0 })
+ if brush.kind == "sphere" then
+ local inner = brush.pattern
+ local pat = inner
+ if mask then
+ pat = function() return inner() end
+ end
+ local guarded = {
+ set = function(_, bx, by, bz, id, d)
+ if mask then local oid, od = get_block(bx, by, bz); if not mask(oid, od) then return end end
+ edit:set(bx, by, bz, id, d)
+ end,
+ place = function(self, bx, by, bz, p) local id, d = p(); self.set(self, bx, by, bz, id, d) end,
+ }
+ W.sphere(guarded, x, y, z, pat, r, r, r, not brush.hollow)
+ elseif brush.kind == "cylinder" then
+ W.cylinder(edit, x, y, z, brush.pattern, r, r, brush.height, not brush.hollow)
+ elseif brush.kind == "set" then
+ for dx = -r, r do for dy = -r, r do for dz = -r, r do
+ if dx * dx + dy * dy + dz * dz <= r * r + 1 then
+ local oid, od = get_block(x + dx, y + dy, z + dz)
+ if not mask or mask(oid, od) then edit:place(x + dx, y + dy, z + dz, brush.pattern) end
+ end
+ end end end
+ elseif brush.kind == "smooth" then
+ smooth_region(edit, { x0 = x - r, x1 = x + r, z0 = z - r, z1 = z + r, y0 = max(0, y - r), y1 = min(127, y + r) }, brush.iterations or 4, mask)
+ elseif brush.kind == "raise" or brush.kind == "lower" then
+ for dx = -r, r do for dz = -r, r do
+ if dx * dx + dz * dz <= r * r then
+ local top = W.top_ground(x + dx, z + dz, 0, 127)
+ if top then
+ if brush.kind == "raise" then
+ local id, d = get_block(x + dx, top, z + dz)
+ edit:set(x + dx, top + 1, z + dz, id, d)
+ else
+ edit:set(x + dx, top, z + dz, 0, 0)
+ end
+ end
+ end
+ end end
+ elseif brush.kind == "gravity" then
+ for dx = -r, r do for dz = -r, r do
+ if dx * dx + dz * dz <= r * r then
+ local bx, bz = x + dx, z + dz
+ local y0 = max(0, y - r)
+ local floorY = y0
+ for yy = y0, min(127, y + r) do
+ local id, d = get_block(bx, yy, bz)
+ if id ~= 0 then
+ if yy ~= floorY then
+ edit:set(bx, floorY, bz, id, d)
+ edit:set(bx, yy, bz, 0, 0)
+ end
+ floorY = floorY + 1
+ end
+ end
+ end
+ end end
+ end
+ edit:commit()
+end
+
+-- ------------------------------------------------------------ item events
+local function is_op(player) return player:is_op() end
+
+-- Adjacent block a right click would have placed (to refresh nothing here, server does it)
+mc.on("block_break", function(player, x, y, z, tile)
+ if not is_op(player) then return end
+ local s = W.session(player)
+ local item = held_id(player)
+
+ if item == WAND and not s.wand_off then
+ set_pos(player, 1, { x, y, z })
+ return false
+ end
+ if item == NAVWAND and not s.wand_off then
+ player:teleport(x + 0.5, y + 1, z + 0.5)
+ return false
+ end
+ local tool = s.tools[item]
+ if tool and tool.type == "wand" then
+ set_pos(player, 1, { x, y, z })
+ return false
+ elseif tool and tool.type == "nav" then
+ player:teleport(x + 0.5, y + 1, z + 0.5)
+ return false
+ end
+
+ -- super pickaxe
+ if s.superpick and PICKAXES[item] then
+ local edit = W.new_edit(s)
+ if s.superpick == "single" then
+ edit:set(x, y, z, 0, 0)
+ elseif s.superpick == "area" then
+ local r = s.superpick_range
+ for dx = -r, r do for dy = -r, r do for dz = -r, r do
+ if dx * dx + dy * dy + dz * dz <= r * r then edit:set(x + dx, y + dy, z + dz, 0, 0) end
+ end end end
+ else
+ local r = s.superpick_range
+ local seen, queue, head = {}, { { x, y, z } }, 1
+ seen[(x * 4096 + z) * 256 + y] = true
+ while head <= #queue do
+ local p = queue[head]; head = head + 1
+ if get_block(p[1], p[2], p[3]) == tile then
+ edit:set(p[1], p[2], p[3], 0, 0)
+ for _, n in ipairs({ { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } }) do
+ local nx, ny, nz = p[1] + n[1], p[2] + n[2], p[3] + n[3]
+ local k = (nx * 4096 + nz) * 256 + ny
+ if not seen[k] and abs(nx - x) <= r and abs(ny - y) <= r and abs(nz - z) <= r then
+ seen[k] = true
+ queue[#queue + 1] = { nx, ny, nz }
+ end
+ end
+ end
+ end
+ end
+ edit:commit()
+ return false
+ end
+end)
+
+mc.on("use_item", function(player, x, y, z, face, item, aux)
+ if not is_op(player) then return end
+ local s = W.session(player)
+
+ if item == WAND and not s.wand_off then
+ set_pos(player, 2, { x, y, z })
+ return false
+ end
+ if item == NAVWAND and not s.wand_off then
+ -- /thru
+ local px, py, pz = player:pos()
+ local _, dx, dz = player:facing()
+ local bx, by, bz = floor(px), floor(py), floor(pz)
+ local inWall = false
+ for i = 1, 100 do
+ local cx, cz = bx + dx * i, bz + dz * i
+ if not free(cx, by, cz) or not free(cx, by + 1, cz) then inWall = true
+ elseif inWall then player:teleport(cx + 0.5, by, cz + 0.5); break end
+ end
+ return false
+ end
+
+ local tool = s.tools[item]
+ if not tool then return end
+ if tool.type == "repl" then
+ local e = W.new_edit(s)
+ e:place(x, y, z, tool.pattern)
+ e:commit()
+ return false
+ elseif tool.type == "info" then
+ local id, d = get_block(x, y, z)
+ player:say(string.format("%s (%d:%d) at (%d, %d, %d)", mc.block.name(id), id, d, x, y, z))
+ return false
+ elseif tool.type == "wand" then
+ set_pos(player, 2, { x, y, z })
+ return false
+ elseif tool.type == "nav" then
+ return false
+ elseif tool.type == "flood" then
+ local e = W.new_edit(s)
+ local target = get_block(x, y, z)
+ local seen, queue, head = {}, { { x, y, z } }, 1
+ seen[(x * 4096 + z) * 256 + y] = true
+ while head <= #queue do
+ local p = queue[head]; head = head + 1
+ e:place(p[1], p[2], p[3], tool.pattern)
+ for _, n in ipairs({ { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } }) do
+ local nx, ny, nz = p[1] + n[1], p[2] + n[2], p[3] + n[3]
+ local k = (nx * 4096 + nz) * 256 + ny
+ if not seen[k] and abs(nx - x) <= tool.range and abs(ny - y) <= tool.range and abs(nz - z) <= tool.range
+ and get_block(nx, ny, nz) == target then
+ seen[k] = true
+ queue[#queue + 1] = { nx, ny, nz }
+ end
+ end
+ end
+ e:commit()
+ return false
+ elseif tool.type == "farwand" then
+ set_pos(player, 2, { x, y, z })
+ return false
+ elseif tool.type == "deltree" then
+ local e = W.new_edit(s)
+ local seen, queue, head = {}, { { x, y, z } }, 1
+ while head <= #queue and #queue < 4000 do
+ local p = queue[head]; head = head + 1
+ local id = get_block(p[1], p[2], p[3])
+ if id == 17 or id == 18 then
+ e:set(p[1], p[2], p[3], 0, 0)
+ for _, n in ipairs({ { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } }) do
+ local nx, ny, nz = p[1] + n[1], p[2] + n[2], p[3] + n[3]
+ local k = (nx * 4096 + nz) * 256 + ny
+ if not seen[k] then seen[k] = true; queue[#queue + 1] = { nx, ny, nz } end
+ end
+ end
+ end
+ e:commit()
+ return false
+ elseif tool.type == "brush" then
+ use_brush(player, s, tool, x, y, z)
+ return false
+ end
+end)
+
+mc.log("WorldEdit loaded: " .. #mc._command_names() .. " commands registered")
diff --git a/package-windows.ps1 b/package-windows.ps1
new file mode 100644
index 0000000..b1e78f9
--- /dev/null
+++ b/package-windows.ps1
@@ -0,0 +1,76 @@
+<#
+ Builds the Windows client and dedicated server (Release, x64) and assembles
+ ready to run folders:
+
+ dist\MinecraftPE-win64\ client (MinecraftPE.exe, data\, lua\, mods\)
+ dist\MinecraftPE-server-win64\ server (MinecraftPE-server.exe, lua\, mods\)
+
+ Requirements: Visual Studio 2022 (C++ workload) and CMake. The first run downloads
+ the dependencies (zlib, libpng, glfw, OpenAL Soft, LuaJIT, stb) with git.
+
+ .\package-windows.ps1 full build + package
+ .\package-windows.ps1 -NoBuild only (re)assemble dist from an existing build
+ .\package-windows.ps1 -Jobs 2 fewer parallel compiler jobs (low memory machines)
+#>
+param(
+ [switch]$NoBuild,
+ [int]$Jobs = 4
+)
+
+$ErrorActionPreference = 'Stop'
+$root = $PSScriptRoot
+$build = Join-Path $root 'build'
+$dist = Join-Path $root 'dist'
+
+# The dependencies are cloned with git; drives that do not record file ownership make git refuse
+# that ("dubious ownership"). Tell git to trust directories for this process only.
+$env:GIT_CONFIG_COUNT = '1'
+$env:GIT_CONFIG_KEY_0 = 'safe.directory'
+$env:GIT_CONFIG_VALUE_0 = '*'
+
+if (-not $NoBuild) {
+ cmake -S $root -B $build -G 'Visual Studio 17 2022' -A x64
+ if ($LASTEXITCODE -ne 0) { throw 'CMake configure failed' }
+
+ # OpenAL Soft needs a lot of memory per compiler process, so the compiler parallelism is limited
+ cmake --build $build --config Release --parallel $Jobs -- /p:CL_MPCount=2
+ if ($LASTEXITCODE -ne 0) { throw 'Build failed' }
+}
+
+$rel = Join-Path $build 'Release'
+foreach ($f in 'MinecraftPE.exe', 'MinecraftPE-server.exe') {
+ if (-not (Test-Path (Join-Path $rel $f))) { throw "$f not found in $rel" }
+}
+
+if (Test-Path $dist) { Remove-Item $dist -Recurse -Force }
+
+# ---- client
+$client = Join-Path $dist 'MinecraftPE-win64'
+New-Item -ItemType Directory -Force $client | Out-Null
+Copy-Item (Join-Path $rel 'MinecraftPE.exe') $client
+Get-ChildItem $rel -Filter *.dll | Copy-Item -Destination $client
+Copy-Item (Join-Path $root 'data') $client -Recurse
+Copy-Item (Join-Path $root 'lua') $client -Recurse
+Copy-Item (Join-Path $root 'mods') $client -Recurse
+
+# ---- server
+$server = Join-Path $dist 'MinecraftPE-server-win64'
+New-Item -ItemType Directory -Force $server | Out-Null
+Copy-Item (Join-Path $rel 'MinecraftPE-server.exe') $server
+Copy-Item (Join-Path $root 'lua') $server -Recurse
+Copy-Item (Join-Path $root 'mods') $server -Recurse
+@"
+port=19132
+level-dir=level
+level-cachepath=.
+level-externalpath=.
+gamemode=creative
+level-name=level
+view-distance=10
+"@ | Set-Content (Join-Path $server 'server.properties') -Encoding ascii
+Set-Content (Join-Path $server 'start-server.bat') "@echo off`r`nMinecraftPE-server.exe`r`npause" -Encoding ascii
+
+Write-Host ''
+Write-Host 'Done:'
+Write-Host " $client"
+Write-Host " $server"
diff --git a/src/SharedConstants.h b/src/SharedConstants.h
index f97ea36..e9394c5 100755
--- a/src/SharedConstants.h
+++ b/src/SharedConstants.h
@@ -16,8 +16,8 @@ namespace SharedConstants
{
// 0.5.0 uses NPv8
// 0.6.0 uses NPv9
- const int NetworkProtocolVersion = 9;
- const int NetworkProtocolLowestSupportedVersion = 9;
+ const int NetworkProtocolVersion = 10;
+ const int NetworkProtocolLowestSupportedVersion = 10;
const int GameProtocolVersion = 1;
const int GameProtocolLowestSupportedVersion = 1;
diff --git a/src/client/Minecraft.cpp b/src/client/Minecraft.cpp
index ded2191..eba68a1 100755
--- a/src/client/Minecraft.cpp
+++ b/src/client/Minecraft.cpp
@@ -3,6 +3,7 @@
#include "client/Options.h"
#include "client/player/input/IBuildInput.h"
#include "commands/CommandManager.hpp"
+#include "lua/LuaEngine.h"
#include "platform/input/Keyboard.h"
#include "world/item/Item.h"
#include "world/item/ItemInstance.h"
@@ -223,6 +224,7 @@ Minecraft::~Minecraft()
screen = NULL;
}
#endif
+ LuaEngine::get().stop();
if (level != NULL) {
level->saveGame();
if (level->getChunkSource())
@@ -330,6 +332,8 @@ void Minecraft::leaveGame(bool renameLevel /*=false*/)
level->getChunkSource()->saveAll(true);
}
+ LuaEngine::get().stop();
+
LOGI("Clearing levels\n");
cameraTargetPlayer = NULL;
@@ -375,14 +379,22 @@ void Minecraft::prepareLevel(const std::string& title) {
if (!level->isNew())
level->setUpdateLights(false);
- int Max = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH;
+ // The world is infinite: only the area around the spawn point is generated
+ // up front, everything else is streamed in around the players while playing.
+ if (level->isNew() && !level->isClientSide) {
+ level->setInitialSpawn(); // @note: should obviously be called from Level itself
+ }
+ const Pos spawn = level->getSharedSpawnPos();
+ const int spawnCx = spawn.x >> 4;
+ const int spawnCz = spawn.z >> 4;
+ const int PrepareRadius = level->isClientSide ? -1 : 4; // a client gets its chunks from the server
+ const int Max = (2 * PrepareRadius + 1) * (2 * PrepareRadius + 1);
int pp = 0;
- for (int x = 8; x < (LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH); x += LevelConstants::CHUNK_WIDTH) {
- for (int z = 8; z < (LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH); z += LevelConstants::CHUNK_WIDTH) {
- progressStagePercentage = 100 * pp++ / Max;
- //printf("level generation progress %d\n", progressStagePercentage);
+ for (int cx = spawnCx - PrepareRadius; cx <= spawnCx + PrepareRadius; cx++) {
+ for (int cz = spawnCz - PrepareRadius; cz <= spawnCz + PrepareRadius; cz++) {
+ progressStagePercentage = 100 * pp++ / Max;
B.start();
- level->getTile(x, 64, z);
+ level->getChunk(cx, cz);
B.stop();
L.start();
if (level->isNew())
@@ -395,11 +407,12 @@ void Minecraft::prepareLevel(const std::string& title) {
level->setUpdateLights(true);
C.start();
- for (int x = 0; x < LevelConstants::CHUNK_CACHE_WIDTH; x++)
{
- for (int z = 0; z < LevelConstants::CHUNK_CACHE_WIDTH; z++)
+ std::vector loadedChunks;
+ level->getChunkSource()->getLoadedChunks(loadedChunks);
+ for (unsigned int i = 0; i < loadedChunks.size(); i++)
{
- LevelChunk* chunk = level->getChunk(x, z);
+ LevelChunk* chunk = loadedChunks[i];
if (chunk && !chunk->createdFromSave)
{
chunk->unsaved = false;
@@ -412,7 +425,6 @@ void Minecraft::prepareLevel(const std::string& title) {
LOGI("status: 3\n");
progressStageStatusId = 3;
if (level->isNew()) {
- level->setInitialSpawn(); // @note: should obviously be called from Level itself
level->saveLevelData();
level->getChunkSource()->saveAll(false);
level->saveGame();
@@ -570,6 +582,10 @@ void Minecraft::tick(int nTick, int maxTick) {
TIMER_POP_PUSH("level");
level->tickEntities();
level->tick();
+ if (!level->isClientSide) LuaEngine::get().tick();
+ if (level->isClientSide && netCallback && !raknetInstance->isServer()) {
+ ((ClientSideNetworkHandler*)netCallback)->updateChunks();
+ }
#ifndef STANDALONE_SERVER
TIMER_POP_PUSH("animateTick");
if (player) {
@@ -1473,6 +1489,8 @@ void Minecraft::_levelGenerated()
level->loadPlayer(player, true);
// if we are client side, we trust the server to have given us a correct position
if (player && !level->isClientSide) {
+ // the saved position can be anywhere in the (infinite) world
+ level->ensureChunksAround((int)player->x, (int)player->z, 3);
player->resetPos(false);
}
@@ -1493,6 +1511,11 @@ void Minecraft::_levelGenerated()
netCallback->levelGenerated(level);
}
+ // Lua mods run where the world is hosted
+ if (!level->isClientSide) {
+ LuaEngine::get().start(this);
+ }
+
#if defined(WIN32) || defined(RPI)
if (_commandServer) {
delete _commandServer;
diff --git a/src/client/gamemode/GameMode.cpp b/src/client/gamemode/GameMode.cpp
index 8009d64..0092c50 100755
--- a/src/client/gamemode/GameMode.cpp
+++ b/src/client/gamemode/GameMode.cpp
@@ -16,6 +16,7 @@
#include "../renderer/LevelRenderer.h"
#endif
#include "../../world/level/material/Material.h"
+#include "../../lua/LuaEngine.h"
GameMode::GameMode( Minecraft* minecraft)
: minecraft(minecraft),
@@ -59,6 +60,9 @@ bool GameMode::destroyBlock(int x, int y, int z, int face) {
if (!oldTile)
return false;
+ if (!level->isClientSide && minecraft->player && LuaEngine::get().onBlockBreak(minecraft->player, x, y, z))
+ return false; // cancelled by a Lua mod
+
if (level->adventureSettings.immutableWorld) {
if (oldTile != (Tile*)Tile::leaves
&& oldTile->material != Material::plant) {
@@ -89,6 +93,8 @@ bool GameMode::useItemOn(Player* player, Level* level, ItemInstance* item, int x
float clickX = hit.x - x;
float clickY = hit.y - y;
float clickZ = hit.z - z;
+ if (!level->isClientSide && player == minecraft->player && LuaEngine::get().onUseItem(player, x, y, z, face, item))
+ return true; // cancelled by a Lua mod
if (level->isClientSide) {
LOGI("%f %f %f \n", player->x, player->y, player->z);
diff --git a/src/client/gui/screens/ConsoleScreen.cpp b/src/client/gui/screens/ConsoleScreen.cpp
index 9d3e874..8eae25f 100644
--- a/src/client/gui/screens/ConsoleScreen.cpp
+++ b/src/client/gui/screens/ConsoleScreen.cpp
@@ -9,6 +9,17 @@
#include "../../../network/packet/MessagePacket.h"
#include "../../../platform/log.h"
#include "util/StringUtils.h"
+#include "../../../network/packet/SetSkinPacket.h"
+#include
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include
+#endif
#include
#include
@@ -63,6 +74,11 @@ void ConsoleScreen::execute()
return minecraft->setScreen(NULL);
}
+ if (_input == "/skin" || _input.compare(0, 6, "/skin ") == 0) {
+ executeSkinCommand(_input.size() > 6 ? Util::stringTrim(_input.substr(6)) : "");
+ return minecraft->setScreen(NULL);
+ }
+
if (minecraft->netCallback && !minecraft->raknetInstance->isServer()) {
MessagePacket packet(_input.c_str());
minecraft->raknetInstance->send(packet);
@@ -89,6 +105,62 @@ void ConsoleScreen::execute()
minecraft->setScreen(NULL);
}
+// /skin [list|auto|]: purely client side, the choice is announced to the server
+void ConsoleScreen::executeSkinCommand(const std::string& arg)
+{
+ const std::string dir = "data/images/skins/";
+ std::vector names;
+#ifdef _WIN32
+ WIN32_FIND_DATAA fd;
+ HANDLE h = FindFirstFileA((dir + "*.png").c_str(), &fd);
+ if (h != INVALID_HANDLE_VALUE) {
+ do {
+ std::string n = fd.cFileName;
+ names.push_back(n.substr(0, n.size() - 4));
+ } while (FindNextFileA(h, &fd));
+ FindClose(h);
+ }
+#endif
+
+ if (arg.empty() || arg == "list") {
+ std::string line = "Skins:";
+ for (size_t i = 0; i < names.size(); ++i) line += " " + names[i];
+ minecraft->gui.addMessage(line);
+ minecraft->gui.addMessage("Use /skin , or /skin auto for the one of your account.");
+ return;
+ }
+
+ LocalPlayer* player = minecraft->player;
+ if (!player) return;
+
+ if (arg == "auto") {
+ minecraft->options.set(OPTIONS_SKIN, std::string("Default"));
+ minecraft->options.save();
+ player->skinName.clear();
+ player->setTextureName("skins/" + player->name + ".png");
+ minecraft->gui.addMessage("Skin reset, it is picked from your username after a restart.");
+ return;
+ }
+
+ bool found = false;
+ for (size_t i = 0; i < names.size(); ++i) if (names[i] == arg) found = true;
+ if (!found) {
+ minecraft->gui.addMessage("No skin named '" + arg + "'. Try /skin list");
+ return;
+ }
+
+ minecraft->options.set(OPTIONS_SKIN, arg);
+ minecraft->options.save();
+ player->skinName = arg;
+ player->setTextureName("skins/" + arg + ".png");
+ minecraft->gui.addMessage("You now wear the '" + arg + "' skin.");
+
+ if (minecraft->level && (minecraft->level->isClientSide || minecraft->raknetInstance->isServer())) {
+ SetSkinPacket packet(player->entityId, arg);
+ minecraft->raknetInstance->send(packet);
+ }
+}
+
// ---------------------------------------------------------------------------
// render
// ---------------------------------------------------------------------------
diff --git a/src/client/gui/screens/ConsoleScreen.h b/src/client/gui/screens/ConsoleScreen.h
index f0c1fd5..80fd859 100644
--- a/src/client/gui/screens/ConsoleScreen.h
+++ b/src/client/gui/screens/ConsoleScreen.h
@@ -25,6 +25,7 @@ public:
private:
void execute();
+ void executeSkinCommand(const std::string& arg);
std::string _input;
int _cursorBlink; // tick counter for cursor blink
diff --git a/src/client/player/LocalPlayer.cpp b/src/client/player/LocalPlayer.cpp
index 29ccf44..738b513 100755
--- a/src/client/player/LocalPlayer.cpp
+++ b/src/client/player/LocalPlayer.cpp
@@ -370,9 +370,18 @@ LocalPlayer::LocalPlayer(Minecraft* minecraft, Level* level, const std::string&
this->name = minecraft->options.getStringValue(OPTIONS_USERNAME);
printf("test \n");
+ // A skin picked with /skin wins over the one from the Mojang servers
+ const std::string chosenSkin = minecraft->options.getStringValue(OPTIONS_SKIN);
+ const bool hasChosenSkin = !chosenSkin.empty() && chosenSkin != "Default"
+ && fileExists("data/images/skins/" + chosenSkin + ".png");
+ if (hasChosenSkin) {
+ textureName = "skins/" + chosenSkin + ".png";
+ skinName = chosenSkin;
+ }
+
// Fetch user skin and cape from Mojang servers in the background (avoids blocking the main thread)
// TODO: Fix this memory leak
- new CThread(fetchSkinForPlayer, this);
+ if (!hasChosenSkin) new CThread(fetchSkinForPlayer, this);
new CThread(fetchCapeForPlayer, this);
}
#endif
diff --git a/src/client/renderer/Chunk.cpp b/src/client/renderer/Chunk.cpp
index 527508a..0d98df5 100755
--- a/src/client/renderer/Chunk.cpp
+++ b/src/client/renderer/Chunk.cpp
@@ -99,6 +99,14 @@ void Chunk::rebuild()
LevelChunk::touchedSky = false;
+ // The world is streamed in: wait until this part and its surroundings exist.
+ // (the chunk cache marks the area dirty again once more chunks arrive)
+ if (!level->hasChunksAt(x0 - 1, 0, z0 - 1, x1 + 1, 1, z1 + 1)) {
+ skyLit = false;
+ compiled = true;
+ return;
+ }
+
int r = 1;
Region region(level, x0 - r, y0 - r, z0 - r, x1 + r, y1 + r, z1 + r);
TileRenderer tileRenderer(®ion);
diff --git a/src/client/renderer/LevelRenderer.cpp b/src/client/renderer/LevelRenderer.cpp
index 1ce3ffd..4b804a5 100755
--- a/src/client/renderer/LevelRenderer.cpp
+++ b/src/client/renderer/LevelRenderer.cpp
@@ -69,7 +69,8 @@ LevelRenderer::LevelRenderer( Minecraft* mc)
destroyProgress(0)
{
#ifdef OPENGL_ES
- int maxChunksWidth = 2 * LevelConstants::LEVEL_WIDTH / CHUNK_SIZE + 1;
+ // enough render chunks for the largest possible view distance (400 blocks, see allChanged)
+ int maxChunksWidth = 400 / CHUNK_SIZE + 1;
numListsOrBuffers = maxChunksWidth * maxChunksWidth * (128/CHUNK_SIZE) * 3;
chunkBuffers = new GLuint[numListsOrBuffers];
glGenBuffers2(numListsOrBuffers, chunkBuffers);
@@ -209,6 +210,14 @@ void LevelRenderer::allChanged()
/*
* if (Minecraft.FLYBY_MODE) { dist = 512 - CHUNK_SIZE * 2; }
*/
+
+ // The world is infinite: keep as many chunks around the player as can be seen
+ {
+ int chunkRadius = dist / 16 + 2;
+ if (chunkRadius < 4) chunkRadius = 4;
+ if (chunkRadius > 16) chunkRadius = 16;
+ LevelConstants::VIEW_DISTANCE_CHUNKS = chunkRadius;
+ }
xChunks = (dist / LevelRenderer::CHUNK_SIZE) + 1;
yChunks = (128 / LevelRenderer::CHUNK_SIZE);
zChunks = (dist / LevelRenderer::CHUNK_SIZE) + 1;
diff --git a/src/client/sound/MusicPlayer.cpp b/src/client/sound/MusicPlayer.cpp
new file mode 100644
index 0000000..366a635
--- /dev/null
+++ b/src/client/sound/MusicPlayer.cpp
@@ -0,0 +1,228 @@
+#include "MusicPlayer.h"
+
+#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
+
+#include
+#include
+
+#define STB_VORBIS_HEADER_ONLY
+#include "stb_vorbis.c"
+
+#include
+#include
+#include
+
+#include "../../platform/log.h"
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include
+#else
+#include
+#endif
+
+namespace {
+
+const char* MUSIC_DIR = "data/music";
+const int BUFFER_COUNT = 4;
+const int FRAMES_PER_BUFFER = 32768;
+
+double now() {
+ using namespace std::chrono;
+ return duration_cast >(steady_clock::now().time_since_epoch()).count();
+}
+
+bool endsWith(const std::string& s, const char* suffix) {
+ std::string suf(suffix);
+ if (s.size() < suf.size()) return false;
+ for (size_t i = 0; i < suf.size(); ++i)
+ if (tolower((unsigned char)s[s.size() - suf.size() + i]) != suf[i]) return false;
+ return true;
+}
+
+} // namespace
+
+MusicPlayer::MusicPlayer()
+: scanned(false),
+ alReady(false),
+ state(Waiting),
+ nextStart(0),
+ lastTrack(-1),
+ source(0),
+ decoder(NULL),
+ channels(2),
+ sampleRate(44100),
+ decoderDone(false)
+{
+ for (int i = 0; i < BUFFER_COUNT; ++i) buffers[i] = 0;
+ srand((unsigned int)time(NULL));
+}
+
+MusicPlayer::~MusicPlayer()
+{
+ stop();
+}
+
+void MusicPlayer::scan()
+{
+ scanned = true;
+ tracks.clear();
+#ifdef _WIN32
+ WIN32_FIND_DATAA fd;
+ HANDLE h = FindFirstFileA((std::string(MUSIC_DIR) + "/*").c_str(), &fd);
+ if (h != INVALID_HANDLE_VALUE) {
+ do {
+ std::string name = fd.cFileName;
+ if (endsWith(name, ".ogg")) tracks.push_back(std::string(MUSIC_DIR) + "/" + name);
+ } while (FindNextFileA(h, &fd));
+ FindClose(h);
+ }
+#else
+ if (DIR* d = opendir(MUSIC_DIR)) {
+ while (dirent* e = readdir(d)) {
+ std::string name = e->d_name;
+ if (endsWith(name, ".ogg")) tracks.push_back(std::string(MUSIC_DIR) + "/" + name);
+ }
+ closedir(d);
+ }
+#endif
+ LOGI("MusicPlayer: %d tracks found in %s\n", (int)tracks.size(), MUSIC_DIR);
+ nextStart = now() + 8.0; // let the world appear before the first track
+}
+
+void MusicPlayer::closeTrack()
+{
+ if (source) {
+ alSourceStop(source);
+ ALint queued = 0;
+ alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
+ while (queued-- > 0) {
+ ALuint b;
+ alSourceUnqueueBuffers(source, 1, &b);
+ }
+ }
+ if (decoder) {
+ stb_vorbis_close(decoder);
+ decoder = NULL;
+ }
+ state = Waiting;
+ trackName.clear();
+}
+
+void MusicPlayer::stop()
+{
+ if (!alReady) return;
+ closeTrack();
+ if (source) alDeleteSources(1, &source);
+ alDeleteBuffers(BUFFER_COUNT, buffers);
+ source = 0;
+ alReady = false;
+}
+
+bool MusicPlayer::fillBuffer(unsigned int buffer)
+{
+ if (decoderDone || !decoder) return false;
+ pcm.resize((size_t)FRAMES_PER_BUFFER * channels);
+ int frames = stb_vorbis_get_samples_short_interleaved(decoder, channels, &pcm[0], FRAMES_PER_BUFFER * channels);
+ if (frames <= 0) {
+ decoderDone = true;
+ return false;
+ }
+ alBufferData(buffer, channels == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16, &pcm[0],
+ frames * channels * (int)sizeof(short), sampleRate);
+ return true;
+}
+
+bool MusicPlayer::startTrack(const std::string& path)
+{
+ int error = 0;
+ decoder = stb_vorbis_open_filename(path.c_str(), &error, NULL);
+ if (!decoder) {
+ LOGE("MusicPlayer: cannot open %s (%d)\n", path.c_str(), error);
+ return false;
+ }
+ stb_vorbis_info info = stb_vorbis_get_info(decoder);
+ channels = info.channels > 1 ? 2 : 1;
+ sampleRate = (int)info.sample_rate;
+ decoderDone = false;
+
+ int queued = 0;
+ for (int i = 0; i < BUFFER_COUNT; ++i) {
+ if (!fillBuffer(buffers[i])) break;
+ alSourceQueueBuffers(source, 1, &buffers[i]);
+ ++queued;
+ }
+ if (queued == 0) {
+ stb_vorbis_close(decoder);
+ decoder = NULL;
+ return false;
+ }
+ alSourcePlay(source);
+ state = Playing;
+
+ size_t slash = path.find_last_of('/');
+ trackName = path.substr(slash == std::string::npos ? 0 : slash + 1);
+ LOGI("MusicPlayer: now playing %s\n", trackName.c_str());
+ return true;
+}
+
+void MusicPlayer::update(float volume)
+{
+ if (!scanned) scan();
+ if (tracks.empty()) return;
+
+ // the OpenAL context is created by the sound system
+ if (!alReady) {
+ if (!alcGetCurrentContext()) return;
+ alGenSources(1, &source);
+ alGenBuffers(BUFFER_COUNT, buffers);
+ alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE);
+ alSource3f(source, AL_POSITION, 0, 0, 0);
+ alSourcef(source, AL_ROLLOFF_FACTOR, 0);
+ alReady = true;
+ }
+
+ if (volume <= 0.0f) {
+ if (state == Playing) closeTrack();
+ return;
+ }
+
+ if (state == Waiting) {
+ if (now() < nextStart) return;
+ int pick = rand() % (int)tracks.size();
+ if (tracks.size() > 1 && pick == lastTrack) pick = (pick + 1) % (int)tracks.size();
+ lastTrack = pick;
+ if (!startTrack(tracks[pick])) nextStart = now() + 20.0;
+ else alSourcef(source, AL_GAIN, volume * 0.6f);
+ return;
+ }
+
+ // Playing: keep the queue filled
+ alSourcef(source, AL_GAIN, volume * 0.6f);
+
+ ALint processed = 0;
+ alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
+ while (processed-- > 0) {
+ ALuint b;
+ alSourceUnqueueBuffers(source, 1, &b);
+ if (fillBuffer(b)) alSourceQueueBuffers(source, 1, &b);
+ }
+
+ ALint queued = 0, srcState = 0;
+ alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
+ alGetSourcei(source, AL_SOURCE_STATE, &srcState);
+ if (queued == 0) {
+ // finished: pause for a while before the next track
+ closeTrack();
+ nextStart = now() + 45.0 + (rand() % 120);
+ } else if (srcState != AL_PLAYING) {
+ alSourcePlay(source); // underrun
+ }
+}
+
+#endif // PLATFORM_DESKTOP
diff --git a/src/client/sound/MusicPlayer.h b/src/client/sound/MusicPlayer.h
new file mode 100644
index 0000000..bb83702
--- /dev/null
+++ b/src/client/sound/MusicPlayer.h
@@ -0,0 +1,48 @@
+#pragma once
+
+#include
+#include
+
+struct stb_vorbis;
+
+/**
+ * Plays the OGG tracks found in "data/music" in random order with pauses in
+ * between, streamed through OpenAL. Volume comes from the music volume option.
+ * Needs the OpenAL context created by SoundSystemAL.
+ */
+class MusicPlayer {
+public:
+ MusicPlayer();
+ ~MusicPlayer();
+
+ // Call once per frame. `volume` is 0..1.
+ void update(float volume);
+
+ void stop();
+ const std::string& currentTrack() const { return trackName; }
+
+private:
+ void scan();
+ bool startTrack(const std::string& path);
+ bool fillBuffer(unsigned int buffer);
+ void closeTrack();
+
+ enum State { Waiting, Playing };
+
+ bool scanned;
+ bool alReady;
+ State state;
+ double nextStart;
+ int lastTrack;
+
+ std::vector tracks;
+ std::string trackName;
+
+ unsigned int source;
+ unsigned int buffers[4];
+ stb_vorbis* decoder;
+ int channels;
+ int sampleRate;
+ std::vector pcm;
+ bool decoderDone;
+};
diff --git a/src/client/sound/SoundEngine.cpp b/src/client/sound/SoundEngine.cpp
index 2f847fb..d6e43d9 100755
--- a/src/client/sound/SoundEngine.cpp
+++ b/src/client/sound/SoundEngine.cpp
@@ -169,6 +169,9 @@ void SoundEngine::destroy()
void SoundEngine::update( Mob* player, float a )
{
+#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
+ music.update(options ? options->getProgressValue(OPTIONS_MUSIC_VOLUME) : 0.0f);
+#endif
if (/*!loaded || */options->getProgressValue(OPTIONS_SOUND_VOLUME) == 0) return;
if (player == NULL) return;
diff --git a/src/client/sound/SoundEngine.h b/src/client/sound/SoundEngine.h
index bf3d131..3d2220e 100755
--- a/src/client/sound/SoundEngine.h
+++ b/src/client/sound/SoundEngine.h
@@ -17,6 +17,10 @@ class Minecraft;
class Mob;
class Options;
+#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
+#include "MusicPlayer.h"
+#endif
+
class SoundEngine
{
static const int SOUND_DISTANCE = 16;
@@ -29,6 +33,10 @@ class SoundEngine
SoundSystem soundSystem;
#endif
+#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
+ MusicPlayer music;
+#endif
+
Options* options;
int idCounter;
//static bool loaded;
diff --git a/src/commands/CommandManager.cpp b/src/commands/CommandManager.cpp
index 16b331c..b82a640 100644
--- a/src/commands/CommandManager.cpp
+++ b/src/commands/CommandManager.cpp
@@ -12,6 +12,7 @@
#include "network/packet/ChatPacket.h"
#include "network/RakNetInstance.h"
#include "world/level/Level.h"
+#include "lua/LuaEngine.h"
CommandManager::CommandManager() {
registerAllCommands();
@@ -31,6 +32,9 @@ std::vector CommandManager::getListAllCommands() {
for (auto& cmd : m_commands) {
ret.push_back(cmd->getName());
}
+ for (auto& name : LuaEngine::get().commandNames()) {
+ ret.push_back(name);
+ }
return ret;
}
@@ -45,15 +49,20 @@ std::string CommandManager::execute(Minecraft& mc, Player& player, const std::st
return it->getName() == cmd;
});
- if (it == m_commands.end()) {
- return "Command /" + cmd + " not found";
- }
-
std::vector args;
std::string tok;
while (ss >> tok) args.push_back(tok);
+ if (it == m_commands.end()) {
+ // maybe a command registered by a Lua mod
+ std::string reply;
+ if (LuaEngine::get().runCommand(&player, cmd, args, reply)) {
+ return reply;
+ }
+ return "Command /" + cmd + " not found";
+ }
+
return (*it)->execute(mc, player, args);
}
diff --git a/src/lua/LuaEngine.cpp b/src/lua/LuaEngine.cpp
new file mode 100644
index 0000000..d3aad99
--- /dev/null
+++ b/src/lua/LuaEngine.cpp
@@ -0,0 +1,628 @@
+#include "LuaEngine.h"
+
+extern "C" {
+#include "lua.h"
+#include "lauxlib.h"
+#include "lualib.h"
+}
+
+#include
+#include
+#include
+#include