From fd17ce32ab85412db3c9ed644a6505c81ab17e83 Mon Sep 17 00:00:00 2001 From: Andrey Tazetdinov Date: Wed, 14 Oct 2026 16:35:21 +0200 Subject: [PATCH 1/3] optimize animator --- doc/en/scripting/ecs.md | 4 + doc/ru/scripting/ecs.md | 4 + res/modules/internal/animation_codegen.lua | 91 +++++++++- res/modules/internal/stdcomp.lua | 2 + src/animation/rigging.hpp | 1 + src/frontend/screens/LevelScreen.cpp | 1 + src/graphics/render/WorldRenderer.cpp | 12 ++ src/graphics/render/WorldRenderer.hpp | 1 + .../scripting/lua/libs/lib__skeleton.cpp | 165 ++++++++++++++++++ src/objects/Entities.cpp | 13 ++ src/objects/Entities.hpp | 2 + 11 files changed, 294 insertions(+), 2 deletions(-) diff --git a/doc/en/scripting/ecs.md b/doc/en/scripting/ecs.md index 0968e2d8d..52396d554 100644 --- a/doc/en/scripting/ecs.md +++ b/doc/en/scripting/ecs.md @@ -191,6 +191,10 @@ rig:set_visible(status: bool) -- Sets the visibility status of a bone by index rig:set_visible(index: int, status: bool) +-- Checks if the entity is out of the camera view in this frame +-- (updated before on_render) +rig:is_culled() -> bool + -- Returns the color of the entity rig:get_color() -> vec4 -- Return the color of the bone by index diff --git a/doc/ru/scripting/ecs.md b/doc/ru/scripting/ecs.md index fb03721c6..2c6d7a96c 100644 --- a/doc/ru/scripting/ecs.md +++ b/doc/ru/scripting/ecs.md @@ -180,6 +180,10 @@ rig:set_visible(status: bool) -- Устанавливает статус видимости кости по индексу rig:set_visible(index: int, status: bool) +-- Проверяет, находится ли сущность вне поля зрения камеры в этом кадре +-- (обновляется перед on_render) +rig:is_culled() -> bool + -- Возвращает цвет сущности rig:get_color() -> vec4 -- Возвращает цвет кости по индексу diff --git a/res/modules/internal/animation_codegen.lua b/res/modules/internal/animation_codegen.lua index 525240f66..6e11006ac 100644 --- a/res/modules/internal/animation_codegen.lua +++ b/res/modules/internal/animation_codegen.lua @@ -5,6 +5,9 @@ local INT_BEZIER = animation.INT_BEZIER local bezier_interpolation = animation.maths.bezier_interpolation +local register_track = __skeleton and __skeleton.register_track +local MAX_NATIVE_VALUES = 150 + local patterns = {} local exclude_patters = { "end", @@ -121,7 +124,8 @@ local env = { end end end, - dump = debug.print + dump = debug.print, + apply_track = __skeleton and __skeleton.apply_track, } local math_funcs = { @@ -245,6 +249,85 @@ local function codegen_rig_target(raw_track, context) return code .. " end" end +-- the same as codegen_rig_target for the entities' skeletons: one +-- apply_track call instead of the matrix calls of every bone +local function codegen_native_rig_target(raw_track, context, track_name) + if not register_track or not track_name then + return nil + end + local layout = {} + local values = 0 + local code = "" + local axis_indices = {X=1, Y=2, Z=3} + local rotation_order = raw_track.rotation_order or "XYZ" + for bone, lineset in pairs(raw_track.linesets) do + 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, false) + local exports = "" + if lineset.target_type == "bone" then + -- the last line of a channel and axis wins, as in codegen_track + local channels = { + [animation.CH_TRANSLATE] = {}, + [animation.CH_ROTATE] = {}, + [animation.CH_SCALE] = {}, + } + for i, line in ipairs(lineset.lines) do + local by_axis = channels[line.channel] + if by_axis and type(line.axis) == "number" then + by_axis[line.axis] = i + end + end + local function export(i) + values = values + 1 + exports = exports .. string.format("\n v%d = l%d", values, i) + return values + end + local entry = {name = bone} + local function vector(by_axis) + if not (by_axis[1] or by_axis[2] or by_axis[3]) then + return nil + end + local v = {0, 0, 0} + for axis = 1, 3 do + if by_axis[axis] then v[axis] = export(by_axis[axis]) end + end + return v + end + entry.t = vector(channels[animation.CH_TRANSLATE]) + local rotation = channels[animation.CH_ROTATE] + for i = 1, 3 do + local axis = axis_indices[rotation_order[i]] + if rotation[axis] then + entry.r = entry.r or {} + table.insert(entry.r, axis - 1) + table.insert(entry.r, export(rotation[axis])) + end + end + entry.s = vector(channels[animation.CH_SCALE]) + if entry.t or entry.r or entry.s then + table.insert(layout, entry) + end + end + code = code .. "\n do" .. lineset_code .. exports .. "\n end\n" + ::continue:: + end + if values > MAX_NATIVE_VALUES then + return nil + end + local id = register_track(track_name, layout) + local names = {} + for i = 1, values do + names[i] = "v" .. i + end + local args = #names > 0 and (", " .. table.concat(names, ", ")) or "" + local declare = #names > 0 and ("\n local " .. table.concat(names, ", ")) or "" + return "\n if target.__native_rig then" .. declare .. code + .. string.format(" apply_track(target.eid, %d%s)\n", id, args) +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" @@ -288,7 +371,11 @@ function internals.compile_animation_track(raw_track, track_name) ), "", "t", env)() end - code = code .. codegen_rig_target(raw_track, context) + local native = codegen_native_rig_target(raw_track, context, track_name) + local rig = codegen_rig_target(raw_track, context) + rig = native .. " elseif" .. rig:sub(5) + end + code = code .. rig code = code .. codegen_object_target(raw_track, context) code = code .. codegen_camera_target(raw_track, context) diff --git a/res/modules/internal/stdcomp.lua b/res/modules/internal/stdcomp.lua index dfea2e7c9..65048629f 100644 --- a/res/modules/internal/stdcomp.lua +++ b/res/modules/internal/stdcomp.lua @@ -48,6 +48,7 @@ local function new_Rigidbody(eid) end local Skeleton = {__index={ + __native_rig=true, get_model=function(self, i) return __skeleton.get_model(self.eid, i) end, set_model=function(self, i, s) return __skeleton.set_model(self.eid, i, s) end, get_matrix=function(self, i, ...) return __skeleton.get_matrix(self.eid, i, ...) end, @@ -61,6 +62,7 @@ local Skeleton = {__index={ get_color=function(self, ...) return __skeleton.get_color(self.eid, ...) end, set_color=function(self, color, ...) return __skeleton.set_color(self.eid, color, ...) end, set_interpolated=function(self, b) return __skeleton.set_interpolated(self.eid, b) end, + is_culled=function(self) return __skeleton.is_culled(self.eid) end, }} local function new_Skeleton(eid) diff --git a/src/animation/rigging.hpp b/src/animation/rigging.hpp index 35d7fd01b..af19810cc 100644 --- a/src/animation/rigging.hpp +++ b/src/animation/rigging.hpp @@ -96,6 +96,7 @@ namespace rigging { std::unordered_map textures; std::vector modelOverrides; bool visible; + bool culled = false; glm::vec4 tint {1.0f, 1.0f, 1.0f, 1.0f}; std::vector boneTints; diff --git a/src/frontend/screens/LevelScreen.cpp b/src/frontend/screens/LevelScreen.cpp index e6f1a0d7e..44fd66d8c 100644 --- a/src/frontend/screens/LevelScreen.cpp +++ b/src/frontend/screens/LevelScreen.cpp @@ -270,6 +270,7 @@ void LevelScreen::draw(float delta) { const DrawContext ctx(nullptr, engine.getWindow(), batch.get()); if (!hud->isPause()) { + renderer->updateEntitiesCulling(camera); scripting::on_entities_render(engine.getTime().getDelta()); scripting::on_frontend_render(); } diff --git a/src/graphics/render/WorldRenderer.cpp b/src/graphics/render/WorldRenderer.cpp index 27dd4dcdd..9e8f6353b 100644 --- a/src/graphics/render/WorldRenderer.cpp +++ b/src/graphics/render/WorldRenderer.cpp @@ -329,6 +329,18 @@ void WorldRenderer::renderInWorldLines( } } +void WorldRenderer::updateEntitiesCulling(const Camera& camera) { + bool culling = engine.getSettings().graphics.frustumCulling.get(); + if (culling) { + frustumCulling->update(camera.getProjView()); + } + level.entities->updateCulling( + culling ? frustumCulling.get() : nullptr, + player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() + : 0 + ); +} + void WorldRenderer::update(const Camera& camera, float delta) { timer += delta; chunksRenderer->update(); diff --git a/src/graphics/render/WorldRenderer.hpp b/src/graphics/render/WorldRenderer.hpp index b3b10f88c..243fe8b94 100644 --- a/src/graphics/render/WorldRenderer.hpp +++ b/src/graphics/render/WorldRenderer.hpp @@ -46,6 +46,7 @@ public: ~WorldRenderer(); void update(const Camera& camera, float delta); + void updateEntitiesCulling(const Camera& camera); void renderFrame( const DrawContext& context, diff --git a/src/logic/scripting/lua/libs/lib__skeleton.cpp b/src/logic/scripting/lua/libs/lib__skeleton.cpp index c1004434f..21dfa4ccc 100644 --- a/src/logic/scripting/lua/libs/lib__skeleton.cpp +++ b/src/logic/scripting/lua/libs/lib__skeleton.cpp @@ -5,6 +5,9 @@ #include "graphics/render/WorldRenderer.hpp" #include "graphics/render/NamedSkeletons.hpp" +#include +#include + namespace scripting { extern WorldRenderer* renderer; } @@ -196,6 +199,165 @@ static int l_exists(lua::State* L) { return lua::pushboolean(L, get_skeleton(L)); } +namespace { + struct NativeTrackBone { + std::string name; + bool translate = false; + int translation[3] {}; + std::vector> rotations; + bool scale = false; + int scaling[3] {}; + }; + + struct NativeTrack { + std::string name; + std::vector bones; + int valuesCount = 0; + std::weak_ptr config; + std::vector indices; + }; + + std::vector native_tracks; +} + +static void read_indices(lua::State* L, int idx, const char* field, int* dst) { + lua_getfield(L, idx, field); + if (lua_istable(L, -1)) { + for (int i = 0; i < 3; i++) { + lua_rawgeti(L, -1, i + 1); + dst[i] = static_cast(lua_tointeger(L, -1)); + lua_pop(L, 1); + } + } + lua_pop(L, 1); +} + +static int l_register_track(lua::State* L) { + NativeTrack track; + track.name = lua::require_string(L, 1); + if (!lua_istable(L, 2)) { + throw std::runtime_error("layout table expected"); + } + int maxValue = 0; + size_t count = lua_objlen(L, 2); + for (size_t i = 1; i <= count; i++) { + lua_rawgeti(L, 2, static_cast(i)); + int bone = lua_gettop(L); + NativeTrackBone entry; + lua_getfield(L, bone, "name"); + entry.name = lua::require_string(L, -1); + lua_pop(L, 1); + + lua_getfield(L, bone, "t"); + entry.translate = lua_istable(L, -1); + lua_pop(L, 1); + read_indices(L, bone, "t", entry.translation); + + lua_getfield(L, bone, "s"); + entry.scale = lua_istable(L, -1); + lua_pop(L, 1); + read_indices(L, bone, "s", entry.scaling); + + lua_getfield(L, bone, "r"); + if (lua_istable(L, -1)) { + size_t n = lua_objlen(L, -1); + for (size_t j = 1; j + 1 <= n; j += 2) { + lua_rawgeti(L, -1, static_cast(j)); + int axis = static_cast(lua_tointeger(L, -1)); + lua_rawgeti(L, -2, static_cast(j + 1)); + int value = static_cast(lua_tointeger(L, -1)); + lua_pop(L, 2); + if (axis < 0 || axis > 2) { + throw std::runtime_error("invalid rotation axis"); + } + entry.rotations.emplace_back(axis, value); + } + } + lua_pop(L, 1); + for (int v : entry.translation) maxValue = std::max(maxValue, v); + for (int v : entry.scaling) maxValue = std::max(maxValue, v); + for (auto [_, v] : entry.rotations) maxValue = std::max(maxValue, v); + track.bones.push_back(std::move(entry)); + lua_pop(L, 1); + } + track.valuesCount = maxValue; + for (size_t i = 0; i < native_tracks.size(); i++) { + if (native_tracks[i].name == track.name) { + native_tracks[i] = std::move(track); + return lua::pushinteger(L, static_cast(i)); + } + } + native_tracks.push_back(std::move(track)); + return lua::pushinteger(L, native_tracks.size() - 1); +} + +static int l_apply_track(lua::State* L) { + auto skeleton = get_skeleton(L); + if (skeleton == nullptr || skeleton->config == nullptr) { + return 0; + } + auto id = lua_tointeger(L, 2); + if (id < 0 || static_cast(id) >= native_tracks.size()) { + throw std::runtime_error("invalid track id"); + } + auto& track = native_tracks[id]; + const auto& config = skeleton->config; + if (track.config.owner_before(config) || config.owner_before(track.config) || + track.config.expired() || track.indices.size() != track.bones.size()) { + track.config = config; + track.indices.clear(); + for (const auto& bone : track.bones) { + auto found = config->find(bone.name); + track.indices.push_back(found ? static_cast(found->getIndex()) : -1); + } + } + constexpr int MAX_VALUES = 256; + float values[MAX_VALUES + 1] {}; + int top = lua_gettop(L); + int count = std::min({track.valuesCount, top - 2, MAX_VALUES}); + for (int i = 1; i <= count; i++) { + values[i] = static_cast(lua_tonumber(L, i + 2)); + } + static const glm::vec3 AXES[] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; + auto value = [&values](int index, float fallback) { + return index > 0 && index <= MAX_VALUES ? values[index] : fallback; + }; + auto& matrices = skeleton->pose.matrices; + for (size_t i = 0; i < track.bones.size(); i++) { + int index = track.indices[i]; + if (index < 0 || static_cast(index) >= matrices.size()) { + continue; + } + const auto& bone = track.bones[i]; + auto& matrix = matrices[index]; + if (bone.translate) { + matrix = glm::translate(matrix, glm::vec3( + value(bone.translation[0], 0.0f), + value(bone.translation[1], 0.0f), + value(bone.translation[2], 0.0f) + )); + } + for (const auto& [axis, v] : bone.rotations) { + matrix = glm::rotate(matrix, glm::radians(value(v, 0.0f)), AXES[axis]); + } + if (bone.scale) { + matrix = glm::scale(matrix, glm::vec3( + value(bone.scaling[0], 1.0f), + value(bone.scaling[1], 1.0f), + value(bone.scaling[2], 1.0f) + )); + } + } + return 0; +} + +static int l_is_culled(lua::State* L) { + if (auto skeleton = get_skeleton(L)) { + return lua::pushboolean(L, skeleton->culled); + } + return lua::pushboolean(L, false); +} + const luaL_Reg skeletonlib[] = { {"get_model", lua::wrap}, {"set_model", lua::wrap}, @@ -212,5 +374,8 @@ const luaL_Reg skeletonlib[] = { {"is_interpolated", lua::wrap}, {"set_interpolated", lua::wrap}, {"exists", lua::wrap}, + {"is_culled", lua::wrap}, + {"register_track", lua::wrap}, + {"apply_track", lua::wrap}, {nullptr, nullptr} }; diff --git a/src/objects/Entities.cpp b/src/objects/Entities.cpp index c231a91cd..ab52da6fe 100644 --- a/src/objects/Entities.cpp +++ b/src/objects/Entities.cpp @@ -509,6 +509,19 @@ void Entities::render( } } +void Entities::updateCulling(const Frustum* frustum, entityid_t fpsEntity) { + auto view = registry->view(); + for (auto [entity, eid, transform, skeleton, rigidbody] : view.each()) { + if (frustum == nullptr || eid.uid == fpsEntity) { + skeleton.culled = false; + continue; + } + const auto& pos = transform.pos; + const auto& halfSize = rigidbody.hitbox.getHalfSize(); + skeleton.culled = !frustum->isBoxVisible(pos - halfSize, pos + halfSize); + } +} + bool Entities::hasBlockingInside(AABB aabb) { constexpr float eps = 0.05f; auto view = registry->view(); diff --git a/src/objects/Entities.hpp b/src/objects/Entities.hpp index 382790b95..c1e8bb11b 100644 --- a/src/objects/Entities.hpp +++ b/src/objects/Entities.hpp @@ -67,6 +67,8 @@ public: entityid_t fpsEntity ); + void updateCulling(const Frustum* frustum, entityid_t fpsEntity); + entityid_t spawn( const EntityDef& def, glm::vec3 position, From 05f978278687b3568cd7e5808f99d04bf377de8e Mon Sep 17 00:00:00 2001 From: Andrey Tazetdinov Date: Wed, 14 Oct 2026 16:46:12 +0200 Subject: [PATCH 2/3] track groups --- res/modules/internal/animation_codegen.lua | 78 ++++++++++++++-------- 1 file changed, 51 insertions(+), 27 deletions(-) diff --git a/res/modules/internal/animation_codegen.lua b/res/modules/internal/animation_codegen.lua index 6e11006ac..f9180297d 100644 --- a/res/modules/internal/animation_codegen.lua +++ b/res/modules/internal/animation_codegen.lua @@ -6,7 +6,7 @@ local INT_BEZIER = animation.INT_BEZIER local bezier_interpolation = animation.maths.bezier_interpolation local register_track = __skeleton and __skeleton.register_track -local MAX_NATIVE_VALUES = 150 +local NATIVE_GROUP_VALUES = 32 local patterns = {} local exclude_patters = { @@ -249,26 +249,44 @@ local function codegen_rig_target(raw_track, context) return code .. " end" end --- the same as codegen_rig_target for the entities' skeletons: one --- apply_track call instead of the matrix calls of every bone + local function codegen_native_rig_target(raw_track, context, track_name) if not register_track or not track_name then return nil end - local layout = {} - local values = 0 - local code = "" local axis_indices = {X=1, Y=2, Z=3} local rotation_order = raw_track.rotation_order or "XYZ" + local code = "" + local groups = 0 + local group = {layout = {}, code = "", values = 0} + + local function flush() + if #group.layout > 0 then + local id = register_track(track_name .. "#" .. groups, group.layout) + groups = groups + 1 + local names = {} + for i = 1, group.values do + names[i] = "v" .. i + end + local declare = #names > 0 and ("\n local " .. table.concat(names, ", ")) or "" + local args = #names > 0 and (", " .. table.concat(names, ", ")) or "" + code = code .. "\n do" .. declare .. group.code + .. string.format(" apply_track(target.eid, %d%s)\n end\n", id, args) + else + code = code .. group.code + end + group = {layout = {}, code = "", values = 0} + end + for bone, lineset in pairs(raw_track.linesets) do 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, false) - local exports = "" + local exported = {} + local entry = {name = bone} if lineset.target_type == "bone" then - -- the last line of a channel and axis wins, as in codegen_track local channels = { [animation.CH_TRANSLATE] = {}, [animation.CH_ROTATE] = {}, @@ -281,11 +299,9 @@ local function codegen_native_rig_target(raw_track, context, track_name) end end local function export(i) - values = values + 1 - exports = exports .. string.format("\n v%d = l%d", values, i) - return values + table.insert(exported, i) + return #exported end - local entry = {name = bone} local function vector(by_axis) if not (by_axis[1] or by_axis[2] or by_axis[3]) then return nil @@ -307,25 +323,32 @@ local function codegen_native_rig_target(raw_track, context, track_name) end end entry.s = vector(channels[animation.CH_SCALE]) - if entry.t or entry.r or entry.s then - table.insert(layout, entry) + end + if group.values + #exported > NATIVE_GROUP_VALUES then + flush() + end + local offset = group.values + local exports = "" + for k, line in ipairs(exported) do + exports = exports .. string.format("\n v%d = l%d", offset + k, line) + end + for _, v in pairs({t = entry.t, s = entry.s}) do + for axis = 1, 3 do + if v[axis] > 0 then v[axis] = v[axis] + offset end end end - code = code .. "\n do" .. lineset_code .. exports .. "\n end\n" + for i = 2, #(entry.r or {}), 2 do + entry.r[i] = entry.r[i] + offset + end + group.values = offset + #exported + group.code = group.code .. "\n do" .. lineset_code .. exports .. "\n end\n" + if entry.t or entry.r or entry.s then + table.insert(group.layout, entry) + end ::continue:: end - if values > MAX_NATIVE_VALUES then - return nil - end - local id = register_track(track_name, layout) - local names = {} - for i = 1, values do - names[i] = "v" .. i - end - local args = #names > 0 and (", " .. table.concat(names, ", ")) or "" - local declare = #names > 0 and ("\n local " .. table.concat(names, ", ")) or "" - return "\n if target.__native_rig then" .. declare .. code - .. string.format(" apply_track(target.eid, %d%s)\n", id, args) + flush() + return "\n if target.__native_rig then" .. code end local function codegen_object_target(raw_track, context) @@ -373,6 +396,7 @@ function internals.compile_animation_track(raw_track, track_name) local native = codegen_native_rig_target(raw_track, context, track_name) local rig = codegen_rig_target(raw_track, context) + if native then rig = native .. " elseif" .. rig:sub(5) end code = code .. rig From bab63edcb284fc43dfe0935375c47308c5cad0f9 Mon Sep 17 00:00:00 2001 From: Andrey Tazetdinov Date: Wed, 14 Oct 2026 17:19:00 +0200 Subject: [PATCH 3/3] fix MSVC build --- src/logic/scripting/lua/libs/lib__skeleton.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/logic/scripting/lua/libs/lib__skeleton.cpp b/src/logic/scripting/lua/libs/lib__skeleton.cpp index 21dfa4ccc..a9a4709c8 100644 --- a/src/logic/scripting/lua/libs/lib__skeleton.cpp +++ b/src/logic/scripting/lua/libs/lib__skeleton.cpp @@ -218,6 +218,8 @@ namespace { }; std::vector native_tracks; + + constexpr int MAX_TRACK_VALUES = 256; } static void read_indices(lua::State* L, int idx, const char* field, int* dst) { @@ -311,16 +313,15 @@ static int l_apply_track(lua::State* L) { track.indices.push_back(found ? static_cast(found->getIndex()) : -1); } } - constexpr int MAX_VALUES = 256; - float values[MAX_VALUES + 1] {}; + float values[MAX_TRACK_VALUES + 1] {}; int top = lua_gettop(L); - int count = std::min({track.valuesCount, top - 2, MAX_VALUES}); + int count = std::min({track.valuesCount, top - 2, MAX_TRACK_VALUES}); for (int i = 1; i <= count; i++) { values[i] = static_cast(lua_tonumber(L, i + 2)); } static const glm::vec3 AXES[] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; auto value = [&values](int index, float fallback) { - return index > 0 && index <= MAX_VALUES ? values[index] : fallback; + return index > 0 && index <= MAX_TRACK_VALUES ? values[index] : fallback; }; auto& matrices = skeleton->pose.matrices; for (size_t i = 0; i < track.bones.size(); i++) {