Commit graph

4 commits

Author SHA1 Message Date
Eduardo Dantas
b0092a9b87
feat(pvp): add Expert PvP world type and combat rules (#4033)
Add Expert PvP world type and combat rules

This commit adds Expert Open PvP support to Canary as an explicit world type through worldType = expert-pvp.

The implementation introduces a dedicated ExpertPvp component for Expert specific combat, relation, field, movement, collision, and marking rules. Existing combat, spell, tile, player, game, and protocol code remain as thin integration points, while the Expert PvP decisions live under src creatures players components pvp.

This keeps the new behavior isolated from the existing world types and avoids spreading Expert PvP specific rules across unrelated systems.

The existing PvP world type handling was also clarified. retro-pvp is now the explicit Retro Open PvP value, while pvp remains supported as a compatibility alias for retro-pvp. no-pvp and pvp-enforced remain outside the Expert PvP decision path.

Main world type changes

• Adds worldType expert-pvp

• Makes retro-pvp the explicit Retro Open PvP config value

• Keeps pvp as a compatibility alias for retro-pvp

• Changes the default config value from pvp to retro-pvp

• Removes the old toggleServerIsRetroPVP config option

• Updates Lua helpers so IsRetroPVP reads the world type string

• Adds IsExpertPVP for Lua scripts

• Keeps no-pvp and pvp-enforced behavior outside the Expert PvP component

The ExpertPvp component centralizes relation classification and decision making for the new world type. It evaluates PvP mode, actor and target relation, combat action type, field ownership, side effects, player collision, and viewer specific situation marks.

The component covers relations such as self, access players, party allies, guild allies, war enemies, direct attackers, protected ally attackers, direct targets, skulled targets, neutral players, monsters, player summons, and NPCs.

Main Expert PvP rules included

• Dove mode behavior

• White Hand behavior

• Yellow Hand behavior

• Red Fist behavior

• Direct combat decisions

• Rune target decisions

• Area spell decisions

• Summon combat decisions

• Field step decisions

• Field damage decisions

• Player walkthrough decisions

• Pathfinding probe decisions

• Viewer specific field visual decisions

• Viewer relative creature situation marks

Combat integration now asks ExpertPvp before allowing Expert PvP relevant actions. This applies to direct attacks, runes, aggressive area spells, mana and health combat, conditions, dispels, default combat actions, and field damage.

When Expert PvP handles an action, it can allow or block the action and apply the correct side effects. These side effects include fight state, PZ lock behavior, skull actions, square feedback, and unjustified kill tracking where applicable.

Secure mode behavior is handled through the Expert PvP relation rules instead of the older broad secure mode check. This allows secure mode retaliation without applying unjustified protection zone locks in cases where the Expert PvP relation allows the response.

Magic Wall and Wild Growth now carry Expert PvP cast time context. When Expert PvP is enabled, these fields are created as safe field variants and receive owner context so the server can evaluate relation dependent behavior later.

Magic Wall and Wild Growth changes

• Stores the field owner context when the rune is cast

• Stores the owner PvP mode at cast time

• Tracks owner targets and attackers at cast time

• Uses safe visual field items as the base item in Expert PvP

• Resolves viewer specific appearance through protocol serialization

• Evaluates collision and pathfinding from the field context

• Evaluates field stepping side effects through ExpertPvp

• Prevents Expert PvP owned safe fields from being removed like regular no-pvp safe fields

• Keeps normal no-pvp behavior for non Expert PvP worlds

Tile and pathfinding logic now consult ExpertPvp for Expert owned fields. This allows Magic Wall and Wild Growth to appear or behave differently depending on the viewer and the PvP relation, while still using the existing movement and tile query paths as the final authority.

Player walkthrough and body blocking were updated so Expert PvP can decide whether a player can walk through another player outside legacy safe zones. Party, guild, war, attacker, protected ally, and target relations are used to keep collision behavior aligned with Expert PvP hand modes.

PvP situation tracking was added so player relations can affect persistent creature marks. The server can now send viewer relative creature marks for the current client profile and refresh visible marks when relevant state changes.

Situation mark updates happen when needed for events such as party changes, guild changes, attacked player tracking, player removal, and visible relation changes.

Protocol changes

• Adds ExpertPvpModeByte as a protocol feature flag

• Enables Expert PvP mode byte support for the Tibia 11.00 profile

• Keeps Tibia 11.00 on the verified four byte Set Tactics layout

• Keeps current 15.25 on its verified three byte tactics layout

• Defaults unsupported profiles safely to Dove mode

• Avoids appending speculative PvP mode bytes to the current 15.25 profile

• Sends Expert PvP controls only when the protocol profile supports them

• Sends viewer relative creature marks only through supported packet layouts

The current 15.25 profile keeps its verified tactics payload layout and does not receive a speculative extra PvP byte. This prevents client desync or crash risk. Unsupported profiles are forced safely to Dove when Expert PvP is enabled but the protocol cannot represent the mode.

Player state now includes a dedicated PvP component. The selected Expert PvP mode is stored on the player and persisted to the database.

Persistence and database changes

• Adds PlayerPvp component

• Adds player getPvpMode and setPvpMode support

• Saves expert_pvp_mode during player save

• Loads expert_pvp_mode during player load

• Adds players.expert_pvp_mode to schema.sql

• Bumps database version to 59

• Adds migration 59 for the players.expert_pvp_mode column

• Skips the migration safely if the column already exists

Lua API support was expanded so scripts can inspect PvP state and attach field context where needed.

Lua API changes

• Adds Player getPvpMode

• Adds Player hasAttacked

• Adds Item setExpertPvpFieldContext

• Updates generated Lua API documentation

• Updates Magic Wall and Wild Growth scripts to attach Expert PvP field context

The PR also updates blessing and death loss behavior to use the new Retro PvP world type detection instead of the removed toggleServerIsRetroPVP config. This keeps existing Retro PvP behavior while moving the decision to the explicit world type model.

Additional behavior covered

• Party relation handling

• Guild relation handling

• War enemy relation handling

• Skull relation handling

• Aggressor relation handling

• Protected ally relation handling

• Field ownership behavior

• Viewer specific field visuals

• Body blocking and player collision

• Situation marks and persistent creature marks

• Defensive PZ lock behavior

• Secure mode retaliation behavior

• Blessing cost and Twist of Fate behavior under Retro PvP detection

Out of scope

• Frag sharing

• player_kills.weight schema changes

• Debug commands

• Unrelated PvP features

• Broad behavior changes to existing world types

Documentation and tests

• Adds Expert PvP implementation roadmap documentation

• Adds Expert PvP porting plan documentation

• Links the new documentation from the systems overview

• Documents the behavioral contract

• Documents the implementation roadmap

• Documents the in game regression matrix

• Adds Expert PvP unit coverage

• Adds protocol profile coverage for Expert PvP mode support

• Adds regression scenarios for all world types

Validation performed

• Built canary target

• Built canary_ut target

• Built canary_it target

• Expert PvP and protocol profile tests passed with 49 of 49 tests

• Full unit binary passed with 311 of 311 tests

• Integration binary passed with 40 of 40 tests

• Manual scenarios were exercised during implementation

• Tested secure mode retaliation

• Tested defensive PZ lock behavior

• Tested Magic Wall and Wild Growth cast time relations

• Tested viewer specific visuals and collision

• Tested situation marks

Test configuration

• Platform Windows x64

• Compiler Microsoft Visual C plus plus 19.44

• Protocol coverage Tibia 11.00 and current 15.25 profiles

Known validation note

Two isolated CTest invocations terminated during global teardown after their test bodies passed. The same behavior reproduces on the main baseline. Running the unit suite in one process passes all 311 tests.

Overall this commit adds Expert Open PvP as a gated world type with dedicated relation based combat and field rules. It keeps existing world types protected from Expert PvP behavior, persists the selected PvP mode, supports protocol safe PvP mode handling, updates Lua APIs and documentation, and adds regression coverage for the new rules.
2026-08-10 18:42:55 -03:00
Eduardo Dantas
f01b4f9060
docs(lua-api): sync screenshot signature (#4027) 2026-07-07 14:17:19 -03:00
Eduardo Dantas
48f7af828c
perf(lua): harden shared userdata and reduce refcount churn (#3987)
Port the production hardening and performance fixes tested on Avalorium into Canary.

This change fixes Lua shared-userdata ownership issues in which std::shared_ptr<T> values stored inside Lua userdata could leak or use the wrong finalizer when the assigned metatable did not match the underlying C++ type. It also reduces avoidable shared_ptr copies and shared_from_this() churn in movement, spectator, and monster hot paths.

Lua userdata fixes:
- Add typed Lua shared-userdata helpers through LuaUserdataTraits<T>.
- Add Lua::registerSharedClass<T>.
- Add Lua::pushSharedUserdata<T>.
- Add Lua::pushBorrowedSharedUserdata<T>.
- Add typed Lua::luaSharedPtrGarbageCollection<T>.
- Migrate KV, Condition, and NetworkMessage to the typed shared-userdata path.
- Migrate high-priority non-SharedObject bindings away from the legacy generic finalizer path.
- Deprecate old untyped shared userdata helpers so new bindings are less likely to repeat the same ownership bug.
- Document the Lua shared-userdata ownership contract and add AGENTS.md review guidance for future binding changes.

Critical leak cases fixed:
- KV values returned by kv:scoped() and player:kv() now use typed cleanup.
- Condition values returned by creature:getCondition() now release the stored std::shared_ptr<Condition> correctly.
- Borrowed NetworkMessage callback userdata now uses a no-op deleter and typed userdata cleanup instead of an invalid ownership path.

Additional bindings migrated:
- revscripts/events
- Combat
- ModalWindow
- Town
- Guild
- Vocation
- Group
- Mount
- Shop
- Loot
- MonsterSpell
- MonsterType
- Spell
- Weapon
- Charm
- Zone
- BatchUpdate

Movement and spectator hot paths:
- Add raw creature type accessors for cheaper type checks without shared_from_this().
- Reduce movement/remove notification refcount churn by using local Player* vectors anchored by the existing strong Spectators snapshot.
- Preserve client index semantics with getClientIndexOfCreature to avoid stack-high ghost or desync regressions.
- Avoid unnecessary self shared_ptr construction in Monster hot paths.

Safety:
- Does not change general game ownership.
- Does not convert Spectators or cache storage to raw pointers.
- Keeps raw Player* values local only, lifetime-anchored by the Spectators' snapshot in the same scope.
- Uses a no-op deleter for borrowed NetworkMessage userdata.
- Leaves polymorphic core userdata such as Creature, Player, Monster, Npc, Item, Container, Tile, and Teleport for a separate audit.
- Keeps Position on the legacy helper because it is represented as a Lua table with a metatable, not as shared userdata.

Validation:
- Ran git diff --check.
- Built Windows release with cmake --preset windows-release.
- Built target canary with cmake --build --preset windows-release --target canary.
- Verified critical legacy patterns are gone with grep checks.
- Verified migrated non-SharedObject bindings no longer use the old shared_ptr pushUserdata plus setMetatable pattern.
- Reviewed before/after profiling from the live-server hotspot context.

This improves the correctness of Lua bindings, reduces shared_ptr lifetime risks, and lowers refcount churn in movement/spectator paths without changing gameplay ownership semantics.
2026-05-28 16:16:27 -03:00
Eduardo Dantas
dd1a95c157
feat: add Lua API documentation and doc generator (#3771)
Add Canary's official Lua API documentation generator and keep the generated Lua API reference synchronized with the C++ Lua binding surface.

Main changes:
- Add LuaApiDocGenerator and LuaBindingScanner to discover Lua classes, methods, globals, constants, parameters, returns, fields, overloads, aliases, source files, and class inheritance from the C++ binding layer.
- Generate docs/lua-api/lua_api.d.lua for Lua Language Server and VSCode IntelliSense.
- Generate docs/lua-api/lua_api.md for human-readable API documentation.
- Generate docs/lua-api/lua_api.json for structured tooling and CI metadata.
- Generate docs/lua-api/lua_api_quality_baseline.json for weak-signature regression tracking.
- Integrate documentation generation into the startup after loadConfigLua, controlled by generateLuaApiDocs and luaApiDocsOutputDirectory.
- Add --generate-lua-api-docs-only so CI can regenerate docs without starting the game server, loading maps, connecting to the database, or running shutdown/save paths.

Generator behavior:
- Force documentation generation in docgen-only mode so CI sync checks cannot silently become no-ops.
- Warn instead of crashing the startup when doc generation fails.
- Write generated files atomically.
- Skip unchanged writes.
- Use deterministic ordering and normalized file endings.
- Keep source paths relative and portable.
- Normalize inferred C++ types into Lua and LuaLS-friendly types.
- Avoid exposing raw C++ types in generated stubs.

LuaLS support:
- Emit LuaLS-compatible annotations, including meta, aliases, classes, fields, overloads, params, returns, inheritance, callable constructors, typed arrays, and operators for supported metamethods.
- Avoid exposing internal metamethods such as __eq, __add, and __gc as normal public Lua methods.
- Add explicit signature overlays with docblocks for APIs where automatic inference is not precise enough.
- Add overlays for high-impact APIs such as Player, Game, Result, db async calls, Actions, TalkActions, Spells, Weapons, MoveEvents, GlobalEvents, CreatureEvents, NpcType, Position, and NetworkMessage.

Editor and documentation:
- Add .luarc.json so LuaLS loads docs/lua-api by default.
- Raise LuaLS preload limits for lua_api.d.lua.
- Exclude generated build, cache, Visual Studio, and vcpkg directories from LuaLS workspace indexing.
- Add tools/setup_vscode_lua_api.ps1 to configure VSCode and LuaLS locally.
- Add docs/systems/lua-api-docgen.md explaining configuration, binding documentation, docblocks, quality baselines, and CI checks.
- Mention the generated Lua API docs from the README and systems index.
- Add Visual Studio project and CMake integration for the generator.

CI and regression protection:
- Add CI sync validation that runs --generate-lua-api-docs-only and checks docs/lua-api for diffs.
- Add tools/check_lua_api_quality.py to compare weak-signature metrics against the committed baseline.
- Add tools/check_lua_api_binding_docs.py to require explicit docblocks when new bindings would generate weak signatures.
- Exclude generated Lua API outputs from Sonar duplication/noise while keeping the generator and tooling checked.

Validation:
- Verified docs/lua-api/lua_api.json parses successfully.
- Verified luac -p passes for docs/lua-api/lua_api.d.lua.
- Verified Lua API binding docs and quality checks pass.
- Verified tools/setup_vscode_lua_api.ps1 -WhatIf succeeds.
- Verified VSCode and LuaLS resolve generated Canary classes and methods from lua_api.d.lua.
- Checked generated docs for stale root-level references, temporary paths, local machine paths, and obvious raw C++ types.

This gives Canary a repeatable source-of-truth pipeline for Lua API documentation, editor IntelliSense, and CI enforcement while keeping the generated docs synchronized with the C++ binding layer.
2026-05-25 14:39:39 -03:00