diff --git a/.github/workflows/appimage.yml b/.github/workflows/appimage.yml index 5bfebeb4d..7b53b3fbf 100644 --- a/.github/workflows/appimage.yml +++ b/.github/workflows/appimage.yml @@ -50,13 +50,13 @@ jobs: - name: Run engine tests timeout-minutes: 5 run: | - chmod +x build/VoxelEngine + chmod +x build/VoxelCore chmod +x AppDir/usr/bin/vctest - AppDir/usr/bin/vctest -e build/VoxelEngine -d dev/tests -u build --memchecker valgrind + AppDir/usr/bin/vctest -e build/VoxelCore -d dev/tests -u build --memchecker valgrind - name: Build AppImage uses: AppImageCrafters/build-appimage-action@fe2205a4d6056be47051f7b1b3811106e9814910 env: - UPDATE_INFO: gh-releases-zsync|MihailRis|VoxelEngine-Cpp|latest|*x86_64.AppImage.zsync + UPDATE_INFO: gh-releases-zsync|MihailRis|voxelcore|latest|*x86_64.AppImage.zsync with: recipe: dev/AppImageBuilder.yml - uses: actions/upload-artifact@v4 diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index 52f7b7183..6956a1f3d 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -62,7 +62,7 @@ jobs: # Build your program with the given configuration run: | cmake --build ${{github.workspace}}/build --config ${{inputs.build_type}} - mv ${{github.workspace}}/build/VoxelEngine VoxelEngine + mv ${{github.workspace}}/build/VoxelCore VoxelCore - name: Run tests if: ${{ inputs.run_tests }} run: ctest --test-dir ${{github.workspace}}/build @@ -70,7 +70,7 @@ jobs: if: ${{ inputs.upload_artifacts }} uses: actions/upload-artifact@v4 with: - name: VoxelEngine + name: VoxelCore path: | - VoxelEngine + VoxelCore res/* diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index b4d9f6328..a446821d8 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -39,7 +39,7 @@ jobs: run: chmod +x dev/fix_dylibs.sh - name: Fix dylibs - run: ./dev/fix_dylibs.sh VoxelEngine Release build + run: ./dev/fix_dylibs.sh VoxelCore Release build - name: Run tests run: ctest --output-on-failure --test-dir build @@ -47,19 +47,19 @@ jobs: - name: Run engine tests timeout-minutes: 5 run: | - chmod +x build/VoxelEngine + chmod +x build/VoxelCore chmod +x AppDir/usr/bin/vctest - AppDir/usr/bin/vctest -e build/VoxelEngine -d dev/tests -u build --output-always --debugger "lldb -batch -o 'run' -o 'thread backtrace all' -o 'quit' -- " + AppDir/usr/bin/vctest -e build/VoxelCore -d dev/tests -u build --output-always --debugger "lldb -batch -o 'run' -o 'thread backtrace all' -o 'quit' -- " - name: Create DMG run: | - mkdir VoxelEngineDmgContent - cp -r build/res VoxelEngineDmgContent/ - cp -r build/VoxelEngine VoxelEngineDmgContent/ - cp -r build/libs VoxelEngineDmgContent/libs - hdiutil create VoxelEngineMacApp.dmg -volname "VoxelEngine" -srcfolder VoxelEngineDmgContent -ov -format UDZO + mkdir VoxelCoreDmgContent + cp -r build/res VoxelCoreDmgContent/ + cp -r build/VoxelCore VoxelCoreDmgContent/ + cp -r build/libs VoxelCoreDmgContent/libs + hdiutil create VoxelCoreMacApp.dmg -volname "VoxelCore" -srcfolder VoxelCoreDmgContent -ov -format UDZO - name: Upload artifacts uses: actions/upload-artifact@v4 with: - name: VoxelEngineMacOs - path: VoxelEngineMacApp.dmg + name: VoxelCoreMacOs + path: VoxelCoreMacApp.dmg diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8a1d17c64..f6b539ba1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -48,7 +48,7 @@ jobs: mkdir release mv ./artifacts/AppImage/VoxelCore-latest-x86_64.AppImage \ ./release/voxelcore-${RELEASE_VERSION}_x86-64.AppImage - mv ./artifacts/VoxelEngineMacOs/VoxelEngineMacApp.dmg \ + mv ./artifacts/VoxelCoreMacOs/VoxelCoreMacApp.dmg \ ./release/voxelcore-${RELEASE_VERSION}_macos.dmg (cd ./artifacts/Windows-Build && zip -r ../../release/voxelcore-${RELEASE_VERSION}_win64.zip .) ls -la ./release diff --git a/.github/workflows/windows-clang.yml b/.github/workflows/windows-clang.yml index 5dd91a576..1fe591ac8 100644 --- a/.github/workflows/windows-clang.yml +++ b/.github/workflows/windows-clang.yml @@ -59,11 +59,10 @@ jobs: run: | mkdir packaged mkdir packaged/res - cp build/VoxelEngine.exe packaged/ + cp build/VoxelCore.exe packaged/ cp build/vctest/vctest.exe packaged/ cp build/*.dll packaged/ cp -r build/res/* packaged/res/ - mv packaged/VoxelEngine.exe packaged/VoxelCore.exe - uses: actions/upload-artifact@v4 with: name: Windows-Build diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index ffcb0c318..ec5322bc0 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -37,7 +37,7 @@ jobs: run: ctest --preset default-vs-msvc-windows - name: Run engine tests run: | - build/vctest/RelWithDebInfo/vctest.exe -e build/RelWithDebInfo/VoxelEngine.exe -d dev/tests -u build + build/vctest/RelWithDebInfo/vctest.exe -e build/RelWithDebInfo/VoxelCore.exe -d dev/tests -u build timeout-minutes: 5 - name: Package for Windows run: | @@ -45,7 +45,6 @@ jobs: cp -r build/RelWithDebInfo/* packaged/ cp build/vctest/RelWithDebInfo/vctest.exe packaged/ cp C:/Windows/System32/msvcp140.dll packaged/msvcp140.dll - mv packaged/VoxelEngine.exe packaged/VoxelCore.exe working-directory: ${{ github.workspace }} - uses: actions/upload-artifact@v4 with: diff --git a/CMakeLists.txt b/CMakeLists.txt index 27a9d507b..a9ac24a1d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.5) -project(VoxelEngine) +project(VoxelCore) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -27,23 +27,23 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Windows") endif() add_subdirectory(src) -add_executable(VoxelEngine src/main.cpp) +add_executable(VoxelCore src/main.cpp) if(VOXELENGINE_BUILD_APPDIR) include(${CMAKE_CURRENT_SOURCE_DIR}/dev/cmake/BuildAppdir.cmake) endif() -target_link_libraries(VoxelEngine PRIVATE VoxelEngineSrc +target_link_libraries(VoxelCore PRIVATE VoxelCoreSrc $<$:winmm>) -target_link_options(VoxelEngine PRIVATE $<$:-no-pie>) +target_link_options(VoxelCore PRIVATE $<$:-no-pie>) # Deploy res to build dir add_custom_command( - TARGET VoxelEngine + TARGET VoxelCore POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different - ${CMAKE_CURRENT_SOURCE_DIR}/res $/res) + ${CMAKE_CURRENT_SOURCE_DIR}/res $/res) if(VOXELENGINE_BUILD_TESTS) enable_testing() diff --git a/Dockerfile b/Dockerfile index 3a06d1afc..fb1a628c4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ # Build docker container: docker build -t voxelcore . # Build project: docker run --rm -it -v$(pwd):/project voxelcore bash -c "cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE -Bbuild && cmake --build build" -# Run project in docker: docker run --rm -it -v$(pwd):/project -v/tmp/.X11-unix:/tmp/.X11-unix -v${XAUTHORITY}:/home/user/.Xauthority:ro -eDISPLAY --network=host voxelcore ./build/VoxelEngine +# Run project in docker: docker run --rm -it -v$(pwd):/project -v/tmp/.X11-unix:/tmp/.X11-unix -v${XAUTHORITY}:/home/user/.Xauthority:ro -eDISPLAY --network=host voxelcore ./build/VoxelCore FROM debian:bookworm-slim LABEL Description="Docker container for building VoxelCore for Linux" diff --git a/README.md b/README.md index 67788d9fd..d040e7707 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ docker run --rm -it \ -v "$XAUTHORITY:/home/user/.Xauthority:ro" \ -e DISPLAY="$DISPLAY" \ --network=host \ - voxel-engine ./build/VoxelEngine + voxel-engine ./build/VoxelCore ``` ### On Windows @@ -218,5 +218,5 @@ docker run --rm -it -v "${PWD}:/project" voxel-engine bash -c "cmake -DCMAKE_BUI #### Step 4. Run the application ```powershell -docker run --rm -it -v "${PWD}:/project" -e DISPLAY=host.docker.internal:0.0 --network=host voxel-engine ./build/VoxelEngine +docker run --rm -it -v "${PWD}:/project" -e DISPLAY=host.docker.internal:0.0 --network=host voxel-engine ./build/VoxelCore ``` diff --git a/dev/AppImageBuilder.yml b/dev/AppImageBuilder.yml index b2c7f09ec..bed1dde47 100644 --- a/dev/AppImageBuilder.yml +++ b/dev/AppImageBuilder.yml @@ -6,7 +6,7 @@ AppDir: name: VoxelCore icon: VoxelCore version: latest - exec: usr/bin/VoxelEngine + exec: usr/bin/VoxelCore exec_args: --dir $HOME/.config/voxelcore --res $APPDIR/usr/share/VoxelCore/res $@ apt: arch: amd64 diff --git a/dev/VoxelCore.desktop b/dev/VoxelCore.desktop index 48809b392..eeaf4be30 100644 --- a/dev/VoxelCore.desktop +++ b/dev/VoxelCore.desktop @@ -3,8 +3,8 @@ Version=1.0 Type=Application Name=VoxelCore Comment=Minecraft-like game engine in C++ with OpenGL -TryExec=VoxelEngine -Exec=VoxelEngine +TryExec=VoxelCore +Exec=VoxelCore Icon=VoxelCore MimeType=image/x-foo; Categories=Game; diff --git a/dev/cmake/BuildAppdir.cmake b/dev/cmake/BuildAppdir.cmake index e3a017e94..7445d1016 100644 --- a/dev/cmake/BuildAppdir.cmake +++ b/dev/cmake/BuildAppdir.cmake @@ -12,4 +12,4 @@ file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/dev/VoxelCore.desktop DESTINATION ${CMAKE_ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/usr/lib) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/usr/lib) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/usr/bin) -install(TARGETS VoxelEngine DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/usr/bin) +install(TARGETS VoxelCore DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/usr/bin) diff --git a/dev/tests/io_stream.lua b/dev/tests/io_stream.lua index d08c68b0c..da2a2efb0 100644 --- a/dev/tests/io_stream.lua +++ b/dev/tests/io_stream.lua @@ -1,34 +1,385 @@ local device = file.create_memory_device() -file.write(device..":test.txt", "Hello\nWorld") -file.write_bytes(device..":test.bin", Bytearray({20, 30, 100, 200, 255})) -local stream = file.open(device..":test.txt", 'r') +local function path(name) return device .. ":" .. name end -local line1 = stream:read_line() -local line2 = stream:read_line() +local function eq_list(actual, expected, msg) + asserts.equals(#actual, #expected, (msg or "list") .. " length") + for i = 1, #expected do + asserts.equals(actual[i], expected[i], (msg or "list") .. "[" .. i .. "]") + end +end -assert(line1 == "Hello") -assert(line2 == "World") +file.write(path("test.txt"), "Hello\nWorld") +file.write_bytes(path("test.bin"), Bytearray({20, 30, 100, 200, 255})) -local stream2 = file.open(device..":test.bin", 'rb') -local data = stream2:read(5) -assert(data[1] == 20) -assert(data[2] == 30) -assert(data[3] == 100) -assert(data[4] == 200) -assert(data[5] == 255) +do + local stream = file.open(path("test.txt"), 'r') + asserts.equals(stream:read_line(), "Hello") + asserts.equals(stream:read_line(), "World") + stream:close() +end -local stream3 = file.open(device..":test.txt", 'r') -assert(stream3:is_alive()) -stream3:close() -assert(not stream3:is_alive()) +do + local stream = file.open(path("test.bin"), 'rb') + local data = stream:read(5) + asserts.equals(data[1], 20); asserts.equals(data[2], 30); asserts.equals(data[3], 100); asserts.equals(data[4], 200); asserts + .equals(data[5], 255) + stream:close() +end -local stream4 = file.open(device..":test.txt", 'r') -stream4:seek('b', 6) -local line = stream4:read_line() -assert(line == "World") +do + local stream = file.open(path("test.txt"), 'r') + assert(stream:is_alive()) + assert(not stream:is_closed()) + stream:close() + assert(not stream:is_alive()) + assert(stream:is_closed()) +end -local stream5 = file.open(device..":test.txt", 'r') -stream5:seek('e', 0) -local pos = stream5:tell() -assert(pos == 11) +do + local stream = file.open(path("test.txt"), 'r') + stream:seek('b', 6) + asserts.equals(stream:read_line(), "World") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + stream:seek('e', 0) + asserts.equals(stream:tell(), 11) + stream:close() +end + +------------------------------------------------------------------------------- +-- text: line endings and end of stream +------------------------------------------------------------------------------- + +do + local stream = file.open(path("test.txt"), 'r') + stream:read_line(); stream:read_line() + asserts.equals(stream:read_line(), nil, "after last line") + asserts.equals(stream:read_line(), nil, "after last line, again") + stream:close() +end + +do + file.write(path("empty.txt"), "") + local stream = file.open(path("empty.txt"), 'r') + asserts.equals(stream:read_line(), nil, "empty file") + stream:close() +end + +do + file.write(path("crlf.txt"), "a\r\nb\rc\nd\r") + local stream = file.open(path("crlf.txt"), 'r') + asserts.equals(stream:read_line(), "a", "CRLF") + asserts.equals(stream:read_line(), "b\rc", "lone CR is kept") + asserts.equals(stream:read_line(), "d\r", "CR at end of stream") + asserts.equals(stream:read_line(), nil) + stream:close() +end + +------------------------------------------------------------------------------- +-- text: read(count) and read_fully +------------------------------------------------------------------------------- + +do + file.write(path("blank.txt"), "\n\nA\nB\n\n") + local stream = file.open(path("blank.txt"), 'r') + eq_list(stream:read(10), {"A", "B"}, "trimmed") + stream:close() +end + +do + local stream = file.open(path("blank.txt"), 'r') + eq_list(stream:read(10, false), {"", "", "A", "B", ""}, "untrimmed") + stream:close() +end + +do + file.write(path("only_blank.txt"), "\n\n\n") + local stream = file.open(path("only_blank.txt"), 'r') + eq_list(stream:read(5), {}, "only empty lines") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + eq_list(stream:read(5), {"Hello", "World"}, "past end of stream") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + assert(not pcall(stream.read, stream, -1), "negative count must fail") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + asserts.equals(stream:read(), "Hello") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + asserts.equals(stream:read_fully(), "Hello\nWorld", "read_fully as string") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + eq_list(stream:read_fully(true), {"Hello", "World"}, "read_fully as lines") + stream:close() +end + +------------------------------------------------------------------------------- +-- text: writing +------------------------------------------------------------------------------- + +do + local stream = file.open(path("out.txt"), 'w') + stream:write("one") + stream:write({"two", "three"}) + stream:write_line("four") + stream:close() + asserts.equals(file.read(path("out.txt")), "one\ntwo\nthree\nfour\n", "text write") +end + +do + local stream = file.open(path("out.txt"), 'w') + assert(not pcall(stream.write, stream, 42), "writing a number in text mode must fail") + stream:close() +end + +------------------------------------------------------------------------------- +-- binary +------------------------------------------------------------------------------- + +do + local stream = file.open(path("test.bin"), 'rb') + eq_list(stream:read(5, true), {20, 30, 100, 200, 255}, "read as table") + stream:close() +end + +do + local stream = file.open(path("test.bin"), 'rb') + stream:read(3) + asserts.equals(#stream:read(10), 2, "short read") + asserts.equals(#stream:read(10), 0, "read at end of stream") + stream:close() +end + +do + local stream = file.open(path("test.bin"), 'rb') + local data = stream:read_fully() + asserts.equals(#data, 5); asserts.equals(data[1], 20); asserts.equals(data[5], 255) + stream:close() +end + +do + local stream = file.open(path("test.bin"), 'rb') + eq_list(stream:read_fully(true), {20, 30, 100, 200, 255}, "read_fully as table") + stream:close() +end + +do + local stream = file.open(path("out.bin"), 'wb') + stream:write({1, 2, 3}) + stream:write(Bytearray({4, 5})) + stream:close() + + local data = file.read_bytes(path("out.bin")) + asserts.equals(#data, 5, "binary write length") + for i = 1, 5 do asserts.equals(data[i], i, "binary write byte " .. i) end +end + +do + local stream = file.open(path("fmt.bin"), 'wb') + stream:write("![WARNING] +> This branch is used for VoxelCore 0.33 development, API is unstable. +> [Proceed to VoxelCore 0.32 documentation](https://github.com/MihailRis/voxelcore/blob/release-0.32/doc/en/main-page.md) + ## Sections - [Assets preloading](assets-preload.md) diff --git a/doc/en/scripting/builtins/libgfx-skeletons.md b/doc/en/scripting/builtins/libgfx-skeletons.md index 4146b4be6..5518cb349 100644 --- a/doc/en/scripting/builtins/libgfx-skeletons.md +++ b/doc/en/scripting/builtins/libgfx-skeletons.md @@ -41,8 +41,14 @@ skeleton:is_visible([optional] index: int) -> bool skeleton:set_visible([optional] index: int, status: bool) -- Returns the color of the entity -skeleton:get_color() -> vec3 +skeleton:get_color() -> vec4 + +-- Returns the color of the bone +skeleton:get_color(index: int) -> vec4 -- Sets the color of the entity -skeleton:set_color(color: vec3) +skeleton:set_color(color: vec4) + +-- Sets the color of the bone +skeleton:set_color(color: vec4, bone: int) ``` diff --git a/doc/en/scripting/builtins/libnetwork.md b/doc/en/scripting/builtins/libnetwork.md index 8893407d4..ecd76bbf3 100644 --- a/doc/en/scripting/builtins/libnetwork.md +++ b/doc/en/scripting/builtins/libnetwork.md @@ -50,7 +50,7 @@ network.get( ) -- Example: -network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/latest", function (s) +network.get("https://api.github.com/repos/MihailRis/voxelcore/releases/latest", function (s) print(json.parse(s).name) -- will output the name of the latest engine release end) diff --git a/doc/en/scripting/ecs.md b/doc/en/scripting/ecs.md index 0473fc852..0968e2d8d 100644 --- a/doc/en/scripting/ecs.md +++ b/doc/en/scripting/ecs.md @@ -185,9 +185,11 @@ rig:index(name: str) -> int -- or the skeleton if no index is specified rig:is_visible([optional] index: int) -> bool +-- Sets the visibility status of the skeleton +rig:set_visible(status: bool) + -- Sets the visibility status of a bone by index --- or the skeleton if no index is specified -rig:set_visible([optional] index: int, status: bool) +rig:set_visible(index: int, status: bool) -- Returns the color of the entity rig:get_color() -> vec4 diff --git a/doc/en/vca.md b/doc/en/vca.md index 7b2bda0b5..1299662f0 100644 --- a/doc/en/vca.md +++ b/doc/en/vca.md @@ -28,6 +28,9 @@ Two kinds of curve definitions are currently available, each producing a value ` - `@scale` - scales an object/bone (multiplier) - `@zoom` - camera zoom (multiplier) - `@texture` - change of a dynamically assigned texture (see [skeleton:set_texture](scripting/ecs.md#skeleton)) +- `@model` - bone model replacement (see [skeleton:set_model](scripting/ecs.md#skeleton)) +- `@show` - visibility of a bone or the entire skeleton/object (if no bone is specified) +- `@color` - color of a bone or the entire skeleton/object (if no bone is specified) (RGBA) ## Metadata @@ -96,6 +99,23 @@ If you do not wish to limit the animation duration via `configure` but want to l } ``` +Example of using flag directives like `show`: + +```vcd +# Specific bone +@show bone head period 20 { + @key frame 0 value on + @key frame 10 value off +} + +# Entire skeleton +@show period 30 { + @key frame 0 value on + @key frame 10 value off +} + +``` + ## Expression curves The attribute describes a function `f(t) = x`, where t is time in seconds. diff --git a/doc/en/xml-ui-layouts.md b/doc/en/xml-ui-layouts.md index 704a0b786..8d04ff4ec 100644 --- a/doc/en/xml-ui-layouts.md +++ b/doc/en/xml-ui-layouts.md @@ -215,6 +215,9 @@ Element is a container. Does not have specific attributes. > [!WARNING] > Inventories position is controlled by the engine and can not be changed by attributes *pos* and *margin* +> [!WARNING] +> Slots not linked to an inventory will not be displayed. "Linked to an inventory" refers to the association between an inventory UI element and an inventory via an ID. This link can be explicitly established using `inventory_ui.inventory = inventory_id`. [(see ui.md)](scripting/ui.md#inventory) + ## *slot* Element must be in direct sub-element of *inventory*. diff --git a/doc/ru/main-page.md b/doc/ru/main-page.md index b826d9dfd..66e1b523a 100644 --- a/doc/ru/main-page.md +++ b/doc/ru/main-page.md @@ -1,5 +1,9 @@ # Документация +>![WARNING] +> В этой ветке ведётся разработка VoxelCore 0.33, API нестабилен. +> [Перейти к документации VoxelCore 0.32](https://github.com/MihailRis/voxelcore/blob/release-0.32/doc/ru/main-page.md) + ## Разделы - [XML разметка интерфейса](xml-ui-layouts.md) diff --git a/doc/ru/scripting/builtins/libgfx-skeletons.md b/doc/ru/scripting/builtins/libgfx-skeletons.md index 2a04d598c..95fa4fe48 100644 --- a/doc/ru/scripting/builtins/libgfx-skeletons.md +++ b/doc/ru/scripting/builtins/libgfx-skeletons.md @@ -42,8 +42,14 @@ skeleton:is_visible([опционально] index: int) -> boolean skeleton:set_visible([опционально] index: int, status: boolean) -- Возвращает цвет сущности -skeleton:get_color() -> vec3 +skeleton:get_color() -> vec4 + +-- Возвращает цвет кости +skeleton:get_color(index: int) -> vec4 -- Устанавливает цвет сущности -skeleton:set_color(color: vec3) -``` \ No newline at end of file +skeleton:set_color(color: vec4) + +-- Устанавливает цвет кости +skeleton:set_color(color: vec4, index: int) +``` diff --git a/doc/ru/scripting/builtins/libnetwork.md b/doc/ru/scripting/builtins/libnetwork.md index c60f0f178..2c322405e 100644 --- a/doc/ru/scripting/builtins/libnetwork.md +++ b/doc/ru/scripting/builtins/libnetwork.md @@ -50,7 +50,7 @@ network.get( ) -- Пример: -network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/latest", function (s) +network.get("https://api.github.com/repos/MihailRis/voxelcore/releases/latest", function (s) print(json.parse(s).name) -- выведет имя последнего релиза движка end) diff --git a/doc/ru/scripting/ecs.md b/doc/ru/scripting/ecs.md index d6a823cf0..fb03721c6 100644 --- a/doc/ru/scripting/ecs.md +++ b/doc/ru/scripting/ecs.md @@ -174,9 +174,11 @@ rig:index(name: str) -> int -- или всего скелета, если индекс не указан rig:is_visible([optional] index: int) -> bool +-- Устанавливает статус видимости всего скелета +rig:set_visible(status: bool) + -- Устанавливает статус видимости кости по индексу --- или всего скелета, если индекс не указан -rig:set_visible([optional] index: int, status: bool) +rig:set_visible(index: int, status: bool) -- Возвращает цвет сущности rig:get_color() -> vec4 diff --git a/doc/ru/vca.md b/doc/ru/vca.md index 2cba3c3ab..41db479b5 100644 --- a/doc/ru/vca.md +++ b/doc/ru/vca.md @@ -28,6 +28,9 @@ VCA файл состоит из набора директив, порядок - `@scale` - масштабирование объекта/кости (множитель) - `@zoom` - масштаб камеры (множитель) - `@texture` - смена динамически-назначаемой текстуры (см. [skeleton:set_texture](scripting/ecs.md#skeleton)) +- `@model` - назначение замены модели кости (см. [skeleton:set_model](scripting/ecs.md#skeleton)) +- `@show` - видимость кости или всего скелета / объекта (если не указана кость) +- `@color` - цвет кости или всего скелета / объекта (если не указана кость) (RGBA) ## Мета-информация @@ -96,6 +99,23 @@ VCA файл состоит из набора директив, порядок } ``` +Пример использования директив-флагов, таких как `show`: + +```vcd +# Конкретная кость +@show bone head period 20 { + @key frame 0 value on + @key frame 10 value off +} + +# Весь скелет +@show period 30 { + @key frame 0 value on + @key frame 10 value off +} + +``` + ## Кривые через выражения Через атрибут описывается функция `f(t) = x` где t - время в секундах. diff --git a/doc/ru/xml-ui-layouts.md b/doc/ru/xml-ui-layouts.md index 9be788e7f..94f396495 100644 --- a/doc/ru/xml-ui-layouts.md +++ b/doc/ru/xml-ui-layouts.md @@ -216,6 +216,9 @@ > [!WARNING] > Расположение инвентарей управляется движком и не может быть изменено свойствами pos, margin и т.д. +> [!WARNING] +> Слоты без привязки к инвентарю не будут отображаться. Под приязкой к инвентарю понимается связь UI элемента inventory с инвентарём по id. Которая может быть явно создана через `inventory_ui.inventory = inventory_id`. [(см ui.md)](scripting/ui.md#инвентарь-inventory) + ## Одиночный слот - *slot* Элемент должен находиться внутри `inventory` элемента, без посредников. diff --git a/doc/specs/binary_json_spec.md b/doc/specs/binary_json_spec.md index 46ed868d6..4bed562e4 100644 --- a/doc/specs/binary_json_spec.md +++ b/doc/specs/binary_json_spec.md @@ -2,7 +2,7 @@ Format version: 1.1 -This binary data format is developed for use as binary version of JSON in [VoxelEngine-Cpp](https://github.com/MihailRis/VoxelEngine-Cpp) and not compatible with [BSON](https://bsonspec.org/spec.html) due to elements/entries syntax and type codes differences +This binary data format is developed for use as binary version of JSON in [voxelcore](https://github.com/MihailRis/voxelcore) and not compatible with [BSON](https://bsonspec.org/spec.html) due to elements/entries syntax and type codes differences ## Basic types diff --git a/flake.nix b/flake.nix index ead09d092..cb6bfe6ca 100644 --- a/flake.nix +++ b/flake.nix @@ -56,7 +56,7 @@ installPhase = '' mkdir -p $out/bin - cp VoxelEngine $out/bin/ + cp VoxelCore $out/bin/ ''; }; in diff --git a/res/content/base/package.json b/res/content/base/package.json index 71b4dca9f..11eb30f3e 100644 --- a/res/content/base/package.json +++ b/res/content/base/package.json @@ -1,6 +1,6 @@ { "id": "base", "title": "Base", - "version": "0.32", + "version": "0.33", "description": "basic content package" } diff --git a/res/modules/animation.lua b/res/modules/animation.lua index 0c7bb7741..a4e1f73d9 100644 --- a/res/modules/animation.lua +++ b/res/modules/animation.lua @@ -39,12 +39,15 @@ local function bezier_interpolation(k0, k1, t) return bezier(k0.value, k0.ry + k0.value, k1.ly + k1.value, k1.value, u) end -local this = { +local M = { CH_TRANSLATE = 1, CH_ROTATE = 2, CH_SCALE = 3, CH_ZOOM = 4, CH_TEXTURE = 5, + CH_SHOW = 6, + CH_MODEL = 7, + CH_COLOR = 8, INT_CONST = 1, INT_LINEAR = 2, @@ -53,7 +56,7 @@ local this = { MAX_DURATION = 1e9, MAX_FRAMES = 1e9, - TRACE_CODEGEN = false, + TRACE_CODEGEN = true, maths = { bezier_interpolation = bezier_interpolation @@ -67,14 +70,14 @@ function internals.store_animation(name, track) loaded_tracks[name] = track end -function this.get_track(identifier) +function M.get_track(identifier) return loaded_tracks[identifier] end local running_actions = {} local playing_tracks = {} -function this.action(func) +function M.action(func) table.insert(running_actions, coroutine.create(func)) end @@ -98,7 +101,7 @@ local PlayingTrack = { } } -function this.play(name, target) +function M.play(name, target) if target and target.reset_pose then target:reset_pose() end @@ -156,4 +159,4 @@ function internals.restore_animation_backup() loaded_tracks, backup_tracks = backup_tracks, {} end -return this +return M diff --git a/res/modules/internal/animation_codegen.lua b/res/modules/internal/animation_codegen.lua index 525240f66..1b637d866 100644 --- a/res/modules/internal/animation_codegen.lua +++ b/res/modules/internal/animation_codegen.lua @@ -15,7 +15,7 @@ local exclude_patters = { } -- TODO: replace with actual expression -> lua translator -local function process_expression(src, memoised, mode) +local function process_expression(src, mode) if mode == 'mul' then src = string.format("(%s) * intensity + (1.0 - intensity)", src) elseif mode == "add" then @@ -30,7 +30,6 @@ local function process_expression(src, memoised, mode) for i, pattern in ipairs(patterns) do local pattern_safe = string.pattern_safe(pattern.pattern) if src:find(pattern_safe) then - memoised[pattern.name] = pattern.pattern src = src:gsub(pattern_safe, pattern.name) end end @@ -76,7 +75,7 @@ local env = { return keys[left].value end left = keys[left] - if interp == INT_CONST then + if not interp or interp == INT_CONST then return left.value end right = keys[right] @@ -137,42 +136,48 @@ local is_multiplier = { [animation.CH_ZOOM] = true, } -local function codegen_track(raw_track, lineset, memoised, keysets, use_tsf) +local function codegen_line(raw_track, lineset, line, index, keysets) + if line.expression then + return "(" .. process_expression(line.expression, + is_multiplier[line.channel] and "mul" or "add") .. ")" + elseif line.keys then + local target_keysets = keysets[lineset.target_name] + if not target_keysets then + target_keysets = {} + keysets[lineset.target_name] = target_keysets + end + target_keysets[index] = line.keys + + if line.curve_func then + local valueat = string.format("curves[%s]", string.escape(line.curve_func)) + return string.format("value_at_custom(keysets['%s'][%d], t * %s %% %s, %s)", + lineset.target_name, index, raw_track.fps, line.period, valueat) + elseif line.channel == animation.CH_TEXTURE then + return string.format("string_at(keysets['%s'][%d], t * %s %% %s)", + lineset.target_name, index, raw_track.fps, line.period) + else + return string.format("value_at(keysets['%s'][%d], t * %s %% %s, %s)", + lineset.target_name, index, raw_track.fps, line.period, line.interp) + end + end +end + +local function codegen_track(raw_track, lineset, keysets, use_tsf, target_type) + if lineset.target_type ~= target_type then + return "" + end + local lines = lineset.lines local code = "" local has_tsf = false local translation = {false, false, false} local rotation = {false, false, false} local scale = {false, false, false} + local color = {false, false, false, false} + for i, line in ipairs(lines) do - if line.expression then - code = code .. "\n local l" .. i .. " = (" .. - process_expression(line.expression, memoised, - is_multiplier[line.channel] and "mul" or "add") .. ")" - elseif line.keys then - local target_keysets = keysets[lineset.target_name] - if not target_keysets then - target_keysets = {} - keysets[lineset.target_name] = target_keysets - end - target_keysets[i] = line.keys - - if line.curve_func then - local valueat = string.format("curves[%s]", string.escape(line.curve_func)) - - code = code .. string.format( - "\n local l%d = value_at_custom(keysets['%s'][%d], t * %s %% %s, %s)", - i, lineset.target_name, i, raw_track.fps, line.period, valueat) - elseif line.channel == animation.CH_TEXTURE then - code = code .. string.format( - "\n local l%d = string_at(keysets['%s'][%d], t * %s %% %s)", - i, lineset.target_name, i, raw_track.fps, line.period) - else - code = code .. string.format( - "\n local l%d = value_at(keysets['%s'][%d], t * %s %% %s, %s)", - i, lineset.target_name, i, raw_track.fps, line.period, line.interp) - end - end + code = code .. string.format("\n local l%d = ", i) + .. codegen_line(raw_track, lineset, line, i, keysets) if line.channel == animation.CH_TRANSLATE then translation[line.axis] = i @@ -186,7 +191,31 @@ local function codegen_track(raw_track, lineset, memoised, keysets, use_tsf) elseif line.channel == animation.CH_ZOOM then code = code .. "\n zoom = l" .. i elseif line.channel == animation.CH_TEXTURE then - code = code .. string.format("\n target:set_texture(%s, %s)", lineset.target_name:escape(), "l"..i) + code = code .. string.format("\n target:set_texture(%s, l%d)", + lineset.target_name:escape(), i) + elseif line.channel == animation.CH_MODEL then + code = code .. string.format("\n target:set_model(bone_index, l%d)", i) + elseif line.channel == animation.CH_SHOW then + if target_type == "bone" then + code = code .. string.format("\n target:set_visible(bone_index, l%d)", i) + else + code = code .. string.format("\n target:set_visible(l%d)", i) + end + elseif line.channel == animation.CH_COLOR then + color[line.axis] = i + end + end + + if color[1] or color[2] or color[3] or color[4] then + local color_vector = "{" .. + (color[1] and ("l" .. color[1]) or '1').. ", " .. + (color[2] and ("l" .. color[2]) or '1').. ", " .. + (color[3] and ("l" .. color[3]) or '1').. ", " .. + (color[4] and ("l" .. color[4]) or '1').. "}" + if target_type == "bone" then + code = code .. "\n target:set_color(" .. color_vector .. ", bone_index)" + else + code = code .. "\n target:set_color(" .. color_vector .. ")" end end @@ -229,14 +258,15 @@ local function codegen_rig_target(raw_track, context) if lineset.target_type ~= "bone" and lineset.target_type ~= "texture" then goto continue end - local lineset_code = codegen_track( - raw_track, lineset, context.memoised, context.keysets, true) + local lineset_code = codegen_track(raw_track, lineset, context.keysets, true, "bone") + code = code .. string.format("\n local bone_index = target:index(%s)", string.escape(bone)) + if context.has_tsf then + code = code .. "\n local dst = target:get_matrix(bone_index)" + end code = code - .. string.format("\n local bone_index = target:index(%s)" - .. "\n local dst = target:get_matrix(bone_index)", string.escape(bone)) .. "\n do" .. lineset_code .. "\n end\n" - if lineset.target_type == "bone" then + if lineset.target_type == "bone" and context.has_tsf then code = code .. " target:set_matrix(bone_index, dst)\n" end @@ -246,17 +276,18 @@ local function codegen_rig_target(raw_track, context) end local function codegen_object_target(raw_track, context) - local code = "\n if target.set_pos then\n" - code = code .. " local dst = mat4.idt()\n" + local code = " local dst = mat4.idt()\n" local lineset = raw_track.linesets[""] if not lineset then return "" end - local lineset_code = codegen_track( - raw_track, lineset, context.memoised, context.keysets, true) + local lineset_code = codegen_track(raw_track, lineset, context.keysets, true) code = code .. "\n do" .. lineset_code .. "\n end\n" - .. " set_matrix(target, dst)\n" - return code .. " end" + + if context.has_tsf then + code = code .. " set_matrix(target, dst)\n" + end + return code end local function codegen_camera_target(raw_track, context) @@ -266,25 +297,37 @@ local function codegen_camera_target(raw_track, context) if not lineset then return "" end - local lineset_code = codegen_track( - raw_track, lineset, context.memoised, context.keysets, false) + local lineset_code = codegen_track(raw_track, lineset, context.keysets, false, "camera") code = code .. "\n do" .. lineset_code .. "\n end\n" .. " target:set_zoom(zoom)\n" return code .. " end" end +local function has_transform_directive(raw_track) + for _, lineset in pairs(raw_track.linesets) do + for _, line in ipairs(lineset.lines) do + if line.channel == animation.CH_TRANSLATE or + line.channel == animation.CH_ROTATE or + line.channel == animation.CH_SCALE then + return true + end + end + end + return false +end + function internals.compile_animation_track(raw_track, track_name) local code = "" local context = { - memoised = {}, keysets = {}, curves = {}, + has_tsf = has_transform_directive(raw_track), } for name, curve in pairs(raw_track.curves) do context.curves[name] = load(string.format( "return function(kl, kr, t) return %s end", - process_expression(curve.func, context.memoised, "curve") + process_expression(curve.func, "curve") ), "", "t", env)() end @@ -292,17 +335,8 @@ function internals.compile_animation_track(raw_track, track_name) code = code .. codegen_object_target(raw_track, context) code = code .. codegen_camera_target(raw_track, context) - local memoised_code = "" - for name, expression in pairs(context.memoised) do - memoised_code = memoised_code .. "\n local " .. name .. " = " - .. expression - end - - if #memoised_code > 0 then - code = memoised_code .. "\n" .. code - end - - local src = "return function(target, t, intensity, m)\n m = m or 1\n intensity = intensity or 1.0\n" + local src = "return function(target, t, intensity, m)\n" + .. " m = m or 1\n intensity = intensity or 1.0\n" .. code .. "\nend" if animation.TRACE_CODEGEN then diff --git a/res/modules/internal/formats/vca.lua b/res/modules/internal/formats/vca.lua index 4ecf4c895..1ebac16f8 100644 --- a/res/modules/internal/formats/vca.lua +++ b/res/modules/internal/formats/vca.lua @@ -8,6 +8,9 @@ local action_to_channel = { scale = animation.CH_SCALE, zoom = animation.CH_ZOOM, texture = animation.CH_TEXTURE, + show = animation.CH_SHOW, + model = animation.CH_MODEL, + color = animation.CH_COLOR, } local curve_to_interp = { @@ -16,14 +19,18 @@ local curve_to_interp = { bezier = animation.INT_BEZIER, } +local boolean_actions = { + show = true +} + local function parse_configure(raw_track, node) if node.fps then - raw_track.fps = node.fps + raw_track.fps = tonumber(node.fps) end if node.frames then - raw_track.duration = node.frames / (node.fps or DEFAULT_FPS) + raw_track.duration = tonumber(node.frames) / (tonumber(raw_track.fps) or DEFAULT_FPS) elseif node.duration then - raw_track.duration = node.duration + raw_track.duration = tonumber(node.duration) end raw_track.rotation_order = string.upper(node["rotation-order"] or "XYZ") end @@ -62,6 +69,70 @@ local function parse_simple_frames(line, node) end end +local function parse_boolean_frames(line, node) + line.keys = {} + for j, key_node in ipairs(node) do + local keyframe = { + frame = tonumber(key_node.frame), + value = key_node.value == "on", + } + table.insert(line.keys, keyframe) + end +end + +local function parse_directive(node, raw_track) + local linesets = raw_track.linesets + local tag = node['#'] + if tag == "configure" then + parse_configure(raw_track, node) + return + elseif tag == "curve" then + raw_track.curves[node.name] = node + return + end + + local target_type = nil + if node.bone then + target_type = "bone" + elseif node.zoom then + target_type = "camera" + elseif tag == "texture" then + target_type = "texture" + end + local target_name = node.bone or node.name or "" + local lineset = linesets[target_name] + if not lineset then + lineset = { + lines = {}, + target_type = target_type, + target_name = target_name, + flag = node.flag, + } + linesets[target_name] = lineset + end + + local channel = action_to_channel[tag] + if not channel then + error("unknown directive " .. tag:escape()) + end + local line = { + axis = node.by and (("xyz"):find(node.by) or ("rgba"):find(node.by)) or "", + channel = channel, + period = node.period or animation.MAX_FRAMES + } + if node.func then + line.expression = node.func + elseif node.curve then + parse_curve(line, node) + elseif boolean_actions[tag] then + parse_boolean_frames(line, node) + else + parse_simple_frames(line, node) + end + + table.insert(lineset.lines, line) +end + local function parse_track(root) local raw_track = { duration = math.huge, @@ -69,56 +140,10 @@ local function parse_track(root) linesets = {}, curves = {}, } - local linesets = raw_track.linesets for i, node in ipairs(root) do - if type(node) == "string" then - goto continue + if type(node) == 'table' then + parse_directive(node, raw_track) end - local tag = node['#'] - if tag == "configure" then - parse_configure(raw_track, node) - goto continue - elseif tag == "curve" then - raw_track.curves[node.name] = node - goto continue - end - - local target_type = nil - if node.bone then - target_type = "bone" - elseif tag == "texture" then - target_type = "texture" - end - local target_name = node.bone or node.name or "" - local lineset = linesets[target_name] - if not lineset then - lineset = { - lines = {}, - target_type = target_type, - target_name = target_name - } - linesets[target_name] = lineset - end - - local channel = action_to_channel[tag] - if not channel then - error("unknown directive " .. tag:escape()) - end - local line = { - axis = node.by and ("xyz"):find(node.by) or "", - channel = channel, - period = node.period or animation.MAX_FRAMES - } - if node.func then - line.expression = node.func - elseif node.curve then - parse_curve(line, node) - else - parse_simple_frames(line, node) - end - - table.insert(lineset.lines, line) - ::continue:: end return raw_track end diff --git a/res/modules/internal/stream/binary.lua b/res/modules/internal/stream/binary.lua new file mode 100644 index 000000000..9d38f3b9b --- /dev/null +++ b/res/modules/internal/stream/binary.lua @@ -0,0 +1,72 @@ +local binary = {} +binary.__index = binary + +local DEFAULT_CHUNK = 8192 + +function binary.new(stream) + return setmetatable({ stream = stream }, binary) +end + +local function to_table(bytes) + local t = {} + for i = 1, #bytes do + t[i] = bytes[i] + end + return t +end + +function binary.read_all(stream) + local result = Bytearray() + local avail = stream:available() + local chunk = avail > 0 and avail or DEFAULT_CHUNK + + while true do + local part = stream:read_some(chunk) + if #part == 0 then break end + result:append(part) + end + + return result +end + +function binary:read(arg, as_table) + local t = type(arg) + + if t == "number" then + local bytes = self.stream:read(arg) + return as_table and to_table(bytes) or bytes + elseif t == "string" then + local size = byteutil.get_size(arg) + local bytes = self.stream:read(size) + if #bytes < size then + error(string.format( + "unexpected end of stream: format %q needs %d bytes, got %d", + arg, size, #bytes), 2) + end + return byteutil.unpack(arg, bytes) + elseif t == "nil" then + error("in binary mode the first argument must be a byteutil format string" + .. " or the number of bytes to read") + else + error("unknown argument type: " .. t) + end +end + +function binary:write(arg, ...) + local t = type(arg) + + if t == "string" then + self.stream:write(byteutil.pack(arg, ...)) + elseif t == "table" then + self.stream:write(Bytearray(arg)) + else + self.stream:write(arg) + end +end + +function binary:read_fully(as_table) + local bytes = binary.read_all(self.stream) + return as_table and to_table(bytes) or bytes +end + +return binary diff --git a/res/modules/internal/stream/blocking.lua b/res/modules/internal/stream/blocking.lua new file mode 100644 index 000000000..a722a733e --- /dev/null +++ b/res/modules/internal/stream/blocking.lua @@ -0,0 +1,19 @@ +local wrapper = require "internal/stream/wrapper" + +local blocking = wrapper.extend({}) + +function blocking.new(inner) + return setmetatable({ inner = inner }, blocking) +end + +function blocking:read(n) + local result = self.inner:read(n) + while #result < n do + coroutine.yield() + if not self.inner:is_alive() then break end + result:append(self.inner:read(n - #result)) + end + return result +end + +return blocking diff --git a/res/modules/internal/stream/buffered.lua b/res/modules/internal/stream/buffered.lua new file mode 100644 index 000000000..621e78ebd --- /dev/null +++ b/res/modules/internal/stream/buffered.lua @@ -0,0 +1,90 @@ +local wrapper = require "internal/stream/wrapper" + +local buffered = wrapper.extend({}) + +buffered.DEFAULT_SIZE = 8192 + +function buffered.new(inner, size, flush_inner) + return setmetatable({ + inner = inner, + size = size or buffered.DEFAULT_SIZE, + flush_inner = flush_inner ~= false, + rbuf = Bytearray(), + wbuf = Bytearray(), + }, buffered) +end + +function buffered:_take(n) + local buf = self.rbuf + if n >= #buf then + self.rbuf = Bytearray() + return buf + end + local part = buf:slice(1, n) + buf:remove(1, n) + return part +end + +function buffered:flush_buffer() + if #self.wbuf > 0 then + local data = self.wbuf + self.wbuf = Bytearray() + self.inner:write(data) + end +end + +function buffered:read(n) + local have = #self.rbuf + if have < n then + if have == 0 and n >= self.size then + return self.inner:read(n) + end + self.rbuf:append(self.inner:read(self.size - have)) + end + return self:_take(n) +end + +buffered.read_some = buffered.read + +function buffered:write(data) + if #self.wbuf + #data > self.size then + self:flush_buffer() + end + if #data >= self.size then + self.inner:write(data) + else + self.wbuf:append(data) + end +end + +function buffered:flush() + self:flush_buffer() + if self.flush_inner then + self.inner:flush() + end +end + +function buffered:available() + return self.inner:available() + #self.rbuf +end + +function buffered:seek(mode, offset) + self:flush_buffer() + if mode == "c" then + offset = offset - #self.rbuf + end + self.rbuf = Bytearray() + self.inner:seek(mode, offset) +end + +function buffered:tell() + return self.inner:tell() - #self.rbuf + #self.wbuf +end + +function buffered:close() + self:flush_buffer() + self.rbuf = Bytearray() + return self.inner:close() +end + +return buffered diff --git a/res/modules/internal/stream/raw.lua b/res/modules/internal/stream/raw.lua new file mode 100644 index 000000000..b7db77919 --- /dev/null +++ b/res/modules/internal/stream/raw.lua @@ -0,0 +1,49 @@ +local raw = {} +raw.__index = raw + +function raw.new(descriptor, io_lib) + return setmetatable({ descriptor = descriptor, io_lib = io_lib }, raw) +end + +function raw:read(n) + return self.io_lib.read(self.descriptor, n) +end + +raw.read_some = raw.read + +function raw:write(data) + self.io_lib.write(self.descriptor, data) +end + +function raw:flush() + if self.io_lib.flush then + self.io_lib.flush(self.descriptor) + elseif not self:is_alive() then + error("stream is closed") + end +end + +function raw:available() + local f = self.io_lib.available + return f and f(self.descriptor) or 0 +end + +function raw:seek(mode, offset) + if not self.io_lib.seek then error("cannot seek this stream") end + self.io_lib.seek(self.descriptor, mode, offset) +end + +function raw:tell() + if not self.io_lib.tell then error("cannot tell this stream") end + return self.io_lib.tell(self.descriptor) +end + +function raw:is_alive() + return self.io_lib.is_alive(self.descriptor) +end + +function raw:close() + return self.io_lib.close(self.descriptor) +end + +return raw diff --git a/res/modules/internal/stream/text.lua b/res/modules/internal/stream/text.lua new file mode 100644 index 000000000..835340b47 --- /dev/null +++ b/res/modules/internal/stream/text.lua @@ -0,0 +1,102 @@ +local binary = require "internal/stream/binary" + +local text = {} +text.__index = text + +local CR = string.byte('\r') +local LF = string.byte('\n') + +function text.new(stream) + return setmetatable({stream = stream}, text) +end + +function text:_read_byte() + return self.stream:read(1)[1] +end + +function text:read_line() + local line = Bytearray() + local got_any = false + + while true do + local b = self:_read_byte() + if b == nil then break end + got_any = true + + if b == LF then + break + elseif b == CR then + local nb = self:_read_byte() + if nb == LF then break end + line:append(CR) + if nb == nil then break end + line:append(nb) + else + line:append(b) + end + end + + if not got_any then return nil end + return utf8.tostring(line) +end + +local function trim_empty(lines) + while #lines > 0 and lines[#lines] == "" do + lines[#lines] = nil + end + while #lines > 0 and lines[1] == "" do + table.remove(lines, 1) + end +end + +function text:read_lines(count, trim) + if count < 0 then error("count of lines to read must be positive") end + + local lines = {} + for i = 1, count do + local line = self:read_line() + if line == nil then break end + lines[i] = line + end + + if trim ~= false then trim_empty(lines) end + return lines +end + +function text:read(count, trim) + if count == nil then + return self:read_line() + end + return self:read_lines(count, trim) +end + +function text:read_fully(as_lines) + if as_lines then + local lines = {} + for line in self.read_line, self do + lines[#lines + 1] = line + end + return lines + end + return utf8.tostring(binary.read_all(self.stream)) +end + +function text:write_line(str) + self.stream:write(utf8.tobytes(str .. "\n")) +end + +-- write(string) | write({ lines... }) +function text:write(arg) + local t = type(arg) + if t == "string" then + self:write_line(arg) + elseif t == "table" then + for i = 1, #arg do + self:write_line(arg[i]) + end + else + error("unknown argument type: " .. t) + end +end + +return text diff --git a/res/modules/internal/stream/wrapper.lua b/res/modules/internal/stream/wrapper.lua new file mode 100644 index 000000000..c6c838aff --- /dev/null +++ b/res/modules/internal/stream/wrapper.lua @@ -0,0 +1,26 @@ +local wrapper = {} +wrapper.__index = wrapper + +function wrapper.extend(cls) + cls.__index = cls + return setmetatable(cls, { __index = wrapper }) +end +function wrapper:read(n) return self.inner:read(n) end + +function wrapper:read_some(n) return self.inner:read_some(n) end + +function wrapper:write(data) return self.inner:write(data) end + +function wrapper:flush() return self.inner:flush() end + +function wrapper:available() return self.inner:available() end + +function wrapper:seek(mode, off) return self.inner:seek(mode, off) end + +function wrapper:tell() return self.inner:tell() end + +function wrapper:is_alive() return self.inner:is_alive() end + +function wrapper:close() return self.inner:close() end + +return wrapper diff --git a/res/modules/io_stream.lua b/res/modules/io_stream.lua index 8776ca810..cd318c72c 100644 --- a/res/modules/io_stream.lua +++ b/res/modules/io_stream.lua @@ -1,444 +1,108 @@ -local io_stream = { } +local raw = require "internal/stream/raw" +local buffered = require "internal/stream/buffered" +local blocking = require "internal/stream/blocking" +local binary = require "internal/stream/binary" +local text = require "internal/stream/text" +local io_stream = {} io_stream.__index = io_stream -local MAX_BUFFER_SIZE = 8192 - -local DEFAULT_MODE = "default" -local BUFFERED_MODE = "buffered" -local YIELD_MODE = "yield" - -local ALL_MODES = { - DEFAULT_MODE, - BUFFERED_MODE, - YIELD_MODE -} - -local FLUSH_MODE_ALL = "all" -local FLUSH_MODE_ONLY_BUFFER = "buffer" - -local ALL_FLUSH_MODES = { - FLUSH_MODE_ALL, - FLUSH_MODE_ONLY_BUFFER -} - -local CR = string.byte('\r') -local LF = string.byte('\n') - -local function read_fully(result, read_func) - local isTable = type(result) == "table" - - local buf - - repeat - buf = read_func(MAX_BUFFER_SIZE) - - if isTable then - for i = 1, #buf do - result[#result + 1] = buf[i] - end - else result:append(buf) end - until #buf == 0 -end - ---[[ -descriptor - descriptor of stream for provided I/O library -binaryMode - if enabled, most methods will expect bytes instead of strings -ioLib - I/O library. Should include the following functions: - read(descriptor: int, length: int) -> Bytearray - May return bytearray with a smaller size if bytes have not arrived yet or have run out - May throw error if descriptor isn't readable - write(descriptor: int, data: Bytearray) - May throw error if descriptor isn't writeable - [optional] seek(descriptor: int, mode: string, offset: int) - Mode may be 'b' (relative begin), 'c' (relative current), 'e' (relative end + 1) - [optional] tell(descriptor: int) -> int - [optional] flush(descriptor: int) - [optional] available(descriptor: int) -> int - is_alive(descriptor: int) -> bool - close(descriptor: int) ---]] +local MODES = { default = true, buffered = true, yield = true } +local FLUSH_MODES = { all = true, buffer = true } function io_stream.new(descriptor, binary_mode, io_lib, mode, flush_mode) - mode = mode or DEFAULT_MODE - flush_mode = flush_mode or FLUSH_MODE_ALL - - local self = setmetatable({}, io_stream) - - self.descriptor = descriptor - self.binary_mode = binary_mode - self.max_buffer_size = MAX_BUFFER_SIZE - self.io_lib = io_lib - - self:set_mode(mode) - self:set_flush_mode(flush_mode) + local self = setmetatable({ + descriptor = descriptor, + io_lib = io_lib, + binary_mode = binary_mode and true or false, + max_buffer_size = buffered.DEFAULT_SIZE, + }, io_stream) + self:set_flush_mode(flush_mode or "all") + self:set_mode(mode or "default") return self end -function io_stream:is_binary_mode() - return self.binary_mode +function io_stream:_rebuild() + local old = self.stream + if old and old.flush_buffer and old:is_alive() then + old:flush_buffer() + end + + local s = raw.new(self.descriptor, self.io_lib) + if self.mode == "buffered" then + s = buffered.new(s, self.max_buffer_size, self.flush_mode == "all") + elseif self.mode == "yield" then + s = blocking.new(s) + end + + self.stream = s + self.text = text.new(s) + self.binary = binary.new(s) end -function io_stream:set_binary_mode(binary_mode) - self.binary_mode = binary_mode ~= nil +function io_stream:_format() + return self.binary_mode and self.binary or self.text end -function io_stream:get_mode() - return self.mode -end +function io_stream:is_binary_mode() return self.binary_mode end +function io_stream:set_binary_mode(v) self.binary_mode = v and true or false end + +function io_stream:get_mode() return self.mode end function io_stream:set_mode(mode) - if not table.has(ALL_MODES, mode) then - error("invalid stream mode: "..mode) - end - - if self.write_buffer then - self.write_buffer:clear() - self.write_buffer = nil - end - - if self.read_buffer then - self.read_buffer:clear() - self.read_buffer = nil - end - - if mode == BUFFERED_MODE then - self.write_buffer = Bytearray(self.max_buffer_size) - self.read_buffer = Bytearray(self.max_buffer_size) - end - + if not MODES[mode] then error("invalid stream mode: " .. tostring(mode)) end self.mode = mode + self:_rebuild() end -function io_stream:get_flush_mode() - return self.flush_mode -end +function io_stream:get_flush_mode() return self.flush_mode end function io_stream:set_flush_mode(flush_mode) - if not table.has(ALL_FLUSH_MODES, flush_mode) then - error("invalid flush mode: " .. flush_mode) + if not FLUSH_MODES[flush_mode] then + error("invalid flush mode: " .. tostring(flush_mode)) end - self.flush_mode = flush_mode + if self.mode == "buffered" then + self.stream.flush_inner = flush_mode == "all" + end end -function io_stream:get_max_buffer_size() - return self.max_buffer_size +function io_stream:get_max_buffer_size() return self.max_buffer_size end + +function io_stream:set_max_buffer_size(size) + self.max_buffer_size = size + if self.mode == "buffered" then self:_rebuild() end end -function io_stream:set_max_buffer_size(max_buffer_size) - self.max_buffer_size = max_buffer_size +function io_stream:read(arg, use_table) return self:_format():read(arg, use_table) end - self.write_buffer = Bytearray(self.max_buffer_size) - self.read_buffer = Bytearray(self.max_buffer_size) -end +function io_stream:write(arg, ...) return self:_format():write(arg, ...) end + +function io_stream:read_fully(use_table) return self:_format():read_fully(use_table) end + +function io_stream:read_line() return self.text:read_line() end + +function io_stream:write_line(str) return self.text:write_line(str) end function io_stream:available(length) - local available = self.io_lib.available and self.io_lib.available(self.descriptor) or 0 - - if self.mode == BUFFERED_MODE then - available = available + #self.read_buffer - end - - if not length then - return available - else - return available >= length - end + local n = self.stream:available() + if length then return n >= length end + return n end -function io_stream:__read(length, from_read_fully) - if self.mode == YIELD_MODE then - if from_read_fully then - return self.io_lib.read(self.descriptor, length) - end +function io_stream:seek(mode, offset) return self.stream:seek(mode, offset) end - local buffer = Bytearray() +function io_stream:tell() return self.stream:tell() end - while #buffer < length do - buffer:append(self.io_lib.read(self.descriptor, length - #buffer)) +function io_stream:is_alive() return self.stream:is_alive() end - if #buffer < length then coroutine.yield() end - end +function io_stream:is_closed() return not self.stream:is_alive() end - return buffer - elseif self.mode == BUFFERED_MODE then - local buf_len = #self.read_buffer - - if buf_len < length then - self.read_buffer:append( - self.io_lib.read(self.descriptor, self.max_buffer_size - buf_len) - ) - end - - buf_len = #self.read_buffer - - length = math.min(buf_len, length) - - local copy = self.read_buffer:slice(1, length) - - if buf_len == length then - self.read_buffer:clear() - else - self.read_buffer:remove(1, length) - end - - return copy - elseif self.mode == DEFAULT_MODE then - return self.io_lib.read(self.descriptor, length) - end -end - -function io_stream:__write(data) - if self.mode == BUFFERED_MODE then - local data_length = #data - - if #self.write_buffer + data_length > self.max_buffer_size then - self:flush() - end - - if data_length > self.max_buffer_size then - local to_write = math.floor(data_length / self.max_buffer_size) * self.max_buffer_size - local to_save = data_length - to_write - - self.io_lib.write(self.descriptor, data:slice(1, to_write)) - - self:flush() - - self.write_buffer = data:slice(to_write + 1, to_save) - else self.write_buffer:append(data) end - elseif self.mode == DEFAULT_MODE or self.mode == YIELD_MODE then - return self.io_lib.write(self.descriptor, data) - end -end - -function io_stream:read_fully(use_table) - if self.binary_mode then - local result = use_table and { } or Bytearray() - - local avail = self:available() - - if avail == 0 then - avail = self.max_buffer_size - end - - read_fully(result, function() return self:__read(avail, true) end) - - return result - else - if use_table then - local lines = { } - - local line - - repeat - line = self:read_line() - - lines[#lines + 1] = line - until not line - - return lines - else - local result = Bytearray() - - read_fully(result, function() return self:__read(self.max_buffer_size) end) - - return utf8.tostring(result) - end - end -end - -function io_stream:read_line() - local result = Bytearray() - - local first = true - - while true do - local char = self:__read(1) - - if #char == 0 then - if first then return else break end - end - - char = char[1] - - if char == LF then break - elseif char == CR then - char = self:__read(1) - - if char[1] == LF then break - else - result:append(CR) - result:append(char[1]) - end - else result:append(char) end - - first = false - end - - return utf8.tostring(result) -end - -function io_stream:write_line(str) - self:__write(utf8.tobytes(str .. "\n")) -end - -function io_stream:read(arg, use_table) - local arg_type = type(arg) - - if self.binary_mode then - local byte_arr - - if arg_type == "number" then - -- using 'arg' as length - - byte_arr = self:__read(arg) - - if use_table == true then - local t = { } - - for i = 1, #byte_arr do - t[i] = byte_arr[i] - end - - return t - else - return byte_arr - end - elseif arg_type == "string" then - return byteutil.unpack( - arg, - self:__read(byteutil.get_size(arg)) - ) - elseif arg_type == "nil" then - error( - "in binary mode the first argument must be a string data format".. - " for the library \"byteutil\" or the number of bytes to read" - ) - else - error("unknown argument type: "..arg_type) - end - else - if not arg then - return self:read_line() - else - local lines_count = arg - local trim_last_empty_lines = use_table - - if use_table == nil then - trim_last_empty_lines = true - end - - if lines_count < 0 then error "count of lines to read must be positive" end - - local result = { } - - for i = 1, lines_count do - result[i] = self:read_line() - end - - if trim_last_empty_lines then - local i = #result - - while i >= 0 do - local length = utf8.length(result[i]) - - if length > 0 then break - else result[i] = nil end - - i = i - 1 - end - - local i = 1 - - while #result > 0 do - local length = utf8.length(result[i]) - - if length > 0 then break - else table.remove(result, i) end - end - end - - return result - end - end -end - -function io_stream:write(arg, ...) - local arg_type = type(arg) - - if self.binary_mode then - local byte_arr - - if arg_type ~= "string" then - -- using arg as bytes table/bytearray - - if arg_type == "table" then - byte_arr = Bytearray(arg) - else - byte_arr = arg - end - else - byte_arr = byteutil.pack(arg, ...) - end - - self:__write(byte_arr) - else - if arg_type == "string" then - self:write_line(arg) - elseif arg_type == "table" then - for i = 1, #arg do - self:write_line(arg[i]) - end - else error("unknown argument type: "..arg_type) end - end -end - -function io_stream:seek(mode, offset) - if not self.io_lib.seek then - error("cannot seek this stream") - end - - self.io_lib.seek(self.descriptor, mode, offset) -end - -function io_stream:tell() - if not self.io_lib.tell then - error("cannot tell this stream") - end - - return self.io_lib.tell(self.descriptor) -end - -function io_stream:is_alive() - return self.io_lib.is_alive(self.descriptor) -end - -function io_stream:is_closed() - return not self:is_alive() -end - -function io_stream:close() - if self.mode == BUFFERED_MODE then - self.read_buffer:clear() - self.write_buffer:clear() - end - - return self.io_lib.close(self.descriptor) -end +function io_stream:close() return self.stream:close() end function io_stream:flush() - if self.mode == BUFFERED_MODE and #self.write_buffer > 0 then - self.io_lib.write(self.descriptor, self.write_buffer) - self.write_buffer:clear() - end - - if self.flush_mode ~= FLUSH_MODE_ONLY_BUFFER then - if self.io_lib.flush then - self.io_lib.flush(self.descriptor) - elseif self:is_closed() then error("stream is closed") end - end + if self.mode ~= "buffered" and self.flush_mode == "buffer" then return end + self.stream:flush() end - -return io_stream \ No newline at end of file +return io_stream diff --git a/res/scripts/stdmin.lua b/res/scripts/stdmin.lua index e1b735478..9fe297aab 100644 --- a/res/scripts/stdmin.lua +++ b/res/scripts/stdmin.lua @@ -183,6 +183,12 @@ function on_deprecated_call(name, alternatives) end end +local __pack_envs = __vc__pack_envs +function __vc_internals.get_pack_env(packid) + return __pack_envs[packid] +end +__vc__pack_envs = nil + function reload_module(name) local prefix, name = parse_path(name) local path = prefix..":modules/"..name..".lua" @@ -196,6 +202,10 @@ function reload_module(name) if script == nil then error(err) end + local env = __pack_envs[prefix] + if env then + script = setfenv(script, env) + end local result = script() if not result then return @@ -270,12 +280,6 @@ function __vc_lock_internal_modules() __internal_locked = true end -local __pack_envs = __vc__pack_envs -function __vc_internals.get_pack_env(packid) - return __pack_envs[packid] -end -__vc__pack_envs = nil - function require(path) if not string.find(path, ':') then local prefix, _ = parse_path(_debug_getinfo(2).source) diff --git a/run.sh b/run.sh index 612f06935..4cc16d57d 100755 --- a/run.sh +++ b/run.sh @@ -31,6 +31,17 @@ function norun { } +function test { + echo "[RUN SCRIPT] Run tests" + cd build + rm -rf ./vctest-run + mkdir ./vctest-run + ./vctest/vctest --exe ./VoxelCore --res res --user ./vctest-run --tests ../dev/tests --memchecker valgrind + cd .. + run= +} + + function help { echo "[RUN SCRIPT] Usage: ./run [ARGUMENT]..." echo "[RUN SCRIPT] Arguments:" @@ -38,6 +49,7 @@ function help { echo "[RUN SCRIPT] -b, --build Build project" echo "[RUN SCRIPT] -r, --rebuild Rebuild project" echo "[RUN SCRIPT] -R, --norun Build without run" + echo "[RUN SCRIPT] -t, --test Run tests (without run)" echo "[RUN SCRIPT] -h, --help Print this page" } @@ -48,6 +60,7 @@ while [ -n "$1" ]; do -b | --build) build ;; -r | --rebuild) rebuild ;; -R | --norun) norun ;; + -t | --test) test ;; -h | --help) help norun break ;; @@ -62,5 +75,5 @@ done if [[ $run ]]; then echo "[RUN SCRIPT] Run project" - ./build/VoxelEngine -fi \ No newline at end of file + ./build/VoxelCore +fi diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 802c06e1a..8eae55c33 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,10 +1,10 @@ -project(VoxelEngineSrc) +project(VoxelCoreSrc) file(GLOB_RECURSE headers ${CMAKE_CURRENT_SOURCE_DIR}/*.hpp) file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) list(REMOVE_ITEM sources ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) -add_library(VoxelEngineSrc STATIC ${sources} ${headers}) +add_library(VoxelCoreSrc STATIC ${sources} ${headers}) find_package(OpenGL REQUIRED) find_package(GLEW REQUIRED) @@ -70,10 +70,10 @@ else() add_library(luajit::luajit ALIAS PkgConfig::luajit) endif() -target_include_directories(VoxelEngineSrc PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_include_directories(VoxelCoreSrc PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries( - VoxelEngineSrc + VoxelCoreSrc PRIVATE glfw OpenGL::GL GLEW::GLEW @@ -91,7 +91,7 @@ target_link_libraries( ) target_compile_options( - VoxelEngineSrc + VoxelCoreSrc PUBLIC $<$: /utf-8 /MP @@ -129,7 +129,7 @@ target_compile_options( >) target_link_options( - VoxelEngineSrc + VoxelCoreSrc PUBLIC $<$: -no-pie diff --git a/src/constants.hpp b/src/constants.hpp index 03900b9e3..c9fc60d32 100644 --- a/src/constants.hpp +++ b/src/constants.hpp @@ -6,7 +6,7 @@ #include inline constexpr int ENGINE_VERSION_MAJOR = 0; -inline constexpr int ENGINE_VERSION_MINOR = 32; +inline constexpr int ENGINE_VERSION_MINOR = 33; #ifdef NDEBUG inline constexpr bool ENGINE_DEBUG_BUILD = false; @@ -14,7 +14,7 @@ inline constexpr bool ENGINE_DEBUG_BUILD = false; inline constexpr bool ENGINE_DEBUG_BUILD = true; #endif // NDEBUG -inline const std::string ENGINE_VERSION_STRING = "0.32"; +inline const std::string ENGINE_VERSION_STRING = "0.33"; inline constexpr uint MAX_SUBPROCESSES = 1; inline constexpr uint MAX_SUBPROCESS_DEPTH = 2; diff --git a/src/delegates.hpp b/src/delegates.hpp index f583f951d..abd489ca2 100644 --- a/src/delegates.hpp +++ b/src/delegates.hpp @@ -8,7 +8,7 @@ using runnable = std::function; template using supplier = std::function; template using consumer = std::function; -using KeyCallback = std::function; +using InputCallback = std::function; // data sources using wstringsupplier = std::function; diff --git a/src/frontend/screens/MenuScreen.cpp b/src/frontend/screens/MenuScreen.cpp index 6472578d9..d9628ceb3 100644 --- a/src/frontend/screens/MenuScreen.cpp +++ b/src/frontend/screens/MenuScreen.cpp @@ -28,7 +28,10 @@ MenuScreen::~MenuScreen() = default; void MenuScreen::onOpen() { engine.getContentControl().resetContent({}); - auto menu = engine.getGUI().getMenu(); + auto& gui = engine.getGUI(); + gui.setActiveFrame(gui::GUI::CORE_MAIN); + + auto menu = gui.getMenu(); menu->reset(); } diff --git a/src/graphics/core/Shader.cpp b/src/graphics/core/Shader.cpp index 1c752ef5a..9dc574fa0 100644 --- a/src/graphics/core/Shader.cpp +++ b/src/graphics/core/Shader.cpp @@ -113,8 +113,6 @@ static inline auto shader_deleter = [](GLuint* shader) { delete shader; }; -inline const uint GL_LOG_LEN = 512; - // shader should be deleted after shader program linking using glshader = std::unique_ptr; @@ -125,12 +123,14 @@ glshader compile_shader(GLenum type, const GLchar* source, const std::string& fi glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { - GLchar infoLog[GL_LOG_LEN]; - glGetShaderInfoLog(shader, GL_LOG_LEN, nullptr, infoLog); + GLint infoLogLength; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength); + auto infoLog = std::make_unique(infoLogLength); + glGetShaderInfoLog(shader, infoLogLength, nullptr, infoLog.get()); glDeleteShader(shader); throw std::runtime_error( "vertex shader compilation failed (" + file + "):\n" + - std::string(infoLog) + std::string(infoLog.get(), infoLogLength) ); } return glshader(new GLuint(shader), shader_deleter); //-V508 @@ -172,10 +172,14 @@ static GLuint compile_program( glGetProgramiv(program, GL_LINK_STATUS, &success); if (!success) { - GLchar infoLog[GL_LOG_LEN]; - glGetProgramInfoLog(program, GL_LOG_LEN, nullptr, infoLog); + GLint infoLogLength; + glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength); + auto infoLog = std::make_unique(infoLogLength); + glGetProgramInfoLog(program, infoLogLength, nullptr, infoLog.get()); + glDeleteProgram(program); throw std::runtime_error( - "shader program linking failed:\n" + std::string(infoLog) + "shader program linking failed:\n" + + std::string(infoLog.get(), infoLogLength) ); } return program; diff --git a/src/graphics/render/ChunksRenderer.cpp b/src/graphics/render/ChunksRenderer.cpp index 82a7fa6d6..6cccbe3fa 100644 --- a/src/graphics/render/ChunksRenderer.cpp +++ b/src/graphics/render/ChunksRenderer.cpp @@ -22,7 +22,7 @@ static debug::Logger logger("chunks-render"); size_t ChunksRenderer::visibleChunks = 0; -static constexpr inline size_t MAX_CHUNKS_ENQUEUED_IN_FRAME = 4; +static constexpr inline size_t MAX_CHUNKS_ENQUEUED_IN_FRAME = 64; class RendererWorker : public util::Worker { BlocksRenderer renderer; @@ -197,8 +197,7 @@ void ChunksRenderer::update() { int loadDistance = settings.chunks.loadDistance.get(); - const int topN = 10; - int top = std::min(meshBuildQueue.size(), topN); + int top = std::min(meshBuildQueue.size(), MAX_CHUNKS_ENQUEUED_IN_FRAME); for (int i = 0; i < top; i++) { glm::ivec2 offset = meshBuildQueue[i]; size_t index = diff --git a/src/graphics/ui/elements/InlineFrame.cpp b/src/graphics/ui/elements/InlineFrame.cpp index 8699fd70b..acf00916e 100644 --- a/src/graphics/ui/elements/InlineFrame.cpp +++ b/src/graphics/ui/elements/InlineFrame.cpp @@ -35,8 +35,15 @@ void InlineFrame::setDocument(const std::shared_ptr& document) { root->setSize(size); - gui.postRunnable([this]() { - scripting::on_ui_open(*this->document, {}); + gui.postRunnable([weak = weak_from_this(), document]() { + auto node = weak.lock(); + if (node == nullptr) { + return; + } + if (static_cast(*node).document != document) { + return; + } + scripting::on_ui_open(*document, {}); }); } diff --git a/src/io/devices/MemoryDevice.cpp b/src/io/devices/MemoryDevice.cpp index f9f4760ee..8b0016cdf 100644 --- a/src/io/devices/MemoryDevice.cpp +++ b/src/io/devices/MemoryDevice.cpp @@ -14,8 +14,13 @@ std::filesystem::path io::MemoryDevice::resolve(std::string_view path) { std::unique_ptr io::MemoryDevice::write(std::string_view path) { std::string filePath = std::string(path); + + auto memoryStream = std::make_unique(); + memoryStream->set_sync_callback([this, filePath](std::string_view data) { + createFile(std::move(filePath), util::Buffer(data.data(), data.size())); + }); return std::make_unique( - std::make_unique(), + std::move(memoryStream), [this, filePath](auto ostream) { auto& memoryStream = dynamic_cast(*ostream); createFile(std::move(filePath), memoryStream.release()); @@ -180,6 +185,10 @@ std::unique_ptr io::MemoryDevice::list(std::string_view path } io::MemoryDevice::Dir* io::MemoryDevice::createDir(std::string path) { + const auto& found = nodes.find(path); + if (found != nodes.end()) { + return found->second.get_if(); + } io::path filePath = path; io::path parent = filePath.parent(); auto parentDir = getDir(parent.string()); @@ -195,6 +204,15 @@ io::MemoryDevice::Dir* io::MemoryDevice::createDir(std::string path) { io::MemoryDevice::Node* io::MemoryDevice::createFile( std::string path, util::Buffer&& content ) { + const auto& found = nodes.find(path); + if (found != nodes.end()) { + auto& node = found->second; + if (!node.holds_alternative()) { + return nullptr; + } + node.data = File {std::move(content)}; + return &node; + } io::path filePath = path; io::path parent = filePath.parent(); auto dir = getDir(parent.string()); diff --git a/src/io/devices/ZipFileDevice.cpp b/src/io/devices/ZipFileDevice.cpp index dce053887..f097f77f6 100644 --- a/src/io/devices/ZipFileDevice.cpp +++ b/src/io/devices/ZipFileDevice.cpp @@ -58,11 +58,20 @@ namespace { } uint32_t to_ms_dos_timestamp(const file_time_type& fileTime) { + // 1980-01-01 00:00, the earliest MS-DOS date + constexpr uint32_t DOS_EPOCH = (0 << 9 | 1 << 5 | 1) << 16; + if (fileTime == file_time_type::min()) { + return DOS_EPOCH; + } auto timePoint = time_point_cast( fileTime - file_time_type::clock::now() + system_clock::now() ); std::time_t timeT = system_clock::to_time_t(timePoint); - std::tm tm = *std::localtime(&timeT); + const std::tm* tmPtr = std::localtime(&timeT); + if (tmPtr == nullptr || tmPtr->tm_year < 80) { + return DOS_EPOCH; + } + const std::tm& tm = *tmPtr; uint16_t date = (tm.tm_year - 80) << 9 | (tm.tm_mon + 1) << 5 | tm.tm_mday; uint16_t time = (tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec / 2); return (date << 16) | time; @@ -173,7 +182,12 @@ ZipFileDevice::ZipFileDevice( entries[entry.fileName] = std::move(entry); } - for (auto& [name, _] : entries) { + std::vector names; + names.reserve(entries.size()); + for (const auto& [name, _] : entries) { + names.push_back(name); + } + for (const auto& name : names) { io::path path = name; while (!(path = path.parent()).pathPart().empty()) { @@ -184,7 +198,6 @@ ZipFileDevice::ZipFileDevice( entry.isDirectory = true; entries[path.pathPart()] = entry; } - break; } for (auto& [_, entry] : entries) { @@ -253,6 +266,9 @@ file_time_type ZipFileDevice::lastWriteTime(std::string_view path) { } bool ZipFileDevice::exists(std::string_view path) { + if (path.empty()) { + return true; + } return entries.find(std::string(path)) != entries.end(); } @@ -441,7 +457,11 @@ static size_t write_zip( void io::write_zip(const path& folder, const path& file) { ByteBuilder central_dir; auto out = io::write(file); - size_t entries = write_zip(folder.pathPart(), folder, *out, central_dir); + auto root = folder.pathPart(); + if (!root.empty() && root.back() != '/') { + root += '/'; + } + size_t entries = write_zip(root, folder, *out, central_dir); size_t central_dir_offset = out->tellp(); out->write(reinterpret_cast(central_dir.data()), central_dir.size()); diff --git a/src/io/memory_ostream.hpp b/src/io/memory_ostream.hpp index 3ff14a994..a46043ba8 100644 --- a/src/io/memory_ostream.hpp +++ b/src/io/memory_ostream.hpp @@ -3,6 +3,9 @@ #include #include #include +#include +#include +#include #include #include @@ -13,81 +16,111 @@ public: explicit memory_buffer(size_t initial_size = 64) : buffer(std::make_unique(initial_size)), capacity(initial_size) { - setp(buffer.get(), buffer.get() + initial_size); + setp(buffer.get(), buffer.get() + capacity); } std::string_view view() const { - return std::string_view(pbase(), pptr() - pbase()); + return std::string_view(pbase(), size()); } util::Buffer release() { - return {std::move(buffer), size()}; + size_t n = size(); + return {std::move(buffer), n}; } size_t size() const { - return pptr() - pbase(); + return std::max(length, position()); + } + + void set_sync_callback(std::function callback) { + on_sync = std::move(callback); } protected: int_type overflow(int_type c) override { if (c == traits_type::eof()) return traits_type::eof(); - const size_t data_size = pptr() - pbase(); - const size_t new_capacity = std::max(capacity * 2, data_size + 1); - auto new_buffer = std::make_unique(new_capacity); - - std::memcpy(new_buffer.get(), pbase(), data_size); - - buffer = std::move(new_buffer); - capacity = new_capacity; - - setp(buffer.get(), buffer.get() + new_capacity); - pbump(data_size); - + reserve(position() + 1); *pptr() = traits_type::to_char_type(c); pbump(1); - return c; } - std::streamsize xsputn(const char* s, std::streamsize count) override { - const std::streamsize avail = epptr() - pptr(); + pos_type seekoff( + off_type off, + std::ios_base::seekdir dir, + std::ios_base::openmode which + ) override { + if (!(which & std::ios_base::out)) { + return pos_type(off_type(-1)); + } + length = size(); - if (avail >= count) { - std::memcpy(pptr(), s, count); - pbump(count); - return count; + off_type base; + switch (dir) { + case std::ios_base::beg: base = 0; break; + case std::ios_base::cur: base = position(); break; + case std::ios_base::end: base = length; break; + default: return pos_type(off_type(-1)); } - std::streamsize written = 0; - if (avail > 0) { - std::memcpy(pptr(), s, avail); - written += avail; - s += avail; - count -= avail; - pbump(avail); + off_type target = base + off; + if (target < 0 || target > static_cast(length)) { + return pos_type(off_type(-1)); } + set_position(target); + return pos_type(target); + } - const size_t data_size = pptr() - pbase(); - const size_t required_capacity = data_size + count; - const size_t new_capacity = std::max(capacity * 2, required_capacity); - auto new_buffer = std::make_unique(new_capacity); - - std::memcpy(new_buffer.get(), pbase(), data_size); - std::memcpy(new_buffer.get() + data_size, s, count); - - buffer = std::move(new_buffer); - capacity = new_capacity; - - setp(buffer.get(), buffer.get() + new_capacity); - pbump(data_size + count); - written += count; - - return written; + pos_type seekpos(pos_type pos, std::ios_base::openmode which) override { + return seekoff(off_type(pos), std::ios_base::beg, which); } private: std::unique_ptr buffer; size_t capacity; + size_t length = 0; + + size_t position() const { + return pptr() - pbase(); + } + + void advance(size_t n) { + while (n > 0) { + int step = static_cast(std::min(n, INT_MAX)); + pbump(step); + n -= step; + } + } + + void set_position(size_t pos) { + setp(buffer.get(), buffer.get() + capacity); + advance(pos); + } + + void reserve(size_t required) { + if (required <= capacity) { + return; + } + size_t pos = position(); + length = size(); + + size_t new_capacity = std::max(capacity * 2, required); + auto new_buffer = std::make_unique(new_capacity); + std::memcpy(new_buffer.get(), buffer.get(), length); + + buffer = std::move(new_buffer); + capacity = new_capacity; + set_position(pos); + } + + int sync() override { + if (on_sync) { + on_sync(view()); + } + return 0; + } + + std::function on_sync; }; class memory_ostream : public std::ostream { @@ -102,6 +135,10 @@ public: util::Buffer release() { return buffer.release(); } + + void set_sync_callback(std::function callback) { + buffer.set_sync_callback(std::move(callback)); + } private: memory_buffer buffer; }; diff --git a/src/logic/scripting/lua/libs/libfile.cpp b/src/logic/scripting/lua/libs/libfile.cpp index 1bcceb6d3..61a7e2191 100644 --- a/src/logic/scripting/lua/libs/libfile.cpp +++ b/src/logic/scripting/lua/libs/libfile.cpp @@ -305,13 +305,14 @@ static int l_read_descriptor(lua::State* L) { int maxlen = lua::tointeger(L, 2); auto& stream = io_descriptors::require_input(descriptor); - if (stream.eof()) { - stream.clear(); - } util::Buffer buffer(maxlen); stream.read(buffer.data(), maxlen); - std::streamsize read_len = stream.gcount(); + std::streamsize read_len = stream.gcount(); + + if (stream.eof()) { + stream.clear(stream.rdstate() & std::ios::badbit); + } return lua::create_bytearray(L, buffer.data(), read_len); } diff --git a/src/logic/scripting/lua/libs/libinput.cpp b/src/logic/scripting/lua/libs/libinput.cpp index 68469bb23..352da415a 100644 --- a/src/logic/scripting/lua/libs/libinput.cpp +++ b/src/logic/scripting/lua/libs/libinput.cpp @@ -44,10 +44,13 @@ static int l_add_callback(lua::State* L) { auto& input = engine->getInput(); if (pos != std::string::npos) { - std::string prefix = bindname.substr(0, pos); + auto prefix = std::string_view(bindname).substr(0, pos); if (prefix == "key") { auto key = input_util::keycode_from(bindname.substr(pos + 1)); handler = input.addKeyCallback(key, actual_callback); + } else if (prefix == "mouse") { + auto mouse = input_util::mousecode_from(bindname.substr(pos + 1)); + handler = input.addMouseCallback(mouse, actual_callback); } } diff --git a/src/logic/scripting/lua/lua_util.cpp b/src/logic/scripting/lua/lua_util.cpp index 6457911b0..d1ca02473 100644 --- a/src/logic/scripting/lua/lua_util.cpp +++ b/src/logic/scripting/lua/lua_util.cpp @@ -263,7 +263,7 @@ runnable lua::create_runnable(State* L) { }; } -KeyCallback lua::create_simple_handler(State* L) { +InputCallback lua::create_simple_handler(State* L) { auto funcptr = create_lambda_handler(L); return [=]() -> bool { if (!get_from_registry(L, LAMBDAS_TABLE, *funcptr, false)) { diff --git a/src/logic/scripting/lua/lua_util.hpp b/src/logic/scripting/lua/lua_util.hpp index 61b56cef3..690fcb32d 100644 --- a/src/logic/scripting/lua/lua_util.hpp +++ b/src/logic/scripting/lua/lua_util.hpp @@ -665,7 +665,7 @@ namespace lua { } runnable create_runnable(lua::State*); - KeyCallback create_simple_handler(lua::State*); + InputCallback create_simple_handler(lua::State*); scripting::common_func create_lambda(lua::State*); scripting::common_func create_lambda_nothrow(lua::State*); diff --git a/src/logic/scripting/scripting_functional.cpp b/src/logic/scripting/scripting_functional.cpp index a6ef42a48..c71133ca8 100644 --- a/src/logic/scripting/scripting_functional.cpp +++ b/src/logic/scripting/scripting_functional.cpp @@ -99,14 +99,21 @@ template std::function create_supplier( const scriptenv& env, const std::string& src, const std::string& file ) { - return [=]() { + return [=, errorLogged = false]() mutable { + lua::stackguard guard(lua::get_main_state()); if (auto L = process_callback(env, src, file)) { - if (lua::isfunction(L, -1)) { - lua::call_nothrow(L, 0); + if (lua::isfunction(L, -1) && !lua::call_nothrow(L, 0)) { + return T {}; + } + try { + return tovalueFunc(L, -1); + } catch (const std::exception& err) { + if (!errorLogged) { + logger.error() << "supplier " << util::quote(src) << ": " + << err.what(); + errorLogged = true; + } } - auto str = tovalueFunc(L, -1); - lua::pop(L); - return str; } return T {}; }; @@ -158,16 +165,33 @@ int_array_consumer scripting::create_int_array_consumer( vec2supplier scripting::create_vec2_supplier( const scriptenv& env, const std::string& src, const std::string& file ) { - return [=]() { - if (auto L = process_callback(env, src, file)) { - if (lua::isfunction(L, -1)) { - lua::call_nothrow(L, 0); + return [=, errorLogged = false]() mutable { + auto L = lua::get_main_state(); + lua::stackguard guard(L); + int top = lua::gettop(L); + if (process_callback(env, src, file)) { + if (lua::isfunction(L, -1) && !lua::call_nothrow(L, 0)) { + return glm::vec2(0, 0); + } + if (lua::gettop(L) - top < 2) { + if (!errorLogged) { + logger.error() << "supplier " << util::quote(src) + << ": two numbers expected"; + errorLogged = true; + } + return glm::vec2(0, 0); + } + try { + auto y = lua::tonumber(L, -1); + auto x = lua::tonumber(L, -2); + return glm::vec2(x, y); + } catch (const std::exception& err) { + if (!errorLogged) { + logger.error() << "supplier " << util::quote(src) << ": " + << err.what(); + errorLogged = true; + } } - auto y = lua::tonumber(L, -1); - lua::pop(L); - auto x = lua::tonumber(L, -1); - lua::pop(L); - return glm::vec2(x, y); } return glm::vec2(0, 0); }; diff --git a/src/objects/Entities.cpp b/src/objects/Entities.cpp index c2ce479c6..c231a91cd 100644 --- a/src/objects/Entities.cpp +++ b/src/objects/Entities.cpp @@ -328,14 +328,17 @@ void Entities::preparePhysics(float delta) { auto view = registry->view(); for (auto [entity, eid, rigidbody] : view.each()) { auto bodyType = rigidbody.hitbox.type; - if (eid.destroyFlag || !rigidbody.enabled || bodyType == BodyType::STATIC) { + if (eid.destroyFlag || !rigidbody.enabled) { continue; } + rigidbody.hitbox.selectable = rigidbody.selectable; rigidbody.hitbox.mass = bodyType == BodyType::DYNAMIC ? rigidbody.mass : std::numeric_limits::infinity(); rigidbody.hitbox.elasticity = rigidbody.elasticity; - rigidbody.hitbox.selectable = rigidbody.selectable; + if (bodyType == BodyType::STATIC) { + continue; + } hitboxes.emplace_back(&rigidbody.hitbox); if (!eid.def.solid) { continue; @@ -477,15 +480,17 @@ void Entities::render( const Frustum* frustum, entityid_t fpsEntity ) { - auto view = registry->view(); - for (auto [entity, eid, transform, skeleton] : view.each()) { + auto view = registry->view(); + for (auto [entity, eid, transform, skeleton, rigidbody] : view.each()) { if (eid.uid == fpsEntity) { continue; } const auto& def = eid.def; const auto& pos = transform.pos; const auto& size = transform.size; - if (frustum && !frustum->isBoxVisible(pos - size, pos + size)) { + const auto& halfSize = rigidbody.hitbox.getHalfSize(); + // todo: more correct frustum culling + if (frustum && !frustum->isBoxVisible(pos - halfSize, pos + halfSize)) { continue; } diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index ca168a064..08b39bd07 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -216,10 +216,17 @@ public: return bindings; } - ObserverHandler addKeyCallback(Keycode key, KeyCallback callback) override { + ObserverHandler addKeyCallback(Keycode key, InputCallback callback) override { return keyCallbacks[key].add(std::move(callback)); } + ObserverHandler addMouseCallback(Mousecode button, InputCallback callback) override { + return addKeyCallback( + static_cast(MOUSE_KEYS_OFFSET + static_cast(button)), + std::move(callback) + ); + } + const std::vector& getPressedKeys() const override { return pressedKeys; } diff --git a/src/window/input.hpp b/src/window/input.hpp index 59d663672..839eeca96 100644 --- a/src/window/input.hpp +++ b/src/window/input.hpp @@ -288,12 +288,13 @@ public: virtual const Bindings& getBindings() const = 0; - virtual ObserverHandler addKeyCallback(Keycode key, KeyCallback callback) = 0; + virtual ObserverHandler addKeyCallback(Keycode key, InputCallback callback) = 0; + virtual ObserverHandler addMouseCallback(Mousecode button, InputCallback callback) = 0; virtual const std::vector& getPressedKeys() const = 0; virtual const std::vector& getCodepoints() const = 0; - ObserverHandler addCallback(const std::string& name, KeyCallback callback) { + ObserverHandler addCallback(const std::string& name, InputCallback callback) { return getBindings().require(name).onactived.add(callback); } }; diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index e2aae2a74..708fb8da1 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -1,22 +1,22 @@ -project(VoxelEngineTest) +project(VoxelCoreTest) file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) find_package(GTest) -add_executable(VoxelEngineTest ${sources}) +add_executable(VoxelCoreTest ${sources}) -target_link_libraries(VoxelEngineTest PRIVATE VoxelEngineSrc GTest::gtest_main) +target_link_libraries(VoxelCoreTest PRIVATE VoxelCoreSrc GTest::gtest_main) # HACK: copy res to test/ folder for fixing problem compatibility MultiConfig # and non MultiConfig builds. Delete in future and use only root res folder Also # this resolve problem with ctests, because it set cwd to # ${CMAKE_CURRENT_BINARY_DIR} add_custom_command( - TARGET VoxelEngineTest + TARGET VoxelCoreTest POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different ${CMAKE_SOURCE_DIR}/res ${CMAKE_CURRENT_BINARY_DIR}/res) include(GoogleTest) -gtest_discover_tests(VoxelEngineTest) +gtest_discover_tests(VoxelCoreTest) diff --git a/test/io/memory_ostream.cpp b/test/io/memory_ostream.cpp new file mode 100644 index 000000000..c1f83e0f8 --- /dev/null +++ b/test/io/memory_ostream.cpp @@ -0,0 +1,22 @@ +#include + +#include "io/memory_ostream.hpp" + +TEST(io, memory_ostream) { + const char data[] = "Hello, world!"; + const int n = std::strlen(data); + + memory_ostream stream; + ASSERT_TRUE(stream.good()); + + stream.write(data, n); + ASSERT_EQ(std::string(stream.view()), std::string(data)); + + stream.seekp(0); + ASSERT_TRUE(stream.good()); + stream.write("Remove", 6); + ASSERT_EQ(std::string(stream.view()), "Remove world!"); + + auto buffer = stream.release(); + ASSERT_EQ(std::string(buffer.data(), buffer.size()), "Remove world!"); +} diff --git a/test/network/curltest.cpp b/test/network/curltest.cpp index e7fc4840d..44a5bb38e 100644 --- a/test/network/curltest.cpp +++ b/test/network/curltest.cpp @@ -8,7 +8,7 @@ TEST(curltest, curltest) { auto network = network::Network::create(settings); network::HttpRequest request {}; - request.url = "https://raw.githubusercontent.com/MihailRis/VoxelEngine-Cpp/refs/" + request.url = "https://raw.githubusercontent.com/MihailRis/voxelcore/refs/" "heads/curl/res/content/base/blocks/lamp.json"; request.onResponse = [](network::HttpResponse response) { if (response.body.empty()) {