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 0ec4358..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 @@ -16,7 +17,9 @@ endif() enum_option(PLATFORM "Desktop;Web" "Platform to build for.") -find_package(Threads REQUIRED) +if(NOT EMSCRIPTEN) + find_package(Threads REQUIRED) +endif() find_package(OpenSSL) if (${PLATFORM} STREQUAL "Desktop") @@ -97,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" @@ -194,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" @@ -215,6 +229,7 @@ file(GLOB SERVER_SOURCES "src/world/phys/HitResult.cpp" "src/commands/*.cpp" + "src/lua/*.cpp" ) file(GLOB CLIENT_SOURCES @@ -300,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 @@ -316,10 +332,20 @@ 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}) +if(WIN32) + target_sources(${PROJECT_NAME} PRIVATE data/images/pe.rc) +endif() + target_compile_definitions(${PROJECT_NAME} PUBLIC ${PLATFORM_CPP}) target_include_directories(${PROJECT_NAME} PUBLIC @@ -327,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" ) @@ -375,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) @@ -396,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 ebdc8cb..9b2fc0c 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,47 @@ # MinecraftPE > [!Warning] -> Github repository **isnt main**. All issues and pull requests should be send in [Gitea Repository](https://gitea.sffempire.ru/Kolyah35/minecraft-pe-0.6.1). +> [Github repository](https://github.com/Minecraft-PE-0-6-1/minecraft-pe-0.6.1-on-all) **isnt main**. All issues and pull requests should be send in [Gitea Repository](https://gitea.sffnetwork.ru/Kolyah35/minecraft-pe-0.6.1). -> [!Important] -> We have a discord server, where you can report bugs or send feedback https://discord.gg/c58YesBxve +> [!Note] +> There is unofficial (not related to Kolyah35 and InviseDivine) discord server, where you can report bugs or send feedback https://discord.gg/udYrbNDfDH Source code for **Minecraft Pocket Edition 0.6.1 alpha** with various fixes and improvements. This project aims to preserve and improve this early version of Minecraft PE. -# TODO / Roadmap -- [x] Add platform GLFW -- [x] Compile for Linux -- [x] Compile for android aarch64 - - [x] Touch control improvements - - [ ] Screen fixes -- [ ] Rewrite platform logic -- [x] Fix sound -- [x] Do a server connection GUI -- [ ] Controller support -- [x] Minecraft server hosting -- [x] Screen fixess -- [x] Fix fog -- [x] Add sprinting -- [x] Chat (semi working) and commands -- [x] Implementing options -- [x] Better F3 +# Features +- Support for modern IOS and Android, Linux, Web +- Improved Dedicated Server (Windows build, anticheat, commands, etc) +- Features from Beta version of Minecraft (Grass tint, Beta sky, Smooth lighting, etc) and other tweaks + +# Screenshots +

+ +menu +settings +worlds +gameplay + +

+ + +# 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 @@ -79,8 +95,14 @@ cmake --build . ``` C:\android-ndk-r14b ``` +3. Install **Build tools 35** with [SDKManager](https://dl.google.com/android/repository/commandlinetools-win-15859902_latest.zip) (build-tools should be in AppData): -3. Run the build script: +```powershell +sdkmanager "build-tools;35.0.0" --sdk_root="%LocalAppData%\Android\Sdk" +sdkmanager "build-tools;android-36" --sdk_root="%LocalAppData%\Android\Sdk" +``` + +4. Run the build script: ```powershell # Full build (NDK + Java + APK + install) @@ -154,7 +176,6 @@ cmake --build . ```bash 35.0.0 - 33.0.2 ``` 6. Download **Android NDK r14b**: @@ -200,7 +221,7 @@ cmake --build . ``` ## iOS ### Xcode -> [Note!] +> [!Note] > There's a precompiled IPA artifact in the GitHub mirror under Actions for those who either don't have Macs or don't want to build themself. But if you want to build youself, you'll need a Mac with Xcode. Download Xcode from the Mac App Store. ### 1. Clone 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/pe.ico b/data/images/pe.ico new file mode 100644 index 0000000..b0e657b Binary files /dev/null and b/data/images/pe.ico differ diff --git a/data/images/pe.rc b/data/images/pe.rc new file mode 100644 index 0000000..331c4ed --- /dev/null +++ b/data/images/pe.rc @@ -0,0 +1 @@ +IDI_ICON1 ICON "pe.ico" \ No newline at end of file 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/data/lang/en_US.lang b/data/lang/en_US.lang index c90c4be..567a52b 100755 --- a/data/lang/en_US.lang +++ b/data/lang/en_US.lang @@ -1020,5 +1020,5 @@ desc.netherbrickitem=Used to form blocks of Nether bricks. desc.netherquartz=Quartz from the Nether, used to create Blocks of Quartz. desc.quartzblock=Decorative block, used to create other kinds of Quartz blocks. desc.stonecutter=For crafting stoneblocks. -desc.seedsmelon=Allows for more melons. +desc.seeds_melon=Allows for more melons. desc.tile.melon=Can be cut up and eaten. 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/project/android/assets/lang/en_US.lang b/project/android/assets/lang/en_US.lang index fedae1c..83c1066 100755 --- a/project/android/assets/lang/en_US.lang +++ b/project/android/assets/lang/en_US.lang @@ -965,5 +965,5 @@ desc.netherbrickitem=Used to form blocks of Nether bricks. desc.netherquartz=Quartz from the Nether, used to create Blocks of Quartz. desc.quartzblock=Decorative block, used to create other kinds of Quartz blocks. desc.stonecutter=For crafting stoneblocks. -desc.seedsmelon=Allows for more melons. +desc.seeds_melon=Allows for more melons. desc.tile.melon=Can be cut up and eaten. diff --git a/project/iosproj/minecraftpe.xcodeproj/project.pbxproj b/project/iosproj/minecraftpe.xcodeproj/project.pbxproj index 9e371ea..57b12b7 100755 --- a/project/iosproj/minecraftpe.xcodeproj/project.pbxproj +++ b/project/iosproj/minecraftpe.xcodeproj/project.pbxproj @@ -47,6 +47,8 @@ 9D293CE816071C08000305C8 /* CreateNewWorld_iphone.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9D293CE616071C08000305C8 /* CreateNewWorld_iphone.xib */; }; 9D293CEB160720D6000305C8 /* worldname_iphone5_3.png in Resources */ = {isa = PBXBuildFile; fileRef = 9D293CEA160720D6000305C8 /* worldname_iphone5_3.png */; }; 9D293CEC160720D6000305C8 /* worldname_iphone5_3.png in Resources */ = {isa = PBXBuildFile; fileRef = 9D293CEA160720D6000305C8 /* worldname_iphone5_3.png */; }; + BEEF202614CFF670005F0002 /* Lighting.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEEF202614CFF670005F0001 /* Lighting.cpp */; }; + BEEF202614CFF670005F0003 /* Lighting.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEEF202614CFF670005F0001 /* Lighting.cpp */; }; D506D3E2161288BD0099FA65 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 9D959AFF16036BEE00E23A6F /* Default-568h@2x.png */; }; D51DC73614581D4E00E3D761 /* itemframe.png in Resources */ = {isa = PBXBuildFile; fileRef = D51DC73514581D4E00E3D761 /* itemframe.png */; }; D51DC74314592B8B00E3D761 /* PVRTexture.m in Sources */ = {isa = PBXBuildFile; fileRef = D51DC74214592B8A00E3D761 /* PVRTexture.m */; }; @@ -1179,8 +1181,19 @@ F99F0FAD2F8436CE00F2B29A /* FoliageColor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F99F0FAB2F8436CE00F2B29A /* FoliageColor.cpp */; }; F99F0FAF2F8436EB00F2B29A /* Color.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F99F0FAE2F8436EB00F2B29A /* Color.cpp */; }; F99F0FB02F8436EB00F2B29A /* Color.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F99F0FAE2F8436EB00F2B29A /* Color.cpp */; }; - BEEF202614CFF670005F0002 /* Lighting.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEEF202614CFF670005F0001 /* Lighting.cpp */; }; - BEEF202614CFF670005F0003 /* Lighting.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEEF202614CFF670005F0001 /* Lighting.cpp */; }; + F9E5A772300E7A8700164066 /* LevelConstants.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A771300E7A8700164066 /* LevelConstants.cpp */; }; + F9E5A775300E7AB700164066 /* CommandManager.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A773300E7AB700164066 /* CommandManager.hpp */; }; + F9E5A776300E7AB700164066 /* CommandManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A774300E7AB700164066 /* CommandManager.cpp */; }; + F9E5A779300E7AD500164066 /* CommandBan.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A777300E7AD500164066 /* CommandBan.cpp */; }; + F9E5A77A300E7AD500164066 /* CommandBan.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A778300E7AD500164066 /* CommandBan.hpp */; }; + F9E5A77D300E7AF400164066 /* CommandHelp.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A77B300E7AF400164066 /* CommandHelp.hpp */; }; + F9E5A77E300E7AF400164066 /* CommandHelp.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A77C300E7AF400164066 /* CommandHelp.cpp */; }; + F9E5A783300E7B0B00164066 /* CommandKick.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A77F300E7B0A00164066 /* CommandKick.hpp */; }; + F9E5A784300E7B0B00164066 /* CommandOp.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A780300E7B0A00164066 /* CommandOp.cpp */; }; + F9E5A785300E7B0B00164066 /* CommandKick.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A781300E7B0B00164066 /* CommandKick.cpp */; }; + F9E5A786300E7B0B00164066 /* CommandOp.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A782300E7B0B00164066 /* CommandOp.hpp */; }; + F9E5A789300E7B3400164066 /* Command.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A787300E7B3400164066 /* Command.cpp */; }; + F9E5A78A300E7B3400164066 /* Command.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A788300E7B3400164066 /* Command.hpp */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -1248,6 +1261,7 @@ 9D293CE616071C08000305C8 /* CreateNewWorld_iphone.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = CreateNewWorld_iphone.xib; path = minecraftpe/dialogs/CreateNewWorld_iphone.xib; sourceTree = ""; }; 9D293CEA160720D6000305C8 /* worldname_iphone5_3.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = worldname_iphone5_3.png; sourceTree = ""; }; 9D959AFF16036BEE00E23A6F /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = ""; }; + BEEF202614CFF670005F0001 /* Lighting.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Lighting.cpp; sourceTree = ""; }; D51A8B01146A200000E5D720 /* minecraftpedemo-info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "minecraftpedemo-info.plist"; sourceTree = ""; }; D51DC73514581D4E00E3D761 /* itemframe.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = itemframe.png; sourceTree = ""; }; D51DC74114592B8A00E3D761 /* PVRTexture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PVRTexture.h; sourceTree = ""; }; @@ -2468,7 +2482,19 @@ F99F0FA82F84369F00F2B29A /* GrassColor.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = GrassColor.cpp; sourceTree = ""; }; F99F0FAB2F8436CE00F2B29A /* FoliageColor.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = FoliageColor.cpp; sourceTree = ""; }; F99F0FAE2F8436EB00F2B29A /* Color.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = Color.cpp; sourceTree = ""; }; - BEEF202614CFF670005F0001 /* Lighting.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Lighting.cpp; path = Lighting.cpp; sourceTree = ""; }; + F9E5A771300E7A8700164066 /* LevelConstants.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = LevelConstants.cpp; path = ../../src/world/level/LevelConstants.cpp; sourceTree = ""; }; + F9E5A773300E7AB700164066 /* CommandManager.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = CommandManager.hpp; path = ../../src/commands/CommandManager.hpp; sourceTree = ""; }; + F9E5A774300E7AB700164066 /* CommandManager.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CommandManager.cpp; path = ../../src/commands/CommandManager.cpp; sourceTree = ""; }; + F9E5A777300E7AD500164066 /* CommandBan.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CommandBan.cpp; path = ../../src/commands/CommandBan.cpp; sourceTree = ""; }; + F9E5A778300E7AD500164066 /* CommandBan.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = CommandBan.hpp; path = ../../src/commands/CommandBan.hpp; sourceTree = ""; }; + F9E5A77B300E7AF400164066 /* CommandHelp.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = CommandHelp.hpp; path = ../../src/commands/CommandHelp.hpp; sourceTree = ""; }; + F9E5A77C300E7AF400164066 /* CommandHelp.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CommandHelp.cpp; path = ../../src/commands/CommandHelp.cpp; sourceTree = ""; }; + F9E5A77F300E7B0A00164066 /* CommandKick.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = CommandKick.hpp; path = ../../src/commands/CommandKick.hpp; sourceTree = ""; }; + F9E5A780300E7B0A00164066 /* CommandOp.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CommandOp.cpp; path = ../../src/commands/CommandOp.cpp; sourceTree = ""; }; + F9E5A781300E7B0B00164066 /* CommandKick.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CommandKick.cpp; path = ../../src/commands/CommandKick.cpp; sourceTree = ""; }; + F9E5A782300E7B0B00164066 /* CommandOp.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = CommandOp.hpp; path = ../../src/commands/CommandOp.hpp; sourceTree = ""; }; + F9E5A787300E7B3400164066 /* Command.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Command.cpp; path = ../../src/commands/Command.cpp; sourceTree = ""; }; + F9E5A788300E7B3400164066 /* Command.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = Command.hpp; path = ../../src/commands/Command.hpp; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -4319,6 +4345,19 @@ D5CF9C37144C225000E4244F = { isa = PBXGroup; children = ( + F9E5A788300E7B3400164066 /* Command.hpp */, + F9E5A787300E7B3400164066 /* Command.cpp */, + F9E5A77F300E7B0A00164066 /* CommandKick.hpp */, + F9E5A781300E7B0B00164066 /* CommandKick.cpp */, + F9E5A782300E7B0B00164066 /* CommandOp.hpp */, + F9E5A780300E7B0A00164066 /* CommandOp.cpp */, + F9E5A77B300E7AF400164066 /* CommandHelp.hpp */, + F9E5A77C300E7AF400164066 /* CommandHelp.cpp */, + F9E5A778300E7AD500164066 /* CommandBan.hpp */, + F9E5A777300E7AD500164066 /* CommandBan.cpp */, + F9E5A773300E7AB700164066 /* CommandManager.hpp */, + F9E5A774300E7AB700164066 /* CommandManager.cpp */, + F9E5A771300E7A8700164066 /* LevelConstants.cpp */, F99D344D2F7372A100DC153E /* Launch Screen.storyboard */, D5E1BA9A1451C8A0007DCC4F /* Default@2x.png */, 9D959AFF16036BEE00E23A6F /* Default-568h@2x.png */, @@ -5451,6 +5490,19 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + F9E5A789300E7B3400164066 /* Command.cpp in Sources */, + F9E5A78A300E7B3400164066 /* Command.hpp in Sources */, + F9E5A783300E7B0B00164066 /* CommandKick.hpp in Sources */, + F9E5A784300E7B0B00164066 /* CommandOp.cpp in Sources */, + F9E5A785300E7B0B00164066 /* CommandKick.cpp in Sources */, + F9E5A786300E7B0B00164066 /* CommandOp.hpp in Sources */, + F9E5A77D300E7AF400164066 /* CommandHelp.hpp in Sources */, + F9E5A77E300E7AF400164066 /* CommandHelp.cpp in Sources */, + F9E5A779300E7AD500164066 /* CommandBan.cpp in Sources */, + F9E5A77A300E7AD500164066 /* CommandBan.hpp in Sources */, + F9E5A775300E7AB700164066 /* CommandManager.hpp in Sources */, + F9E5A776300E7AB700164066 /* CommandManager.cpp in Sources */, + F9E5A772300E7A8700164066 /* LevelConstants.cpp in Sources */, F912B8CF2F6C3D5200BC60DF /* TextBox.h in Sources */, D5CF9C57144C225000E4244F /* main.mm in Sources */, D5CF9C5B144C225000E4244F /* minecraftpeAppDelegate.mm in Sources */, diff --git a/src/SharedConstants.cpp b/src/SharedConstants.cpp index 4a31175..ee64aa9 100755 --- a/src/SharedConstants.cpp +++ b/src/SharedConstants.cpp @@ -4,12 +4,11 @@ namespace Common { std::string getGameVersionString(const std::string& versionSuffix /* = "" */) { - std::string result = std::string("v0.6.1") + versionSuffix; + std::string result = std::string("v0.1.0 (forked from v0.6.1 alpha)") + versionSuffix; // append 64-bit port marker only on Android 64‑bit targets #if defined(ANDROID) && (defined(__aarch64__) || defined(__x86_64__)) - result += " (64-bit port)"; + result += " (64-bit)"; #endif - result += " alpha"; return result; } 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 8c90b6f..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()) @@ -293,7 +295,7 @@ void Minecraft::setLevel(Level* level, const std::string& message /* ="" */, Loc level->ops.emplace(op); _hasSignaledGeneratingLevelFinished = false; -#ifdef STANDALONE_SERVER +#if defined(STANDALONE_SERVER) || defined(PLATFORM_WEB) const bool threadedLevelCreation = false; #else const bool threadedLevelCreation = true; @@ -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(); @@ -516,7 +528,7 @@ void Minecraft::tick(int nTick, int maxTick) { if (missTime > 0) missTime--; #ifndef STANDALONE_SERVER if (!screen && player) { - if (player->health <= 0) { + if (player->hasDied()) { setScreen(new DeathScreen()); } } @@ -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/Options.cpp b/src/client/Options.cpp index 0785d4d..c67f68d 100755 --- a/src/client/Options.cpp +++ b/src/client/Options.cpp @@ -65,17 +65,13 @@ OptionBool useVignette("useVignette", true); OptionBool useTouchscreen("useTouchscreen", true); OptionBool serverVisible("servervisible", true); - -OptionBool foliageTint("foliagetint", true); - +OptionBool foliageTint("foliagetint", false); OptionInt fogType("fogType", 0, 0, 2); OptionBool javaHud("javaHud", false); OptionBool betaSky("betaSky", false); - OptionBool tintedSide("tintedSide", false); - OptionBool blockOutline("blockOutline", false); OptionBool restoredAnims("restoredAnims", true); @@ -200,16 +196,13 @@ void Options::initTable() { m_options[OPTIONS_ALLOW_SPRINT] = &allowSprint; m_options[OPTIONS_RPI_CURSOR] = &rpiCursor; m_options[OPTIONS_FOLIAGE_TINT] = &foliageTint; - // more options yay m_options[OPTIONS_FOG_TYPE] = &fogType; m_options[OPTIONS_DEBUG_STYLE] = &debugStyle; m_options[OPTIONS_BETA_SKY] = &betaSky; - m_options[OPTIONS_TINTED_SIDE] = &tintedSide; - m_options[OPTIONS_JAVA_HUD] = &javaHud; m_options[OPTIONS_AUTOJUMP] = &autoJump; diff --git a/src/client/Options.h b/src/client/Options.h index 001a555..c33c93b 100755 --- a/src/client/Options.h +++ b/src/client/Options.h @@ -89,7 +89,7 @@ enum OptionId { OPTIONS_RPI_CURSOR, OPTIONS_FOLIAGE_TINT, - OPTIONS_FOG_TYPE, + OPTIONS_FOG_TYPE, OPTIONS_JAVA_HUD, OPTIONS_RESTORED_ANIMS, OPTIONS_TINTED_SIDE, 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/Screen.cpp b/src/client/gui/Screen.cpp index a6bcc6f..1a19efb 100755 --- a/src/client/gui/Screen.cpp +++ b/src/client/gui/Screen.cpp @@ -61,6 +61,12 @@ bool Screen::handleBackEvent( bool isDown ) return false; } +void Screen::tick() { + for (auto& textbox : textBoxes) { + textbox->tick(minecraft); + } +} + void Screen::updateEvents() { if (passEvents) @@ -110,10 +116,12 @@ void Screen::keyboardEvent() keyPressed(Keyboard::getEventKey()); } } + void Screen::keyboardTextEvent() { charPressed(Keyboard::getChar()); } + void Screen::renderBackground() { renderBackground(0); diff --git a/src/client/gui/Screen.h b/src/client/gui/Screen.h index be44d5c..16b551a 100755 --- a/src/client/gui/Screen.h +++ b/src/client/gui/Screen.h @@ -31,7 +31,7 @@ public: virtual void keyboardTextEvent(); virtual bool handleBackEvent(bool isDown); - virtual void tick() {} + virtual void tick(); virtual void removed() {} diff --git a/src/client/gui/components/GuiElementContainer.cpp b/src/client/gui/components/GuiElementContainer.cpp index 9cfbb09..377538a 100755 --- a/src/client/gui/components/GuiElementContainer.cpp +++ b/src/client/gui/components/GuiElementContainer.cpp @@ -35,6 +35,17 @@ void GuiElementContainer::removeChild( GuiElement* element ) { children.erase(it); } +bool GuiElementContainer::containsPointInChildren(int x, int y) const { + for (auto it = children.begin(); it != children.end(); ++it) { + GuiElement* child = *it; + if (child == NULL || !child->visible) continue; + if (child->pointInside(x, y)) return true; + const GuiElementContainer* container = dynamic_cast(child); + if (container != NULL && container->containsPointInChildren(x, y)) return true; + } + return false; +} + void GuiElementContainer::tick( Minecraft* minecraft ) { for(std::vector::iterator it = children.begin(); it != children.end(); ++it) { (*it)->tick(minecraft); diff --git a/src/client/gui/components/GuiElementContainer.h b/src/client/gui/components/GuiElementContainer.h index d20f9d3..06df761 100755 --- a/src/client/gui/components/GuiElementContainer.h +++ b/src/client/gui/components/GuiElementContainer.h @@ -5,16 +5,17 @@ class Tesselator; class Minecraft; -class GuiElementContainer : public GuiElement { -public: - GuiElementContainer(bool active=false, bool visible=true, int x = 0, int y = 0, int width=24, int height=24); - virtual ~GuiElementContainer(); - virtual void render(Minecraft* minecraft, int xm, int ym); - virtual void setupPositions(); - virtual void addChild(GuiElement* element); - virtual void removeChild(GuiElement* element); - - virtual void tick( Minecraft* minecraft ); +class GuiElementContainer : public GuiElement { +public: + GuiElementContainer(bool active=false, bool visible=true, int x = 0, int y = 0, int width=24, int height=24); + virtual ~GuiElementContainer(); + virtual void render(Minecraft* minecraft, int xm, int ym); + virtual void setupPositions(); + virtual void addChild(GuiElement* element); + virtual void removeChild(GuiElement* element); + bool containsPointInChildren(int x, int y) const; + + virtual void tick( Minecraft* minecraft ); virtual void mouseClicked( Minecraft* minecraft, int x, int y, int buttonNum ); virtual void mouseReleased( Minecraft* minecraft, int x, int y, int buttonNum ); diff --git a/src/client/gui/components/OptionsGroup.cpp b/src/client/gui/components/OptionsGroup.cpp index 54212d5..d4dd161 100755 --- a/src/client/gui/components/OptionsGroup.cpp +++ b/src/client/gui/components/OptionsGroup.cpp @@ -1,115 +1,219 @@ -#include "OptionsGroup.h" -#include "../../Minecraft.h" -#include "ImageButton.h" -#include "OptionsItem.h" -#include "Slider.h" -#include "../../../locale/I18n.h" -#include "TextOption.h" -#include "KeyOption.h" - -OptionsGroup::OptionsGroup( std::string labelID ) { - label = I18n::get(labelID); -} - -void OptionsGroup::setupPositions() { - // First we write the header and then we add the items - int curY = y + 18; - for(std::vector::iterator it = children.begin(); it != children.end(); ++it) { - (*it)->width = width - 5; - - (*it)->y = curY; - (*it)->x = x + 10; - (*it)->setupPositions(); - curY += (*it)->height + 3; - } - height = curY; -} - -void OptionsGroup::render( Minecraft* minecraft, int xm, int ym ) { - float padX = 10.0f; - float padY = 5.0f; - - minecraft->font->draw(label, (float)x + padX, (float)y + padY, 0xffffffff, false); - - super::render(minecraft, xm, ym); -} - -OptionsGroup& OptionsGroup::addOptionItem(OptionId optId, Minecraft* minecraft ) { - auto option = minecraft->options.getOpt(optId); - - if (option == nullptr) return *this; - - // TODO: do a options key class to check it faster via dynamic_cast - if (option->getStringId().find("options.key") != std::string::npos) createKey(optId, minecraft); - else if (dynamic_cast(option)) createToggle(optId, minecraft); - else if (dynamic_cast(option)) createProgressSlider(optId, minecraft); - else if (dynamic_cast(option)) createStepSlider(optId, minecraft); - else if (dynamic_cast(option)) createTextbox(optId, minecraft); - - return *this; -} - -// TODO: wrap this copypaste shit into templates - -void OptionsGroup::createToggle(OptionId optId, Minecraft* minecraft ) { - ImageDef def; - - def.setSrc(IntRectangle(160, 206, 39, 20)); - def.name = "gui/touchgui.png"; - def.width = 39 * 0.7f; - def.height = 20 * 0.7f; - - OptionButton* element = new OptionButton(optId); - element->setImageDef(def, true); - element->updateImage(&minecraft->options); - - std::string itemLabel = I18n::get(minecraft->options.getOpt(optId)->getStringId()); - - OptionsItem* item = new OptionsItem(optId, itemLabel, element); - - addChild(item); - setupPositions(); -} - -void OptionsGroup::createProgressSlider(OptionId optId, Minecraft* minecraft ) { - Slider* element = new SliderFloat(minecraft, optId); - element->width = 100; - element->height = 20; - - std::string itemLabel = I18n::get(minecraft->options.getOpt(optId)->getStringId()); - OptionsItem* item = new OptionsItem(optId, itemLabel, element); - addChild(item); - setupPositions(); -} - -void OptionsGroup::createStepSlider(OptionId optId, Minecraft* minecraft ) { - Slider* element = new SliderInt(minecraft, optId); - element->width = 100; - element->height = 20; - std::string itemLabel = I18n::get(minecraft->options.getOpt(optId)->getStringId()); - OptionsItem* item = new OptionsItem(optId, itemLabel, element); - addChild(item); - setupPositions(); -} - -void OptionsGroup::createTextbox(OptionId optId, Minecraft* minecraft) { - TextBox* element = new TextOption(minecraft, optId); - element->width = 100; - element->height = 20; - - std::string itemLabel = I18n::get(minecraft->options.getOpt(optId)->getStringId()); - OptionsItem* item = new OptionsItem(optId, itemLabel, element); - addChild(item); - setupPositions(); -} - -void OptionsGroup::createKey(OptionId optId, Minecraft* minecraft) { - KeyOption* element = new KeyOption(minecraft, optId); - element->width = 50; - element->height = 20; - - std::string itemLabel = I18n::get(minecraft->options.getOpt(optId)->getStringId()); - OptionsItem* item = new OptionsItem(optId, itemLabel, element); - addChild(item); - setupPositions(); -} \ No newline at end of file +#include "OptionsGroup.h" +#include "../../Minecraft.h" +#include "ImageButton.h" +#include "OptionsItem.h" +#include "Slider.h" +#include "../../../locale/I18n.h" +#include "TextOption.h" +#include "KeyOption.h" +#include +#include "../Gui.h" +#include "../Screen.h" +#include "../../../platform/input/Mouse.h" +#include "../../../util/Mth.h" + +OptionsGroup::OptionsGroup( std::string labelID ) { + label = I18n::get(labelID); +} + +void OptionsGroup::setupPositions() { + const int labelHeight = 18; + const int bottomPadding = 36; + const float requestedScroll = scrollOffsetY; + const int scrollOffset = (int)requestedScroll; + int curY = y + labelHeight - scrollOffset; + const int contentStartY = y + labelHeight; + + // First we write the header and then we add the items + for(auto it = children.begin(); it != children.end(); ++it) { + (*it)->width = width - 5; + + (*it)->y = curY; + (*it)->x = x + 10; + (*it)->setupPositions(); + curY += (*it)->height + 3; + } + curY += bottomPadding; + contentHeight = std::max(0, curY - contentStartY + scrollOffset); + maxScrollOffsetY = std::max(0, contentHeight - (height - labelHeight)); + const float clampedScroll = Mth::clamp(requestedScroll, 0.0f, maxScrollOffsetY); + if (clampedScroll != requestedScroll) { + scrollOffsetY = clampedScroll; + setupPositions(); + } +} + +void OptionsGroup::render( Minecraft* minecraft, int xm, int ym ) { + float padX = 10.0f; + float padY = 5.0f; + const int labelHeight = 18; + + minecraft->font->draw(label, (float)x + padX, (float)y + padY, 0xffffffff, false); + + glEnable2(GL_SCISSOR_TEST); + glScissor( + Gui::GuiScale * x, + minecraft->height - Gui::GuiScale * (y + height), + Gui::GuiScale * width, + Gui::GuiScale * (height - labelHeight) + ); + + super::render(minecraft, xm, ym); + glDisable2(GL_SCISSOR_TEST); +} + +void OptionsGroup::tick(Minecraft* minecraft) { + int xm = Mouse::getX(); + int ym = Mouse::getY(); + if (minecraft->screen != NULL) { + minecraft->screen->toGUICoordinate(xm, ym); + } + + bool leftDown = Mouse::isButtonDown(MouseAction::ACTION_LEFT); + + if (trackingScrollGesture && leftDown) { + int dy = ym - lastDragY; + int dx = xm - dragStartX; + if (!scrollingGesture) { + int totalDx = xm - dragStartX; + int totalDy = ym - dragStartY; + if (std::abs(totalDx) >= ScrollStartThreshold || std::abs(totalDy) >= ScrollStartThreshold) { + if (std::abs(totalDy) >= std::abs(totalDx)) { + scrollingGesture = true; + } else if (!touchDispatched) { + super::mouseClicked(minecraft, touchStartX, touchStartY, MouseAction::ACTION_LEFT); + touchDispatched = true; + } + } + } + if (scrollingGesture && dy != 0) { + scrollByPixels((float)dy); + } + lastDragY = ym; + } + super::tick(minecraft); +} + +void OptionsGroup::mouseClicked(Minecraft* minecraft, int x, int y, int buttonNum) { + trackingScrollGesture = false; + scrollingGesture = false; + touchDispatched = false; + + if (buttonNum == MouseAction::ACTION_LEFT && pointInside(x, y)) { + trackingScrollGesture = true; + dragStartX = x; + dragStartY = y; + lastDragY = y; + touchStartX = x; + touchStartY = y; + return; + } + + super::mouseClicked(minecraft, x, y, buttonNum); +} + +void OptionsGroup::mouseReleased(Minecraft* minecraft, int x, int y, int buttonNum) { + bool wasScrolling = scrollingGesture; + bool wasTracking = trackingScrollGesture; + trackingScrollGesture = false; + scrollingGesture = false; + if (buttonNum == MouseAction::ACTION_LEFT && wasTracking && !touchDispatched && pointInside(touchStartX, touchStartY)) { + super::mouseClicked(minecraft, touchStartX, touchStartY, buttonNum); + touchDispatched = true; + } + + if (!wasScrolling) { + super::mouseReleased(minecraft, x, y, buttonNum); + } +} + +void OptionsGroup::scrollByPixels(float deltaY) { + if (deltaY == 0.0f || maxScrollOffsetY <= 0.0f) return; + + scrollOffsetY = Mth::clamp(scrollOffsetY - deltaY, 0.0f, maxScrollOffsetY); + setupPositions(); +} + +bool OptionsGroup::isScrollingGestureActive() const { + return trackingScrollGesture || scrollingGesture; +} + +OptionsGroup& OptionsGroup::addOptionItem(OptionId optId, Minecraft* minecraft ) { + auto option = minecraft->options.getOpt(optId); + + if (option == nullptr) return *this; + + // TODO: do a options key class to check it faster via dynamic_cast + if (option->getStringId().find("options.key") != std::string::npos) createKey(optId, minecraft); + else if (dynamic_cast(option)) createToggle(optId, minecraft); + else if (dynamic_cast(option)) createProgressSlider(optId, minecraft); + else if (dynamic_cast(option)) createStepSlider(optId, minecraft); + else if (dynamic_cast(option)) createTextbox(optId, minecraft); + + return *this; +} + +// TODO: wrap this copypaste shit into templates + +void OptionsGroup::createToggle(OptionId optId, Minecraft* minecraft ) { + ImageDef def; + + def.setSrc(IntRectangle(160, 206, 39, 20)); + def.name = "gui/touchgui.png"; + def.width = 39 * 0.7f; + def.height = 20 * 0.7f; + + OptionButton* element = new OptionButton(optId); + element->setImageDef(def, true); + element->updateImage(&minecraft->options); + + std::string itemLabel = I18n::get(minecraft->options.getOpt(optId)->getStringId()); + + OptionsItem* item = new OptionsItem(optId, itemLabel, element); + + addChild(item); + setupPositions(); +} + +void OptionsGroup::createProgressSlider(OptionId optId, Minecraft* minecraft ) { + Slider* element = new SliderFloat(minecraft, optId); + element->width = 100; + element->height = 20; + + std::string itemLabel = I18n::get(minecraft->options.getOpt(optId)->getStringId()); + OptionsItem* item = new OptionsItem(optId, itemLabel, element); + addChild(item); + setupPositions(); +} + +void OptionsGroup::createStepSlider(OptionId optId, Minecraft* minecraft ) { + Slider* element = new SliderInt(minecraft, optId); + element->width = 100; + element->height = 20; + std::string itemLabel = I18n::get(minecraft->options.getOpt(optId)->getStringId()); + OptionsItem* item = new OptionsItem(optId, itemLabel, element); + addChild(item); + setupPositions(); +} + +void OptionsGroup::createTextbox(OptionId optId, Minecraft* minecraft) { + TextBox* element = new TextOption(minecraft, optId); + element->width = 100; + element->height = 20; + + std::string itemLabel = I18n::get(minecraft->options.getOpt(optId)->getStringId()); + OptionsItem* item = new OptionsItem(optId, itemLabel, element); + addChild(item); + setupPositions(); +} + +void OptionsGroup::createKey(OptionId optId, Minecraft* minecraft) { + KeyOption* element = new KeyOption(minecraft, optId); + element->width = 50; + element->height = 20; + + std::string itemLabel = I18n::get(minecraft->options.getOpt(optId)->getStringId()); + OptionsItem* item = new OptionsItem(optId, itemLabel, element); + addChild(item); + setupPositions(); +} diff --git a/src/client/gui/components/OptionsGroup.h b/src/client/gui/components/OptionsGroup.h index 24d28bd..bb284fa 100755 --- a/src/client/gui/components/OptionsGroup.h +++ b/src/client/gui/components/OptionsGroup.h @@ -1,32 +1,49 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsGroup_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsGroup_H__ - -//package net.minecraft.client.gui; - -#include -#include "GuiElementContainer.h" -#include "ScrollingPane.h" -#include "../../Options.h" - -class Font; -class Minecraft; - -class OptionsGroup: public GuiElementContainer { - typedef GuiElementContainer super; -public: - OptionsGroup(std::string labelID); - virtual void setupPositions(); - virtual void render(Minecraft* minecraft, int xm, int ym); - OptionsGroup& addOptionItem(OptionId optId, Minecraft* minecraft); -protected: - - void createToggle(OptionId optId, Minecraft* minecraft); - void createProgressSlider(OptionId optId, Minecraft* minecraft); - void createStepSlider(OptionId optId, Minecraft* minecraft); - void createTextbox(OptionId optId, Minecraft* minecraft); - void createKey(OptionId optId, Minecraft* minecraft); - - std::string label; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsGroup_H__*/ +#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsGroup_H__ +#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsGroup_H__ + +//package net.minecraft.client.gui; + +#include +#include "GuiElementContainer.h" +#include "ScrollingPane.h" +#include "../../Options.h" + +class Font; +class Minecraft; + +class OptionsGroup: public GuiElementContainer { + typedef GuiElementContainer super; +public: + OptionsGroup(std::string labelID); + virtual void setupPositions(); + virtual void render(Minecraft* minecraft, int xm, int ym); + virtual void tick(Minecraft* minecraft); + virtual void mouseClicked(Minecraft* minecraft, int x, int y, int buttonNum); + virtual void mouseReleased(Minecraft* minecraft, int x, int y, int buttonNum); + OptionsGroup& addOptionItem(OptionId optId, Minecraft* minecraft); + void scrollByPixels(float deltaY); + bool isScrollingGestureActive() const; +protected: + + void createToggle(OptionId optId, Minecraft* minecraft); + void createProgressSlider(OptionId optId, Minecraft* minecraft); + void createStepSlider(OptionId optId, Minecraft* minecraft); + void createTextbox(OptionId optId, Minecraft* minecraft); + void createKey(OptionId optId, Minecraft* minecraft); + + std::string label; + int contentHeight = 0; + float scrollOffsetY = 0.f; + float maxScrollOffsetY = 0.f; + bool trackingScrollGesture = false; + bool scrollingGesture = false; + bool touchDispatched = false; + int dragStartX = 0; + int dragStartY = 0; + int lastDragY = 0; + int touchStartX = 0; + int touchStartY = 0; + static const int ScrollStartThreshold = 5; +}; + +#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsGroup_H__*/ diff --git a/src/client/gui/components/ScrollingPane.cpp b/src/client/gui/components/ScrollingPane.cpp index 090bc3a..79dd11c 100755 --- a/src/client/gui/components/ScrollingPane.cpp +++ b/src/client/gui/components/ScrollingPane.cpp @@ -204,22 +204,23 @@ void ScrollingPane::render( int xm, int ym, float alpha ) { const float bxx = bbox.x - (fpx /*+ dx*alpha*/) + (nw.xf - nw.x); const float byy = bbox.y - (fpy /*+ dy*alpha*/) + (nw.yf - nw.y); - for (int y = nw.y; y <= se.y; ++y) - for (int x = nw.x; x <= se.x; ++x) { - int id = y * columns + x; - if (y <0 || id < 0 || id >= numItems) continue; // @todo: break rather - if (isNotSet(SF_WrapX) && (x < 0 || x >= columns)) continue; // @todo: break rather - GridItem item; //@todo: v- Does not support SF_Wrapping - item.id = id; - item.xf = bxx + x * itemBbox.w; - item.yf = byy + y * itemBbox.h; - item.x = (int)item.xf; - item.y = (int)item.yf; - //LOGI("i: %d (%.1f, %.1f)\t", id, item.xf, item.yf); - if (isSet(SF_MultiSelect)) item.selected = selected[id]; - else item.selected = (id == selectedId); + for (int y = nw.y; y <= se.y; ++y) { + for (int x = nw.x; x <= se.x; ++x) { + int id = y * columns + x; + if (y <0 || id < 0 || id >= numItems) continue; // @todo: break rather + if (isNotSet(SF_WrapX) && (x < 0 || x >= columns)) continue; // @todo: break rather + GridItem item; //@todo: v- Does not support SF_Wrapping + item.id = id; + item.xf = bxx + x * itemBbox.w; + item.yf = byy + y * itemBbox.h; + item.x = (int)item.xf; + item.y = (int)item.yf; + //LOGI("i: %d (%.1f, %.1f)\t", id, item.xf, item.yf); + if (isSet(SF_MultiSelect)) item.selected = selected[id]; + else item.selected = (id == selectedId); - itemsToRender.push_back(item); + itemsToRender.push_back(item); + } } renderBatch(itemsToRender, alpha); diff --git a/src/client/gui/screens/ChestScreen.cpp b/src/client/gui/screens/ChestScreen.cpp index c9383c9..8a7b81e 100755 --- a/src/client/gui/screens/ChestScreen.cpp +++ b/src/client/gui/screens/ChestScreen.cpp @@ -329,7 +329,10 @@ bool ChestScreen::handleAddItem(FillingContainer* from, FillingContainer* to, in added = (takenItem.count != wantedCount); if (added) { - item->count -= (wantedCount - takenItem.count); + if (!minecraft->isCreativeMode()) { + item->count -= (wantedCount - takenItem.count); + } + std::vector changed; std::vector items = getItems(toPane); differ.getDiff(items, changed); diff --git a/src/client/gui/screens/ConsoleScreen.cpp b/src/client/gui/screens/ConsoleScreen.cpp index 42f47ee..8eae25f 100644 --- a/src/client/gui/screens/ConsoleScreen.cpp +++ b/src/client/gui/screens/ConsoleScreen.cpp @@ -6,9 +6,20 @@ #include "../../../world/level/Level.h" #include "../../../network/RakNetInstance.h" #include "../../../network/ServerSideNetworkHandler.h" -#include "../../../network/packet/ChatPacket.h" +#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,29 +74,93 @@ void ConsoleScreen::execute() return minecraft->setScreen(NULL); } - if (_input[0] == '/') { - // Command + 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); + } else if (_input[0] == '/') { _input = Util::stringTrim(_input.substr(1)); - - std::istringstream iss(minecraft->commandManager().execute(*minecraft, *minecraft->player, _input)); - for (std::string line; std::getline(iss, line); ) { + + std::istringstream iss( + minecraft->commandManager().execute(*minecraft, *minecraft->player, _input) + ); + + for (std::string line; std::getline(iss, line);) { minecraft->gui.addMessage(line); } - } else { - // @ai @rewrite - if (minecraft->netCallback && minecraft->raknetInstance->isServer()) { - static_cast(minecraft->netCallback)->displayGameMessage(_input); - } else if (minecraft->netCallback) { - ChatPacket chatPkt(_input); - minecraft->raknetInstance->send(chatPkt); - } else { - minecraft->gui.addMessage("<" + minecraft->player->name + "> " + _input); + } + else { + if (minecraft->raknetInstance->isServer()) { + MessagePacket packet(_input.c_str()); + minecraft->raknetInstance->send(packet); } + + minecraft->gui.addMessage("<" + minecraft->player->name + "> " + _input); } 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/gui/screens/DeathScreen.cpp b/src/client/gui/screens/DeathScreen.cpp index e97b103..0d881a1 100755 --- a/src/client/gui/screens/DeathScreen.cpp +++ b/src/client/gui/screens/DeathScreen.cpp @@ -72,7 +72,7 @@ void DeathScreen::render( int xm, int ym, float a ) if (minecraft->options.getIntValue(OPTIONS_MENU_STYLE) == 2){ glPushMatrix2(); glScalef2(2, 2, 2); - drawCenteredString(font, "Game over!", width / 2 / 2, height / 8, 0xffffff); + drawCenteredString(font, I18n::get("deathScreen.title.hardcore"), width / 4, height / 8, 0xffffff); glPopMatrix2(); std::stringstream ss; ss << "Score: &e" << minecraft->player->getScore(); @@ -80,7 +80,7 @@ if (minecraft->options.getIntValue(OPTIONS_MENU_STYLE) == 2){ } else { glPushMatrix2(); glScalef2(2, 2, 2); - drawCenteredString(font, "You died!", width / 2 / 2, height / 8, 0xffffff); + drawCenteredString(font, I18n::get("deathScreen.title"), width / 4, height / 8, 0xffffff); glPopMatrix2(); } diff --git a/src/client/gui/screens/FurnaceScreen.cpp b/src/client/gui/screens/FurnaceScreen.cpp index 58d6df2..eb9861f 100755 --- a/src/client/gui/screens/FurnaceScreen.cpp +++ b/src/client/gui/screens/FurnaceScreen.cpp @@ -500,6 +500,8 @@ ItemInstance FurnaceScreen::moveOver(const ItemInstance* item, int maxCount) { setIfNotSet(doRecreatePane, newSize != oldSize); return removed; } + + return ItemInstance(); } diff --git a/src/client/gui/screens/OptionsScreen.cpp b/src/client/gui/screens/OptionsScreen.cpp index d4eced8..bdccde0 100755 --- a/src/client/gui/screens/OptionsScreen.cpp +++ b/src/client/gui/screens/OptionsScreen.cpp @@ -121,6 +121,7 @@ void OptionsScreen::setupPositions() { (*it)->x = categoryButtons[0]->width; (*it)->y = bHeader->height; (*it)->width = width - categoryButtons[0]->width; + (*it)->height = height - bHeader->height; (*it)->setupPositions(); } @@ -237,8 +238,10 @@ void OptionsScreen::generateOptionScreens() { .addOptionItem(OPTIONS_BAR_ON_TOP, minecraft) .addOptionItem(OPTIONS_MENU_STYLE, minecraft) .addOptionItem(OPTIONS_RPI_CURSOR, minecraft) +#ifndef __APPLE__ .addOptionItem(OPTIONS_FOLIAGE_TINT, minecraft) .addOptionItem(OPTIONS_TINTED_SIDE, minecraft) +#endif .addOptionItem(OPTIONS_JAVA_HUD, minecraft) .addOptionItem(OPTIONS_FOG_TYPE, minecraft) .addOptionItem(OPTIONS_BETA_SKY, minecraft) @@ -261,6 +264,12 @@ void OptionsScreen::mouseReleased(int x, int y, int buttonNum) { super::mouseReleased(x, y, buttonNum); } +void OptionsScreen::mouseWheel(int dx, int dy, int xm, int ym) { + if (currentOptionsGroup != NULL && currentOptionsGroup->pointInside(xm, ym) && dy != 0) { + currentOptionsGroup->scrollByPixels((float)dy * 18.0f); + } +} + void OptionsScreen::keyPressed(int eventKey) { if (currentOptionsGroup != NULL) currentOptionsGroup->keyPressed(minecraft, eventKey); diff --git a/src/client/gui/screens/OptionsScreen.h b/src/client/gui/screens/OptionsScreen.h index b02c7b8..dd1e73e 100755 --- a/src/client/gui/screens/OptionsScreen.h +++ b/src/client/gui/screens/OptionsScreen.h @@ -27,6 +27,7 @@ public: virtual void mouseClicked(int x, int y, int buttonNum); virtual void mouseReleased(int x, int y, int buttonNum); + virtual void mouseWheel(int dx, int dy, int xm, int ym); virtual void keyPressed(int eventKey); virtual void charPressed(char inputChar); diff --git a/src/client/gui/screens/SimpleChooseLevelScreen.cpp b/src/client/gui/screens/SimpleChooseLevelScreen.cpp index c5a1278..37f5c72 100755 --- a/src/client/gui/screens/SimpleChooseLevelScreen.cpp +++ b/src/client/gui/screens/SimpleChooseLevelScreen.cpp @@ -8,13 +8,14 @@ #include "../../../platform/time.h" #include "../../../platform/input/Keyboard.h" #include "../../../platform/log.h" +#include SimpleChooseLevelScreen::SimpleChooseLevelScreen(const std::string& levelName) -: bHeader(0), - bGamemode(0), - bCheats(0), - bBack(0), - bCreate(0), +: bHeader(nullptr), + bGamemode(nullptr), + bCheats(nullptr), + bBack(nullptr), + bCreate(nullptr), levelName(levelName), hasChosen(false), gamemode(GameType::Survival), @@ -42,10 +43,10 @@ void SimpleChooseLevelScreen::init() // first") when the name already existed. ChooseLevelScreen::init(); - tLevelName.text = "New world"; + tLevelName.text = I18n::get("selectWorld.newWorld"); // header + close button - bHeader = new Touch::THeader(0, "Create World"); + bHeader = new Touch::THeader(0, I18n::get("selectWorld.create")); // create the back/X button as ImageButton like CreditsScreen bBack = new ImageButton(2, ""); { @@ -56,14 +57,14 @@ void SimpleChooseLevelScreen::init() def.setSrc(IntRectangle(150, 0, (int)def.width, (int)def.height)); bBack->setImageDef(def, true); } - if (/* minecraft->useTouchscreen() */ true) { - bGamemode = new Touch::TButton(1, "Survival mode"); + if (minecraft->options.getIntValue(OPTIONS_MENU_STYLE) != 2) { + bGamemode = new Touch::TButton(1, I18n::get("selectWorld.gameMode.survival")); bCheats = new Touch::TButton(4, "Cheats: Off"); - bCreate = new Touch::TButton(3, "Create"); + bCreate = new Touch::TButton(3, I18n::get("selectWorld.create")); } else { - bGamemode = new Button(1, "Survival mode"); + bGamemode = new Button(1, I18n::get("selectWorld.gameMode.survival")); bCheats = new Button(4, "Cheats: Off"); - bCreate = new Button(3, "Create"); + bCreate = new Button(3, I18n::get("Create")); } buttons.push_back(bHeader); diff --git a/src/client/model/HumanoidModel.cpp b/src/client/model/HumanoidModel.cpp index bf004ec..e6515ea 100755 --- a/src/client/model/HumanoidModel.cpp +++ b/src/client/model/HumanoidModel.cpp @@ -21,6 +21,9 @@ HumanoidModel::HumanoidModel( float g /*= 0*/, float yOffset /*= 0*/, int texW / texWidth = texW; texHeight = texH; + // texWidth = 64; + // texHeight = 32; + head.setModel(this); hair.setModel(this); body.setModel(this); diff --git a/src/client/player/LocalPlayer.cpp b/src/client/player/LocalPlayer.cpp index 86a345f..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 @@ -554,9 +563,9 @@ void LocalPlayer::aiStep() { //if (onGround && abilities.flying) // abilities.flying = false; - yBobO = yBob; - xBobO = xBob; - xBob += (xRot - xBob) * 0.5; + yBobO = yBob; + xBobO = xBob; + xBob += (xRot - xBob) * 0.5; yBob += (yRot - yBob) * 0.5; if (interpolateOnly()) @@ -774,22 +783,19 @@ void LocalPlayer::startCrafting(int x, int y, int z, int tableSize) { void LocalPlayer::startStonecutting(int x, int y, int z) { #ifndef STANDALONE_SERVER - if (!minecraft->isCreativeMode()) - minecraft->setScreen( new StonecutterScreen() ); + minecraft->setScreen( new StonecutterScreen() ); #endif } void LocalPlayer::openFurnace( FurnaceTileEntity* e ) { #ifndef STANDALONE_SERVER - if (!minecraft->isCreativeMode()) - minecraft->setScreen( new FurnaceScreen(this, e) ); + minecraft->setScreen( new FurnaceScreen(this, e) ); #endif } void LocalPlayer::openContainer( ChestTileEntity* container ) { #ifndef STANDALONE_SERVER - if (!minecraft->isCreativeMode()) - minecraft->setScreen( new ChestScreen(this, container) ); + minecraft->setScreen( new ChestScreen(this, container) ); #endif } diff --git a/src/client/player/LocalPlayer.h b/src/client/player/LocalPlayer.h index d1fef05..aa0b956 100755 --- a/src/client/player/LocalPlayer.h +++ b/src/client/player/LocalPlayer.h @@ -23,7 +23,7 @@ public: void tick(); - float yBob, xBob; // shredder added from b1.8/4j for the hand swaying animation + float yBob, xBob; // shredder added from b1.8/4j for the hand swaying animation float yBobO, xBobO; // shredder added from b1.8/4j for the hand swaying animation void move(float xa, float ya, float za); 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/GameRenderer.cpp b/src/client/renderer/GameRenderer.cpp index c4bc08c..3ea22a0 100755 --- a/src/client/renderer/GameRenderer.cpp +++ b/src/client/renderer/GameRenderer.cpp @@ -440,7 +440,7 @@ float GameRenderer::getFov(float a, bool applyEffects) { fov *= this->oFov + (this->fov - this->oFov) * a; if (player->isUnderLiquid(Material::water)) fov = 60; - if (player->health <= 0) { + if (player->hasDied()) { float duration = player->deathTime + a; fov /= ((1 - 500 / (duration + 500)) * 2.0f + 1); @@ -537,7 +537,7 @@ void GameRenderer::bobHurt(float a) { float hurt = player->hurtTime - a; - if (player->health <= 0) { + if (player->hasDied()) { float duration = player->deathTime + a; glRotatef2(40 - (40 * 200) / (duration + 200), 0, 0, 1); } diff --git a/src/client/renderer/ItemInHandRenderer.cpp b/src/client/renderer/ItemInHandRenderer.cpp index fb83bdd..eb2be2b 100755 --- a/src/client/renderer/ItemInHandRenderer.cpp +++ b/src/client/renderer/ItemInHandRenderer.cpp @@ -291,14 +291,13 @@ void ItemInHandRenderer::render( float a ) Lighting::turnOn(mc); glPopMatrix2(); - if (localPlayer) // shredder added, basically does the hand swaying animation from b1.8 - { - float xrr = localPlayer->xBobO + (localPlayer->xBob - localPlayer->xBobO) * a; - float yrr = localPlayer->yBobO + (localPlayer->yBob - localPlayer->yBobO) * a; - // 4J - was using player->xRot and yRot directly here rather than interpolating between old & current with a - float yr = player->yRotO + (player->yRot - player->yRotO) * a; - glRotatef((xr - xrr) * 0.1f, 1, 0, 0); - glRotatef((yr - yrr) * 0.1f, 0, 1, 0); + if (localPlayer) { // shredder added, basically does the hand swaying animation from b1.8 + float xrr = localPlayer->xBobO + (localPlayer->xBob - localPlayer->xBobO) * a; + float yrr = localPlayer->yBobO + (localPlayer->yBob - localPlayer->yBobO) * a; + // 4J - was using player->xRot and yRot directly here rather than interpolating between old & current with a + float yr = player->yRotO + (player->yRot - player->yRotO) * a; + glRotatef((xr - xrr) * 0.1f, 1, 0, 0); + glRotatef((yr - yrr) * 0.1f, 0, 1, 0); } float br = mc->level->getBrightness(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); @@ -425,6 +424,8 @@ void ItemInHandRenderer::render( float a ) EntityRenderer* er = EntityRenderDispatcher::getInstance()->getRenderer(mc->player); HumanoidMobRenderer* playerRenderer = (HumanoidMobRenderer*) er; + EntityRenderDispatcher::getInstance()->setModernSkin((Entity*)(player)); + float ss = 1; glScalef2(ss, ss, ss); playerRenderer->renderHand(); diff --git a/src/client/renderer/LevelRenderer.cpp b/src/client/renderer/LevelRenderer.cpp index ba57fb6..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); @@ -185,11 +186,14 @@ void LevelRenderer::allChanged() lastFogType = mc->options.getIntValue(OPTIONS_FOG_TYPE); +#ifndef __APPLE__ bool tint = mc->options.getBooleanValue(OPTIONS_FOLIAGE_TINT); + bool sideTint = mc->options.getBooleanValue(OPTIONS_TINTED_SIDE); +#else + bool tint = false, sideTint = false; +#endif FoliageColor::setUseTint(tint); GrassColor::setUseTint(tint); - - bool sideTint = mc->options.getBooleanValue(OPTIONS_TINTED_SIDE); TileRenderer::setUseTint(sideTint); @@ -206,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/renderer/entity/EntityRenderDispatcher.cpp b/src/client/renderer/entity/EntityRenderDispatcher.cpp index b0edea7..9381b89 100755 --- a/src/client/renderer/entity/EntityRenderDispatcher.cpp +++ b/src/client/renderer/entity/EntityRenderDispatcher.cpp @@ -137,6 +137,11 @@ void EntityRenderDispatcher::render( Entity* entity, float x, float y, float z, } } +void EntityRenderDispatcher::setModernSkin(Entity* player) { + PlayerRenderer* rend = (PlayerRenderer*)(getRenderer(player)); + rend->setModernSkin((Mob*)player); +} + EntityRenderer* EntityRenderDispatcher::getRenderer( Entity* entity ) { EntityRendererId rendererId = entity->entityRendererId; diff --git a/src/client/renderer/entity/EntityRenderDispatcher.h b/src/client/renderer/entity/EntityRenderDispatcher.h index 06c4eac..180b4ef 100755 --- a/src/client/renderer/entity/EntityRenderDispatcher.h +++ b/src/client/renderer/entity/EntityRenderDispatcher.h @@ -45,6 +45,8 @@ public: Font* getFont(); void onGraphicsReset(); + + void setModernSkin(Entity* player); private: void assign(EntityRendererId id, EntityRenderer* renderer); public: diff --git a/src/client/renderer/entity/EntityRenderer.cpp b/src/client/renderer/entity/EntityRenderer.cpp index a1b18c0..691ddfb 100755 --- a/src/client/renderer/entity/EntityRenderer.cpp +++ b/src/client/renderer/entity/EntityRenderer.cpp @@ -257,7 +257,7 @@ void EntityRenderer::renderShadow(Entity* e, float x, float y, float z, float po //Textures* textures = entityRenderDispatcher->textures; //textures->bind(textures->loadTexture("%clamp%/environment/shadow.png")); Textures* textures = entityRenderDispatcher->textures; - textures->loadAndBindTexture("/misc/shadow.png"); + textures->loadAndBindTexture("misc/shadow.png"); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); @@ -298,6 +298,7 @@ void EntityRenderer::renderShadow(Entity* e, float x, float y, float z, float po tt.draw(); glColor4f2(1, 1, 1, 1); + // tt.color(1.f, 1.f, 1.f, 1.f); glDisable2(GL_BLEND); glDepthMask(true); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); @@ -315,7 +316,7 @@ void EntityRenderer::renderTileShadow(Tile* tt, float x, float y, float z, int x float a = ((pow - (y - (yt + yo)) / 2) * 0.5f) * getLevel()->getBrightness(xt, yt, zt); if (a < 0) return; if (a > 1) a = 1; - // t.color(1, 1, 1, (float) a); + // t.color(1.f, 1.f, 1.f, (float) a); glColor4f2(1, 1, 1, (float) a); float x0 = xt + tt->xx0 + xo; diff --git a/src/client/renderer/entity/ItemRenderer.cpp b/src/client/renderer/entity/ItemRenderer.cpp index d103fcc..4c48a3b 100755 --- a/src/client/renderer/entity/ItemRenderer.cpp +++ b/src/client/renderer/entity/ItemRenderer.cpp @@ -189,9 +189,9 @@ void ItemRenderer::renderGuiItem(Font* font, Textures* textures, const ItemInsta // it we're batching for saving the // buffer, this will fail miserably t.endOverrideAndDraw(); - glDisable2(GL_TEXTURE_2D); - fillRect(t, x, y, w, h, 0xff0000); - glEnable2(GL_TEXTURE_2D); + // glDisable2(GL_TEXTURE_2D); + // fillRect(t, x, y, w, h, 0xff0000); + // glEnable2(GL_TEXTURE_2D); renderGuiItemCorrect(font, textures, item, int(x), int(y)); t.beginOverride(); } diff --git a/src/client/renderer/entity/PlayerRenderer.cpp b/src/client/renderer/entity/PlayerRenderer.cpp index 092b9dc..93685fd 100755 --- a/src/client/renderer/entity/PlayerRenderer.cpp +++ b/src/client/renderer/entity/PlayerRenderer.cpp @@ -70,13 +70,18 @@ void PlayerRenderer::renderName( Mob* mob, float x, float y, float z ){ } } -void PlayerRenderer::render(Entity* mob_, float x, float y, float z, float rot, float a) { - Mob* mob = (Mob*) mob_; +// @note fix player skin system +void PlayerRenderer::setModernSkin(Mob* mob) { HumanoidModel* desired = isModernPlayerSkin(mob) ? playerModel64 : playerModel32; if (model != desired || humanoidModel != desired) { model = desired; humanoidModel = desired; } +} + +void PlayerRenderer::render(Entity* mob_, float x, float y, float z, float rot, float a) { + Mob* mob = (Mob*) mob_; + setModernSkin(mob); /* LOGI("[PlayerRenderer] %s: skin=%s, modelTex=%dx%d, desired=%s\n", ((Player*)mob)->name.c_str(), mob->getTexture().c_str(), humanoidModel->texWidth, humanoidModel->texHeight, diff --git a/src/client/renderer/entity/PlayerRenderer.h b/src/client/renderer/entity/PlayerRenderer.h index d4b25e2..1105c4b 100755 --- a/src/client/renderer/entity/PlayerRenderer.h +++ b/src/client/renderer/entity/PlayerRenderer.h @@ -19,6 +19,8 @@ public: virtual void renderName(Mob* mob, float x, float y, float z); virtual void onGraphicsReset(); + + void setModernSkin(Mob* mob); private: HumanoidModel* playerModel32; HumanoidModel* playerModel64; 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/Command.hpp b/src/commands/Command.hpp index fb3fdd0..e19ad45 100644 --- a/src/commands/Command.hpp +++ b/src/commands/Command.hpp @@ -2,18 +2,12 @@ #include #include -enum CommandFlags { - COMMAND_FLAG_SINGLEPLAYER_ONLY = (1 << 1), - COMMAND_FLAG_NO_ARGS = (1 << 2), -}; - class Minecraft; class Player; class Command { public: const std::string& getName() { return m_name; } - const CommandFlags getFlags() { return m_flags; } bool isPlayerOp(Minecraft& mc, Player& player); @@ -21,8 +15,7 @@ public: virtual std::string help(Minecraft& mc) = 0; protected: - Command(const std::string& name, CommandFlags flags = (CommandFlags)0) : m_name(name), m_flags(flags) {} + Command(const std::string& name) : m_name(name) {} const std::string m_name; - const CommandFlags m_flags; }; \ No newline at end of file diff --git a/src/commands/CommandBan.cpp b/src/commands/CommandBan.cpp index 0373d5b..3877d95 100644 --- a/src/commands/CommandBan.cpp +++ b/src/commands/CommandBan.cpp @@ -36,14 +36,14 @@ std::string CommandBan::execute(Minecraft& mc, Player& player, const std::vector (*it)->remove(); mc.raknetInstance->getPeer()->CloseConnection((*it)->owner, true); } else { - for (auto& banned : mc.level->bannedPpl) { + for (auto& banned : mc.level->bannedPlayers) { if (nicknameLower == banned) { return args[0] + "already banned!"; } } } - mc.level->bannedPpl.insert(nicknameLower); + mc.level->bannedPlayers.insert(nicknameLower); return "ban: successfully banned player " + args[0]; } diff --git a/src/commands/CommandGimmieItems.cpp b/src/commands/CommandGimmieItems.cpp new file mode 100644 index 0000000..9a7f542 --- /dev/null +++ b/src/commands/CommandGimmieItems.cpp @@ -0,0 +1,33 @@ +#include "CommandGimmieItems.hpp" +#include +#include +#include + +CommandGimmieItems::CommandGimmieItems() : Command("gimmieitems") {} + +std::string CommandGimmieItems::execute(Minecraft& mc, Player& player, const std::vector& args) { + if (mc.level != nullptr) { + if (mc.level->getLevelData()->getAllowCheats()) { + player.inventory->add(new ItemInstance(Item::ironIngot, 64)); + player.inventory->add(new ItemInstance(Item::ironIngot, 34)); + player.inventory->add(new ItemInstance(Tile::stonecutterBench)); + player.inventory->add(new ItemInstance(Tile::workBench)); + player.inventory->add(new ItemInstance(Tile::furnace)); + player.inventory->add(new ItemInstance(Tile::wood, 54)); + player.inventory->add(new ItemInstance(Item::stick, 14)); + player.inventory->add(new ItemInstance(Item::coal, 31)); + player.inventory->add(new ItemInstance(Tile::sand, 6)); + player.inventory->add(new ItemInstance(Item::dye_powder, 23, DyePowderItem::PURPLE)); + + return "Grant debug items. Have fun!"; + } else { + return "Cheats are not allowed!"; + } + } + + return "World not loaded"; +} + +std::string CommandGimmieItems::help(Minecraft& mc) { + return "Usage: /gimmieitems"; +} \ No newline at end of file diff --git a/src/commands/CommandGimmieItems.hpp b/src/commands/CommandGimmieItems.hpp new file mode 100644 index 0000000..d3fa66e --- /dev/null +++ b/src/commands/CommandGimmieItems.hpp @@ -0,0 +1,9 @@ +#include "Command.hpp" + +class CommandGimmieItems : public Command { +public: + CommandGimmieItems(); + + std::string execute(Minecraft& mc, Player& player, const std::vector& args); + std::string help(Minecraft& mc); +}; \ No newline at end of file diff --git a/src/commands/CommandManager.cpp b/src/commands/CommandManager.cpp index fbb9324..b82a640 100644 --- a/src/commands/CommandManager.cpp +++ b/src/commands/CommandManager.cpp @@ -8,9 +8,11 @@ #include "commands/CommandKick.hpp" #include "commands/CommandOp.hpp" #include "commands/CommandBan.hpp" +#include "commands/CommandGimmieItems.hpp" #include "network/packet/ChatPacket.h" #include "network/RakNetInstance.h" #include "world/level/Level.h" +#include "lua/LuaEngine.h" CommandManager::CommandManager() { registerAllCommands(); @@ -21,6 +23,7 @@ void CommandManager::registerAllCommands() { m_commands.push_back(new CommandKick()); m_commands.push_back(new CommandOp()); m_commands.push_back(new CommandBan()); + // m_commands.push_back(new CommandGimmieItems()); } std::vector CommandManager::getListAllCommands() { @@ -29,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; } @@ -43,23 +49,21 @@ 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 (!mc.level->isClientSide || (*it)->getFlags() & CommandFlags::COMMAND_FLAG_SINGLEPLAYER_ONLY) { - return (*it)->execute(mc, player, args); - } else { - ChatPacket packet("/" + input); - mc.raknetInstance->send(packet); + + 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 ""; + return (*it)->execute(mc, player, args); } Command* CommandManager::getCommand(const std::string& name) { 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 +#include +#include +#include + +#include "client/Minecraft.h" +#include "network/RakNetInstance.h" +#include "network/ServerSideNetworkHandler.h" +#include "network/packet/ChatPacket.h" +#include "network/packet/ChunkDataPacket.h" +#include "network/packet/MovePlayerPacket.h" +#include "network/packet/SendInventoryPacket.h" +#include "network/packet/UpdateBlockPacket.h" +#include "platform/log.h" +#include "raknet/RakPeerInterface.h" +#include "raknet/PacketPriority.h" +#include "world/entity/EntityTypes.h" +#include "world/entity/MobFactory.h" +#include "world/entity/item/ItemEntity.h" +#include "world/entity/player/Inventory.h" +#include "world/entity/player/Player.h" +#include "world/item/Item.h" +#include "world/item/ItemInstance.h" +#include "world/level/Level.h" +#include "world/level/LightLayer.h" +#include "world/level/LevelConstants.h" +#include "world/level/chunk/LevelChunk.h" +#include "world/level/material/Material.h" +#include "world/level/tile/Tile.h" +#include "world/phys/HitResult.h" +#include "util/Mth.h" + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#define MKDIR(p) _mkdir(p) +#else +#include +#include +#define MKDIR(p) mkdir(p, 0755) +#endif + +namespace { + +Minecraft* MC() { return LuaEngine::get().minecraft(); } +Level* LV() { Minecraft* m = MC(); return m ? m->level : NULL; } + +Player* findPlayer(int id) { + Level* level = LV(); + if (!level) return NULL; + for (unsigned int i = 0; i < level->players.size(); ++i) + if (level->players[i]->entityId == id) return level->players[i]; + return NULL; +} + +ServerSideNetworkHandler* server() { + Minecraft* m = MC(); + if (m && m->raknetInstance && m->raknetInstance->isServer() && m->netCallback) + return (ServerSideNetworkHandler*)m->netCallback; + return NULL; +} + +bool isLocalPlayer(Player* p) { + return (Entity*)p == (Entity*)MC()->player; +} + +void sendChat(Player* p, const std::string& text) { + if (!p) return; + if (isLocalPlayer(p)) { +#ifndef STANDALONE_SERVER + MC()->gui.addMessage(text); +#else + LOGI("%s\n", text.c_str()); +#endif + return; + } + if (ServerSideNetworkHandler* s = server()) { + ChatPacket packet(text); + RakNet::BitStream bs; + packet.write(&bs); + MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->owner, false); + } +} + +void broadcastChat(const std::string& text) { +#ifndef STANDALONE_SERVER + if (MC()->player) MC()->gui.addMessage(text); +#else + LOGI("%s\n", text.c_str()); +#endif + if (server()) { + ChatPacket packet(text); + RakNet::BitStream bs; + packet.write(&bs); + MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true); + } +} + +// ---- bulk edits: blocks are written silently and the touched chunks are re-sent once at the end +struct DirtyBox { int x0, y0, z0, x1, y1, z1; }; +std::map g_dirty; + +void markDirty(int x, int y, int z) { + const long long key = LevelConstants::chunkKey(x >> 4, z >> 4); + std::map::iterator it = g_dirty.find(key); + if (it == g_dirty.end()) { + DirtyBox b = { x, y, z, x, y, z }; + g_dirty[key] = b; + } else { + DirtyBox& b = it->second; + if (x < b.x0) b.x0 = x; if (x > b.x1) b.x1 = x; + if (y < b.y0) b.y0 = y; if (y > b.y1) b.y1 = y; + if (z < b.z0) b.z0 = z; if (z > b.z1) b.z1 = z; + } +} + +// ---- lua helpers +int argInt(lua_State* L, int i) { return (int)lua_tointeger(L, i); } +float argNum(lua_State* L, int i) { return (float)lua_tonumber(L, i); } + +// ================================================================== world +int l_get_block(lua_State* L) { + Level* level = LV(); + int x = argInt(L, 1), y = argInt(L, 2), z = argInt(L, 3); + lua_pushinteger(L, level->getTile(x, y, z)); + lua_pushinteger(L, level->getData(x, y, z)); + return 2; +} + +int l_set_block(lua_State* L) { + Level* level = LV(); + int x = argInt(L, 1), y = argInt(L, 2), z = argInt(L, 3); + int id = argInt(L, 4), data = argInt(L, 5); + bool silent = lua_toboolean(L, 6) != 0; + if (y < 0 || y >= LevelConstants::LEVEL_HEIGHT || id < 0 || id > 255 || (id > 0 && !Tile::tiles[id])) { + lua_pushboolean(L, 0); + return 1; + } + bool changed; + if (silent) { + changed = level->setTileAndDataNoUpdate(x, y, z, id, data & 15); + if (changed) markDirty(x, y, z); + } else { + changed = level->setTileAndData(x, y, z, id, data & 15); + } + lua_pushboolean(L, changed); + return 1; +} + +int l_flush(lua_State* L) { + Level* level = LV(); + ServerSideNetworkHandler* srv = server(); + int count = 0; + for (std::map::iterator it = g_dirty.begin(); it != g_dirty.end(); ++it) { + DirtyBox& b = it->second; + const int cx = b.x0 >> 4, cz = b.z0 >> 4; + + // lighting of the touched volume + const int y0 = (b.y0 - 1 < 0) ? 0 : b.y0 - 1; + const int y1 = (b.y1 + 1 > LevelConstants::LEVEL_HEIGHT - 1) ? LevelConstants::LEVEL_HEIGHT - 1 : b.y1 + 1; + level->updateLight(LightLayer::Sky, b.x0 - 1, y0, b.z0 - 1, b.x1 + 1, y1, b.z1 + 1); + level->updateLight(LightLayer::Block, b.x0 - 1, y0, b.z0 - 1, b.x1 + 1, y1, b.z1 + 1); + level->setTilesDirty(b.x0 - 1, y0, b.z0 - 1, b.x1 + 1, y1, b.z1 + 1); + + if (srv) { + LevelChunk* chunk = level->getChunk(cx, cz); + ChunkDataPacket packet(cx, cz, chunk); + RakNet::BitStream bs; + packet.write(&bs); + MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true); + } + ++count; + } + g_dirty.clear(); + lua_pushinteger(L, count); + return 1; +} + +int l_solid_height(lua_State* L) { + Level* level = LV(); + int x = argInt(L, 1), z = argInt(L, 2); + for (int y = LevelConstants::LEVEL_HEIGHT - 1; y >= 0; --y) { + int id = level->getTile(x, y, z); + if (id > 0 && Tile::tiles[id] && Tile::tiles[id]->material->blocksMotion()) { + lua_pushinteger(L, y); + return 1; + } + } + lua_pushinteger(L, -1); + return 1; +} + +int l_loaded(lua_State* L) { + lua_pushboolean(L, LV()->hasChunkAt(argInt(L, 1), 64, argInt(L, 2))); + return 1; +} + +int l_ensure(lua_State* L) { + LV()->ensureChunksAround(argInt(L, 1), argInt(L, 2), argInt(L, 3)); + return 0; +} + +int l_get_time(lua_State* L) { lua_pushinteger(L, LV()->getTime()); return 1; } +int l_set_time(lua_State* L) { LV()->setTime(argInt(L, 1)); return 0; } +int l_seed(lua_State* L) { lua_pushnumber(L, (double)LV()->getSeed()); return 1; } + +int l_explode(lua_State* L) { + LV()->explode(NULL, argNum(L, 1), argNum(L, 2), argNum(L, 3), argNum(L, 4)); + return 0; +} + +int l_spawn_mob(lua_State* L) { + Level* level = LV(); + Mob* mob = MobFactory::CreateMob(argInt(L, 1), level); + if (!mob) { lua_pushnil(L); return 1; } + mob->moveTo(argNum(L, 2), argNum(L, 3), argNum(L, 4), 0, 0); + level->addEntity(mob); + lua_pushinteger(L, mob->entityId); + return 1; +} + +int l_drop_item(lua_State* L) { + Level* level = LV(); + ItemInstance item(argInt(L, 1), argInt(L, 2), argInt(L, 3)); + level->addEntity(new ItemEntity(level, argNum(L, 4), argNum(L, 5), argNum(L, 6), item)); + return 0; +} + +// butcher(x, y, z, radius, includeFriendly) -> count +int l_butcher(lua_State* L) { + Level* level = LV(); + float x = argNum(L, 1), y = argNum(L, 2), z = argNum(L, 3), r = argNum(L, 4); + bool friendly = lua_toboolean(L, 5) != 0; + int n = 0; + for (unsigned int i = 0; i < level->entities.size(); ++i) { + Entity* e = level->entities[i]; + if (e->removed || !e->isMob() || e->isPlayer()) continue; + if (!friendly && e->getCreatureBaseType() != MobTypes::BaseEnemy) continue; + float dx = e->x - x, dy = e->y - y, dz = e->z - z; + if (r > 0 && dx * dx + dy * dy + dz * dz > r * r) continue; + e->remove(); + ++n; + } + lua_pushinteger(L, n); + return 1; +} + +// ================================================================== players +int l_players(lua_State* L) { + Level* level = LV(); + lua_newtable(L); + int n = 0; + for (unsigned int i = 0; i < level->players.size(); ++i) { + lua_pushinteger(L, level->players[i]->entityId); + lua_rawseti(L, -2, ++n); + } + return 1; +} + +int l_pname(lua_State* L) { + Player* p = findPlayer(argInt(L, 1)); + if (!p) { lua_pushnil(L); return 1; } + lua_pushstring(L, p->name.c_str()); + return 1; +} + +int l_ppos(lua_State* L) { + Player* p = findPlayer(argInt(L, 1)); + if (!p) return 0; + lua_pushnumber(L, p->x); + lua_pushnumber(L, p->y - p->heightOffset); // feet + lua_pushnumber(L, p->z); + lua_pushnumber(L, p->yRot); + lua_pushnumber(L, p->xRot); + return 5; +} + +int l_pteleport(lua_State* L) { + Player* p = findPlayer(argInt(L, 1)); + if (!p) return 0; + float x = argNum(L, 2), y = argNum(L, 3), z = argNum(L, 4); + float yaw = lua_isnumber(L, 5) ? argNum(L, 5) : p->yRot; + float pitch = lua_isnumber(L, 6) ? argNum(L, 6) : p->xRot; + LV()->ensureChunksAround((int)floorf(x), (int)floorf(z), 2); + p->moveTo(x, y, z, yaw, pitch); + if (!isLocalPlayer(p) && server()) { + MovePlayerPacket packet(p->entityId, p->x, p->y - p->heightOffset, p->z, p->xRot, p->yRot); + RakNet::BitStream bs; + packet.write(&bs); + MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true); + } + return 0; +} + +int l_pmsg(lua_State* L) { + sendChat(findPlayer(argInt(L, 1)), lua_tostring(L, 2)); + return 0; +} + +int l_broadcast(lua_State* L) { + broadcastChat(lua_tostring(L, 1)); + return 0; +} + +int l_pop(lua_State* L) { + Player* p = findPlayer(argInt(L, 1)); + if (!p) { lua_pushboolean(L, 0); return 1; } + std::string lower = p->name; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + lua_pushboolean(L, LV()->ops.find(lower) != LV()->ops.end()); + return 1; +} + +int l_pheld(lua_State* L) { + Player* p = findPlayer(argInt(L, 1)); + ItemInstance* item = p ? p->inventory->getSelected() : NULL; + if (!item || item->isNull()) { lua_pushinteger(L, 0); lua_pushinteger(L, 0); lua_pushinteger(L, 0); return 3; } + lua_pushinteger(L, item->id); + lua_pushinteger(L, item->getAuxValue()); + lua_pushinteger(L, item->count); + return 3; +} + +int l_pgive(lua_State* L) { + Player* p = findPlayer(argInt(L, 1)); + if (!p) return 0; + p->inventory->add(new ItemInstance(argInt(L, 2), argInt(L, 3), argInt(L, 4))); + if (!isLocalPlayer(p) && server()) { + SendInventoryPacket packet(p, false); + RakNet::BitStream bs; + packet.write(&bs); + MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->owner, false); + } + return 0; +} + +int l_pgamemode(lua_State* L) { + lua_pushinteger(L, LV()->getLevelData()->getGameType()); + return 1; +} + +// trace(id, maxDist) -> x, y, z, face (the block the player looks at) +int l_ptrace(lua_State* L) { + Player* p = findPlayer(argInt(L, 1)); + float dist = lua_isnumber(L, 2) ? argNum(L, 2) : 128.0f; + if (!p) return 0; + float yaw = p->yRot * Mth::DEGRAD, pitch = p->xRot * Mth::DEGRAD; + Vec3 dir(-sinf(yaw) * cosf(pitch), -sinf(pitch), cosf(yaw) * cosf(pitch)); + Vec3 a(p->x, p->y, p->z); + Vec3 b(a.x + dir.x * dist, a.y + dir.y * dist, a.z + dir.z * dist); + HitResult hit = LV()->clip(a, b, false, false); + if (!hit.isHit() || hit.type != TILE) return 0; + lua_pushinteger(L, hit.x); + lua_pushinteger(L, hit.y); + lua_pushinteger(L, hit.z); + lua_pushinteger(L, hit.f); + return 4; +} + +int l_log(lua_State* L) { + LOGI("[lua] %s\n", lua_tostring(L, 1)); + return 0; +} + +int l_mkdir(lua_State* L) { + MKDIR(lua_tostring(L, 1)); + return 0; +} + +// listdir(path) -> { {name=, dir=bool}, ... } +int l_listdir(lua_State* L) { + std::string path = lua_tostring(L, 1); + lua_newtable(L); + int n = 0; +#ifdef _WIN32 + WIN32_FIND_DATAA fd; + HANDLE h = FindFirstFileA((path + "/*").c_str(), &fd); + if (h != INVALID_HANDLE_VALUE) { + do { + if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue; + lua_newtable(L); + lua_pushstring(L, fd.cFileName); + lua_setfield(L, -2, "name"); + lua_pushboolean(L, (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0); + lua_setfield(L, -2, "dir"); + lua_rawseti(L, -2, ++n); + } while (FindNextFileA(h, &fd)); + FindClose(h); + } +#else + if (DIR* d = opendir(path.c_str())) { + while (dirent* e = readdir(d)) { + if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue; + struct stat st; + bool isDir = stat((path + "/" + e->d_name).c_str(), &st) == 0 && S_ISDIR(st.st_mode); + lua_newtable(L); + lua_pushstring(L, e->d_name); + lua_setfield(L, -2, "name"); + lua_pushboolean(L, isDir); + lua_setfield(L, -2, "dir"); + lua_rawseti(L, -2, ++n); + } + closedir(d); + } +#endif + return 1; +} + +const luaL_Reg api[] = { + { "_get_block", l_get_block }, { "_set_block", l_set_block }, { "_flush", l_flush }, + { "_solid_height", l_solid_height }, { "_loaded", l_loaded }, { "_ensure", l_ensure }, + { "_get_time", l_get_time }, { "_set_time", l_set_time }, { "_seed", l_seed }, + { "_explode", l_explode }, { "_spawn_mob", l_spawn_mob }, { "_drop_item", l_drop_item }, + { "_butcher", l_butcher }, + { "_players", l_players }, { "_pname", l_pname }, { "_ppos", l_ppos }, { "_pteleport", l_pteleport }, + { "_pmsg", l_pmsg }, { "_broadcast", l_broadcast }, { "_pop", l_pop }, { "_pheld", l_pheld }, + { "_pgive", l_pgive }, { "_pgamemode", l_pgamemode }, { "_ptrace", l_ptrace }, + { "_log", l_log }, { "_mkdir", l_mkdir }, { "_listdir", l_listdir }, + { NULL, NULL } +}; + +int traceback(lua_State* L) { + const char* msg = lua_tostring(L, 1); + luaL_traceback(L, L, msg ? msg : "(error)", 1); + return 1; +} + +// calls the function sitting below `nargs` arguments; returns false on error +bool protectedCall(lua_State* L, int nargs, int nresults) { + int base = lua_gettop(L) - nargs; + lua_pushcfunction(L, traceback); + lua_insert(L, base); + int rc = lua_pcall(L, nargs, nresults, base); + lua_remove(L, base); + if (rc != 0) { + LOGE("[lua] %s\n", lua_tostring(L, -1)); + lua_pop(L, 1); + return false; + } + return true; +} + +bool fileExists(const std::string& p) { + std::ifstream f(p.c_str()); + return f.good(); +} + +} // namespace + +// =================================================================== engine +LuaEngine& LuaEngine::get() { + static LuaEngine engine; + return engine; +} + +void LuaEngine::start(Minecraft* minecraft) { + if (L) stop(); + mc = minecraft; + g_dirty.clear(); + + L = luaL_newstate(); + luaL_openlibs(L); + + lua_newtable(L); + luaL_register(L, NULL, api); + lua_setglobal(L, "mc"); + + // prelude: the friendly API on top of the primitives above + const char* candidates[] = { "lua/prelude.lua", "data/lua/prelude.lua", "../lua/prelude.lua" }; + std::string prelude; + for (unsigned int i = 0; i < sizeof(candidates) / sizeof(candidates[0]); ++i) + if (fileExists(candidates[i])) { prelude = candidates[i]; break; } + if (prelude.empty()) { + LOGE("[lua] lua/prelude.lua not found, Lua mods are disabled\n"); + lua_close(L); + L = 0; + return; + } + if (luaL_loadfile(L, prelude.c_str()) != 0 || !protectedCall(L, 0, 0)) { + if (lua_gettop(L) > 0) { LOGE("[lua] %s\n", lua_tostring(L, -1)); } + lua_close(L); + L = 0; + return; + } + + MKDIR("mods"); + loadMods(); + LOGI("[lua] LuaJIT mod host started\n"); +} + +void LuaEngine::stop() { + if (!L) return; + lua_getglobal(L, "mc"); + lua_getfield(L, -1, "_fire"); + lua_remove(L, -2); + lua_pushstring(L, "stop"); + lua_pushnil(L); + protectedCall(L, 2, 1); + lua_pop(L, 1); + lua_close(L); + L = 0; + mc = 0; +} + +void LuaEngine::loadMods() { + lua_getglobal(L, "mc"); + lua_getfield(L, -1, "_load_mods"); + lua_remove(L, -2); + protectedCall(L, 0, 0); +} + +void LuaEngine::tick() { + if (!L) return; + lua_getglobal(L, "mc"); + lua_getfield(L, -1, "_tick"); + lua_remove(L, -2); + protectedCall(L, 0, 0); +} + +// Calls mc._fire(event, ...) with `nargs` arguments already pushed after the event name. +bool LuaEngine::fire(const char* event, int nargs, bool cancellable) { + // stack now: args...; put the function and the event below them + lua_getglobal(L, "mc"); + lua_getfield(L, -1, "_fire"); + lua_remove(L, -2); + lua_insert(L, -(nargs + 1)); + lua_pushstring(L, event); + lua_insert(L, -(nargs + 1)); + bool cancelled = false; + if (protectedCall(L, nargs + 1, 1)) { + if (cancellable && lua_isboolean(L, -1) && !lua_toboolean(L, -1)) cancelled = true; + lua_pop(L, 1); + } + return cancelled; +} + +void LuaEngine::onPlayerJoin(Player* player) { + if (!L) return; + lua_pushinteger(L, player->entityId); + fire("join", 1, false); +} + +void LuaEngine::onPlayerLeave(Player* player) { + if (!L) return; + lua_pushinteger(L, player->entityId); + fire("leave", 1, false); +} + +bool LuaEngine::onChat(Player* player, const std::string& message) { + if (!L) return false; + lua_pushinteger(L, player->entityId); + lua_pushstring(L, message.c_str()); + return fire("chat", 2, true); +} + +bool LuaEngine::onBlockBreak(Player* player, int x, int y, int z) { + if (!L) return false; + lua_pushinteger(L, player->entityId); + lua_pushinteger(L, x); lua_pushinteger(L, y); lua_pushinteger(L, z); + lua_pushinteger(L, MC()->level->getTile(x, y, z)); + return fire("block_break", 5, true); +} + +bool LuaEngine::onUseItem(Player* player, int x, int y, int z, int face, ItemInstance* item) { + if (!L) return false; + lua_pushinteger(L, player->entityId); + lua_pushinteger(L, x); lua_pushinteger(L, y); lua_pushinteger(L, z); + lua_pushinteger(L, face); + lua_pushinteger(L, item && !item->isNull() ? item->id : 0); + lua_pushinteger(L, item && !item->isNull() ? item->getAuxValue() : 0); + return fire("use_item", 7, true); +} + +bool LuaEngine::runCommand(Player* player, const std::string& name, const std::vector& args, std::string& reply) { + if (!L) return false; + lua_getglobal(L, "mc"); + lua_getfield(L, -1, "_run_command"); + lua_remove(L, -2); + lua_pushinteger(L, player->entityId); + lua_pushstring(L, name.c_str()); + lua_newtable(L); + for (unsigned int i = 0; i < args.size(); ++i) { + lua_pushstring(L, args[i].c_str()); + lua_rawseti(L, -2, i + 1); + } + bool handled = false; + if (protectedCall(L, 3, 2)) { + handled = lua_toboolean(L, -2) != 0; + if (lua_isstring(L, -1)) reply = lua_tostring(L, -1); + lua_pop(L, 2); + } + return handled; +} + +std::vector LuaEngine::commandNames() { + std::vector names; + if (!L) return names; + lua_getglobal(L, "mc"); + lua_getfield(L, -1, "_command_names"); + lua_remove(L, -2); + if (protectedCall(L, 0, 1)) { + int n = (int)lua_objlen(L, -1); + for (int i = 1; i <= n; ++i) { + lua_rawgeti(L, -1, i); + if (lua_isstring(L, -1)) names.push_back(lua_tostring(L, -1)); + lua_pop(L, 1); + } + lua_pop(L, 1); + } + return names; +} diff --git a/src/lua/LuaEngine.h b/src/lua/LuaEngine.h new file mode 100644 index 0000000..d5049d6 --- /dev/null +++ b/src/lua/LuaEngine.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include + +class Minecraft; +class Player; +class ItemInstance; +struct lua_State; + +/** + * LuaJIT mod host. Mods live in "mods//main.lua" (or "mods/.lua") + * next to the executable and run on the machine that hosts the world (dedicated + * server, single player, or a listening client). See mods/README.md for the API. + */ +class LuaEngine { +public: + static LuaEngine& get(); + + // Called once the level of a hosting game is ready + void start(Minecraft* mc); + void stop(); + bool active() const { return L != 0; } + + void tick(); + + // Events. The "cancellable" ones return true when a mod cancelled the action. + void onPlayerJoin(Player* player); + void onPlayerLeave(Player* player); + bool onChat(Player* player, const std::string& message); + bool onBlockBreak(Player* player, int x, int y, int z); + bool onUseItem(Player* player, int x, int y, int z, int face, ItemInstance* item); + bool onAttackBlock(Player* player, int x, int y, int z) { return onBlockBreak(player, x, y, z); } + + // Chat commands registered by mods. Returns false when nobody knows `name`. + bool runCommand(Player* player, const std::string& name, const std::vector& args, std::string& reply); + std::vector commandNames(); + + // Used by the bindings + Minecraft* minecraft() const { return mc; } + lua_State* state() const { return L; } + +private: + LuaEngine() : L(0), mc(0) {} + void loadMods(); + bool fire(const char* event, int nargs, bool cancellable); + + lua_State* L; + Minecraft* mc; +}; diff --git a/src/main_android_java.cpp b/src/main_android_java.cpp index c89ae03..d407ba7 100755 --- a/src/main_android_java.cpp +++ b/src/main_android_java.cpp @@ -220,16 +220,23 @@ static int androidKeyToInternal(int androidKey) { JNIEXPORT void JNICALL Java_com_mojang_minecraftpe_MainActivity_nativeOnKeyDown(JNIEnv* env, jclass cls, jint keyCode) { LOGI("@nativeOnKeyDown: %d\n", keyCode); - int mapped = androidKeyToInternal(keyCode); - Keyboard::feed(mapped, true); + + // @rewrite + + if (keyCode != AKEYCODE_1) { + int mapped = androidKeyToInternal(keyCode); + Keyboard::feed(mapped, true); + } } JNIEXPORT void JNICALL Java_com_mojang_minecraftpe_MainActivity_nativeTextChar(JNIEnv* env, jclass cls, jint unicodeChar) { + LOGI("@nativeTextChar: %d '%c'", unicodeChar, (char)unicodeChar); // soft-keyboards may send a backspace as a character code - if (unicodeChar == 8) { + // Kolyah35: i dont believe :v + /*if (unicodeChar == 8) { Keyboard::feed(Keyboard::KEY_BACKSPACE, true); Keyboard::feed(Keyboard::KEY_BACKSPACE, false); - } else if (unicodeChar > 0 && unicodeChar < 128) { + } else*/ if (unicodeChar > 0 && unicodeChar < 128) { Keyboard::feedText((char)unicodeChar); } } diff --git a/src/main_dedicated.cpp b/src/main_dedicated.cpp index fcf14ce..87b45be 100755 --- a/src/main_dedicated.cpp +++ b/src/main_dedicated.cpp @@ -91,16 +91,22 @@ int main(int numArguments, char* pszArgs[]) { } port = std::stoi(findStringInConfig("port", propString)); - worldSize = std::stoi(findStringInConfig("world-size", propString)); - if (worldSize < 16 || worldSize > 32) { - throw std::runtime_error("Incorrect world size."); + // The world is infinite. "view-distance" (in chunks) is how far around every + // player the server keeps chunks loaded. The old "world-size" is ignored. + try { + worldSize = std::stoi(findStringInConfig("view-distance", propString)); + if (worldSize < 3 || worldSize > 32) { + throw std::runtime_error("view-distance must be between 3 and 32."); + } + } catch (const std::out_of_range&) { + throw std::runtime_error("Incorrect view-distance."); + } catch (const std::runtime_error& e) { + if (std::string(e.what()) == "Cannot find value") worldSize = 10; + else throw; } + LevelConstants::VIEW_DISTANCE_CHUNKS = worldSize; - LevelConstants::CHUNK_CACHE_WIDTH = worldSize; - LevelConstants::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH; - LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH; - cachePath = findStringInConfig("level-cachepath", propString); externalPath = findStringInConfig("level-externalpath", propString); levelName = findStringInConfig("level-name", propString); @@ -116,7 +122,7 @@ int main(int numArguments, char* pszArgs[]) { gamemode = GameType::Survival; } - printf("%d %s %s %d %d\n", port, cachePath.c_str(), externalPath.c_str(), gamemode, LevelConstants::CHUNK_CACHE_WIDTH); + printf("%d %s %s %d %d\n", port, cachePath.c_str(), externalPath.c_str(), gamemode, LevelConstants::VIEW_DISTANCE_CHUNKS); } else { std::ofstream defaultProperties("server.properties"); @@ -132,7 +138,7 @@ int main(int numArguments, char* pszArgs[]) { buffer << "level-externalpath=" << defaultSettings.getExternalPath() << std::endl; buffer << "gamemode=survival" << std::endl; buffer << "level-name=" << defaultSettings.getLevelName() << std::endl; - buffer << "world-size=16" << std::endl; + buffer << "view-distance=10" << std::endl; defaultProperties << buffer.str(); @@ -190,13 +196,13 @@ int main(int numArguments, char* pszArgs[]) { while (std::getline(banned, line)) { if (!line.empty()) { - ((MAIN_CLASS*)g_app)->level->bannedPpl.insert(line); + ((MAIN_CLASS*)g_app)->level->bannedPlayers.insert(line); } } } else { - std::ofstream bannedPpl("banned-players.txt"); + std::ofstream bannedPlayers("banned-players.txt"); - if (!bannedPpl.is_open()) { + if (!bannedPlayers.is_open()) { throw std::runtime_error("Cannot create banned players list."); } } @@ -225,7 +231,7 @@ int main(int numArguments, char* pszArgs[]) { std::ofstream bannedWrite("banned-players.txt"); if (bannedWrite.is_open()) { - for (auto& banned : ((MAIN_CLASS*)g_app)->level->bannedPpl) { + for (auto& banned : ((MAIN_CLASS*)g_app)->level->bannedPlayers) { bannedWrite << banned << std::endl; } bannedWrite.close(); diff --git a/src/network/ClientSideNetworkHandler.cpp b/src/network/ClientSideNetworkHandler.cpp index 022b35f..d0fee5f 100755 --- a/src/network/ClientSideNetworkHandler.cpp +++ b/src/network/ClientSideNetworkHandler.cpp @@ -43,12 +43,10 @@ ClientSideNetworkHandler::ClientSideNetworkHandler(Minecraft* minecraft, IRakNet : minecraft(minecraft), raknetInstance(raknetInstance), level(NULL), - requestNextChunkPosition(0), - requestNextChunkIndex(0) + initialLoadDone(false), + initialPending(0), + spiralRadius(-1) { - NumRequestChunks = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH; - requestNextChunkIndexList.resize(NumRequestChunks); - chunksLoaded.resize(NumRequestChunks); rakPeer = raknetInstance->getPeer(); } @@ -56,35 +54,93 @@ ClientSideNetworkHandler::~ClientSideNetworkHandler() { } -void ClientSideNetworkHandler::requestNextChunk() +void ClientSideNetworkHandler::requestChunk(int x, int z) { - if (requestNextChunkIndex < NumRequestChunks) - { - IntPair& chunk = requestNextChunkIndexList[requestNextChunkIndex]; - RequestChunkPacket packet(chunk.x, chunk.y); - raknetInstance->send(packet); + const long long key = LevelConstants::chunkKey(x, z); + if (requestedChunks.count(key) || loadedChunks.count(key)) return; - //LOGI("requesting chunks @ (%d, %d)\n", chunk.x, chunk.y); - - //raknetInstance->send(new RequestChunkPacket(requestNextChunkPosition % LevelConstants::CHUNK_CACHE_WIDTH, requestNextChunkPosition / LevelConstants::CHUNK_CACHE_WIDTH)); - requestNextChunkIndex++; - requestNextChunkPosition++; - } -} - -bool ClientSideNetworkHandler::areAllChunksLoaded() -{ - return (requestNextChunkPosition >= (LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH)); + RequestChunkPacket packet(x, z); + raknetInstance->send(packet); + requestedChunks.insert(key); } bool ClientSideNetworkHandler::isChunkLoaded(int x, int z) { - if (x < 0 || x >= LevelConstants::CHUNK_CACHE_WIDTH || z < 0 || z >= LevelConstants::CHUNK_CACHE_WIDTH) { - LOGE("Error: Tried to request chunk (%d, %d)\n", x, z); - return true; + return loadedChunks.count(LevelConstants::chunkKey(x, z)) != 0; +} + +// Keeps the chunks around the local player in sync with the server: asks for +// the ones that came into range (nearest first) and drops the ones left behind. +void ClientSideNetworkHandler::updateChunks() +{ + if (!level || !minecraft->player || !initialLoadDone) return; + + Player* p = minecraft->player; + const int pcx = Mth::floor(p->x / 16.0f); + const int pcz = Mth::floor(p->z / 16.0f); + const int radius = LevelConstants::VIEW_DISTANCE_CHUNKS + 1; + + if (radius != spiralRadius) { + spiralRadius = radius; + spiral.clear(); + for (int dx = -radius; dx <= radius; ++dx) + for (int dz = -radius; dz <= radius; ++dz) + if (dx * dx + dz * dz <= radius * radius + radius) + spiral.push_back(std::make_pair(dx, dz)); + struct ByDistance { + bool operator()(const std::pair& a, const std::pair& b) const { + return a.first * a.first + a.second * a.second < b.first * b.first + b.second * b.second; + } + }; + std::stable_sort(spiral.begin(), spiral.end(), ByDistance()); } - return chunksLoaded[x * LevelConstants::CHUNK_CACHE_WIDTH + z]; - //return areAllChunksLoaded(); + + // Request what is missing, a few at a time + int budget = 4; + if (requestedChunks.size() < 16) { + for (unsigned int i = 0; i < spiral.size() && budget > 0; ++i) { + const int cx = pcx + spiral[i].first; + const int cz = pcz + spiral[i].second; + const long long key = LevelConstants::chunkKey(cx, cz); + if (requestedChunks.count(key) || loadedChunks.count(key)) continue; + requestChunk(cx, cz); + --budget; + } + } + + // Forget chunks that are far away now + const int unloadRadius = radius + 2; + std::vector victims; + for (std::set::iterator it = loadedChunks.begin(); it != loadedChunks.end() && victims.size() < 8; ++it) { + const int cx = (int)(*it >> 32); + const int cz = (int)(*it & 0xffffffffLL); + if (std::abs(cx - pcx) > unloadRadius || std::abs(cz - pcz) > unloadRadius) + victims.push_back(*it); + } + for (std::set::iterator it = requestedChunks.begin(); it != requestedChunks.end() && victims.size() < 8; ++it) { + const int cx = (int)(*it >> 32); + const int cz = (int)(*it & 0xffffffffLL); + if (std::abs(cx - pcx) > unloadRadius || std::abs(cz - pcz) > unloadRadius) + victims.push_back(*it); + } + for (unsigned int i = 0; i < victims.size(); ++i) { + const int cx = (int)(victims[i] >> 32); + const int cz = (int)(victims[i] & 0xffffffffLL); + loadedChunks.erase(victims[i]); + requestedChunks.erase(victims[i]); + level->getChunkSource()->unloadChunk(cx, cz); + } +} + +// The chunks right around the player arrived: the server may now send everything else. +void ClientSideNetworkHandler::finishInitialLoad() +{ + if (initialLoadDone) return; + initialLoadDone = true; + + ReadyPacket packet(ReadyPacket::READY_REQUESTEDCHUNKS); + raknetInstance->send(packet); + bufferedBlockUpdates.clear(); } void ClientSideNetworkHandler::onConnect(const RakNet::RakNetGUID& hostGuid) @@ -104,10 +160,8 @@ void ClientSideNetworkHandler::onUnableToConnect() void ClientSideNetworkHandler::onDisconnect(const RakNet::RakNetGUID& guid) { - LevelConstants::CHUNK_CACHE_WIDTH = 16; - LevelConstants::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH; - LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH; - + clearChunksLoaded(); + // TODO: Good disconnecting LOGI("onDisconnect\n"); if (level) @@ -174,18 +228,8 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, StartGam } #endif - // @todo @note i think its trash - // we can put it directly to selectLevel? - if (packet->chunkCacheWidth != 0) { - printf("lol \n"); - LevelConstants::CHUNK_CACHE_WIDTH = packet->chunkCacheWidth; - LevelConstants::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH; - LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH; - LevelChunk::ChunkBlockCount = LevelConstants::CHUNK_BLOCK_COUNT; - } - NumRequestChunks = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH; - requestNextChunkIndexList.resize(NumRequestChunks); - chunksLoaded.resize(NumRequestChunks); + // The world is infinite, the chunk cache width sent by the server is a legacy field. + clearChunksLoaded(); const std::string& levelId = LevelStorageSource::TempLevelId; LevelStorageSource* storageSource = minecraft->getLevelSource(); @@ -448,7 +492,7 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, TakeItem LOGI("TakeItemPacket\n"); - ItemInstance* item; + ItemInstance* item = new ItemInstance(); item->count = packet->count; item->id = packet->itemId; @@ -499,6 +543,7 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, UpdateBl int x = packet->x, z = packet->z; + // Updates for chunks we do not hold are already part of the chunk data we will get if (isChunkLoaded(x >> 4, z >> 4)) { //LOGI("chunk is loaded - UPDATE @ %d, %d, %d -- %d, %d\n", x, packet->y, z, packet->blockId, packet->blockData); @@ -506,15 +551,6 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, UpdateBl int y = packet->y; int tileId = Tile::transformToValidBlockId(packet->blockId, x, y, z); level->setTileAndData(x, y, z, tileId, packet->blockData); - } else { - SBufferedBlockUpdate update; - update.blockId = packet->blockId; - update.blockData = packet->blockData; - update.setData = true; - update.x = packet->x; - update.y = packet->y; - update.z = packet->z; - bufferedBlockUpdates.push_back(update); } } @@ -555,6 +591,14 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChunkDat } //LOGI("ChunkDataPacket\n"); + const long long chunkKey = LevelConstants::chunkKey(packet->x, packet->z); + const bool requested = requestedChunks.erase(chunkKey) > 0; + if (!requested && loadedChunks.count(chunkKey) == 0) { + // we do not want this chunk (any more) + return; + } + // (a chunk we already hold can be pushed again, e.g. after a bulk edit by a mod) + LevelChunk* chunk = level->getChunkSource()->create(packet->x, packet->z); if (!chunk || chunk->isEmpty()) { @@ -672,66 +716,11 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChunkDat //chunk->terrainPopulated = true; chunk->unsaved = false; - chunksLoaded[packet->x * LevelConstants::CHUNK_CACHE_WIDTH + packet->z] = true; + loadedChunks.insert(chunkKey); - if (areAllChunksLoaded()) - { - ReadyPacket packet(ReadyPacket::READY_REQUESTEDCHUNKS); - raknetInstance->send(packet); - - for (unsigned int i = 0; i < bufferedBlockUpdates.size(); i++) - { - const SBufferedBlockUpdate& update = bufferedBlockUpdates[i]; - int tileId = Tile::transformToValidBlockId( update.blockId, update.x, update.y, update.z ); - if (update.setData) - level->setTileAndData(update.x, update.y, update.z, tileId, update.blockData); - else - level->setTile(update.x, update.y, update.z, tileId); - } - bufferedBlockUpdates.clear(); + if (requested && !initialLoadDone && initialPending > 0 && --initialPending == 0) { + finishInitialLoad(); } - else - { - requestNextChunk(); - } -} - -class _ChunkSorter -{ -public: - _ChunkSorter(int x, int z) - : x(x), - y(z) - { - } - - bool operator() (const IntPair& a, const IntPair& b) { - const int ax = a.x - x, ay = a.y - y; - const int bx = b.x - x, by = b.y - y; - return (ax*ax + ay*ay) < (bx*bx + by*by); - } -private: - int x; - int y; -}; - - -void ClientSideNetworkHandler::arrangeRequestChunkOrder() { - clearChunksLoaded(); - - // Default sort is around center of the world - int cx = LevelConstants::CHUNK_CACHE_WIDTH / 2; - int cz = LevelConstants::CHUNK_CACHE_WIDTH / 2; - - // If player exists, let's sort around him - Player* p = minecraft? minecraft->player : NULL; - if (p) { - cx = Mth::floor(p->x / (float)LevelConstants::CHUNK_WIDTH); - cz = Mth::floor(p->z / (float)LevelConstants::CHUNK_DEPTH); - } - - _ChunkSorter sorter(cx, cz); - std::sort(requestNextChunkIndexList.begin(), requestNextChunkIndexList.end(), sorter); } void ClientSideNetworkHandler::levelGenerated(Level* level) @@ -740,8 +729,26 @@ void ClientSideNetworkHandler::levelGenerated(Level* level) ReadyPacket packet(ReadyPacket::READY_CLIENTGENERATION); raknetInstance->send(packet); - arrangeRequestChunkOrder(); - requestNextChunk(); +#ifndef STANDALONE_SERVER + if (minecraft && minecraft->player) { + const std::string skin = minecraft->options.getStringValue(OPTIONS_SKIN); + if (!skin.empty() && skin != "Default") { + SetSkinPacket skinPacket(minecraft->player->entityId, skin); + raknetInstance->send(skinPacket); + } + } +#endif + + // First ask for the chunks right around the player + clearChunksLoaded(); + Player* p = minecraft ? minecraft->player : NULL; + const int pcx = p ? Mth::floor(p->x / 16.0f) : 0; + const int pcz = p ? Mth::floor(p->z / 16.0f) : 0; + const int r = 2; + for (int dx = -r; dx <= r; ++dx) + for (int dz = -r; dz <= r; ++dz) + requestChunk(pcx + dx, pcz + dz); + initialPending = (int)requestedChunks.size(); } void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, PlayerEquipmentPacket* packet) @@ -1017,12 +1024,28 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, Adventur packet->fillIn(level->adventureSettings); } +void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet) +{ + if (!level) return; + Entity* e = level->getEntity(packet->entityId); + if (!e || !e->isPlayer() || e == minecraft->player) return; + + Player* p = (Player*)e; + p->skinName = packet->skin.C_String(); +#ifndef STANDALONE_SERVER + // every client ships the same skin files; anything we do not have keeps the default look + const std::string file = "data/images/skins/" + p->skinName + ".png"; + if (FILE* fp = fopen(file.c_str(), "rb")) { + fclose(fp); + p->setTextureName("skins/" + p->skinName + ".png"); + } +#endif +} + void ClientSideNetworkHandler::clearChunksLoaded() { - // Init the chunk positions - for (int i = 0; i < NumRequestChunks; ++i) { - requestNextChunkIndexList[i].x = i / LevelConstants::CHUNK_WIDTH; - requestNextChunkIndexList[i].y = i % LevelConstants::CHUNK_WIDTH; - chunksLoaded[i] = false; - } + requestedChunks.clear(); + loadedChunks.clear(); + initialLoadDone = false; + initialPending = 0; } diff --git a/src/network/ClientSideNetworkHandler.h b/src/network/ClientSideNetworkHandler.h index 57e0d81..e68f58d 100755 --- a/src/network/ClientSideNetworkHandler.h +++ b/src/network/ClientSideNetworkHandler.h @@ -7,6 +7,7 @@ #include "../world/level/LevelConstants.h" #include +#include class Minecraft; class Level; @@ -81,15 +82,17 @@ public: virtual void handle(const RakNet::RakNetGUID& source, TakeItemPacket* packet); virtual void handle(const RakNet::RakNetGUID& source, WantCreatePacket* packet); virtual void handle(const RakNet::RakNetGUID& source, SendInventoryPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet); + + // Streams chunks in/out around the local player. Called once per game tick. + void updateChunks(); private: - void requestNextChunk(); - void arrangeRequestChunkOrder(); - bool isChunkLoaded(int x, int z); - bool areAllChunksLoaded(); void clearChunksLoaded(); + void requestChunk(int x, int z); + void finishInitialLoad(); private: Minecraft* minecraft; @@ -100,13 +103,14 @@ private: RakNet::RakNetGUID serverGuid; BlockUpdateList bufferedBlockUpdates; - int requestNextChunkPosition; - int NumRequestChunks; - - int requestNextChunkIndex; - std::vector requestNextChunkIndexList; - std::vector chunksLoaded; + // The world is infinite: only the chunks around the player are kept. + std::set requestedChunks; // asked from the server, data not here yet + std::set loadedChunks; // data received and applied + bool initialLoadDone; + int initialPending; + std::vector > spiral; + int spiralRadius; }; #endif diff --git a/src/network/NetEventCallback.h b/src/network/NetEventCallback.h index db3e22b..3a05a9d 100755 --- a/src/network/NetEventCallback.h +++ b/src/network/NetEventCallback.h @@ -52,6 +52,7 @@ class ContainerSetDataPacket; class ContainerSetContentPacket; class WantCreatePacket; class ChatPacket; +class SetSkinPacket; class SignUpdatePacket; class Minecraft; class Level; @@ -119,6 +120,7 @@ public: virtual void handle(const RakNet::RakNetGUID& source, ContainerSetSlotPacket* packet) {} virtual void handle(const RakNet::RakNetGUID& source, ContainerSetContentPacket* packet) {} virtual void handle(const RakNet::RakNetGUID& source, ChatPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet) {} virtual void handle(const RakNet::RakNetGUID& source, SignUpdatePacket* packet) {} virtual void handle(const RakNet::RakNetGUID& source, AdventureSettingsPacket* packet) {} virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet) {} diff --git a/src/network/Packet.cpp b/src/network/Packet.cpp index d060356..b83d54a 100755 --- a/src/network/Packet.cpp +++ b/src/network/Packet.cpp @@ -177,6 +177,9 @@ Packet* MinecraftPackets::createPacket(int id) case PACKET_ADVENTURESETTINGS: packet = new AdventureSettingsPacket(); break; + case PACKET_SETSKIN: + packet = new SetSkinPacket(); + break; } return packet; diff --git a/src/network/Packet.h b/src/network/Packet.h index 3525bd4..d1f6849 100755 --- a/src/network/Packet.h +++ b/src/network/Packet.h @@ -88,6 +88,8 @@ enum MinecraftPacketIds PACKET_SIGNUPDATE, PACKET_ADVENTURESETTINGS, + + PACKET_SETSKIN, /* PACKET_PRELOGIN, PACKET_CHAT, diff --git a/src/network/RakNetInstance.cpp b/src/network/RakNetInstance.cpp index 75a2814..d5e3ad0 100755 --- a/src/network/RakNetInstance.cpp +++ b/src/network/RakNetInstance.cpp @@ -200,7 +200,7 @@ void RakNetInstance::runEvents(NetEventCallback* callback) case ID_DISCONNECTION_NOTIFICATION: case ID_CONNECTION_LOST: callback->onDisconnect(currentEvent->guid); - break; + return; case ID_UNCONNECTED_PONG: { RakNet::TimeMS time; diff --git a/src/network/ServerSideNetworkHandler.cpp b/src/network/ServerSideNetworkHandler.cpp index 474d9ad..fb8099a 100755 --- a/src/network/ServerSideNetworkHandler.cpp +++ b/src/network/ServerSideNetworkHandler.cpp @@ -38,6 +38,7 @@ #include "../client/sound/SoundEngine.h" #endif #include "../server/ServerPlayer.h" +#include "../lua/LuaEngine.h" #include "../world/entity/item/FallingTile.h" #define TIMES(x) for(int itc ## __LINE__ = 0; itc ## __LINE__ < x; ++ itc ## __LINE__) @@ -155,6 +156,24 @@ void ServerSideNetworkHandler::displayGameMessage(const std::string& message) raknetInstance->send(packet); } +void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, MessagePacket* packet) +{ + auto player = getPlayer(source); + + if (player == nullptr) return; // @todo maybe kick? + std::string msg = packet->message.C_String(); + + if (msg[0] == '/') { + // This is a command + + ChatPacket resp(minecraft->commandManager().execute(*minecraft, *player, Util::stringTrim(msg.substr(1)))); + return sendPrivate(resp, source); + } + + if (LuaEngine::get().onChat(player, msg)) return; + displayGameMessage("<" + player->name + "> " + msg); +} + void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChatPacket* packet) { auto player = getPlayer(source); @@ -168,6 +187,7 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChatPack return sendPrivate(resp, source); } + if (LuaEngine::get().onChat(player, packet->message)) return; displayGameMessage("<" + player->name + "> " + packet->message); } @@ -189,6 +209,7 @@ void ServerSideNetworkHandler::onDisconnect(const RakNet::RakNetGUID& guid) if (player->owner == guid) { minecraft->level->getLevelStorage()->savePlayer(*player); + LuaEngine::get().onPlayerLeave(player); std::string message = player->name; message += " disconnected from the game"; @@ -240,7 +261,7 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, LoginPac } } - for (auto& banned : level->bannedPpl) { + for (auto& banned : level->bannedPlayers) { if (nicknameLower == banned) { loginStatus = packet->newProto ? LoginStatus::Failed_Banned : LoginStatus::Failed_ClientOld; break; @@ -267,6 +288,9 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, LoginPac LOGI("Adding new player... isCreative: %i\n", minecraft->isCreativeMode()); + // The world is streamed in around the players: make sure the ground below the new player exists + level->ensureChunksAround((int)newPlayer->x, (int)newPlayer->z, 2); + // Reset the player so he doesn't spawn inside blocks while (newPlayer->y > 0) { newPlayer->setPos(newPlayer->x, newPlayer->y, newPlayer->z); @@ -335,6 +359,11 @@ void ServerSideNetworkHandler::onReady_ClientGeneration(const RakNet::RakNetGUID for (unsigned int i = 0; i < players.size(); i++) { Player* player = players[i]; + if (!player->skinName.empty()) { + SetSkinPacket skinPacket(player->entityId, player->skinName); + sendPrivate(skinPacket, source); + } + bitStream.Reset(); AddPlayerPacket(player).write(&bitStream); rakPeer->Send(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, source, false); @@ -347,6 +376,7 @@ void ServerSideNetworkHandler::onReady_ClientGeneration(const RakNet::RakNetGUID } level->addEntity(newPlayer); + LuaEngine::get().onPlayerJoin(newPlayer); #ifndef STANDALONE_SERVER minecraft->gui.addMessage(newPlayer->name + " joined the game"); #else @@ -368,7 +398,9 @@ void ServerSideNetworkHandler::onReady_ClientGeneration(const RakNet::RakNetGUID if (!minecraft->level->getLevelStorage()->loadPlayer(*newPlayer)) { LOGW("Failed to load %s data\n", newPlayer->name.c_str()); } - + // the saved position can be anywhere in the world + level->ensureChunksAround((int)newPlayer->x, (int)newPlayer->z, 2); + // Credits to EpikIzCool bitStream.Reset(); MovePlayerPacket mv(newPlayer->entityId, newPlayer->x, newPlayer->y - newPlayer->heightOffset, @@ -471,6 +503,13 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RemoveBl int x = packet->x, y = packet->y, z = packet->z; + if (LuaEngine::get().onBlockBreak(player, x, y, z)) { + // a mod cancelled it: put the block back on the client + UpdateBlockPacket restore(x, y, z, level->getTile(x, y, z), level->getData(x, y, z)); + sendPrivate(restore, source); + return; + } + // code copied from GameMode.cpp int oldId = level->getTile(x, y, z); int data = level->getData(x, y, z); @@ -622,6 +661,31 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, Interact } } +static bool validSkinName(const std::string& s) { + if (s.empty() || s.size() > 32) return false; + for (size_t i = 0; i < s.size(); ++i) { + char c = s[i]; + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-')) + return false; + } + return true; +} + +void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet) +{ + if (!level) return; + Player* player = getPlayer(source); + if (!player) return; + + std::string skin = packet->skin.C_String(); + if (!validSkinName(skin)) skin.clear(); + player->skinName = skin; + + // everybody else needs to know (the sender already wears it) + SetSkinPacket out(player->entityId, skin); + redistributePacket(&out, source); +} + void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, AnimatePacket* packet) { if (!level) @@ -719,6 +783,21 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, UseItemP Player* player = (Player*) entity; int x = packet->x, y = packet->y, z = packet->z; + + if (packet->face != 255 && LuaEngine::get().onUseItem(player, x, y, z, packet->face, &packet->item)) { + // cancelled by a mod: refresh the clicked block and the block that would have been placed + static const int dx[] = { 0, 0, 0, 0, -1, 1 }; + static const int dy[] = { -1, 1, 0, 0, 0, 0 }; + static const int dz[] = { 0, 0, -1, 1, 0, 0 }; + UpdateBlockPacket a(x, y, z, level->getTile(x, y, z), level->getData(x, y, z)); + sendPrivate(a, source); + if (packet->face < 6) { + int px = x + dx[packet->face], py = y + dy[packet->face], pz = z + dz[packet->face]; + UpdateBlockPacket b(px, py, pz, level->getTile(px, py, pz), level->getData(px, py, pz)); + sendPrivate(b, source); + } + return; + } Tile* t = Tile::tiles[level->getTile(x, y, z)]; if (t == Tile::invisible_bedrock) return; diff --git a/src/network/ServerSideNetworkHandler.h b/src/network/ServerSideNetworkHandler.h index 1e9585d..d2a2858 100755 --- a/src/network/ServerSideNetworkHandler.h +++ b/src/network/ServerSideNetworkHandler.h @@ -48,6 +48,7 @@ public: //virtual void handle(const RakNet::RakNetGUID& source, TeleportEntityPacket* packet); virtual void handle(const RakNet::RakNetGUID& source, InteractPacket* packet); virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet); virtual void handle(const RakNet::RakNetGUID& source, UseItemPacket* packet); virtual void handle(const RakNet::RakNetGUID& source, EntityEventPacket* packet); virtual void handle(const RakNet::RakNetGUID& source, PlayerActionPacket* packet); @@ -58,6 +59,8 @@ public: virtual void handle(const RakNet::RakNetGUID& source, ContainerClosePacket* packet); virtual void handle(const RakNet::RakNetGUID& source, SignUpdatePacket* packet); virtual void handle(const RakNet::RakNetGUID& source, ChatPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, MessagePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, WantCreatePacket* packet); bool allowsIncomingConnections() { return _allowIncoming; } diff --git a/src/network/command/CommandServer.cpp b/src/network/command/CommandServer.cpp index 280b0a9..3deaa8a 100755 --- a/src/network/command/CommandServer.cpp +++ b/src/network/command/CommandServer.cpp @@ -92,7 +92,7 @@ static std::string ToStringOk(const T& a, const T& b, const T& c) { std::stringstream ss; ss << a << "," << b << "," << c << "\n"; return ss.str(); -} +} static bool inRange(int c, int lowInclusive, int highInclusive) { return c >= lowInclusive && c <= highInclusive; @@ -233,12 +233,8 @@ std::string CommandServer::parse(ConnectedClient& client, const std::string& s) apiPosTranslate.from(x0, y0, z0); apiPosTranslate.from(x1, y1, z1); - if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; - if (z0 < 0) z0 = 0; - if (x1 >= LevelConstants::LEVEL_WIDTH ) x1 = LevelConstants::LEVEL_WIDTH - 1; if (y1 >= LevelConstants::LEVEL_HEIGHT) y1 = LevelConstants::LEVEL_HEIGHT - 1; - if (z1 >= LevelConstants::LEVEL_DEPTH ) z1 = LevelConstants::LEVEL_DEPTH - 1; for (int y = y0; y <= y1; ++y) for (int z = z0; z <= z1; ++z) diff --git a/src/network/packet/PacketInclude.h b/src/network/packet/PacketInclude.h index ff884d2..0ae79e8 100755 --- a/src/network/packet/PacketInclude.h +++ b/src/network/packet/PacketInclude.h @@ -9,6 +9,7 @@ #include "AnimatePacket.h" #include "AdventureSettingsPacket.h" #include "ChatPacket.h" +#include "SetSkinPacket.h" #include "ContainerAckPacket.h" #include "ContainerOpenPacket.h" #include "ContainerClosePacket.h" diff --git a/src/network/packet/SetSkinPacket.h b/src/network/packet/SetSkinPacket.h new file mode 100644 index 0000000..1f48ed7 --- /dev/null +++ b/src/network/packet/SetSkinPacket.h @@ -0,0 +1,38 @@ +#ifndef NET_MINECRAFT_NETWORK_PACKET__SetSkinPacket_H__ +#define NET_MINECRAFT_NETWORK_PACKET__SetSkinPacket_H__ + +#include "../Packet.h" + +// Tells everyone which skin file (data/images/skins/.png) a player wears. +class SetSkinPacket: public Packet +{ +public: + int entityId; + RakNet::RakString skin; + + SetSkinPacket() : entityId(0) {} + SetSkinPacket(int entityId, const std::string& skin) + : entityId(entityId), + skin(skin.c_str()) + {} + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETSKIN)); + bitStream->Write(entityId); + bitStream->Write(skin); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + bitStream->Read(skin); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (SetSkinPacket*)this); + } +}; + +#endif /*NET_MINECRAFT_NETWORK_PACKET__SetSkinPacket_H__*/ diff --git a/src/platform/audio/SoundSystemAL.cpp b/src/platform/audio/SoundSystemAL.cpp index 7ea7289..3000608 100755 --- a/src/platform/audio/SoundSystemAL.cpp +++ b/src/platform/audio/SoundSystemAL.cpp @@ -10,13 +10,10 @@ static const char* errIdString = 0; void checkError() { + ALenum err = alGetError(); + if(err == AL_NO_ERROR) return; - while (1) { - ALenum err = alGetError(); - if(err == AL_NO_ERROR) return; - - LOGI("### SoundSystemAL error: %d ####: %s\n", err, errIdString==0?"(none)":errIdString); - } + LOGI("### SoundSystemAL error: %d ####: %s\n", err, errIdString==0?"(none)":errIdString); } //typedef ALvoid AL_APIENTRY (*alBufferDataStaticProcPtr) (const ALint bid, ALenum format, ALvoid *data, ALsizei size, ALsizei freq); diff --git a/src/world/entity/Entity.cpp b/src/world/entity/Entity.cpp index 47ac1d8..e32694b 100755 --- a/src/world/entity/Entity.cpp +++ b/src/world/entity/Entity.cpp @@ -878,10 +878,10 @@ bool Entity::load( CompoundTag* tag ) float yy = pos->getFloat(1); float zz = pos->getFloat(2); - // Add a small padding if standing next to the world edges + // The world is infinite, only keep the position inside the coordinate system const float padding = bbWidth * 0.5f + 0.001f; - xx = Mth::clamp(xx, padding, (float)LevelConstants::LEVEL_WIDTH - padding); - zz = Mth::clamp(zz, padding, (float)LevelConstants::LEVEL_DEPTH - padding); + xx = Mth::clamp(xx, -(float)LevelConstants::LEVEL_WIDTH + padding, (float)LevelConstants::LEVEL_WIDTH - padding); + zz = Mth::clamp(zz, -(float)LevelConstants::LEVEL_DEPTH + padding, (float)LevelConstants::LEVEL_DEPTH - padding); xo = xOld = x = xx; yo = yOld = y = yy; diff --git a/src/world/entity/Mob.cpp b/src/world/entity/Mob.cpp index e275ea8..726f444 100755 --- a/src/world/entity/Mob.cpp +++ b/src/world/entity/Mob.cpp @@ -224,7 +224,7 @@ void Mob::baseTick() if (hurtTime > 0) hurtTime--; if (invulnerableTime > 0) invulnerableTime--; - if (health <= 0) { + if (this->hasDied()) { deathTime++; if (deathTime > SharedConstants::TicksPerSecond) { beforeRemove(); @@ -437,7 +437,8 @@ void Mob::setSize( float w, float h ) void Mob::heal( int heal ) { - if (health <= 0) return; + if (this->hasDied()) return; + health += heal; if (health > 20) health = 20; invulnerableTime = invulnerableDuration / 2; @@ -447,7 +448,8 @@ bool Mob::hurt( Entity* source, int dmg ) { if (level->isClientSide) return false; noActionTime = 0; - if (health <= 0) return false; + + if (this->hasDied()) return false; this->walkAnimSpeed = 1.5f; @@ -485,7 +487,7 @@ bool Mob::hurt( Entity* source, int dmg ) } } - if (health <= 0) { + if (this->hasDied()) { if (sound) level->playSound(this, getDeathSound(), getSoundVolume(), getVoicePitch()); die(source); } else { @@ -892,7 +894,7 @@ void Mob::newServerAiStep() { bool Mob::isImmobile() { - return health <= 0; + return this->hasDied(); } void Mob::jumpFromGround() diff --git a/src/world/entity/Mob.h b/src/world/entity/Mob.h index f9a0fa0..40ee980 100755 --- a/src/world/entity/Mob.h +++ b/src/world/entity/Mob.h @@ -127,6 +127,8 @@ public: virtual ItemInstance* getCarriedItem() {return NULL;} virtual int getUseItemDuration() {return 0;} virtual void swing(); + + inline bool hasDied() { return health <= 0; } protected: virtual void causeFallDamage(float distance); diff --git a/src/world/entity/player/Player.cpp b/src/world/entity/player/Player.cpp index 487b361..a5fcb26 100755 --- a/src/world/entity/player/Player.cpp +++ b/src/world/entity/player/Player.cpp @@ -390,7 +390,7 @@ void Player::travel(float xa, float ya) { /*protected*/ bool Player::isImmobile() { - return health <= 0 || isSleeping(); + return hasDied() || isSleeping(); } /*protected*/ @@ -447,8 +447,8 @@ void Player::aiStep() { float tBob = (float) Mth::sqrt(xd * xd + zd * zd); float tTilt = (float) Mth::atan(-yd * 0.2f) * 15.f; if (tBob > 0.1f) tBob = 0.1f; - if (!onGround || health <= 0) tBob = 0; - if (onGround || health <= 0) tTilt = 0; + if (!onGround || hasDied()) tBob = 0; + if (onGround || hasDied()) tTilt = 0; bob += (tBob - bob) * 0.4f; tilt += (tTilt - tilt) * 0.8f; @@ -518,14 +518,6 @@ bool Player::isCreativeModeAllowed() { return true; } -//void Player::drop() { -// //drop(inventory.removeItem(inventory.selected, 1), false); -//} - -void Player::drop(ItemInstance* item) { - drop(item, false); -} - void Player::drop(ItemInstance* item, bool randomly) { if (item == NULL || item->isNull()) return; @@ -559,11 +551,6 @@ void Player::drop(ItemInstance* item, bool randomly) { thrownItem->zd += Mth::sin(dir) * pow; } - reallyDrop(thrownItem); -} - -/*protected*/ -void Player::reallyDrop(ItemEntity* thrownItem) { level->addEntity(thrownItem); } @@ -680,7 +667,7 @@ bool Player::hurt(Entity* source, int dmg) { if (abilities.invulnerable) return false; noActionTime = 0; - if (health <= 0) return false; + if (hasDied()) return false; if(isSleeping() && !level->isClientSide) { stopSleepInBed(true, true, false); } diff --git a/src/world/entity/player/Player.h b/src/world/entity/player/Player.h index 0fb7dae..3b2fb5d 100755 --- a/src/world/entity/player/Player.h +++ b/src/world/entity/player/Player.h @@ -91,10 +91,7 @@ public: void handleEntityEvent(char id); virtual void take(Entity* e, int orgCount); - //void drop(); - virtual void drop(ItemInstance* item); - virtual void drop(ItemInstance* item, bool randomly); - void reallyDrop(ItemEntity* thrownItem); + virtual void drop(ItemInstance* item, bool randomly = false); bool canDestroy(Tile* tile); float getDestroySpeed(Tile* tile); @@ -167,6 +164,7 @@ public: float oBob, bob; std::string name; + std::string skinName; // file name (without .png) in data/images/skins, empty = default int dimension; Abilities abilities; diff --git a/src/world/item/Item.cpp b/src/world/item/Item.cpp index 1430743..9f27efa 100755 --- a/src/world/item/Item.cpp +++ b/src/world/item/Item.cpp @@ -274,7 +274,7 @@ void Item::initItems() { //Item::diode = (new TilePlanterItem(100, Tile::diode_off))->setIcon(6, 5)->setCategory(ItemCategory::Mechanisms)->setDescriptionId("diode"); Item::shears = (ShearsItem*)(new ShearsItem(103))->setIcon(13, 5)->setCategory(ItemCategory::Tools)->setDescriptionId("shears"); Item::melon = (new FoodItem(104, 2, false))->setIcon(13, 6)->setCategory(ItemCategory::FoodArmor)->setDescriptionId("melon"); - Item::seeds_melon = (new SeedItem(106, Tile::melonStem->id, Tile::farmland->id))->setIcon(14, 3)->setCategory(ItemCategory::FoodArmor)->setDescriptionId("seedsMelon"); + Item::seeds_melon = (new SeedItem(106, Tile::melonStem->id, Tile::farmland->id))->setIcon(14, 3)->setCategory(ItemCategory::FoodArmor)->setDescriptionId("seeds_melon"); Item::beef_raw = (new FoodItem(107, 3, /*FoodConstants.FOOD_SATURATION_LOW,*/ true))->setIcon(9, 6)->setCategory(ItemCategory::FoodArmor)->setDescriptionId("beefRaw"); Item::beef_cooked = (new FoodItem(108, 8, /*FoodConstants.FOOD_SATURATION_GOOD,*/ true))->setIcon(10, 6)->setCategory(ItemCategory::FoodArmor)->setDescriptionId("beefCooked"); Item::chicken_raw = (new FoodItem(109, 2, /*FoodConstants.FOOD_SATURATION_LOW,*/ true))->setIcon(9, 7)->setCategory(ItemCategory::FoodArmor)->setDescriptionId("chickenRaw"); diff --git a/src/world/level/ChunkPos.h b/src/world/level/ChunkPos.h index 8f3140b..5272f5a 100755 --- a/src/world/level/ChunkPos.h +++ b/src/world/level/ChunkPos.h @@ -32,7 +32,7 @@ public: } bool operator<(const ChunkPos& rhs) const { - return hashCode() < rhs.hashCode(); + return x < rhs.x || (x == rhs.x && z < rhs.z); } float distanceToSqr(const Entity* e) const { diff --git a/src/world/level/Level.cpp b/src/world/level/Level.cpp index 522bad1..a1f3bf9 100755 --- a/src/world/level/Level.cpp +++ b/src/world/level/Level.cpp @@ -281,8 +281,7 @@ void Level::tickTiles() { for (int i = 0; i < pollChunkOffsetsSize; i += 2) { const int xp = xx + pollChunkOffsets[i]; const int zp = zz + pollChunkOffsets[i+1]; - if (xp >= 0 && xp < LevelConstants::CHUNK_CACHE_WIDTH && - zp >= 0 && zp < LevelConstants::CHUNK_CACHE_WIDTH) + if (hasChunk(xp, zp)) _chunksToPoll.insert(ChunkPos(xp, zp)); } } @@ -431,17 +430,13 @@ bool Level::findPath(Path* path, Entity* from, int xBest, int yBest, int zBest, /*protected*/ void Level::setInitialSpawn() { isFindingSpawn = true; - int xSpawn = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH / 2; // (Level.MAX_LEVEL_SIZE - 100) * 0; + // The world is infinite: start looking for dry land around the origin. + int xSpawn = 0; int ySpawn = 64; - int zSpawn = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH / 2; // (Level.MAX_LEVEL_SIZE - 100) * 0; + int zSpawn = 0; while (!dimension->isValidSpawn(xSpawn, zSpawn)) { xSpawn += random.nextInt(32) - random.nextInt(32); zSpawn += random.nextInt(32) - random.nextInt(32); - - if (xSpawn < 4) xSpawn += 32; - if (xSpawn >= LevelConstants::LEVEL_WIDTH-4) xSpawn -= 32; - if (zSpawn < 4) zSpawn += 32; - if (zSpawn >= LevelConstants::LEVEL_DEPTH-4) zSpawn -= 32; } levelData.setSpawn(xSpawn, ySpawn, zSpawn); isFindingSpawn = false; @@ -457,11 +452,6 @@ void Level::validateSpawn() { while (getTopTile(xSpawn, zSpawn) == 0 || getTopTile(xSpawn, zSpawn) == Tile::invisible_bedrock->id) { xSpawn += random.nextInt(8) - random.nextInt(8); zSpawn += random.nextInt(8) - random.nextInt(8); - - if (xSpawn < 4) xSpawn += 8; - if (xSpawn >= LevelConstants::LEVEL_WIDTH-4) xSpawn -= 8; - if (zSpawn < 4) zSpawn += 8; - if (zSpawn >= LevelConstants::LEVEL_DEPTH-4) zSpawn -= 8; } levelData.setXSpawn(xSpawn); levelData.setZSpawn(zSpawn); @@ -947,10 +937,8 @@ HitResult Level::clip(const Vec3& A, const Vec3& b, bool liquid /*= false*/, boo if (solidOnly && tile != NULL && tile->getAABB(this, xTile0, yTile0, zTile0) == NULL) { // No collision } else if (t > 0 && tile->mayPick(data, liquid)) { - if(xTile0 >= 0 && zTile0 >= 0 && xTile0 < LevelConstants::LEVEL_WIDTH && zTile0 < LevelConstants::LEVEL_WIDTH) { - HitResult r = tile->clip(this, xTile0, yTile0, zTile0, a, b); - if (r.isHit()) return r; - } + HitResult r = tile->clip(this, xTile0, yTile0, zTile0, a, b); + if (r.isHit()) return r; } } return HitResult(); @@ -1022,7 +1010,12 @@ bool Level::addEntity(Entity* e) { if (e->isPlayer() && std::find(players.begin(), players.end(), e) == players.end()) { players.push_back( (Player*) e ); } - getChunk(xc, zc)->addEntity(e); + if (!isClientSide || hasChunk(xc, zc)) { + getChunk(xc, zc)->addEntity(e); + } else { + // chunk not streamed in yet: the entity is attached by Level::tick(Entity*) later + e->inChunk = false; + } entities.push_back(e); entityIdLookup[e->entityId] = e; entityAdded(e); @@ -2250,9 +2243,20 @@ void Level::setNightMode( bool isNightMode ) { } bool Level::inRange( int x, int y, int z ) { - return x >= 0 && x < LevelConstants::LEVEL_WIDTH + return x > -LevelConstants::LEVEL_WIDTH && x < LevelConstants::LEVEL_WIDTH && y >= 0 && y < LevelConstants::LEVEL_HEIGHT - && z >= 0 && z < LevelConstants::LEVEL_DEPTH; + && z > -LevelConstants::LEVEL_DEPTH && z < LevelConstants::LEVEL_DEPTH; +} + +// Makes sure the chunks around a block position exist (generating/loading +// them right now). Used before something is placed in an area that no +// player has streamed in yet. +void Level::ensureChunksAround(int x, int z, int radiusInChunks) { + const int cx = x >> 4; + const int cz = z >> 4; + for (int dx = -radiusInChunks; dx <= radiusInChunks; ++dx) + for (int dz = -radiusInChunks; dz <= radiusInChunks; ++dz) + getChunk(cx + dx, cz + dz); } // diff --git a/src/world/level/Level.h b/src/world/level/Level.h index 17c1d48..d8a2ad9 100755 --- a/src/world/level/Level.h +++ b/src/world/level/Level.h @@ -274,6 +274,7 @@ public: */ /*virtual*/ void setInitialSpawn(); bool inRange(int x, int y, int z); + void ensureChunksAround(int x, int z, int radiusInChunks); protected: void setZombieAi(std::vector& zombies); /*virtual*/ void entityAdded(Entity* e); @@ -312,7 +313,7 @@ public: Random random; std::set ops; - std::set bannedPpl; + std::set bannedPlayers; protected: bool isFindingSpawn; diff --git a/src/world/level/LevelConstants.cpp b/src/world/level/LevelConstants.cpp index 6a36246..b4a51f6 100644 --- a/src/world/level/LevelConstants.cpp +++ b/src/world/level/LevelConstants.cpp @@ -1,10 +1,14 @@ #include "LevelConstants.h" int LevelConstants::LEVEL_HEIGHT = 128; -int LevelConstants::CHUNK_CACHE_WIDTH = 16; // in chunks int LevelConstants::CHUNK_WIDTH = 16; // in blocks int LevelConstants::CHUNK_DEPTH = 16; -int LevelConstants::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * CHUNK_WIDTH; -int LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * CHUNK_DEPTH; +// The world is infinite: these are only the outer bounds of the coordinate +// system (blocks), kept far away so nothing ever reaches them in practice. +int LevelConstants::LEVEL_WIDTH = 32000000; +int LevelConstants::LEVEL_DEPTH = 32000000; +// Legacy value, only sent over the network for compatibility. +int LevelConstants::CHUNK_CACHE_WIDTH = 16; // in chunks +int LevelConstants::VIEW_DISTANCE_CHUNKS = 10; // chunks kept loaded around every player int LevelConstants::CHUNK_COLUMNS = LevelConstants::CHUNK_WIDTH * LevelConstants::CHUNK_DEPTH; -int LevelConstants::CHUNK_BLOCK_COUNT = LevelConstants::CHUNK_COLUMNS * LevelConstants::LEVEL_HEIGHT; \ No newline at end of file +int LevelConstants::CHUNK_BLOCK_COUNT = LevelConstants::CHUNK_COLUMNS * LevelConstants::LEVEL_HEIGHT; diff --git a/src/world/level/LevelConstants.h b/src/world/level/LevelConstants.h index ed77861..a0d62b9 100755 --- a/src/world/level/LevelConstants.h +++ b/src/world/level/LevelConstants.h @@ -1,14 +1,22 @@ -#pragma once - -class LevelConstants { -public: - static int CHUNK_CACHE_WIDTH; // in chunks - static int LEVEL_WIDTH; - static int LEVEL_DEPTH; - static int LEVEL_HEIGHT; - - static int CHUNK_WIDTH; // in blocks - static int CHUNK_DEPTH; - static int CHUNK_COLUMNS; - static int CHUNK_BLOCK_COUNT; -}; \ No newline at end of file +#pragma once + +class LevelConstants { +public: + static int CHUNK_CACHE_WIDTH; // legacy: only used by the network protocol + static int LEVEL_WIDTH; // blocks, outer bound of the (infinite) world + static int LEVEL_DEPTH; + static int LEVEL_HEIGHT; + + // Number of chunks around each player that the server keeps loaded. + static int VIEW_DISTANCE_CHUNKS; + + static int CHUNK_WIDTH; // in blocks + static int CHUNK_DEPTH; + static int CHUNK_COLUMNS; + static int CHUNK_BLOCK_COUNT; + + // Chunk coordinates are packed into one 64 bit key. + static long long chunkKey(int x, int z) { + return ((long long)x << 32) | (unsigned int)z; + } +}; diff --git a/src/world/level/MobSpawner.cpp b/src/world/level/MobSpawner.cpp index 5e5dc90..9381562 100755 --- a/src/world/level/MobSpawner.cpp +++ b/src/world/level/MobSpawner.cpp @@ -38,12 +38,20 @@ int MobSpawner::tick(Level* level, bool spawnEnemies, bool spawnFriendlies) { // (The code above is the same as in the java version) // This code goes over the whole map one "row" at a time - // Spawn friendlies == loop over whole map, and disable Monster spawning this tick + // Spawn friendlies == loop over the chunks around every player, and disable Monster spawning this tick if (spawnFriendlies) { spawnEnemies = false; - for (int i = 0; i < 256; ++i) - chunksToPoll.insert( std::make_pair( ChunkPos(i>>4, i&15), false) ); - + const int r = 8; + for (unsigned int pi = 0; pi < level->players.size(); ++pi) { + Player* p = level->players[pi]; + int xx = Mth::floor(p->x / 16); + int zz = Mth::floor(p->z / 16); + for (int x = -r; x <= r; x++) + for (int z = -r; z <= r; z++) { + if (level->hasChunk(xx + x, zz + z)) + chunksToPoll.insert(std::make_pair(ChunkPos(xx + x, zz + z), false)); + } + } } else { // Only spawn mobs, check around one player per tick (@todo: optimize the "count instances of"?) static unsigned int _pid = 0; @@ -57,7 +65,7 @@ int MobSpawner::tick(Level* level, bool spawnEnemies, bool spawnFriendlies) { for (int z = -r; z <= r; z++) { const int cx = xx + x; const int cz = zz + z; - if (cx >= 0 && cx < 16 && cz >= 0 && cz < 16) + if (level->hasChunk(cx, cz)) chunksToPoll.insert(std::make_pair(ChunkPos(cx, cz), false )); } } diff --git a/src/world/level/chunk/ChunkCache.cpp b/src/world/level/chunk/ChunkCache.cpp new file mode 100644 index 0000000..dbfada9 --- /dev/null +++ b/src/world/level/chunk/ChunkCache.cpp @@ -0,0 +1,380 @@ +#include "ChunkCache.h" + +#include +#include +#include + +#include "../tile/entity/TileEntity.h" +#include "../../entity/EntityFactory.h" +#include "../../entity/player/Player.h" +#include "../../../nbt/CompoundTag.h" +#include "../../../nbt/ListTag.h" +#include "../../../platform/log.h" +#include "../../../platform/time.h" +#include "../../../util/Mth.h" + +ChunkCache::ChunkCache(Level* level_, ChunkStorage* storage_, ChunkSource* source_) +: loadBudgetMs(10), + manualStreaming(false), + xLast(-999999999), + zLast(-999999999), + source(source_), + storage(storage_), + level(level_), + last(NULL), + tickCount(0), + spiralRadius(-1), + playerRoundRobin(0) +{ + isChunkCache = true; + emptyChunk = new EmptyLevelChunk(level_, NULL, 0, 0); + LOGI("Chunk cache created (infinite world).\n"); +} + +ChunkCache::~ChunkCache() +{ + delete source; + delete emptyChunk; + + for (ChunkMap::iterator it = chunks.begin(); it != chunks.end(); ++it) { + it->second->deleteBlockData(); + delete it->second; + } + chunks.clear(); +} + +bool ChunkCache::hasChunk(int x, int z) +{ + if (x == xLast && z == zLast && last != NULL) + return true; + return chunks.find(LevelConstants::chunkKey(x, z)) != chunks.end(); +} + +LevelChunk* ChunkCache::create(int x, int z) +{ + return getChunk(x, z); +} + +LevelChunk* ChunkCache::getChunk(int x, int z) +{ + if (x == xLast && z == zLast && last != NULL) { + return last; + } + + const long long key = LevelConstants::chunkKey(x, z); + ChunkMap::iterator found = chunks.find(key); + if (found != chunks.end()) { + xLast = x; + zLast = z; + last = found->second; + return last; + } + + bool fromSave = false; + LevelChunk* newChunk = load(x, z); + if (newChunk != NULL) { + fromSave = true; + } else if (source == NULL) { + // nothing can create this chunk + return emptyChunk; + } else { + newChunk = source->getChunk(x, z); + } + + chunks[key] = newChunk; + xLast = x; + zLast = z; + last = newChunk; + + newChunk->lightLava(); + + if (fromSave) { + for (int cx = 0; cx < 16; cx++) + { + for (int cz = 0; cz < 16; cz++) + { + int height = level->getHeightmap(cx + x * 16, cz + z * 16); + for (int cy = height; cy >= 0; cy--) + { + level->updateLight(LightLayer::Sky, cx + x * 16, cy, cz + z * 16, cx + x * 16, cy, cz + z * 16); + level->updateLight(LightLayer::Block, cx + x * 16 - 1, cy, cz + z * 16 - 1, cx + x * 16 + 1, cy, cz + z * 16 + 1); + } + } + } + } + + newChunk->load(); + restoreEntities(newChunk); + + if (!newChunk->terrainPopulated && hasChunk(x + 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x + 1, z)) postProcess(this, x, z); + if (hasChunk(x - 1, z) && !getChunk(x - 1, z)->terrainPopulated && hasChunk(x - 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x - 1, z)) postProcess(this, x - 1, z); + if (hasChunk(x, z - 1) && !getChunk(x, z - 1)->terrainPopulated && hasChunk(x + 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x + 1, z)) postProcess(this, x, z - 1); + if (hasChunk(x - 1, z - 1) && !getChunk(x - 1, z - 1)->terrainPopulated && hasChunk(x - 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x - 1, z)) postProcess(this, x - 1, z - 1); + + xLast = x; + zLast = z; + last = newChunk; + + // let the renderers know that there is something to draw here now + level->setTilesDirty(x * 16 - 1, 0, z * 16 - 1, x * 16 + 16, LevelConstants::LEVEL_HEIGHT - 1, z * 16 + 16); + return newChunk; +} + +void ChunkCache::postProcess(ChunkSource* parent, int x, int z) +{ + LevelChunk* chunk = getChunk(x, z); + if (!chunk->terrainPopulated) { + chunk->terrainPopulated = true; + if (source != NULL) { + source->postProcess(parent, x, z); + chunk->clearUpdateMap(); + // the decorations belong to the generated state, make sure they are written out + chunk->unsaved = true; + } + } +} + +LevelChunk* ChunkCache::load(int x, int z) +{ + if (storage == NULL || level->isClientSide) return NULL; + + LevelChunk* levelChunk = storage->load(level, x, z); + if (levelChunk != NULL) { + levelChunk->lastSaveTime = level->getTime(); + } + return levelChunk; +} + +void ChunkCache::save(LevelChunk* levelChunk) +{ + if (storage == NULL || levelChunk->dontSave) return; + + levelChunk->lastSaveTime = level->getTime(); + storage->save(level, levelChunk); + levelChunk->unsaved = false; +} + +bool ChunkCache::hasLiveData(LevelChunk* levelChunk) +{ + return levelChunk->countEntities() > 0 || !levelChunk->getTileEntityMap().empty(); +} + +// Spawns the entities and tile entities that were stored together with a chunk +void ChunkCache::restoreEntities(LevelChunk* levelChunk) +{ + CompoundTag* tag = levelChunk->pendingData; + if (!tag) return; + levelChunk->pendingData = NULL; + + if (!level->isClientSide) { + if (tag->contains("TileEntities", Tag::TAG_List)) { + ListTag* tileEntityTags = tag->getList("TileEntities"); + for (int i = 0; i < tileEntityTags->size(); ++i) { + Tag* _et = tileEntityTags->get(i); + if (!_et || _et->getId() != Tag::TAG_Compound) continue; + + if (TileEntity* te = TileEntity::loadStatic((CompoundTag*)_et)) { + if (!levelChunk->hasTileEntityAt(te)) { + levelChunk->addTileEntity(te); + } else { + delete te; + } + } + } + } + if (tag->contains("Entities", Tag::TAG_List)) { + ListTag* entityTags = tag->getList("Entities"); + for (int i = 0; i < entityTags->size(); ++i) { + Tag* _et = entityTags->get(i); + if (!_et || _et->getId() != Tag::TAG_Compound) continue; + + if (Entity* e = EntityFactory::loadEntity((CompoundTag*)_et, level)) { + level->addEntity(e); + } + } + } + } + + tag->deleteChildren(); + delete tag; +} + +void ChunkCache::unloadChunk(int x, int z) +{ + ChunkMap::iterator it = chunks.find(LevelConstants::chunkKey(x, z)); + if (it == chunks.end()) return; + + LevelChunk* chunk = it->second; + + if (!level->isClientSide) { + // Write the chunk (and everything living in it) out first + save(chunk); + + // The entities leave the world together with their chunk; they come back when it is loaded again + std::vector es; + chunk->collectEntities(es); + for (unsigned int i = 0; i < es.size(); ++i) { + Entity* e = es[i]; + if (e->isPlayer()) continue; + e->inChunk = false; + level->removeEntity(e); + } + } + chunk->detachEntities(); + + chunks.erase(it); + if (last == chunk) { + last = NULL; + xLast = zLast = -999999999; + } + + // Tile entities are owned by the level + LevelChunk::TEMap& teMap = chunk->getTileEntityMapMutable(); + for (LevelChunk::TEMap::iterator te = teMap.begin(); te != teMap.end(); ++te) { + TileEntity* t = te->second; + if (!t) continue; + Util::remove(level->pendingTileEntities, t); + Util::remove(level->tileEntities, t); + delete t; + } + teMap.clear(); + + chunk->unload(); + if (source) source->releaseChunk(x, z); + chunk->deleteBlockData(); + delete chunk; +} + +void ChunkCache::getLoadedChunks(std::vector& out) +{ + out.reserve(out.size() + chunks.size()); + for (ChunkMap::iterator it = chunks.begin(); it != chunks.end(); ++it) + out.push_back(it->second); +} + +bool ChunkCache::tick() +{ + tickCount++; + if (storage != NULL) storage->tick(); + + if (!level->isClientSide && !manualStreaming) { + streamAroundPlayers(); + if ((tickCount % 10) == 0) unloadFarChunks(); + autosave(); + } + return source != NULL ? source->tick() : false; +} + +void ChunkCache::streamAroundPlayers() +{ + const PlayerList& players = level->players; + if (players.empty()) return; + + const int radius = LevelConstants::VIEW_DISTANCE_CHUNKS; + if (radius != spiralRadius) { + spiralRadius = radius; + spiral.clear(); + for (int dx = -radius; dx <= radius; ++dx) + for (int dz = -radius; dz <= radius; ++dz) + if (dx * dx + dz * dz <= radius * radius + radius) + spiral.push_back(std::make_pair(dx, dz)); + struct ByDistance { + bool operator()(const std::pair& a, const std::pair& b) const { + return a.first * a.first + a.second * a.second < b.first * b.first + b.second * b.second; + } + }; + std::stable_sort(spiral.begin(), spiral.end(), ByDistance()); + } + + std::vector > centers; + for (unsigned int i = 0; i < players.size(); ++i) { + Player* p = players[i]; + if (p->removed) continue; + centers.push_back(std::make_pair(Mth::floor(p->x / 16.0f), Mth::floor(p->z / 16.0f))); + } + if (centers.empty()) return; + + const int start = getTimeMs(); + for (unsigned int i = 0; i < spiral.size(); ++i) { + for (unsigned int c = 0; c < centers.size(); ++c) { + const int cx = centers[c].first + spiral[i].first; + const int cz = centers[c].second + spiral[i].second; + if (!hasChunk(cx, cz)) { + getChunk(cx, cz); + if (getTimeMs() - start >= loadBudgetMs) return; + } + } + } +} + +void ChunkCache::unloadFarChunks() +{ + const PlayerList& players = level->players; + if (players.empty()) return; + + std::vector > centers; + for (unsigned int i = 0; i < players.size(); ++i) { + Player* p = players[i]; + centers.push_back(std::make_pair(Mth::floor(p->x / 16.0f), Mth::floor(p->z / 16.0f))); + } + + const int unloadRadius = LevelConstants::VIEW_DISTANCE_CHUNKS + 3; + std::vector > victims; + for (ChunkMap::iterator it = chunks.begin(); it != chunks.end() && victims.size() < 6; ++it) { + LevelChunk* c = it->second; + bool isNear = false; + for (unsigned int i = 0; i < centers.size(); ++i) { + if (std::abs(c->x - centers[i].first) <= unloadRadius && std::abs(c->z - centers[i].second) <= unloadRadius) { + isNear = true; + break; + } + } + if (!isNear) victims.push_back(std::make_pair(c->x, c->z)); + } + for (unsigned int i = 0; i < victims.size(); ++i) + unloadChunk(victims[i].first, victims[i].second); +} + +void ChunkCache::autosave() +{ + if (storage == NULL) return; + + if ((tickCount % 1200) == 0) { + autosaveQueue.clear(); + for (ChunkMap::iterator it = chunks.begin(); it != chunks.end(); ++it) { + LevelChunk* c = it->second; + if (c->shouldSave(false) || hasLiveData(c)) + autosaveQueue.push_back(it->first); + } + } + + for (int n = 0; n < 3 && !autosaveQueue.empty(); ++n) { + long long key = autosaveQueue.front(); + autosaveQueue.pop_front(); + ChunkMap::iterator it = chunks.find(key); + if (it != chunks.end()) save(it->second); + } +} + +void ChunkCache::saveAll(bool onlyUnsaved) +{ + if (storage == NULL) return; + + std::vector toSave; + for (ChunkMap::iterator it = chunks.begin(); it != chunks.end(); ++it) { + LevelChunk* c = it->second; + if (c->dontSave) continue; + if (!onlyUnsaved || c->shouldSave(false) || hasLiveData(c)) + toSave.push_back(c); + } + storage->saveAll(level, toSave); + for (unsigned int i = 0; i < toSave.size(); ++i) + toSave[i]->unsaved = false; +} + +std::string ChunkCache::gatherStats() +{ + std::stringstream ss; + ss << "ChunkCache: " << chunks.size(); + return ss.str(); +} diff --git a/src/world/level/chunk/ChunkCache.h b/src/world/level/chunk/ChunkCache.h index fbb2d77..0462d00 100755 --- a/src/world/level/chunk/ChunkCache.h +++ b/src/world/level/chunk/ChunkCache.h @@ -1,270 +1,87 @@ -#ifndef NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__ -#define NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__ - -//package net.minecraft.world.level.chunk; - -#include "ChunkSource.h" -#include "storage/ChunkStorage.h" -#include "EmptyLevelChunk.h" -#include "../Level.h" -#include "../LevelConstants.h" - -class ChunkCache: public ChunkSource { - //static const int LevelConstants::CHUNK_CACHE_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH; // WAS 32; - static const int MAX_SAVES = 2; -public: - ChunkCache(Level* level_, ChunkStorage* storage_, ChunkSource* source_) - : xLast(-999999999), - zLast(-999999999), - last(NULL), - level(level_), - storage(storage_), - source(source_) - { - isChunkCache = true; - //emptyChunk = new EmptyLevelChunk(level_, emptyChunkBlocks, 0, 0); - emptyChunk = new EmptyLevelChunk(level_, NULL, 0, 0); - - chunks = new LevelChunk *[LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH]; - memset(chunks, 0, sizeof(LevelChunk*) * LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH); - LOGI("Chunks allocated."); - } - - ~ChunkCache() { - delete source; - delete emptyChunk; - - for (int i = 0; i < LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH; i++) - { - if (chunks[i]) - { - chunks[i]->deleteBlockData(); - delete chunks[i]; - } - } - } - - bool fits(int x, int z) { - return (x >= 0 && z >= 0 && x < LevelConstants::CHUNK_CACHE_WIDTH && z < LevelConstants::CHUNK_CACHE_WIDTH); - } - - bool hasChunk(int x, int z) { - // with a fixed world size, chunks outside the fitting area are always available (emptyChunks) - if (!fits(x, z)) return true; - - if (x == xLast && z == zLast && last != NULL) { - return true; - } - int xs = x & (LevelConstants::CHUNK_CACHE_WIDTH - 1); - int zs = z & (LevelConstants::CHUNK_CACHE_WIDTH - 1); - int slot = xs + zs * LevelConstants::CHUNK_CACHE_WIDTH; - return chunks[slot] != NULL && (chunks[slot] == emptyChunk || chunks[slot]->isAt(x, z)); - } - - LevelChunk* create(int x, int z) { - return getChunk(x, z); - } - - LevelChunk* getChunk(int x, int z) { - //static Stopwatch sw; - //sw.start(); - - if (x == xLast && z == zLast && last != NULL) { - return last; - } - if (!fits(x, z)) return emptyChunk; - //if (!level->isFindingSpawn && !fits(x, z)) return emptyChunk; - int xs = x & (LevelConstants::CHUNK_CACHE_WIDTH - 1); - int zs = z & (LevelConstants::CHUNK_CACHE_WIDTH - 1); - int slot = xs + zs * LevelConstants::CHUNK_CACHE_WIDTH; - if (!hasChunk(x, z)) { - if (chunks[slot] != NULL) { - chunks[slot]->unload(); - save(chunks[slot]); - saveEntities(chunks[slot]); - } - - LevelChunk* newChunk = load(x, z); - bool updateLights = false; - if (newChunk == NULL) { - if (source == NULL) { - newChunk = emptyChunk; - } else { - newChunk = source->getChunk(x, z); - } - } else { - //return emptyChunk; - updateLights = true; - } - chunks[slot] = newChunk; - newChunk->lightLava(); - - if (updateLights) - { - for (int cx = 0; cx < 16; cx++) - { - for (int cz = 0; cz < 16; cz++) - { - int height = level->getHeightmap(cx + x * 16, cz + z * 16); - for (int cy = height; cy >= 0; cy--) - { - level->updateLight(LightLayer::Sky, cx + x * 16, cy, cz + z * 16, cx + x * 16, cy, cz + z * 16); - level->updateLight(LightLayer::Block, cx + x * 16 - 1, cy, cz + z * 16 - 1, cx + x * 16 + 1, cy, cz + z * 16 + 1); - } - } - } - //level->updateLight(LightLayer::Sky, x * 16, 0, z * 16, x * 16 + 15, 128, z * 16 + 15); - //level->updateLight(LightLayer::Block, x * 16, 0, z * 16, x * 16 + 15, 128, z * 16 + 15); - } - - if (chunks[slot] != NULL) { - chunks[slot]->load(); - } - - if (!chunks[slot]->terrainPopulated && hasChunk(x + 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x + 1, z)) postProcess(this, x, z); - if (hasChunk(x - 1, z) && !getChunk(x - 1, z)->terrainPopulated && hasChunk(x - 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x - 1, z)) postProcess(this, x - 1, z); - if (hasChunk(x, z - 1) && !getChunk(x, z - 1)->terrainPopulated && hasChunk(x + 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x + 1, z)) postProcess(this, x, z - 1); - if (hasChunk(x - 1, z - 1) && !getChunk(x - 1, z - 1)->terrainPopulated && hasChunk(x - 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x - 1, z)) postProcess(this, x - 1, z - 1); - } - xLast = x; - zLast = z; - last = chunks[slot]; - - //sw.stop(); - //sw.printEvery(500000, "ChunkCache::load: "); - - return chunks[slot]; - } - - Biome::MobList getMobsAt(const MobCategory& mobCategory, int x, int y, int z) { - return source->getMobsAt(mobCategory, x, y, z); - } - - void postProcess(ChunkSource* parent, int x, int z) { - if (!fits(x, z)) return; - LevelChunk* chunk = getChunk(x, z); - if (!chunk->terrainPopulated) { - chunk->terrainPopulated = true; - if (source != NULL) { - source->postProcess(parent, x, z); - chunk->clearUpdateMap(); - } - } - } - - //bool save(bool force, ProgressListener progressListener) { - // int saves = 0; - // int count = 0; - // if (progressListener != NULL) { - // for (int i = 0; i < chunks.length; i++) { - // if (chunks[i] != NULL && chunks[i].shouldSave(force)) { - // count++; - // } - // } - // } - // int cc = 0; - // for (int i = 0; i < chunks.length; i++) { - // if (chunks[i] != NULL) { - // if (force && !chunks[i].dontSave) saveEntities(chunks[i]); - // if (chunks[i].shouldSave(force)) { - // save(chunks[i]); - // chunks[i].unsaved = false; - // if (++saves == MAX_SAVES && !force) return false; - // if (progressListener != NULL) { - // if (++cc % 10 == 0) { - // progressListener.progressStagePercentage(cc * 100 / count); - // } - // } - // } - // } - // } - - // if (force) { - // if (storage == NULL) return true; - // storage.flush(); - // } - // return true; - //} - - bool tick() { - if (storage != NULL) storage->tick(); - return source->tick(); - } - - bool shouldSave() { - return true; - } - - std::string gatherStats() { - // return "ChunkCache: 1024"; - std::stringstream ss; - ss << "ChunkCache: " << LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH; - return ss.str(); - } - - void saveAll(bool onlyUnsaved) { - if (storage != NULL) { - std::vector chunks; - for (int z = 0; z < LevelConstants::CHUNK_CACHE_WIDTH; ++z) - for (int x = 0; x < LevelConstants::CHUNK_CACHE_WIDTH; ++x) { - LevelChunk* chunk = level->getChunk(x, z); - if (!onlyUnsaved || chunk->shouldSave(false)) - chunks.push_back( chunk ); - } - storage->saveAll(level, chunks); - } - } -private: - LevelChunk* load(int x, int z) { - if (storage == NULL) return emptyChunk; - if (x < 0 || x >= LevelConstants::CHUNK_CACHE_WIDTH || z < 0 || z >= LevelConstants::CHUNK_CACHE_WIDTH) - { - return emptyChunk; - } - //try { - LevelChunk* levelChunk = storage->load(level, x, z); - if (levelChunk != NULL) { - levelChunk->lastSaveTime = level->getTime(); - } - return levelChunk; - //} catch (Exception e) { - // e.printStackTrace(); - // return emptyChunk; - //} - } - - void saveEntities(LevelChunk* levelChunk) { - if (storage == NULL) return; - //try { - storage->saveEntities(level, levelChunk); - //} catch (Error e) { - // e.printStackTrace(); - //} - } - - void save(LevelChunk* levelChunk) { - if (storage == NULL) return; - //try { - levelChunk->lastSaveTime = level->getTime(); - storage->save(level, levelChunk); - //} catch (IOException e) { - // e.printStackTrace(); - //} - } - -public: - int xLast; - int zLast; -private: - //unsigned char emptyChunkBlocks[LevelChunk::ChunkBlockCount]; - LevelChunk* emptyChunk; - ChunkSource* source; - ChunkStorage* storage; - LevelChunk** chunks; - Level* level; - - LevelChunk* last; - -}; - -#endif /*NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__*/ +#ifndef NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__ +#define NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__ + +//package net.minecraft.world.level.chunk; + +#include +#include +#include + +#include "ChunkSource.h" +#include "storage/ChunkStorage.h" +#include "EmptyLevelChunk.h" +#include "../Level.h" +#include "../LevelConstants.h" + +/** + * Holds every chunk of the (infinite) world that is currently in memory. + * + * On a server / in single player the cache streams chunks in around each + * player, saves and unloads the ones that are left behind, and persists the + * entities and tile entities that live in them. On a multiplayer client the + * chunks are driven by the network handler instead (see unloadChunk). + */ +class ChunkCache: public ChunkSource { +public: + ChunkCache(Level* level_, ChunkStorage* storage_, ChunkSource* source_); + ~ChunkCache(); + + bool hasChunk(int x, int z); + LevelChunk* create(int x, int z); + LevelChunk* getChunk(int x, int z); + + Biome::MobList getMobsAt(const MobCategory& mobCategory, int x, int y, int z) { + return source->getMobsAt(mobCategory, x, y, z); + } + + void postProcess(ChunkSource* parent, int x, int z); + + bool tick(); + bool shouldSave() { return true; } + std::string gatherStats(); + + void saveAll(bool onlyUnsaved); + void unloadChunk(int x, int z); + void getLoadedChunks(std::vector& out); + int getLoadedChunkCount() { return (int)chunks.size(); } + + // Chunks around the players that were not generated/loaded yet are + // created nearest first, at most for this many milliseconds per tick. + int loadBudgetMs; + + // Disables the automatic loading/unloading around the players. + bool manualStreaming; + +public: + int xLast; + int zLast; + +private: + LevelChunk* load(int x, int z); + void save(LevelChunk* levelChunk); + void restoreEntities(LevelChunk* levelChunk); + bool hasLiveData(LevelChunk* levelChunk); + + void streamAroundPlayers(); + void unloadFarChunks(); + void autosave(); + + typedef std::unordered_map ChunkMap; + ChunkMap chunks; + + LevelChunk* emptyChunk; + ChunkSource* source; + ChunkStorage* storage; + Level* level; + + LevelChunk* last; + + int tickCount; + int unloadRadiusCache; + std::vector > spiral; // chunk offsets sorted by distance + int spiralRadius; + unsigned int playerRoundRobin; + std::deque autosaveQueue; +}; + +#endif /*NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__*/ diff --git a/src/world/level/chunk/ChunkSource.h b/src/world/level/chunk/ChunkSource.h index c1e029f..0cf1b75 100755 --- a/src/world/level/chunk/ChunkSource.h +++ b/src/world/level/chunk/ChunkSource.h @@ -1,46 +1,56 @@ -#ifndef NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__ -#define NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__ - -//package net.minecraft.world.level.chunk; - -#include -#include "../biome/Biome.h" - -class ProgressListener; -class LevelChunk; - -class ChunkSource -{ -public: - bool isChunkCache; - - ChunkSource() - : isChunkCache(false) - {} - - virtual ~ChunkSource(){} - - virtual bool hasChunk(int x, int y) = 0; - - virtual LevelChunk* getChunk(int x, int z) = 0; - - virtual LevelChunk* create(int x, int z) = 0; - - virtual void postProcess(ChunkSource* parent, int x, int z) = 0; - - //virtual bool save(bool force, ProgressListener* progressListener) = 0; - - virtual bool tick() = 0; - - virtual bool shouldSave() = 0; - virtual void saveAll(bool onlyUnsaved) {} - - virtual Biome::MobList getMobsAt(const MobCategory& mobCategory, int x, int y, int z) = 0; - - /** - * Returns some stats that are rendered when the user holds F3. - */ - virtual std::string gatherStats() = 0; -}; - -#endif /*NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__*/ +#ifndef NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__ +#define NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__ + +//package net.minecraft.world.level.chunk; + +#include +#include +#include "../biome/Biome.h" + +class ProgressListener; +class LevelChunk; + +class ChunkSource +{ +public: + bool isChunkCache; + + ChunkSource() + : isChunkCache(false) + {} + + virtual ~ChunkSource(){} + + virtual bool hasChunk(int x, int y) = 0; + + virtual LevelChunk* getChunk(int x, int z) = 0; + + // Called when the owner of the chunk has unloaded (and freed) it, so a + // generator that keeps its own lookup table must forget about it. + virtual void releaseChunk(int x, int z) {} + + // Saves (server) and frees a chunk. Only chunk caches keep chunks. + virtual void unloadChunk(int x, int z) {} + virtual void getLoadedChunks(std::vector& out) {} + virtual int getLoadedChunkCount() { return 0; } + + virtual LevelChunk* create(int x, int z) = 0; + + virtual void postProcess(ChunkSource* parent, int x, int z) = 0; + + //virtual bool save(bool force, ProgressListener* progressListener) = 0; + + virtual bool tick() = 0; + + virtual bool shouldSave() = 0; + virtual void saveAll(bool onlyUnsaved) {} + + virtual Biome::MobList getMobsAt(const MobCategory& mobCategory, int x, int y, int z) = 0; + + /** + * Returns some stats that are rendered when the user holds F3. + */ + virtual std::string gatherStats() = 0; +}; + +#endif /*NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__*/ diff --git a/src/world/level/chunk/LevelChunk.cpp b/src/world/level/chunk/LevelChunk.cpp index fd61715..528a228 100755 --- a/src/world/level/chunk/LevelChunk.cpp +++ b/src/world/level/chunk/LevelChunk.cpp @@ -9,6 +9,7 @@ #include "../tile/entity/TileEntity.h" #include "../tile/EntityTile.h" #include "../LevelConstants.h" +#include "../../../nbt/CompoundTag.h" /*static*/ bool LevelChunk::touchedSky = false; @@ -41,7 +42,13 @@ LevelChunk::LevelChunk( Level* level, unsigned char* blocks, int x, int z ) LevelChunk::~LevelChunk() { - //delete blocks; + //delete blocks; (see deleteBlockData) + delete[] heightmap; + delete[] updateMap; + if (pendingData) { + pendingData->deleteChildren(); + delete pendingData; + } } void LevelChunk::init() @@ -49,6 +56,8 @@ void LevelChunk::init() heightmap = new char[LevelConstants::CHUNK_COLUMNS]; updateMap = new unsigned char[LevelConstants::CHUNK_COLUMNS]; + pendingData = NULL; + loaded = false; terrainPopulated = false; dontSave = false; unsaved = false; @@ -537,6 +546,23 @@ void LevelChunk::getEntitiesOfClass( int type, const AABB& bb, EntityList& list } } +void LevelChunk::collectEntities(std::vector& out) const +{ + for (int yc = 0; yc < EntityBlocksArraySize; yc++) { + out.insert(out.end(), entityBlocks[yc].begin(), entityBlocks[yc].end()); + } +} + +void LevelChunk::detachEntities() +{ + for (int yc = 0; yc < EntityBlocksArraySize; yc++) { + for (unsigned int i = 0; i < entityBlocks[yc].size(); i++) { + entityBlocks[yc][i]->inChunk = false; + } + entityBlocks[yc].clear(); + } +} + int LevelChunk::countEntities() { int entityCount = 0; diff --git a/src/world/level/chunk/LevelChunk.h b/src/world/level/chunk/LevelChunk.h index 8fe7281..65fa412 100755 --- a/src/world/level/chunk/LevelChunk.h +++ b/src/world/level/chunk/LevelChunk.h @@ -16,6 +16,7 @@ class Entity; class LightLayer; class AABB; class TileEntity; +class CompoundTag; typedef std::vector EntityList; class LevelChunk @@ -99,6 +100,12 @@ public: virtual bool isEmpty(); const TEMap& getTileEntityMap() const; + TEMap& getTileEntityMapMutable() { return tileEntities; } + + // Appends every entity registered in this chunk (players included) + void collectEntities(std::vector& out) const; + // Forgets that the entities of this chunk are listed here (the chunk is going away) + void detachEntities(); private: void lightGap(int x, int z, int source); void lightGaps(int x, int z); @@ -125,6 +132,10 @@ public: int x, z; int xt, zt; + // Entities and tile entities read from the save file, waiting to be spawned + // by the chunk cache once the chunk is registered in the level (owned). + CompoundTag* pendingData; + bool terrainPopulated; bool unsaved; bool dontSave; diff --git a/src/world/level/levelgen/RandomLevelSource.cpp b/src/world/level/levelgen/RandomLevelSource.cpp index dbaa87b..09ed7e1 100755 --- a/src/world/level/levelgen/RandomLevelSource.cpp +++ b/src/world/level/levelgen/RandomLevelSource.cpp @@ -537,9 +537,13 @@ LevelChunk* RandomLevelSource::create(int x, int z) { return getChunk(x, z); } +void RandomLevelSource::releaseChunk(int x, int z) { + chunkMap.erase(LevelConstants::chunkKey(x, z)); +} + LevelChunk* RandomLevelSource::getChunk(int xOffs, int zOffs) { //static int chunkx = 0; - int hashedPos = ChunkPos::hashCode(xOffs, zOffs); + const long long hashedPos = LevelConstants::chunkKey(xOffs, zOffs); ChunkMap::iterator it = chunkMap.find(hashedPos); if (it != chunkMap.end()) diff --git a/src/world/level/levelgen/RandomLevelSource.h b/src/world/level/levelgen/RandomLevelSource.h index e8b88e4..ebdc0a0 100755 --- a/src/world/level/levelgen/RandomLevelSource.h +++ b/src/world/level/levelgen/RandomLevelSource.h @@ -7,20 +7,9 @@ class Biome; class Level; class LevelChunk; -#if 1 || USE_MAP - #include - typedef std::map ChunkMap; -#else - #if defined(__APPLE__) - #include - namespace std { - using namespace __gnu_cxx; - } - #else - #include - #endif - typedef std::hash_map ChunkMap; -#endif +#include +// Keyed by LevelConstants::chunkKey(x, z) +typedef std::map ChunkMap; #include "../chunk/ChunkSource.h" @@ -44,6 +33,7 @@ public: bool hasChunk(int x, int y); LevelChunk* create(int x, int z); LevelChunk* getChunk(int xOffs, int zOffs); + void releaseChunk(int x, int z); void prepareHeights(int xOffs, int zOffs, unsigned char* blocks, /*Biome*/void* biomes, float* temperatures); void buildSurfaces(int xOffs, int zOffs, unsigned char* blocks, Biome** biomes); diff --git a/src/world/level/storage/ExternalFileLevelStorage.cpp b/src/world/level/storage/ExternalFileLevelStorage.cpp index 93ee9f1..d31c50c 100755 --- a/src/world/level/storage/ExternalFileLevelStorage.cpp +++ b/src/world/level/storage/ExternalFileLevelStorage.cpp @@ -8,6 +8,7 @@ #include "ExternalFileLevelStorage.h" #include "FolderMethods.h" #include "../chunk/LevelChunk.h" +#include "../chunk/ChunkSource.h" #include "../Level.h" #include "../LevelConstants.h" #include "platform/log.h" @@ -82,10 +83,7 @@ ExternalFileLevelStorage::ExternalFileLevelStorage(const std::string& levelId, c : levelId(levelId), levelPath(fullPath), loadedLevelData(NULL), - regionFile(NULL), - entitiesFile(NULL), tickCount(0), - lastSavedEntitiesTick(-999999), level(NULL), loadedStorageVersion(SharedConstants::StorageVersion) { @@ -109,10 +107,53 @@ ExternalFileLevelStorage::ExternalFileLevelStorage(const std::string& levelId, c ExternalFileLevelStorage::~ExternalFileLevelStorage() { - delete regionFile; + closeRegions(); delete loadedLevelData; } +void ExternalFileLevelStorage::closeRegions() +{ + for (std::map::iterator it = regions.begin(); it != regions.end(); ++it) + delete it->second; + regions.clear(); + regionOrder.clear(); +} + +// Region files are opened on demand; only a handful stay open at once. +RegionFile* ExternalFileLevelStorage::getRegion(int chunkX, int chunkZ) +{ + const int rx = chunkX >> 5; + const int rz = chunkZ >> 5; + const long long key = LevelConstants::chunkKey(rx, rz); + + std::map::iterator it = regions.find(key); + if (it != regions.end()) { + regionOrder.remove(key); + regionOrder.push_back(key); + return it->second; + } + + static const size_t MaxOpenRegions = 12; + while (regions.size() >= MaxOpenRegions && !regionOrder.empty()) { + long long oldest = regionOrder.front(); + regionOrder.pop_front(); + std::map::iterator ot = regions.find(oldest); + if (ot != regions.end()) { + delete ot->second; + regions.erase(ot); + } + } + + RegionFile* region = new RegionFile(levelPath, rx, rz); + if (!region->open()) { + delete region; + return NULL; + } + regions[key] = region; + regionOrder.push_back(key); + return region; +} + void ExternalFileLevelStorage::saveLevelData(LevelData& levelData, std::vector* players) { ExternalFileLevelStorage::saveLevelData(levelPath, levelData, players); } @@ -341,10 +382,6 @@ bool ExternalFileLevelStorage::readPlayerData(const std::string& filename, Level // Fix coordinates Vec3& pos = dest.playerData.pos; - if (pos.x < 0.5f) pos.x = 0.5f; - if (pos.z < 0.5f) pos.z = 0.5f; - if (pos.x > (LevelConstants::LEVEL_WIDTH - 0.5f)) pos.x = LevelConstants::LEVEL_WIDTH - 0.5f; - if (pos.z > (LevelConstants::LEVEL_DEPTH - 0.5f)) pos.z = LevelConstants::LEVEL_DEPTH - 0.5f; if (pos.y < 0) pos.y = 64; dest.playerDataVersion = version; @@ -357,61 +394,15 @@ bool ExternalFileLevelStorage::readPlayerData(const std::string& filename, Level void ExternalFileLevelStorage::tick() { + // Chunks (and the entities inside them) are saved by the chunk cache. tickCount++; - if ((tickCount % 1000) == 0 && level) { - LOGI("Saving level...\n"); - - // look for chunks that needs to be saved - for (int z = 0; z < LevelConstants::CHUNK_CACHE_WIDTH; z++) - { - for (int x = 0; x < LevelConstants::CHUNK_CACHE_WIDTH; x++) - { - LevelChunk* chunk = level->getChunk(x, z); - if (chunk && chunk->unsaved) - { - int pos = x + z * LevelConstants::CHUNK_CACHE_WIDTH; - UnsavedChunkList::iterator prev = unsavedChunkList.begin(); - for ( ; prev != unsavedChunkList.end(); ++prev) - { - if ((*prev).pos == pos) - { - // the chunk has been modified again, so update its time - (*prev).addedToList = RakNet::GetTimeMS(); - break; - } - } - if (prev == unsavedChunkList.end()) - { - UnsavedLevelChunk unsaved; - unsaved.pos = pos; - unsaved.addedToList = RakNet::GetTimeMS(); - unsaved.chunk = chunk; - unsavedChunkList.push_back(unsaved); - } - chunk->unsaved = false; // not actually saved, but in our working list at least - } - } - } - - savePendingUnsavedChunks(2); - } - if (tickCount - lastSavedEntitiesTick > (60 * SharedConstants::TicksPerSecond)) { - saveEntities(level, NULL); - } } void ExternalFileLevelStorage::save(Level* level, LevelChunk* levelChunk) { - if (!regionFile) - { - regionFile = new RegionFile(levelPath); - if (!regionFile->open()) - { - delete regionFile; - regionFile = NULL; - return; - } - } + RegionFile* region = getRegion(levelChunk->x, levelChunk->z); + if (!region) + return; // Write chunk RakNet::BitStream chunkData; @@ -423,29 +414,68 @@ void ExternalFileLevelStorage::save(Level* level, LevelChunk* levelChunk) chunkData.Write((const char*)levelChunk->updateMap, LevelConstants::CHUNK_COLUMNS); - regionFile->writeChunk(levelChunk->x, levelChunk->z, chunkData); + // Flags: bit 0 = the terrain decorations (trees, ores, ...) were placed + unsigned char flags = levelChunk->terrainPopulated ? 1 : 0; + chunkData.Write((const char*)&flags, 1); - // Write entities + // Entities and tile entities that live in this chunk + if (!level->isClientSide) { + CompoundTag base; + ListTag* entityTags = new ListTag(); + ListTag* tileEntityTags = new ListTag(); + std::vector chunkEntities; + levelChunk->collectEntities(chunkEntities); + for (unsigned int i = 0; i < chunkEntities.size(); ++i) { + Entity* e = chunkEntities[i]; + if (e->removed || e->isPlayer()) continue; + + CompoundTag* tag = new CompoundTag(); + if (e->save(tag)) + entityTags->add(tag); + else + delete tag; + } + + const LevelChunk::TEMap& teMap = levelChunk->getTileEntityMap(); + for (LevelChunk::TEMapCIterator it = teMap.begin(); it != teMap.end(); ++it) { + TileEntity* te = it->second; + if (!te || te->isRemoved() || !te->shouldSave()) continue; + + CompoundTag* tag = new CompoundTag(); + if (te->save(tag)) + tileEntityTags->add(tag); + else + delete tag; + } + + const bool hasData = entityTags->size() > 0 || tileEntityTags->size() > 0; + base.put("Entities", entityTags); + base.put("TileEntities", tileEntityTags); + + if (hasData) { + RakNet::BitStream stream; + RakDataOutput dos(stream); + NbtIo::write(&base, &dos); + int numBytes = (int)stream.GetNumberOfBytesUsed(); + chunkData.Write(numBytes); + chunkData.Write((const char*)stream.GetData(), numBytes); + } + base.deleteChildren(); + } + + region->writeChunk(levelChunk->x & 31, levelChunk->z & 31, chunkData); //LOGI("Saved chunk (%d, %d)\n", levelChunk->x, levelChunk->z); - } LevelChunk* ExternalFileLevelStorage::load(Level* level, int x, int z) { - if (!regionFile) - { - regionFile = new RegionFile(levelPath); - if (!regionFile->open()) - { - delete regionFile; - regionFile = NULL; - return NULL; - } - } + RegionFile* region = getRegion(x, z); + if (!region) + return NULL; RakNet::BitStream* chunkData = NULL; - if (!regionFile->readChunk(x, z, &chunkData)) + if (!region->readChunk(x & 31, z & 31, &chunkData)) { //LOGI("Failed to read data for %d, %d\n", x, z); return NULL; @@ -463,47 +493,37 @@ LevelChunk* ExternalFileLevelStorage::load(Level* level, int x, int z) chunkData->Read((char*)levelChunk->blockLight.data, LevelConstants::CHUNK_BLOCK_COUNT / 2); } chunkData->Read((char*)levelChunk->updateMap, LevelConstants::CHUNK_COLUMNS); - // This will be difficult to maintain.. Storage version could be per chunk - // too (but probably better to just read all -> write all, so that all - // chunks got same version anyway) - //if (loadedStorageVersion >= ChunkVersion_Entity) { - // int dictSize; - // chunkData->Read(dictSize); - // RakDataInput dis(*chunkData); - // Tag* tmp = Tag::readNamedTag(&dis); - // if (tmp && tmp->getId() == Tag::TAG_Compound) { - // CompoundTag* tag = (CompoundTag*) tmp; + // Chunks written by older versions end here and were always fully decorated + bool populated = true; + if (chunkData->GetNumberOfUnreadBits() >= 8) { + unsigned char flags = 0; + chunkData->Read((char*)&flags, 1); + populated = (flags & 1) != 0; + } - // delete tmp; - // } - //} + // Optional trailer: the entities and tile entities of the chunk + if (!level->isClientSide && chunkData->GetNumberOfUnreadBits() >= 32) { + int numBytes = 0; + chunkData->Read(numBytes); + if (numBytes > 0 && numBytes <= (int)(chunkData->GetNumberOfUnreadBits() >> 3)) { + unsigned char* buf = new unsigned char[numBytes]; + chunkData->Read((char*)buf, numBytes); + + RakNet::BitStream stream(buf, numBytes, false); + RakDataInput dis(stream); + levelChunk->pendingData = NbtIo::read(&dis); + + delete[] buf; + } + } delete [] chunkData->GetData(); delete chunkData; - //bool dbg = (x == 7 && z == 9); - - //int t = 0; - //for (int i = 0; i < LevelConstants::CHUNK_COLUMNS; ++i) { - // char bits = levelChunk->updateMap[i]; - // t += (bits != 0); - // int xx = x * 16 + i%16; - // int zz = z * 16 + i/16; - // if (dbg && xx == 125 && zz == 152) { - // LOGI("xz: %d, %d: %d\n", xx, zz, bits); - // for (int j = 0; j < 8; ++j) { - // if (bits & (1 << j)) { - // LOGI("%d - %d\n", j << 4, ((j+1) << 4) - 1); - // } - // } - // } - //} - // // Convert LevelChunks here if necessary // - //LOGI("level version: %d: upd: %d - (%d, %d)\n", loadedStorageVersion, t, x, z); bool changed = false; // Loaded level has old Cloth types (one Tile* per color) @@ -511,104 +531,39 @@ LevelChunk* ExternalFileLevelStorage::load(Level* level, int x, int z) changed |= LevelConverters::v1_ClothIdToClothData(levelChunk); // Loaded level is newer than our level - replace all unavailable block types - //if (loadedStorageVersion > SharedConstants::StorageVersion) - changed |= LevelConverters::ReplaceUnavailableBlocks(levelChunk); + changed |= LevelConverters::ReplaceUnavailableBlocks(levelChunk); levelChunk->recalcHeightmap(); levelChunk->unsaved = changed; - levelChunk->terrainPopulated = true; + levelChunk->terrainPopulated = populated; levelChunk->createdFromSave = true; return levelChunk; } -void ExternalFileLevelStorage::saveEntities( Level* level, LevelChunk* levelChunk ) -{ - lastSavedEntitiesTick = tickCount; - int count = 0; - float st = getTimeS(); - - // Version 1: Save ALL Entities for all chunks in one structure - EntityList& entities = level->entities; - - ListTag* entityTags = new ListTag(); - for (unsigned int i = 0; i < entities.size(); ++i) { - Entity* e = entities[i]; - - CompoundTag* tag = new CompoundTag(); - if (e->save(tag)) { - count++; - entityTags->add(tag); - } else - delete tag; - } - - // Version 1: Save ALL TileEntities for all chunks in one structure - TileEntityList& tileEntities = level->tileEntities; - //TileEntityList keep, dontKeep; - //partitionTileEntities - - ListTag* tileEntityTags = new ListTag(); - for (unsigned int i = 0; i < tileEntities.size(); ++i) { - TileEntity* e = tileEntities[i]; - if (!e->shouldSave()) continue; - - CompoundTag* tag = new CompoundTag(); - if (e->save(tag)) { - count++; - tileEntityTags->add(tag); - } else - delete tag; - } - - CompoundTag base; - base.put("Entities", entityTags); - base.put("TileEntities", tileEntityTags); - - RakNet::BitStream stream; - RakDataOutput dos(stream); - NbtIo::write(&base, &dos); - int numBytes = stream.GetNumberOfBytesUsed(); - - FILE* fp = fopen((levelPath + "/entities.dat").c_str(), "wb"); - if (fp) { - int version = 1; - fwrite("ENT\0", 1, 4, fp); - fwrite(&version, sizeof(int), 1, fp); - fwrite(&numBytes, sizeof(int), 1, fp); - fwrite(stream.GetData(), 1, numBytes, fp); - fclose(fp); - } - - base.deleteChildren(); - - float tt = getTimeS() - st; - LOGI("Time to save %d entities: %f s. Size: %d bytes\n", count, tt, numBytes); -} - +// Imports the global entities.dat that older versions of the game wrote. void ExternalFileLevelStorage::loadEntities(Level* level, LevelChunk* chunk) { - lastSavedEntitiesTick = tickCount; - FILE* fp = fopen((levelPath + "/entities.dat").c_str(), "rb"); - if (fp) { - char header[5]; - int version, numBytes; - fread(header, 1, 4, fp); - fread(&version, sizeof(int), 1, fp); - fread(&numBytes, sizeof(int), 1, fp); + const std::string path = levelPath + "/entities.dat"; + FILE* fp = fopen(path.c_str(), "rb"); + if (!fp) return; - int left = getRemainingFileSize(fp); - if (numBytes <= left && numBytes > 0) { - unsigned char* buf = new unsigned char[numBytes]; + char header[5] = {0}; + int version = 0, numBytes = 0; + fread(header, 1, 4, fp); + fread(&version, sizeof(int), 1, fp); + fread(&numBytes, sizeof(int), 1, fp); - fread(buf, 1, numBytes, fp); + int left = getRemainingFileSize(fp); + if (numBytes <= left && numBytes > 0) { + unsigned char* buf = new unsigned char[numBytes]; - RakNet::BitStream stream(buf, numBytes, false); - RakDataInput dis(stream); + fread(buf, 1, numBytes, fp); - CompoundTag* tag = NbtIo::read(&dis); - // - // Read Entity:es - // + RakNet::BitStream stream(buf, numBytes, false); + RakDataInput dis(stream); + + CompoundTag* tag = NbtIo::read(&dis); + if (tag) { if (tag->contains("Entities", Tag::TAG_List)) { ListTag* entityTags = tag->getList("Entities"); for (int i = 0; i < entityTags->size(); ++i) { @@ -623,9 +578,6 @@ void ExternalFileLevelStorage::loadEntities(Level* level, LevelChunk* chunk) { } } } - // - // Read TileEntity:s - // if (tag->contains("TileEntities", Tag::TAG_List)) { ListTag* tileEntityTags = tag->getList("TileEntities"); for (int i = 0; i < tileEntityTags->size(); ++i) { @@ -636,67 +588,35 @@ void ExternalFileLevelStorage::loadEntities(Level* level, LevelChunk* chunk) { } CompoundTag* et = (CompoundTag*)_et; if (TileEntity* e = TileEntity::loadStatic(et)) { - - LevelChunk* chunk = level->getChunkAt(e->x, e->z); - if (chunk && !chunk->hasTileEntityAt(e)) { - LOGI("Adding TileEntity %d to %d, %d, %d\n", e->type, e->x, e->y, e->z); - chunk->addTileEntity(e); + LevelChunk* lc = level->getChunkAt(e->x, e->z); + if (lc && !lc->hasTileEntityAt(e)) { + lc->addTileEntity(e); } else { - if (!chunk) - LOGE("Couldn't find chunk at %d, %d to add %d\n", e->x, e->z, e->type); - else - LOGE("Already have TileEntity at %d, %d to add %d\n", e->x, e->z, e->type); delete e; } } } } - tag->deleteChildren(); delete tag; - - delete[] buf; } - LOGI("header: %s, version: %d, bytes: %d (remaining: %d)\n", header, version, numBytes, left); - - //fread(stream.GetData(), 1, numBytes, fp); - fclose(fp); + delete[] buf; } + fclose(fp); + + // Entities are stored per chunk from now on. + const std::string migrated = path + ".migrated"; + remove(migrated.c_str()); + rename(path.c_str(), migrated.c_str()); } void ExternalFileLevelStorage::saveGame(Level* level) { - saveEntities(level, NULL); -} - -int ExternalFileLevelStorage::savePendingUnsavedChunks( int maxCount ) { - if (maxCount < 0) - maxCount = unsavedChunkList.size(); - - int count = 0; - while (++count <= maxCount && !unsavedChunkList.empty()) { - - UnsavedChunkList::iterator it = unsavedChunkList.begin(); - UnsavedChunkList::iterator remove = unsavedChunkList.begin(); - UnsavedLevelChunk* oldest = &(*it); - - for ( ; it != unsavedChunkList.end(); ++it) { - if ((*it).addedToList < oldest->addedToList) { - oldest = &(*it); - remove = it; - } - } - LevelChunk* chunk = oldest->chunk; - unsavedChunkList.erase(remove); - - save(level, chunk); - } - return count; + if (level && level->getChunkSource()) + level->getChunkSource()->saveAll(true); } void ExternalFileLevelStorage::saveAll( Level* level, std::vector& levelChunks ) { ChunkStorage::saveAll(level, levelChunks); - int numChunks = savePendingUnsavedChunks(-1); - LOGI("Saving %d additional chunks.\n", numChunks); } #endif /*DEMO_MODE*/ diff --git a/src/world/level/storage/ExternalFileLevelStorage.h b/src/world/level/storage/ExternalFileLevelStorage.h index 9aad448..f817c15 100755 --- a/src/world/level/storage/ExternalFileLevelStorage.h +++ b/src/world/level/storage/ExternalFileLevelStorage.h @@ -7,6 +7,7 @@ #include #include +#include //#include "com/mojang/nbt/CompoundTag.h" #include "LevelStorage.h" @@ -16,16 +17,6 @@ class Player; class Dimension; class RegionFile; - -typedef struct UnsavedLevelChunk -{ - int pos; - RakNet::TimeMS addedToList; - LevelChunk* chunk; -} UnsavedLevelChunk; - -typedef std::list UnsavedChunkList; - /*public*/ class ExternalFileLevelStorage: public LevelStorage, @@ -54,16 +45,15 @@ public: static bool writeLevelData(const std::string& datFileName, LevelData& dest, const std::vector* players); static void saveLevelData(const std::string& directory, LevelData& levelData, std::vector* players); - int savePendingUnsavedChunks(int maxCount); - // // ChunkStorage methods // virtual LevelChunk* load(Level* level, int x, int z); void save(Level* level, LevelChunk* levelChunk); - // @note, loadEntities and saveEntities dont use second parameter + // Entities and tile entities are saved together with their chunk. This + // only imports the old global "entities.dat" of worlds saved by older + // versions (once). void loadEntities(Level* level, LevelChunk* levelChunk); - void saveEntities(Level* level, LevelChunk* levelChunk); void saveGame(Level* level); void saveAll(Level* level, std::vector& levelChunks); @@ -83,17 +73,20 @@ public: virtual void tick(); virtual void flush() {} private: + RegionFile* getRegion(int chunkX, int chunkZ); + void closeRegions(); + std::string levelId; std::string levelPath; LevelData* loadedLevelData; - RegionFile* regionFile; - RegionFile* entitiesFile; + + // Open region files, least recently used first + std::list regionOrder; + std::map regions; Level* level; int tickCount; int loadedStorageVersion; - UnsavedChunkList unsavedChunkList; - int lastSavedEntitiesTick; }; #endif /*NET_MINECRAFT_WORLD_LEVEL_STORAGE__ExternalFileLevelStorage_H__*/ diff --git a/src/world/level/storage/RegionFile.cpp b/src/world/level/storage/RegionFile.cpp index 3edecce..cf08087 100755 --- a/src/world/level/storage/RegionFile.cpp +++ b/src/world/level/storage/RegionFile.cpp @@ -13,12 +13,27 @@ static void logAssert(int actual, int expected) { } } -RegionFile::RegionFile(const std::string& basePath) +/*static*/ +std::string RegionFile::fileNameFor(const std::string& basePath, int regionX, int regionZ) +{ + std::string name = basePath; + name += "/"; + if (regionX == 0 && regionZ == 0) { + name += REGION_DAT_NAME; + } else { + name += "r."; + name += std::to_string(regionX); + name += "."; + name += std::to_string(regionZ); + name += ".dat"; + } + return name; +} + +RegionFile::RegionFile(const std::string& basePath, int regionX, int regionZ) : file(NULL) { - filename = basePath; - filename += "/"; - filename += REGION_DAT_NAME; + filename = fileNameFor(basePath, regionX, regionZ); offsets = new int[SECTOR_INTS]; @@ -96,6 +111,7 @@ void RegionFile::close() bool RegionFile::readChunk(int x, int z, RakNet::BitStream** destChunkData) { + if (!file) return false; int offset = offsets[x + z * SECTOR_COLS]; if (offset == 0) @@ -127,6 +143,7 @@ bool RegionFile::readChunk(int x, int z, RakNet::BitStream** destChunkData) bool RegionFile::writeChunk(int x, int z, RakNet::BitStream& chunkData) { + if (!file) return false; int size = chunkData.GetNumberOfBytesUsed() + sizeof(int); int offset = offsets[x + z * SECTOR_COLS]; diff --git a/src/world/level/storage/RegionFile.h b/src/world/level/storage/RegionFile.h index 3d743ef..2b9e1f2 100755 --- a/src/world/level/storage/RegionFile.h +++ b/src/world/level/storage/RegionFile.h @@ -1,31 +1,38 @@ -#ifndef NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__ -#define NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__ - -#include -#include -#include "../../../raknet/BitStream.h" - -typedef std::map FreeSectorMap; - -class RegionFile -{ -public: - RegionFile(const std::string& basePath); - virtual ~RegionFile(); - - bool open(); - bool readChunk(int x, int z, RakNet::BitStream** destChunkData); - bool writeChunk(int x, int z, RakNet::BitStream& chunkData); -private: - bool write(int sector, RakNet::BitStream& chunkData); - void close(); - - FILE* file; - std::string filename; - int* offsets; - int* emptyChunk; - FreeSectorMap sectorFree; -}; - - -#endif /*NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__*/ +#ifndef NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__ +#define NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__ + +#include +#include +#include "../../../raknet/BitStream.h" + +typedef std::map FreeSectorMap; + +// One region holds the 32x32 chunks with (x >> 5, z >> 5) == (regionX, regionZ). +// Region (0, 0) lives in the legacy "chunks.dat" so worlds created by the old +// fixed-size versions keep loading. +class RegionFile +{ +public: + RegionFile(const std::string& basePath, int regionX, int regionZ); + virtual ~RegionFile(); + + bool open(); + void close(); + + // x and z are chunk coordinates local to the region (0..31) + bool readChunk(int x, int z, RakNet::BitStream** destChunkData); + bool writeChunk(int x, int z, RakNet::BitStream& chunkData); + + static std::string fileNameFor(const std::string& basePath, int regionX, int regionZ); +private: + bool write(int sector, RakNet::BitStream& chunkData); + + FILE* file; + std::string filename; + int* offsets; + int* emptyChunk; + FreeSectorMap sectorFree; +}; + + +#endif /*NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__*/ diff --git a/src/world/level/tile/DoorTile.cpp b/src/world/level/tile/DoorTile.cpp index 7aea82f..203e424 100755 --- a/src/world/level/tile/DoorTile.cpp +++ b/src/world/level/tile/DoorTile.cpp @@ -3,6 +3,7 @@ #include "../Level.h" #include "../../item/Item.h" #include "../../entity/player/Player.h" +#include "world/level/LevelSettings.h" DoorTile::DoorTile(int id, const Material* material) : super(id, material) @@ -150,7 +151,7 @@ void DoorTile::setOpen(Level* level, int x, int y, int z, bool shouldOpen) { void DoorTile::neighborChanged(Level* level, int x, int y, int z, int type) { int data = level->getData(x, y, z); - if ((data & UPPER_BIT) == 0) { + if ((data & C_IS_UPPER_MASK) == 0) { bool spawn = false; if (level->getTile(x, y + 1, z) != id) { level->setTile(x, y, z, 0); @@ -164,7 +165,7 @@ void DoorTile::neighborChanged(Level* level, int x, int y, int z, int type) { } } if (spawn) { - if (!level->isClientSide) { + if (!level->isClientSide && level->getLevelData()->getGameType() != GameType::Creative) { // use default chance (1.0) so the drop always occurs spawnResources(level, x, y, z, data); } @@ -193,7 +194,7 @@ int DoorTile::getResource(int data, Random* random) { // itself never drops anything and playerDestroy suppresses spawning // from the top. This prevents duplicate drops if the bottom half is // mined. - if ((data & UPPER_BIT) != 0) return 0; + if ((data & C_IS_UPPER_MASK) != 0) return 0; if (material == Material::metal) return Item::door_iron->id; return Item::door_wood->id; } @@ -205,7 +206,7 @@ HitResult DoorTile::clip(Level* level, int xt, int yt, int zt, const Vec3& a, co // override to prevent double-dropping when top half is directly mined void DoorTile::playerDestroy(Level* level, Player* player, int x, int y, int z, int data) { - if ((data & UPPER_BIT) == 0) { + if ((data & C_IS_UPPER_MASK) == 0) { // only let the lower half handle the actual spawning super::playerDestroy(level, player, x, y, z, data); } @@ -225,7 +226,7 @@ bool DoorTile::mayPlace(Level* level, int x, int y, int z, unsigned char face) { int DoorTile::getCompositeData( LevelSource* level, int x, int y, int z ) { int data = level->getData(x, y, z); - bool isUpper = (data & UPPER_BIT) != 0; + bool isUpper = (data & C_IS_UPPER_MASK) != 0; int lowerData; int upperData; if (isUpper) { diff --git a/src/world/level/tile/DoorTile.h b/src/world/level/tile/DoorTile.h index 250d274..bd585e5 100755 --- a/src/world/level/tile/DoorTile.h +++ b/src/world/level/tile/DoorTile.h @@ -17,7 +17,6 @@ class DoorTile: public Tile { typedef Tile super; public: - static const int UPPER_BIT = 8; static const int C_DIR_MASK = 3; static const int C_OPEN_MASK = 4; static const int C_LOWER_DATA_MASK = 7; diff --git a/src/world/level/tile/TallGrass.cpp b/src/world/level/tile/TallGrass.cpp index dbd3738..497279e 100755 --- a/src/world/level/tile/TallGrass.cpp +++ b/src/world/level/tile/TallGrass.cpp @@ -43,8 +43,10 @@ int TallGrass::getColor( int auxData ) { int TallGrass::getColor( LevelSource* level, int x, int y, int z ) { int d = level->getData(x, y, z); if (d == DEAD_SHRUB); //return 0xffffff; // i removed this to make it accurate to beta 1.6.6 instead of early java release versions + + level->getBiomeSource()->getBiomeBlock(x, z, 1, 1); float temp = level->getBiomeSource()->temperatures[0]; // shredder added - float rain = level->getBiomeSource()->downfalls[0]; // shredder added + float rain = level->getBiomeSource()->downfalls != nullptr ? level->getBiomeSource()->downfalls[0] : 0; // shredder added if (!GrassColor::useTint && d == DEAD_SHRUB){ return 0xffffff; } diff --git a/src/world/level/tile/Tile.cpp b/src/world/level/tile/Tile.cpp index 6736bc7..b4948ba 100755 --- a/src/world/level/tile/Tile.cpp +++ b/src/world/level/tile/Tile.cpp @@ -512,16 +512,7 @@ float Tile::getBrightness( LevelSource* level, int x, int y, int z ) bool Tile::shouldRenderFace( LevelSource* level, int x, int y, int z, int face ) { if (face == 0 && y == -1) return false; - // For fixed size worlds //@todo: external constants rather than magic numbers - // @fixme @ahtung temp fix - - auto xz = LevelConstants::CHUNK_CACHE_WIDTH == 16 ? 256 : - LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH / (LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH / 256 / 2); - - if (face == 2 && z == -1) return false; - if (face == 3 && z == xz) return false; - if (face == 4 && x == -1) return false; - if (face == 5 && x == xz) return false; + // The world is infinite, there is no edge whose outer faces could be skipped // Common if (face == 0 && yy0 > 0) return true; if (face == 1 && yy1 < 1) return true; diff --git a/src/world/level/tile/entity/NetherReactorTileEntity.cpp b/src/world/level/tile/entity/NetherReactorTileEntity.cpp index 5b4728a..07a89c1 100755 --- a/src/world/level/tile/entity/NetherReactorTileEntity.cpp +++ b/src/world/level/tile/entity/NetherReactorTileEntity.cpp @@ -130,7 +130,7 @@ Vec3 NetherReactorTileEntity::getSpawnPosition( float minDistance, float varible void NetherReactorTileEntity::spawnEnemy() { Mob* mob = MobFactory::CreateMob(MobTypes::PigZombie, level); Vec3 enemyPosition = getSpawnPosition(3, 4, -1); - while(enemyPosition.x < 0 || enemyPosition.z < 0 || enemyPosition.x >= LevelConstants::LEVEL_WIDTH || enemyPosition.z >= LevelConstants::LEVEL_DEPTH) { + while(enemyPosition.x <= -LevelConstants::LEVEL_WIDTH || enemyPosition.z <= -LevelConstants::LEVEL_DEPTH || enemyPosition.x >= LevelConstants::LEVEL_WIDTH || enemyPosition.z >= LevelConstants::LEVEL_DEPTH) { enemyPosition = getSpawnPosition(3, 4, -1); } MobSpawner::addMob(level, mob, enemyPosition.x, enemyPosition.y, enemyPosition.z, 0, 0, true); @@ -140,7 +140,7 @@ void NetherReactorTileEntity::spawnEnemy() { void NetherReactorTileEntity::spawnItem() { Vec3 itemPosition= getSpawnPosition(3, 4, -1); - while(itemPosition.x < 0 || itemPosition.z < 0 || itemPosition.x >= LevelConstants::LEVEL_WIDTH || itemPosition.z >= LevelConstants::LEVEL_DEPTH) { + while(itemPosition.x <= -LevelConstants::LEVEL_WIDTH || itemPosition.z <= -LevelConstants::LEVEL_DEPTH || itemPosition.x >= LevelConstants::LEVEL_WIDTH || itemPosition.z >= LevelConstants::LEVEL_DEPTH) { itemPosition = getSpawnPosition(3, 4, -1); } ItemEntity* item = new ItemEntity(level, itemPosition.x, itemPosition.y, itemPosition.z, getSpawnItem()); diff --git a/tools/convert-music.ps1 b/tools/convert-music.ps1 new file mode 100644 index 0000000..1432469 --- /dev/null +++ b/tools/convert-music.ps1 @@ -0,0 +1,23 @@ +<# + Converts FLAC/MP3/WAV files to the OGG Vorbis tracks the game plays from data\music. + + .\tools\convert-music.ps1 -Source "F:\Music\Minecraft - Volume Alpha" -Prefix alpha + .\tools\convert-music.ps1 -Source "F:\Music\Minecraft - Volume Beta" -Prefix beta + + Needs ffmpeg (with libvorbis) in PATH. Every .ogg in data\music is shuffled by the + in-game music player, volume is the "Music" slider in the options. +#> +param( + [Parameter(Mandatory)] [string]$Source, + [string]$Prefix = 'track', + [string]$Out = (Join-Path $PSScriptRoot '..\data\music') +) +New-Item -ItemType Directory -Force $Out | Out-Null +Get-ChildItem -LiteralPath $Source -Include *.flac, *.mp3, *.wav, *.m4a -Recurse | ForEach-Object { + $name = ($_.BaseName -replace '[^\w\- ]', '') -replace '\s+', '_' + $dst = Join-Path $Out "${Prefix}_$name.ogg" + if (-not (Test-Path $dst)) { + & ffmpeg -loglevel error -y -i $_.FullName -vn -map_metadata -1 -acodec libvorbis -aq 4 -ar 44100 -ac 2 $dst + Write-Host $dst + } +}