Compare commits
7
Commits
pathfinding2
...
server2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
50f621fb16 | ||
|
|
c1be26023b | ||
|
|
4e40a1825a | ||
|
|
53328484b8 | ||
|
|
542fc191fa | ||
|
|
a784da9fb4 | ||
|
|
90669ff333 |
No files matched your search
+18
-21
@@ -352,9 +352,8 @@ messages contain numbered command bundles.
|
|||||||
- Locations are keyed by location ID.
|
- Locations are keyed by location ID.
|
||||||
- Each location stores NPC and interactive-object state in ID-keyed objects.
|
- Each location stores NPC and interactive-object state in ID-keyed objects.
|
||||||
- Pending interaction targets and character references use stable IDs.
|
- Pending interaction targets and character references use stable IDs.
|
||||||
- Character navigation persistence includes waypoints, actual previous-tick
|
- Character navigation persistence includes waypoints, the retry timer, and the
|
||||||
movement, blocked/retry state, the blocker ID, and the NPC cooldown sequence
|
NPC cooldown sequence and cursor.
|
||||||
and cursor.
|
|
||||||
- Immutable content such as meshes, initial taxi configuration, and object
|
- Immutable content such as meshes, initial taxi configuration, and object
|
||||||
definitions is reconstructed from campaign configuration.
|
definitions is reconstructed from campaign configuration.
|
||||||
- Configuration is loaded first and mutable saved state is overlaid in place.
|
- Configuration is loaded first and mutable saved state is overlaid in place.
|
||||||
@@ -426,6 +425,14 @@ Protocol v2 uses server-sequenced deterministic lockstep:
|
|||||||
- Post-tick canonical hashes exclude persistence timestamps and local
|
- Post-tick canonical hashes exclude persistence timestamps and local
|
||||||
presentation state. A mismatch is diagnosed but not automatically repaired.
|
presentation state. A mismatch is diagnosed but not automatically repaired.
|
||||||
|
|
||||||
|
Within one tick the server keeps only each player's last order (destination,
|
||||||
|
`set_target`, or `clear_attack_target`); `applyScheduledCommand()` defines their
|
||||||
|
semantics identically on the server and replicas. A stalled client freezes and
|
||||||
|
then fast-forwards through all buffered contiguous ticks; any lost connection
|
||||||
|
(including a clean close or rejection) returns the client to the main menu, and
|
||||||
|
the server broadcasts a disable command for the departed player's character. See
|
||||||
|
`WEBSOCKET_NETWORKING.md` for details.
|
||||||
|
|
||||||
No wall-clock timestamp participates in simulation. `steady_clock` paces the
|
No wall-clock timestamp participates in simulation. `steady_clock` paces the
|
||||||
server and local render accumulator only, so different machine clocks do not
|
server and local render accumulator only, so different machine clocks do not
|
||||||
affect command placement or state. The current missing-packet policy is to stall;
|
affect command placement or state. The current missing-packet policy is to stall;
|
||||||
@@ -489,25 +496,15 @@ cmake --build proj-windows/build --config Debug --target ShadowOverBishkekDemo -
|
|||||||
- A lockstep compatibility fingerprint must match before the client accepts the
|
- A lockstep compatibility fingerprint must match before the client accepts the
|
||||||
initial state.
|
initial state.
|
||||||
|
|
||||||
### Dynamic Navigation Occupancy
|
### Navigation Replanning
|
||||||
|
|
||||||
`LocationGameState` is the authoritative boundary for character-aware planning.
|
`CharacterState::setTarget` and `CharacterState::forceReplan` share one path
|
||||||
It collects enabled, living, stationary players and NPCs in stable ID order and
|
computation. Movement along the resulting waypoints is resolved by the ORCA
|
||||||
passes their positions and collision radii to `LocationNetworkState` and
|
solver in `LocationGameState::update` (see `PATHFINDING.md`). An NPC that
|
||||||
`PathFinder`. The requester is excluded; moving characters are transparent to
|
cannot find a path waits for the next deterministic, ID-shuffled cooldown from
|
||||||
planning. “Moving” here means actual previous-tick displacement
|
its serialized retry sequence before replanning; the retry timer, cooldown
|
||||||
(`movedLastTick`), not merely owning an active path, so visually stalled
|
sequence, and cursor are serialized character state. Static navigation topology
|
||||||
characters remain planning obstacles. Route planning uses full avoidance radii;
|
changes route through the same centralized replanning path.
|
||||||
the movement guard uses smaller contact radii.
|
|
||||||
|
|
||||||
Every character movement step is guarded against stable-ID-ordered reservations
|
|
||||||
initialized from tick-start geometry. Accepted steps update their reservation
|
|
||||||
before later characters advance, preventing two movers from ending a tick
|
|
||||||
overlapped. Blocked/retry counters, cooldown sequence/cursor, and blocker ID are
|
|
||||||
serialized character state. Head-on players and bots cancel their commands;
|
|
||||||
NPCs retain their targets and consume the next deterministic, ID-shuffled
|
|
||||||
cooldown before replanning. Static navigation topology changes route through
|
|
||||||
the same centralized replanning path.
|
|
||||||
|
|
||||||
## Main Files
|
## Main Files
|
||||||
|
|
||||||
|
|||||||
+2
-5
@@ -208,9 +208,6 @@ its closest boundary.
|
|||||||
After ORCA:
|
After ORCA:
|
||||||
|
|
||||||
- accepted position and `newVel` become authoritative state;
|
- accepted position and `newVel` become authoritative state;
|
||||||
- `movedLastTick` is set from actual displacement;
|
|
||||||
- `movementBlockedTicks` is reset after movement or incremented when a desired
|
|
||||||
move produced no displacement;
|
|
||||||
- walking/standing animation state follows actual movement;
|
- walking/standing animation state follows actual movement;
|
||||||
- facing follows the accepted ORCA velocity.
|
- facing follows the accepted ORCA velocity.
|
||||||
|
|
||||||
@@ -221,11 +218,11 @@ not initialize its raw integer.
|
|||||||
## 9. Deterministic lockstep requirements
|
## 9. Deterministic lockstep requirements
|
||||||
|
|
||||||
All clients must begin a tick with identical state. The following movement
|
All clients must begin a tick with identical state. The following movement
|
||||||
history is serialized in schema version 6:
|
history is serialized in schema version 7:
|
||||||
|
|
||||||
- exact raw fixed-point `velocity` components;
|
- exact raw fixed-point `velocity` components;
|
||||||
- path targets, waypoints, and waypoint index;
|
- path targets, waypoints, and waypoint index;
|
||||||
- `movedLastTick` and blocked/retry counters;
|
- the navigation retry timer;
|
||||||
- deterministic retry sequence and cursor;
|
- deterministic retry sequence and cursor;
|
||||||
- animation frame, state, `resetAnim`, and attack phase;
|
- animation frame, state, `resetAnim`, and attack phase;
|
||||||
- facing and target-facing angles.
|
- facing and target-facing angles.
|
||||||
|
|||||||
+76
-7
@@ -62,6 +62,75 @@ configured player slot connects or disconnects.
|
|||||||
locations against the replica and presents completed-tick events. It never
|
locations against the replica and presents completed-tick events. It never
|
||||||
advances simulation from a render-frame delta.
|
advances simulation from a render-frame delta.
|
||||||
|
|
||||||
|
## Delayed Ticks and Connection Loss
|
||||||
|
|
||||||
|
- **Delay.** The client never advances simulation from wall-clock time. If tick N
|
||||||
|
is missing it stalls: the world looks frozen, but input is still sent (the
|
||||||
|
server schedules it two ticks after it arrives). When the missing ticks arrive
|
||||||
|
the client applies all contiguous buffered ticks in one `update()` call, so
|
||||||
|
the game visibly fast-forwards. There is no timeout or resynchronization.
|
||||||
|
- **Connection lost.** `WebsocketGameClient::connectionFailed()` becomes true
|
||||||
|
on any socket error, any close after connecting (including a clean server
|
||||||
|
close), a `server_full`/`incompatible` rejection, or a compatibility
|
||||||
|
fingerprint mismatch. `Game` then unloads the campaign and returns to the main
|
||||||
|
menu / campaign selection (checked once loading has completed).
|
||||||
|
- **Server side.** A read error, close, or write error releases the slot, closes
|
||||||
|
the socket, and schedules `SetCharacterEnabledCommand(enabled=false)` for the
|
||||||
|
next tick, which is broadcast so every replica disables that character.
|
||||||
|
Inputs queued from a released slot in the same update are discarded.
|
||||||
|
- There is no application-level heartbeat; a silently dead peer is detected by
|
||||||
|
Beast's idle timeout.
|
||||||
|
|
||||||
|
## Message Signing and Rate Limiting
|
||||||
|
|
||||||
|
- **Session secret.** On connect the server generates 32 random bytes and sends
|
||||||
|
them hex-encoded as `sessionSecret` in `initial_state`. The client must receive
|
||||||
|
a valid 64-hex-character secret or the message is rejected.
|
||||||
|
- **Per-message key.** `key = SHA-256(sessionSecret || appPepper || bigEndian(clientSequence))`.
|
||||||
|
The pepper is rebuilt at run time from three masked fragments in separate
|
||||||
|
functions (`MessageAuth.h`); it is never one contiguous constant. This raises
|
||||||
|
the cost of extraction but cannot stop a determined reverse engineer, since the
|
||||||
|
client must hold it. Change the fragments for each release if desired.
|
||||||
|
- **Signature.** Every client input envelope carries `signature =
|
||||||
|
hex(HMAC-SHA256(key, "type|clientSequence|payload"))`, where `payload` is the
|
||||||
|
canonical JSON dump. `clientSequence` starts at 1 per connection and must
|
||||||
|
strictly increase (replay protection).
|
||||||
|
- **Validation order (server, per session, on the network thread).** rate limit,
|
||||||
|
then signature, then sequence, then payload parsing.
|
||||||
|
- **Rate limit.** More than `kMaxCommandsPerSecond` (20) messages inside a
|
||||||
|
sliding one-second window counts every message, valid or not.
|
||||||
|
- **Kick.** A rate-limit, signature or replay failure makes the server send a
|
||||||
|
final `error` (`rate_limited`, `invalid_signature` or `replayed_message`),
|
||||||
|
ignore the session, and close it. The slot is released and
|
||||||
|
`SetCharacterEnabledCommand(enabled=false)` is broadcast like any disconnect.
|
||||||
|
The client treats any error other than `invalid_input` as a lost connection and
|
||||||
|
returns to the menu. A malformed but correctly signed payload only yields
|
||||||
|
`invalid_input` and does not kick.
|
||||||
|
- **Primitives.** SHA-256/HMAC are implemented in the header-only
|
||||||
|
`src/game_server/MessageAuth.h`, because the standalone server and the web
|
||||||
|
client do not link OpenSSL. It is checked against the standard test vectors.
|
||||||
|
- **Limits.** Over plain `ws://` the secret travels in cleartext, so use `wss://`
|
||||||
|
(the reverse proxy). Only client inputs are signed; the server's tick messages
|
||||||
|
are not.
|
||||||
|
|
||||||
|
## Multiple Commands per Frame
|
||||||
|
|
||||||
|
A client may send several inputs in one frame; each is a separate message. The
|
||||||
|
server keeps, per player and per scheduled tick, only the **last order**, where
|
||||||
|
an order is `destination_input`, `set_target`, or `clear_attack_target`.
|
||||||
|
`try_attack_combo` and presence commands are never dropped. Orders are applied
|
||||||
|
by the shared `applyScheduledCommand()` (`LockstepApply.h`) on the server and on
|
||||||
|
every replica:
|
||||||
|
|
||||||
|
- destination: clear the attack target, then walk to the point;
|
||||||
|
- `set_target`: stop the current walk, then attack (the chase path is planned by
|
||||||
|
the simulation);
|
||||||
|
- `clear_attack_target`: clear the attack target only.
|
||||||
|
|
||||||
|
So "walk to A, then attack NPC 1" attacks, and "attack NPC 1, then walk to A"
|
||||||
|
walks. The client therefore sends the destination before `set_target` when a
|
||||||
|
hostile NPC is clicked, and no longer sends redundant trailing clears.
|
||||||
|
|
||||||
## Campaign Routing
|
## Campaign Routing
|
||||||
|
|
||||||
The graphical game uses stable router objects for `IGameServer` and
|
The graphical game uses stable router objects for `IGameServer` and
|
||||||
@@ -116,7 +185,8 @@ Message types are:
|
|||||||
- `tick` (server to client): tick ID, globally sequenced destination,
|
- `tick` (server to client): tick ID, globally sequenced destination,
|
||||||
character-action, and character-presence commands, and post-tick diagnostic
|
character-action, and character-presence commands, and post-tick diagnostic
|
||||||
state hash;
|
state hash;
|
||||||
- `error` (server to client): invalid input, incompatibility, or full server.
|
- `error` (server to client): invalid input, incompatibility, full server, or a
|
||||||
|
kick (`rate_limited`, `invalid_signature`, `replayed_message`).
|
||||||
|
|
||||||
Protocol v1 is not compatible. Malformed payloads, non-finite or out-of-range
|
Protocol v1 is not compatible. Malformed payloads, non-finite or out-of-range
|
||||||
coordinates, duplicate client sequences, empty action IDs, and unsupported
|
coordinates, duplicate client sequences, empty action IDs, and unsupported
|
||||||
@@ -201,12 +271,11 @@ submission, and contiguous tick consumption.
|
|||||||
|
|
||||||
- Paths are calculated independently on every lockstep participant from the
|
- Paths are calculated independently on every lockstep participant from the
|
||||||
same ordered commands and tick-start occupancy. Integer A* costs, stable
|
same ordered commands and tick-start occupancy. Integer A* costs, stable
|
||||||
character IDs, serialized previous-tick movement and blocked/retry state, and deterministic
|
character IDs, serialized retry state, and deterministic nearest-reachable
|
||||||
nearest-reachable ties keep route selection aligned.
|
ties keep route selection aligned.
|
||||||
- Moving characters are omitted from A* but remain solid to the authoritative
|
- Movement between waypoints is resolved by the ORCA solver. NPCs that cannot
|
||||||
movement guard. After three blocked ticks, players/bots cancel movement while
|
find a path consume the next serialized cooldown from their deterministic
|
||||||
NPCs stop and consume the next serialized cooldown from their deterministic
|
retry sequence before replanning.
|
||||||
retry sequence before replanning around the blocker.
|
|
||||||
- Opposing traffic can wait in a one-character-wide corridor because the
|
- Opposing traffic can wait in a one-character-wide corridor because the
|
||||||
current policy does not reserve future space-time cells.
|
current policy does not reserve future space-time cells.
|
||||||
- Only preconfigured player slots can connect; dynamic join/spawn commands are
|
- Only preconfigured player slots can connect; dynamic join/spawn commands are
|
||||||
|
|||||||
@@ -505,8 +505,6 @@
|
|||||||
-15.038200378417969
|
-15.038200378417969
|
||||||
],
|
],
|
||||||
"hp": 100.0,
|
"hp": 100.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
10,
|
10,
|
||||||
@@ -599,7 +597,6 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"money": 5500,
|
"money": 5500,
|
||||||
"playerMaxHp": 200.0,
|
|
||||||
"players": {
|
"players": {
|
||||||
"player1": {
|
"player1": {
|
||||||
"animationFrame": 0.0,
|
"animationFrame": 0.0,
|
||||||
@@ -621,8 +618,6 @@
|
|||||||
0.0
|
0.0
|
||||||
],
|
],
|
||||||
"hp": 200.0,
|
"hp": 200.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [],
|
"navigationRetryCooldownTicks": [],
|
||||||
"navigationRetryTicks": 0,
|
"navigationRetryTicks": 0,
|
||||||
@@ -797,7 +792,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"savedAt": "2026-11-10 20:38",
|
"savedAt": "2026-11-10 20:38",
|
||||||
"schemaVersion": 6,
|
"schemaVersion": 7,
|
||||||
"taxiIsCalled": false,
|
"taxiIsCalled": false,
|
||||||
"tutorialJournalScreenOpened": false,
|
"tutorialJournalScreenOpened": false,
|
||||||
"tutorialNeedOpenTaxiScreen": false,
|
"tutorialNeedOpenTaxiScreen": false,
|
||||||
|
|||||||
@@ -2,8 +2,8 @@
|
|||||||
"localState": {
|
"localState": {
|
||||||
"locations": {
|
"locations": {
|
||||||
"park_korea": {
|
"park_korea": {
|
||||||
"cameraAzimuth": -2.3499999046325684,
|
"cameraAzimuth": -2.35,
|
||||||
"cameraInclination": 1.103600025177002
|
"cameraInclination": 1.1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -49,9 +49,9 @@
|
|||||||
"alpha": 1.0,
|
"alpha": 1.0,
|
||||||
"isActive": true,
|
"isActive": true,
|
||||||
"isAnimating": false,
|
"isAnimating": false,
|
||||||
"positionX": 0.60000002384185791,
|
"positionX": 0.6,
|
||||||
"positionY": 0.45736101269721985,
|
"positionY": 0.457,
|
||||||
"positionZ": 3.8499999046325684,
|
"positionZ": 3.85,
|
||||||
"rotationY": 0.0,
|
"rotationY": 0.0,
|
||||||
"scale": 1.0
|
"scale": 1.0
|
||||||
},
|
},
|
||||||
@@ -59,9 +59,9 @@
|
|||||||
"alpha": 1.0,
|
"alpha": 1.0,
|
||||||
"isActive": true,
|
"isActive": true,
|
||||||
"isAnimating": false,
|
"isAnimating": false,
|
||||||
"positionX": 1.3999999761581421,
|
"positionX": 1.4,
|
||||||
"positionY": 0.45736101269721985,
|
"positionY": 0.457,
|
||||||
"positionZ": 3.8499999046325684,
|
"positionZ": 3.85,
|
||||||
"rotationY": 0.0,
|
"rotationY": 0.0,
|
||||||
"scale": 1.0
|
"scale": 1.0
|
||||||
},
|
},
|
||||||
@@ -69,9 +69,9 @@
|
|||||||
"alpha": 1.0,
|
"alpha": 1.0,
|
||||||
"isActive": true,
|
"isActive": true,
|
||||||
"isAnimating": false,
|
"isAnimating": false,
|
||||||
"positionX": 2.2000000476837158,
|
"positionX": 2.2,
|
||||||
"positionY": 0.45736101269721985,
|
"positionY": 0.457,
|
||||||
"positionZ": 3.8499999046325684,
|
"positionZ": 3.85,
|
||||||
"rotationY": 0.0,
|
"rotationY": 0.0,
|
||||||
"scale": 1.0
|
"scale": 1.0
|
||||||
},
|
},
|
||||||
@@ -80,8 +80,8 @@
|
|||||||
"isActive": true,
|
"isActive": true,
|
||||||
"isAnimating": false,
|
"isAnimating": false,
|
||||||
"positionX": 3.0,
|
"positionX": 3.0,
|
||||||
"positionY": 0.45736101269721985,
|
"positionY": 0.457,
|
||||||
"positionZ": 3.8499999046325684,
|
"positionZ": 3.85,
|
||||||
"rotationY": 0.0,
|
"rotationY": 0.0,
|
||||||
"scale": 1.0
|
"scale": 1.0
|
||||||
},
|
},
|
||||||
@@ -90,7 +90,7 @@
|
|||||||
"isActive": true,
|
"isActive": true,
|
||||||
"isAnimating": false,
|
"isAnimating": false,
|
||||||
"positionX": 0.0,
|
"positionX": 0.0,
|
||||||
"positionY": 3.2000000476837158,
|
"positionY": 3.2,
|
||||||
"positionZ": 0.0,
|
"positionZ": 0.0,
|
||||||
"rotationY": 0.0,
|
"rotationY": 0.0,
|
||||||
"scale": 1.0
|
"scale": 1.0
|
||||||
@@ -100,8 +100,8 @@
|
|||||||
"isActive": true,
|
"isActive": true,
|
||||||
"isAnimating": false,
|
"isAnimating": false,
|
||||||
"positionX": -1.0,
|
"positionX": -1.0,
|
||||||
"positionY": 0.91500002145767212,
|
"positionY": 0.915,
|
||||||
"positionZ": -3.9000000953674316,
|
"positionZ": -3.9,
|
||||||
"rotationY": 0.0,
|
"rotationY": 0.0,
|
||||||
"scale": 1.0
|
"scale": 1.0
|
||||||
},
|
},
|
||||||
@@ -110,8 +110,8 @@
|
|||||||
"isActive": true,
|
"isActive": true,
|
||||||
"isAnimating": false,
|
"isAnimating": false,
|
||||||
"positionX": 0.0,
|
"positionX": 0.0,
|
||||||
"positionY": 0.91500002145767212,
|
"positionY": 0.915,
|
||||||
"positionZ": -3.9000000953674316,
|
"positionZ": -3.9,
|
||||||
"rotationY": 0.0,
|
"rotationY": 0.0,
|
||||||
"scale": 1.0
|
"scale": 1.0
|
||||||
},
|
},
|
||||||
@@ -120,8 +120,8 @@
|
|||||||
"isActive": true,
|
"isActive": true,
|
||||||
"isAnimating": false,
|
"isAnimating": false,
|
||||||
"positionX": 1.0,
|
"positionX": 1.0,
|
||||||
"positionY": 0.91500002145767212,
|
"positionY": 0.915,
|
||||||
"positionZ": -3.9000000953674316,
|
"positionZ": -3.9,
|
||||||
"rotationY": 0.0,
|
"rotationY": 0.0,
|
||||||
"scale": 1.0
|
"scale": 1.0
|
||||||
}
|
}
|
||||||
@@ -147,8 +147,6 @@
|
|||||||
-12.0
|
-12.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
2,
|
2,
|
||||||
@@ -204,8 +202,6 @@
|
|||||||
-12.0
|
-12.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
8,
|
8,
|
||||||
@@ -261,8 +257,6 @@
|
|||||||
-12.5
|
-12.5
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
2,
|
2,
|
||||||
@@ -318,8 +312,6 @@
|
|||||||
-12.5
|
-12.5
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
3,
|
3,
|
||||||
@@ -375,8 +367,6 @@
|
|||||||
-13.0
|
-13.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
8,
|
8,
|
||||||
@@ -432,8 +422,6 @@
|
|||||||
-13.0
|
-13.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
7,
|
7,
|
||||||
@@ -489,8 +477,6 @@
|
|||||||
-14.0
|
-14.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
2,
|
2,
|
||||||
@@ -546,8 +532,6 @@
|
|||||||
-14.0
|
-14.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
8,
|
8,
|
||||||
@@ -603,8 +587,6 @@
|
|||||||
-14.5
|
-14.5
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
2,
|
2,
|
||||||
@@ -660,8 +642,6 @@
|
|||||||
-14.5
|
-14.5
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
3,
|
3,
|
||||||
@@ -717,8 +697,6 @@
|
|||||||
-15.0
|
-15.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
8,
|
8,
|
||||||
@@ -774,8 +752,6 @@
|
|||||||
-15.0
|
-15.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
7,
|
7,
|
||||||
@@ -846,7 +822,6 @@
|
|||||||
},
|
},
|
||||||
"money": 5500,
|
"money": 5500,
|
||||||
"playerHp": 200.0,
|
"playerHp": 200.0,
|
||||||
"playerMaxHp": 200.0,
|
|
||||||
"players": {
|
"players": {
|
||||||
"player1": {
|
"player1": {
|
||||||
"animationFrame": 0.0,
|
"animationFrame": 0.0,
|
||||||
@@ -1038,7 +1013,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"savedAt": "2026-11-05 17:43",
|
"savedAt": "2026-11-05 17:43",
|
||||||
"schemaVersion": 6,
|
"schemaVersion": 7,
|
||||||
"taxiIsCalled": false,
|
"taxiIsCalled": false,
|
||||||
"tutorialJournalScreenOpened": false,
|
"tutorialJournalScreenOpened": false,
|
||||||
"tutorialNeedOpenTaxiScreen": false,
|
"tutorialNeedOpenTaxiScreen": false,
|
||||||
|
|||||||
@@ -147,8 +147,6 @@
|
|||||||
-12.0
|
-12.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
2,
|
2,
|
||||||
@@ -204,8 +202,6 @@
|
|||||||
-12.0
|
-12.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
8,
|
8,
|
||||||
@@ -261,8 +257,6 @@
|
|||||||
-12.5
|
-12.5
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
2,
|
2,
|
||||||
@@ -318,8 +312,6 @@
|
|||||||
-12.5
|
-12.5
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
3,
|
3,
|
||||||
@@ -375,8 +367,6 @@
|
|||||||
-13.0
|
-13.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
8,
|
8,
|
||||||
@@ -432,8 +422,6 @@
|
|||||||
-13.0
|
-13.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
7,
|
7,
|
||||||
@@ -489,8 +477,6 @@
|
|||||||
-14.0
|
-14.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
2,
|
2,
|
||||||
@@ -546,8 +532,6 @@
|
|||||||
-14.0
|
-14.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
8,
|
8,
|
||||||
@@ -603,8 +587,6 @@
|
|||||||
-14.5
|
-14.5
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
2,
|
2,
|
||||||
@@ -660,8 +642,6 @@
|
|||||||
-14.5
|
-14.5
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
3,
|
3,
|
||||||
@@ -717,8 +697,6 @@
|
|||||||
-15.0
|
-15.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
8,
|
8,
|
||||||
@@ -774,8 +752,6 @@
|
|||||||
-15.0
|
-15.0
|
||||||
],
|
],
|
||||||
"hp": 35.0,
|
"hp": 35.0,
|
||||||
"movedLastTick": false,
|
|
||||||
"movementBlockedTicks": 0,
|
|
||||||
"navigationRetryCooldownIndex": 0,
|
"navigationRetryCooldownIndex": 0,
|
||||||
"navigationRetryCooldownTicks": [
|
"navigationRetryCooldownTicks": [
|
||||||
7,
|
7,
|
||||||
@@ -846,7 +822,6 @@
|
|||||||
},
|
},
|
||||||
"money": 5500,
|
"money": 5500,
|
||||||
"playerHp": 200.0,
|
"playerHp": 200.0,
|
||||||
"playerMaxHp": 200.0,
|
|
||||||
"players": {
|
"players": {
|
||||||
"player1": {
|
"player1": {
|
||||||
"animationFrame": 0.0,
|
"animationFrame": 0.0,
|
||||||
@@ -1038,7 +1013,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"savedAt": "2026-11-05 17:43",
|
"savedAt": "2026-11-05 17:43",
|
||||||
"schemaVersion": 6,
|
"schemaVersion": 7,
|
||||||
"taxiIsCalled": false,
|
"taxiIsCalled": false,
|
||||||
"tutorialJournalScreenOpened": false,
|
"tutorialJournalScreenOpened": false,
|
||||||
"tutorialNeedOpenTaxiScreen": false,
|
"tutorialNeedOpenTaxiScreen": false,
|
||||||
|
|||||||
@@ -125,7 +125,7 @@
|
|||||||
"y": 10,
|
"y": 10,
|
||||||
"width": 160,
|
"width": 160,
|
||||||
"height": 36,
|
"height": 36,
|
||||||
"text": "v. 1.1.3",
|
"text": "v. 1.1.4",
|
||||||
"fontSize": 24,
|
"fontSize": 24,
|
||||||
"textCentered": false,
|
"textCentered": false,
|
||||||
"topAligned": true,
|
"topAligned": true,
|
||||||
|
|||||||
@@ -116,7 +116,7 @@
|
|||||||
"y": 10,
|
"y": 10,
|
||||||
"width": 160,
|
"width": 160,
|
||||||
"height": 36,
|
"height": 36,
|
||||||
"text": "v. 1.1.3",
|
"text": "v. 1.1.4",
|
||||||
"fontSize": 24,
|
"fontSize": 24,
|
||||||
"textCentered": false,
|
"textCentered": false,
|
||||||
"topAligned": true,
|
"topAligned": true,
|
||||||
|
|||||||
@@ -125,7 +125,7 @@
|
|||||||
"y": 10,
|
"y": 10,
|
||||||
"width": 160,
|
"width": 160,
|
||||||
"height": 36,
|
"height": 36,
|
||||||
"text": "v. 1.1.3",
|
"text": "v. 1.1.4",
|
||||||
"fontSize": 24,
|
"fontSize": 24,
|
||||||
"textCentered": false,
|
"textCentered": false,
|
||||||
"topAligned": true,
|
"topAligned": true,
|
||||||
|
|||||||
@@ -125,7 +125,7 @@
|
|||||||
"y": 10,
|
"y": 10,
|
||||||
"width": 160,
|
"width": 160,
|
||||||
"height": 36,
|
"height": 36,
|
||||||
"text": "v. 1.1.3",
|
"text": "v. 1.1.4",
|
||||||
"fontSize": 24,
|
"fontSize": 24,
|
||||||
"textCentered": false,
|
"textCentered": false,
|
||||||
"topAligned": true,
|
"topAligned": true,
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
#include "LocationGameState.h"
|
#include "LocationGameState.h"
|
||||||
#include "game_server/InternalGameServer.h"
|
#include "game_server/InternalGameServer.h"
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
|
#include <fstream>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
@@ -116,6 +118,34 @@ int main()
|
|||||||
FRG::makeNetworkCompatibilityFingerprint(reorderedContent)) {
|
FRG::makeNetworkCompatibilityFingerprint(reorderedContent)) {
|
||||||
return fail("Compatibility fingerprint ignored navigation-map order");
|
return fail("Compatibility fingerprint ignored navigation-map order");
|
||||||
}
|
}
|
||||||
|
const std::filesystem::path lineEndingResource =
|
||||||
|
std::filesystem::temp_directory_path() /
|
||||||
|
"frg_fingerprint_line_endings.json";
|
||||||
|
FRG::CampaignConfig lineEndingCampaign;
|
||||||
|
lineEndingCampaign.id = "line_endings";
|
||||||
|
lineEndingCampaign.networkCompatibility = "line-endings-test";
|
||||||
|
lineEndingCampaign.locationConfigPaths = {
|
||||||
|
lineEndingResource.string()};
|
||||||
|
FRG::LocationConfig lineEndingLocation;
|
||||||
|
lineEndingLocation.id = "test";
|
||||||
|
lineEndingCampaign.locations.push_back(lineEndingLocation);
|
||||||
|
{
|
||||||
|
std::ofstream output(lineEndingResource, std::ios::binary);
|
||||||
|
output << "{\r\n \"id\": \"test\"\r\n}\r\n";
|
||||||
|
}
|
||||||
|
const std::string crlfFingerprint =
|
||||||
|
FRG::makeNetworkCompatibilityFingerprint(lineEndingCampaign);
|
||||||
|
{
|
||||||
|
std::ofstream output(
|
||||||
|
lineEndingResource, std::ios::binary | std::ios::trunc);
|
||||||
|
output << "{\n \"id\": \"test\"\n}\n";
|
||||||
|
}
|
||||||
|
const std::string lfFingerprint =
|
||||||
|
FRG::makeNetworkCompatibilityFingerprint(lineEndingCampaign);
|
||||||
|
std::filesystem::remove(lineEndingResource);
|
||||||
|
if (crlfFingerprint != lfFingerprint) {
|
||||||
|
return fail("Compatibility fingerprint depends on line endings");
|
||||||
|
}
|
||||||
|
|
||||||
FRG::LocationDefinition definition;
|
FRG::LocationDefinition definition;
|
||||||
definition.config.id = "test_location";
|
definition.config.id = "test_location";
|
||||||
@@ -309,20 +339,98 @@ int main()
|
|||||||
return fail("Enabled player acquired an autonomous attack target");
|
return fail("Enabled player acquired an autonomous attack target");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
FRG::CharacterState drawAnimation;
|
||||||
|
drawAnimation.configureAsPlayer();
|
||||||
|
drawAnimation.enabled = true;
|
||||||
|
drawAnimation.setAnimationMetadata(
|
||||||
|
FRG::AnimationState::STAND_TO_ACTION, 0, 100);
|
||||||
|
drawAnimation.setAnimationMetadata(
|
||||||
|
FRG::AnimationState::ACTION_IDLE, 0, 100);
|
||||||
|
FRG::CharacterObservation attackTarget{
|
||||||
|
point(0.f, 0.f, 1.f), 100.f};
|
||||||
|
drawAnimation.update(100, {&attackTarget, nullptr});
|
||||||
|
if (drawAnimation.currentState != FRG::AnimationState::STAND_TO_ACTION ||
|
||||||
|
std::abs(drawAnimation.animationFrame - 8.333333f) > 0.001f ||
|
||||||
|
drawAnimation.showWeapon) {
|
||||||
|
return fail("Weapon draw animation did not advance at 2x speed");
|
||||||
|
}
|
||||||
|
drawAnimation.update(200, {&attackTarget, nullptr});
|
||||||
|
if (!drawAnimation.showWeapon) {
|
||||||
|
return fail("Weapon draw animation did not use its frame visibility threshold");
|
||||||
|
}
|
||||||
|
|
||||||
|
FRG::CharacterState sheathAnimation;
|
||||||
|
sheathAnimation.configureAsPlayer();
|
||||||
|
sheathAnimation.enabled = true;
|
||||||
|
sheathAnimation.currentState = FRG::AnimationState::ACTION_IDLE;
|
||||||
|
sheathAnimation.setAnimationMetadata(
|
||||||
|
FRG::AnimationState::ACTION_TO_STAND, 0, 100);
|
||||||
|
sheathAnimation.update(100, {nullptr, nullptr});
|
||||||
|
if (sheathAnimation.currentState != FRG::AnimationState::ACTION_TO_STAND ||
|
||||||
|
std::abs(sheathAnimation.animationFrame - 8.333333f) > 0.001f ||
|
||||||
|
!sheathAnimation.showWeapon) {
|
||||||
|
return fail("Weapon sheath animation did not advance at 2x speed");
|
||||||
|
}
|
||||||
|
sheathAnimation.update(300, {nullptr, nullptr});
|
||||||
|
if (sheathAnimation.showWeapon) {
|
||||||
|
return fail("Weapon sheath animation did not hide at its frame visibility threshold");
|
||||||
|
}
|
||||||
|
|
||||||
|
FRG::CharacterState ordinaryAnimation;
|
||||||
|
ordinaryAnimation.configureAsPlayer();
|
||||||
|
ordinaryAnimation.enabled = true;
|
||||||
|
ordinaryAnimation.currentState = FRG::AnimationState::STAND;
|
||||||
|
ordinaryAnimation.setAnimationMetadata(
|
||||||
|
FRG::AnimationState::STAND, 0, 100);
|
||||||
|
ordinaryAnimation.update(100, {nullptr, nullptr});
|
||||||
|
if (std::abs(ordinaryAnimation.animationFrame - 4.1666665f) > 0.001f) {
|
||||||
|
return fail("Ordinary animation playback rate changed unexpectedly");
|
||||||
|
}
|
||||||
|
|
||||||
|
FRG::CharacterState completedDrawAnimation;
|
||||||
|
completedDrawAnimation.configureAsPlayer();
|
||||||
|
completedDrawAnimation.enabled = true;
|
||||||
|
completedDrawAnimation.setAnimationMetadata(
|
||||||
|
FRG::AnimationState::STAND_TO_ACTION, 0, 30);
|
||||||
|
completedDrawAnimation.setAnimationMetadata(
|
||||||
|
FRG::AnimationState::ACTION_IDLE, 0, 30);
|
||||||
|
for (int i = 0; i < 4; ++i)
|
||||||
|
completedDrawAnimation.update(
|
||||||
|
100, {&attackTarget, nullptr});
|
||||||
|
if (completedDrawAnimation.currentState !=
|
||||||
|
FRG::AnimationState::ACTION_IDLE) {
|
||||||
|
return fail("Accelerated weapon draw animation did not complete");
|
||||||
|
}
|
||||||
|
|
||||||
|
FRG::CharacterState completedSheathAnimation;
|
||||||
|
completedSheathAnimation.configureAsPlayer();
|
||||||
|
completedSheathAnimation.enabled = true;
|
||||||
|
completedSheathAnimation.currentState = FRG::AnimationState::ACTION_IDLE;
|
||||||
|
completedSheathAnimation.setAnimationMetadata(
|
||||||
|
FRG::AnimationState::ACTION_TO_STAND, 0, 30);
|
||||||
|
for (int i = 0; i < 4; ++i)
|
||||||
|
completedSheathAnimation.update(
|
||||||
|
100, {nullptr, nullptr});
|
||||||
|
if (completedSheathAnimation.currentState != FRG::AnimationState::STAND) {
|
||||||
|
return fail("Accelerated weapon sheath animation did not complete");
|
||||||
|
}
|
||||||
|
|
||||||
FRG::CharacterState guardedMover;
|
FRG::CharacterState guardedMover;
|
||||||
nlohmann::json guardedJson;
|
nlohmann::json guardedJson;
|
||||||
guardedMover.velocity = {
|
guardedMover.velocity = {
|
||||||
FRG::fp::from_raw_value(12345),
|
FRG::fp::from_raw_value(12345),
|
||||||
FRG::fp::from_raw_value(-6789)};
|
FRG::fp::from_raw_value(-6789)};
|
||||||
|
guardedMover.navigationOutcome =
|
||||||
|
FRG::PathFinder::PathOutcome::NearestReachable;
|
||||||
guardedMover.save(guardedJson);
|
guardedMover.save(guardedJson);
|
||||||
FRG::CharacterState restoredGuardedMover;
|
FRG::CharacterState restoredGuardedMover;
|
||||||
restoredGuardedMover.load(guardedJson);
|
restoredGuardedMover.load(guardedJson);
|
||||||
if (restoredGuardedMover.movementBlockedTicks !=
|
if (restoredGuardedMover.navigationRetryTicks !=
|
||||||
guardedMover.movementBlockedTicks ||
|
|
||||||
restoredGuardedMover.navigationRetryTicks !=
|
|
||||||
guardedMover.navigationRetryTicks ||
|
guardedMover.navigationRetryTicks ||
|
||||||
restoredGuardedMover.velocity.x.raw_value() != 12345 ||
|
restoredGuardedMover.velocity.x.raw_value() != 12345 ||
|
||||||
restoredGuardedMover.velocity.y.raw_value() != -6789) {
|
restoredGuardedMover.velocity.y.raw_value() != -6789 ||
|
||||||
|
restoredGuardedMover.navigationOutcome !=
|
||||||
|
FRG::PathFinder::PathOutcome::NearestReachable) {
|
||||||
return fail("Character velocity did not round trip");
|
return fail("Character velocity did not round trip");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
#include "game_server/NetworkProtocol.h"
|
#include "game_server/NetworkProtocol.h"
|
||||||
|
#include "game_server/MessageAuth.h"
|
||||||
#include "LocationState.h"
|
#include "LocationState.h"
|
||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
@@ -41,6 +42,7 @@ int main()
|
|||||||
initial.assignedPlayerId = "player1";
|
initial.assignedPlayerId = "player1";
|
||||||
initial.snapshotTick = 42;
|
initial.snapshotTick = 42;
|
||||||
initial.compatibilityFingerprint = "lockstep-v2:battle_zone_multiplayer";
|
initial.compatibilityFingerprint = "lockstep-v2:battle_zone_multiplayer";
|
||||||
|
initial.sessionSecret = FRG::auth::generateSessionSecretHex();
|
||||||
const std::string message = FRG::makeInitialStateMessage(initial);
|
const std::string message = FRG::makeInitialStateMessage(initial);
|
||||||
FRG::InitialStateMessage parsed;
|
FRG::InitialStateMessage parsed;
|
||||||
std::string error;
|
std::string error;
|
||||||
@@ -48,6 +50,10 @@ int main()
|
|||||||
FRG::parseInitialStateMessage(message, parsed, error),
|
FRG::parseInitialStateMessage(message, parsed, error),
|
||||||
"valid initial-state envelope was rejected");
|
"valid initial-state envelope was rejected");
|
||||||
require(parsed.state == original, "state payload did not round trip");
|
require(parsed.state == original, "state payload did not round trip");
|
||||||
|
require(
|
||||||
|
parsed.sessionSecret == initial.sessionSecret &&
|
||||||
|
parsed.sessionSecret.size() == 64,
|
||||||
|
"session secret did not round trip");
|
||||||
require(parsed.snapshotTick == 42, "snapshot tick did not round trip");
|
require(parsed.snapshotTick == 42, "snapshot tick did not round trip");
|
||||||
require(
|
require(
|
||||||
parsed.assignedPlayerId == "player1",
|
parsed.assignedPlayerId == "player1",
|
||||||
@@ -189,5 +195,109 @@ int main()
|
|||||||
actionTick.commands[0]),
|
actionTick.commands[0]),
|
||||||
"character action was not scheduled with input delay");
|
"character action was not scheduled with input delay");
|
||||||
|
|
||||||
|
// Primitives against published test vectors.
|
||||||
|
{
|
||||||
|
const FRG::auth::Digest abc =
|
||||||
|
FRG::auth::sha256(FRG::auth::toBytes("abc"));
|
||||||
|
require(
|
||||||
|
FRG::auth::hexEncode(abc.data(), abc.size()) ==
|
||||||
|
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
|
||||||
|
"SHA-256 test vector failed");
|
||||||
|
const FRG::auth::Digest mac = FRG::auth::hmacSha256(
|
||||||
|
FRG::auth::Bytes(20, 0x0b), FRG::auth::toBytes("Hi There"));
|
||||||
|
require(
|
||||||
|
FRG::auth::hexEncode(mac.data(), mac.size()) ==
|
||||||
|
"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
|
||||||
|
"HMAC-SHA256 RFC 4231 test vector failed");
|
||||||
|
require(
|
||||||
|
FRG::auth::generateSessionSecretHex() !=
|
||||||
|
FRG::auth::generateSessionSecretHex(),
|
||||||
|
"session secrets are not random");
|
||||||
|
require(
|
||||||
|
FRG::auth::deriveMessageKey({1}, FRG::auth::appPepper(), 1) !=
|
||||||
|
FRG::auth::deriveMessageKey({1}, FRG::auth::appPepper(), 2),
|
||||||
|
"message key does not depend on the sequence");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Signed input messages.
|
||||||
|
{
|
||||||
|
const std::string secret = FRG::auth::generateSessionSecretHex();
|
||||||
|
const std::string otherSecret = FRG::auth::generateSessionSecretHex();
|
||||||
|
const std::string signedMessage = FRG::signInputMessage(
|
||||||
|
FRG::makeDestinationInputMessage({5, point(1.f, 0.f, 2.f)}), secret);
|
||||||
|
std::uint64_t sequence = 0;
|
||||||
|
std::string authError;
|
||||||
|
require(
|
||||||
|
FRG::verifyInputMessage(signedMessage, secret, sequence, authError) &&
|
||||||
|
sequence == 5,
|
||||||
|
"valid signature was rejected");
|
||||||
|
FRG::DestinationInputMessage stillParses;
|
||||||
|
require(
|
||||||
|
FRG::parseDestinationInputMessage(signedMessage, stillParses, authError),
|
||||||
|
"signed message no longer parses");
|
||||||
|
require(
|
||||||
|
!FRG::verifyInputMessage(signedMessage, otherSecret, sequence, authError),
|
||||||
|
"signature verified under another session secret");
|
||||||
|
require(
|
||||||
|
!FRG::verifyInputMessage(
|
||||||
|
FRG::makeDestinationInputMessage({5, point(1.f, 0.f, 2.f)}),
|
||||||
|
secret, sequence, authError),
|
||||||
|
"unsigned message was accepted");
|
||||||
|
nlohmann::json tampered = nlohmann::json::parse(signedMessage);
|
||||||
|
tampered["payload"]["target"][0] = 50.0;
|
||||||
|
require(
|
||||||
|
!FRG::verifyInputMessage(tampered.dump(), secret, sequence, authError),
|
||||||
|
"tampered payload was accepted");
|
||||||
|
nlohmann::json resequenced = nlohmann::json::parse(signedMessage);
|
||||||
|
resequenced["payload"]["clientSequence"] = 6;
|
||||||
|
require(
|
||||||
|
!FRG::verifyInputMessage(resequenced.dump(), secret, sequence, authError),
|
||||||
|
"re-sequenced message was accepted");
|
||||||
|
const std::string action = FRG::signInputMessage(
|
||||||
|
FRG::makeCharacterActionInputMessage({9, "set_target", "npc_1"}), secret);
|
||||||
|
require(
|
||||||
|
FRG::verifyInputMessage(action, secret, sequence, authError) &&
|
||||||
|
sequence == 9,
|
||||||
|
"signed character action was rejected");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Several orders in one frame: only the player's last order survives.
|
||||||
|
FRG::LockstepTimeline burst(2);
|
||||||
|
burst.schedule("player1", point(1.f, 0.f, 1.f));
|
||||||
|
burst.scheduleCharacterAction("player1", "clear_attack_target");
|
||||||
|
burst.scheduleCharacterAction("player1", "try_attack_combo");
|
||||||
|
burst.schedule("player2", point(9.f, 0.f, 9.f));
|
||||||
|
burst.scheduleCharacterAction("player1", "set_target", "npc_1");
|
||||||
|
burst.advance();
|
||||||
|
const FRG::TickMessage burstTick = burst.advance();
|
||||||
|
require(
|
||||||
|
burstTick.commands.size() == 3,
|
||||||
|
"superseded orders were not coalesced");
|
||||||
|
require(
|
||||||
|
std::holds_alternative<FRG::ScheduledCharacterActionCommand>(
|
||||||
|
burstTick.commands[0]) &&
|
||||||
|
std::get<FRG::ScheduledCharacterActionCommand>(
|
||||||
|
burstTick.commands[0]).action == "try_attack_combo",
|
||||||
|
"combo was dropped or reordered");
|
||||||
|
require(
|
||||||
|
std::get<FRG::ScheduledDestinationCommand>(
|
||||||
|
burstTick.commands[1]).playerId == "player2",
|
||||||
|
"another player's order was coalesced away");
|
||||||
|
require(
|
||||||
|
std::get<FRG::ScheduledCharacterActionCommand>(
|
||||||
|
burstTick.commands[2]).action == "set_target",
|
||||||
|
"last order did not win");
|
||||||
|
|
||||||
|
FRG::LockstepTimeline reversed(2);
|
||||||
|
reversed.scheduleCharacterAction("player1", "set_target", "npc_1");
|
||||||
|
reversed.schedule("player1", point(3.f, 0.f, 3.f));
|
||||||
|
reversed.advance();
|
||||||
|
const FRG::TickMessage reversedTick = reversed.advance();
|
||||||
|
require(
|
||||||
|
reversedTick.commands.size() == 1 &&
|
||||||
|
std::holds_alternative<FRG::ScheduledDestinationCommand>(
|
||||||
|
reversedTick.commands[0]),
|
||||||
|
"destination after attack did not replace the attack order");
|
||||||
|
|
||||||
return EXIT_SUCCESS;
|
return EXIT_SUCCESS;
|
||||||
}
|
}
|
||||||
@@ -58,6 +58,30 @@ int main()
|
|||||||
const Eigen::Vector3f end(5.f, 0.f, 5.f);
|
const Eigen::Vector3f end(5.f, 0.f, 5.f);
|
||||||
const auto path = pathFinder.findPathToNearest(start, end);
|
const auto path = pathFinder.findPathToNearest(start, end);
|
||||||
if (path.size() < 2) return fail("Path query did not produce a route");
|
if (path.size() < 2) return fail("Path query did not produce a route");
|
||||||
|
const auto exactResult = pathFinder.findPathResult(
|
||||||
|
FRG::Vec3fp::fromEigen(start), FRG::Vec3fp::fromEigen(end));
|
||||||
|
if (exactResult.outcome !=
|
||||||
|
FRG::PathFinder::PathOutcome::ReachedExactGoal ||
|
||||||
|
exactResult.waypoints.size() < 2 ||
|
||||||
|
exactResult.endpoint.x != static_cast<FRG::fp>(end.x()) ||
|
||||||
|
exactResult.endpoint.z != static_cast<FRG::fp>(end.z())) {
|
||||||
|
return fail("Reachable destination was not reported as exact");
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto blockedResult = pathFinder.findPathResult(
|
||||||
|
FRG::Vec3fp::fromEigen(start),
|
||||||
|
FRG::Vec3fp::fromEigen(Eigen::Vector3f(0.f, 0.f, 0.f)));
|
||||||
|
if (blockedResult.outcome !=
|
||||||
|
FRG::PathFinder::PathOutcome::NearestReachable ||
|
||||||
|
blockedResult.waypoints.empty() ||
|
||||||
|
!pathFinder.isWalkable(blockedResult.endpoint)) {
|
||||||
|
return fail("Blocked destination did not return a reachable partial path");
|
||||||
|
}
|
||||||
|
if ((blockedResult.endpoint -
|
||||||
|
FRG::Vec3fp::fromEigen(Eigen::Vector3f(0.f, 0.f, 0.f))).normSquared() <=
|
||||||
|
static_cast<FRG::fp>(0.01f * 0.01f)) {
|
||||||
|
return fail("Blocked destination was incorrectly reported as reached");
|
||||||
|
}
|
||||||
if (!pathFinder.isWalkable(Eigen::Vector3f(0.f, 0.f, 5.f)))
|
if (!pathFinder.isWalkable(Eigen::Vector3f(0.f, 0.f, 5.f)))
|
||||||
return fail("Walkability query failed");
|
return fail("Walkability query failed");
|
||||||
if (path.back().y() != 2.5f)
|
if (path.back().y() != 2.5f)
|
||||||
|
|||||||
@@ -341,5 +341,25 @@ int main()
|
|||||||
authoritative.snapshot()->players.at("player2").state.enabled,
|
authoritative.snapshot()->players.at("player2").state.enabled,
|
||||||
"reconnected player was not enabled");
|
"reconnected player was not enabled");
|
||||||
|
|
||||||
|
// Flooding past the per-second command limit kicks the player.
|
||||||
|
for (int i = 0; i < 40; ++i)
|
||||||
|
replacement.submit(FRG::SetCharacterDestinationCommand{
|
||||||
|
{}, {}, point(static_cast<float>(i), 0.f, 0.f), {}});
|
||||||
|
require(
|
||||||
|
waitFor([&]() {
|
||||||
|
replacement.update(0);
|
||||||
|
return replacement.connectionFailed();
|
||||||
|
}),
|
||||||
|
"command flood did not get the player kicked");
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||||
|
server.update();
|
||||||
|
require(
|
||||||
|
waitFor([&]() {
|
||||||
|
client->update(0);
|
||||||
|
return !client->snapshot()->players.at("player2").state.enabled;
|
||||||
|
}) &&
|
||||||
|
!authoritative.snapshot()->players.at("player2").state.enabled,
|
||||||
|
"kicked player's character was not disabled for everyone");
|
||||||
|
|
||||||
return EXIT_SUCCESS;
|
return EXIT_SUCCESS;
|
||||||
}
|
}
|
||||||
+18
-11
@@ -29,18 +29,23 @@ namespace FRG {
|
|||||||
void hashString(std::uint64_t& hash, const std::string& value)
|
void hashString(std::uint64_t& hash, const std::string& value)
|
||||||
{
|
{
|
||||||
const std::uint64_t size = static_cast<std::uint64_t>(value.size());
|
const std::uint64_t size = static_cast<std::uint64_t>(value.size());
|
||||||
hashBytes(hash, &size, sizeof(size));
|
for (unsigned int shift = 0; shift < 64; shift += 8) {
|
||||||
|
const unsigned char byte =
|
||||||
|
static_cast<unsigned char>((size >> shift) & 0xffu);
|
||||||
|
hashBytes(hash, &byte, sizeof(byte));
|
||||||
|
}
|
||||||
hashBytes(hash, value.data(), value.size());
|
hashBytes(hash, value.data(), value.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
bool hasAnimationExtension(const std::string& value)
|
bool hasExtension(const std::string& value, const std::string& expected)
|
||||||
{
|
{
|
||||||
if (value.size() < 5) return false;
|
if (value.size() < expected.size()) return false;
|
||||||
std::string extension = value.substr(value.size() - 5);
|
std::string extension =
|
||||||
|
value.substr(value.size() - expected.size());
|
||||||
std::transform(
|
std::transform(
|
||||||
extension.begin(), extension.end(), extension.begin(),
|
extension.begin(), extension.end(), extension.begin(),
|
||||||
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
|
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
|
||||||
return extension == ".anim";
|
return extension == expected;
|
||||||
}
|
}
|
||||||
|
|
||||||
void collectAnimationPaths(
|
void collectAnimationPaths(
|
||||||
@@ -48,7 +53,7 @@ namespace FRG {
|
|||||||
{
|
{
|
||||||
if (value.is_string()) {
|
if (value.is_string()) {
|
||||||
const std::string path = value.get<std::string>();
|
const std::string path = value.get<std::string>();
|
||||||
if (hasAnimationExtension(path)) animationPaths.insert(path);
|
if (hasExtension(path, ".anim")) animationPaths.insert(path);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (value.is_array()) {
|
if (value.is_array()) {
|
||||||
@@ -244,17 +249,19 @@ namespace FRG {
|
|||||||
const std::vector<char> bytes =
|
const std::vector<char> bytes =
|
||||||
readCompatibilityResource(path, zipFile);
|
readCompatibilityResource(path, zipFile);
|
||||||
hashString(hash, path);
|
hashString(hash, path);
|
||||||
hashBytes(hash, bytes.data(), bytes.size());
|
if (hasExtension(path, ".json")) {
|
||||||
if (path.size() >= 5 &&
|
|
||||||
path.substr(path.size() - 5) == ".json") {
|
|
||||||
try {
|
try {
|
||||||
collectAnimationPaths(
|
const json parsed = json::parse(bytes.begin(), bytes.end());
|
||||||
json::parse(bytes.begin(), bytes.end()), animationPaths);
|
const std::string canonical = parsed.dump();
|
||||||
|
hashString(hash, canonical);
|
||||||
|
collectAnimationPaths(parsed, animationPaths);
|
||||||
} catch (const std::exception& error) {
|
} catch (const std::exception& error) {
|
||||||
throw std::runtime_error(
|
throw std::runtime_error(
|
||||||
"Cannot fingerprint invalid JSON resource '" + path +
|
"Cannot fingerprint invalid JSON resource '" + path +
|
||||||
"': " + error.what());
|
"': " + error.what());
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
hashBytes(hash, bytes.data(), bytes.size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const std::string& path : animationPaths) {
|
for (const std::string& path : animationPaths) {
|
||||||
|
|||||||
+187
-587
@@ -14,9 +14,6 @@
|
|||||||
#include "Location.h"
|
#include "Location.h"
|
||||||
|
|
||||||
namespace FRG {
|
namespace FRG {
|
||||||
extern float x;
|
|
||||||
extern float y;
|
|
||||||
|
|
||||||
Dialogue::TranslationDatabase Character::nameTranslations;
|
Dialogue::TranslationDatabase Character::nameTranslations;
|
||||||
|
|
||||||
std::shared_ptr<const CharacterState> Character::stateSnapshot() const {
|
std::shared_ptr<const CharacterState> Character::stateSnapshot() const {
|
||||||
@@ -49,7 +46,7 @@ Eigen::Vector3f Character::renderPosition() const {
|
|||||||
|
|
||||||
float Character::getHp() const {
|
float Character::getHp() const {
|
||||||
auto state = stateSnapshot();
|
auto state = stateSnapshot();
|
||||||
return state ? state->getHp() : 0.f;
|
return state ? state->hp : 0.f;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Character::loadAnimation(AnimationState animState, const std::string& filename, const std::string& zipFile) {
|
void Character::loadAnimation(AnimationState animState, const std::string& filename, const std::string& zipFile) {
|
||||||
@@ -114,30 +111,6 @@ std::unique_ptr<Character> Character::createFromState(const CharacterState& st,
|
|||||||
if (tex) c->setTexture(meshName, tex);
|
if (tex) c->setTexture(meshName, tex);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!st.creationInfo.weaponMeshPath.empty()) {
|
|
||||||
const std::string& wp = st.creationInfo.weaponMeshPath;
|
|
||||||
try {
|
|
||||||
if (wp.size() >= 4 && wp.substr(wp.size() - 4) == ".bin")
|
|
||||||
c->weaponMesh.data = LoadModelFromBinFile(wp, zip);
|
|
||||||
else
|
|
||||||
c->weaponMesh.data = LoadFromTextFile02(wp, zip);
|
|
||||||
|
|
||||||
if (st.creationInfo.weaponMeshMove != Eigen::Vector3f::Zero())
|
|
||||||
c->weaponMesh.data.Move(st.creationInfo.weaponMeshMove);
|
|
||||||
if (st.creationInfo.weaponMeshScale != 1.0f)
|
|
||||||
c->weaponMesh.data.Scale(st.creationInfo.weaponMeshScale);
|
|
||||||
|
|
||||||
c->weaponMesh.RefreshVBO();
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
std::cerr << "Character::createFromState: failed to load weapon mesh '" << wp << "': " << e.what() << std::endl;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
c->weaponTexture = loadTex(st.creationInfo.weaponTexturePath);
|
|
||||||
c->weaponAttachBoneName = st.creationInfo.weaponAttachBoneName;
|
|
||||||
c->weaponInitialPosition = st.creationInfo.weaponInitialPosition;
|
|
||||||
c->weaponInitialRotation = st.creationInfo.weaponInitialRotation.toRotationMatrix();
|
|
||||||
|
|
||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,8 +181,6 @@ void Character::updateAnimationForRender(const CharacterState& state) {
|
|||||||
anim.gpuSkinningShaderData.ComputeSkinningMatrices(
|
anim.gpuSkinningShaderData.ComputeSkinningMatrices(
|
||||||
anim.model.startBones, anim.model.animations[0].keyFrames,
|
anim.model.startBones, anim.model.animations[0].keyFrames,
|
||||||
anim.currentFrame);
|
anim.currentFrame);
|
||||||
if (!state.useGpuSkinning)
|
|
||||||
anim.model.Interpolate(anim.currentFrame);
|
|
||||||
}
|
}
|
||||||
anim.lastFrame = anim.currentFrame;
|
anim.lastFrame = anim.currentFrame;
|
||||||
}
|
}
|
||||||
@@ -257,97 +228,117 @@ void Character::update(int64_t deltaMs, const CharacterUpdateEvents* events) {
|
|||||||
updateAnimationForRender(state);
|
updateAnimationForRender(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Character::draw(Renderer& renderer) {
|
// ==================== Draw helpers ====================
|
||||||
renderer.RenderUniform1f("uAlpha", 1.0f);
|
|
||||||
glDisable(GL_BLEND);
|
|
||||||
|
|
||||||
auto stateSnapshot = this->stateSnapshot();
|
namespace {
|
||||||
if (!stateSnapshot) return;
|
|
||||||
CharacterState state = interpolatedState(*stateSnapshot);
|
void setPlayerEyePos(Renderer& renderer) {
|
||||||
if (!state.enabled) return;
|
const float playerEyePos[3] = { 0.0f, 0.0f, -Environment::zoom };
|
||||||
|
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePos);
|
||||||
|
}
|
||||||
|
|
||||||
|
void pushCharacterProjection(Renderer& renderer) {
|
||||||
|
renderer.PushPerspectiveProjectionMatrix(1.0 / 1.5,
|
||||||
|
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
||||||
|
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Model-space transform shared by every character pass (mesh and weapon).
|
||||||
|
void applyModelTransform(Renderer& renderer, const CharacterState& state) {
|
||||||
|
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
||||||
|
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
||||||
|
renderer.ScaleMatrix(state.modelScale);
|
||||||
|
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
||||||
|
}
|
||||||
|
|
||||||
|
void bindShadowMap(GLuint shadowMapTex) {
|
||||||
|
glActiveTexture(GL_TEXTURE1);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, shadowMapTex);
|
||||||
|
glActiveTexture(GL_TEXTURE0);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct NightLights {
|
||||||
|
const float* posEye;
|
||||||
|
const float* dirEye;
|
||||||
|
const float* colors;
|
||||||
|
int count;
|
||||||
|
const float* worldXZ;
|
||||||
|
const float* limitXZ;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Uniforms shared by the "night_fog" family of shaders (without shadows).
|
||||||
|
void applyNightUniforms(Renderer& renderer, const NightLights& lights,
|
||||||
|
const float* ambientColor, const float* fogColor) {
|
||||||
|
renderer.RenderUniform1i(textureUniformName, 0);
|
||||||
|
renderer.RenderUniform3fv("uAmbientColor", ambientColor);
|
||||||
|
renderer.RenderUniform3fv("uFogColor", fogColor);
|
||||||
|
setPlayerEyePos(renderer);
|
||||||
|
renderer.RenderUniform1i("uPointLightCount", lights.count);
|
||||||
|
if (lights.count > 0) {
|
||||||
|
renderer.RenderUniform3fvArray("uPointLightPos[0]", lights.count, lights.posEye);
|
||||||
|
renderer.RenderUniform3fvArray("uPointLightDir[0]", lights.count, lights.dirEye);
|
||||||
|
renderer.RenderUniform3fvArray("uPointLightColor[0]", lights.count, lights.colors);
|
||||||
|
renderer.RenderUniform2fvArray("uPointLightWorldXZ[0]", lights.count, lights.worldXZ);
|
||||||
|
renderer.RenderUniform2fvArray("uPointLightLimitXZ[0]", lights.count, lights.limitXZ);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Uniforms shared by the "night_fog_*_shadow" family of shaders.
|
||||||
|
void applyNightShadowUniforms(Renderer& renderer, const NightLights& lights,
|
||||||
|
const Eigen::Matrix4f& lightFromCamera,
|
||||||
|
const float* ambientColor, const float* fogColor) {
|
||||||
|
renderer.RenderUniform1i(textureUniformName, 0);
|
||||||
|
renderer.RenderUniform1i("uShadowMap", 1);
|
||||||
|
renderer.RenderUniform3fv("uAmbientColor", ambientColor);
|
||||||
|
renderer.RenderUniform3fv("uFogColor", fogColor);
|
||||||
|
renderer.RenderUniformMatrix4fv("uLightFromCamera", false, lightFromCamera.data());
|
||||||
|
if (lights.count > 0) renderer.RenderUniform3fv("uLightDir", lights.dirEye);
|
||||||
|
setPlayerEyePos(renderer);
|
||||||
|
renderer.RenderUniform1i("uPointLightCount", lights.count);
|
||||||
|
if (lights.count > 0) {
|
||||||
|
renderer.RenderUniform3fvArray("uPointLightPos[0]", lights.count, lights.posEye);
|
||||||
|
renderer.RenderUniform3fvArray("uPointLightDir[0]", lights.count, lights.dirEye);
|
||||||
|
renderer.RenderUniform3fvArray("uPointLightColor[0]", lights.count, lights.colors);
|
||||||
|
}
|
||||||
|
renderer.RenderUniform2fvArray("uPointLightWorldXZ[0]", lights.count, lights.worldXZ);
|
||||||
|
renderer.RenderUniform2fvArray("uPointLightLimitXZ[0]", lights.count, lights.limitXZ);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
bool Character::prepareForDraw(CharacterState& state) {
|
||||||
|
auto snapshot = stateSnapshot();
|
||||||
|
if (!snapshot) return false;
|
||||||
|
state = interpolatedState(*snapshot);
|
||||||
|
if (!state.enabled) return false;
|
||||||
|
updateAnimationForRender(state);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Character::drawHitSparks(Renderer& renderer) {
|
||||||
if (hitSparkEmitter.isConfigured() && hitSparkEmitter.getActiveParticleCount() > 0) {
|
if (hitSparkEmitter.isConfigured() && hitSparkEmitter.getActiveParticleCount() > 0) {
|
||||||
hitSparkEmitter.draw(renderer, 1.0f, Environment::width, Environment::height, false);
|
hitSparkEmitter.draw(renderer, 1.0f, Environment::width, Environment::height, false);
|
||||||
}
|
}
|
||||||
updateAnimationForRender(state);
|
|
||||||
|
|
||||||
if (state.useGpuSkinning) {
|
|
||||||
drawGpuSkinning(renderer, state);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
AnimationState drawState = resolveActiveState(state);
|
|
||||||
auto it = animations.find(drawState);
|
|
||||||
if (it == animations.end()) return;
|
|
||||||
|
|
||||||
renderer.shaderManager.PushShader("fog");
|
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
|
||||||
const float playerEyePos[3] = { 0.0f, 0.0f, -Environment::zoom };
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePos);
|
|
||||||
|
|
||||||
renderer.PushPerspectiveProjectionMatrix(1.0 / 1.5,
|
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
|
|
||||||
renderer.PushMatrix();
|
|
||||||
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
|
||||||
renderer.ScaleMatrix(state.modelScale);
|
|
||||||
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
|
||||||
|
|
||||||
auto& anim = it->second;
|
|
||||||
for (const auto& name : anim.model.meshNamesOrdered) {
|
|
||||||
auto mit = anim.model.meshes.find(name);
|
|
||||||
if (mit == anim.model.meshes.end()) continue;
|
|
||||||
auto tit = meshTextures.find(name);
|
|
||||||
if (tit == meshTextures.end() || !tit->second) continue;
|
|
||||||
glBindTexture(GL_TEXTURE_2D, tit->second->getTexID());
|
|
||||||
modelMutable.AssignFrom(mit->second.mesh);
|
|
||||||
modelMutable.RefreshVBO();
|
|
||||||
renderer.DrawVertexRenderStruct(modelMutable);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderer.PopMatrix();
|
|
||||||
|
|
||||||
drawAttachedWeapon(renderer, state);
|
|
||||||
|
|
||||||
renderer.PopProjectionMatrix();
|
|
||||||
renderer.shaderManager.PopShader();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Character::drawGpuSkinning(Renderer& renderer, const CharacterState& state) {
|
BoneAnimationDataNew* Character::prepareGpuSkinning(const CharacterState& state) {
|
||||||
AnimationState drawState = resolveActiveState(state);
|
auto it = animations.find(resolveActiveState(state));
|
||||||
auto it = animations.find(drawState);
|
if (it == animations.end()) return nullptr;
|
||||||
if (it == animations.end()) return;
|
|
||||||
|
|
||||||
auto& anim = it->second;
|
auto& anim = it->second;
|
||||||
anim.gpuSkinningShaderData.prepareGpuSkinningVBOs(anim.model);
|
anim.gpuSkinningShaderData.prepareGpuSkinningVBOs(anim.model);
|
||||||
|
|
||||||
if (anim.gpuSkinningShaderData.skinningMatrices.empty()) {
|
if (anim.gpuSkinningShaderData.skinningMatrices.empty()) {
|
||||||
if (anim.model.animations.empty() || anim.model.animations[0].keyFrames.empty()) return;
|
if (anim.model.animations.empty() || anim.model.animations[0].keyFrames.empty()) return nullptr;
|
||||||
anim.gpuSkinningShaderData.ComputeSkinningMatrices(
|
anim.gpuSkinningShaderData.ComputeSkinningMatrices(
|
||||||
anim.model.startBones, anim.model.animations[0].keyFrames,
|
anim.model.startBones, anim.model.animations[0].keyFrames,
|
||||||
anim.currentFrame);
|
anim.currentFrame);
|
||||||
if (anim.gpuSkinningShaderData.skinningMatrices.empty()) return;
|
if (anim.gpuSkinningShaderData.skinningMatrices.empty()) return nullptr;
|
||||||
}
|
}
|
||||||
|
return &anim;
|
||||||
|
}
|
||||||
|
|
||||||
static const std::string skinningShaderName = "fog_skinning";
|
void Character::drawSkinnedMeshes(Renderer& renderer, BoneAnimationDataNew& anim, bool bindTextures) {
|
||||||
static const std::string boneMatricesUniform = "uBoneMatrices[0]";
|
static const std::string boneMatricesUniform = "uBoneMatrices[0]";
|
||||||
|
|
||||||
renderer.shaderManager.PushShader(skinningShaderName);
|
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
|
||||||
const float playerEyePosSkin[3] = { 0.0f, 0.0f, -Environment::zoom };
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosSkin);
|
|
||||||
|
|
||||||
renderer.PushPerspectiveProjectionMatrix(1.0 / 1.5,
|
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
|
|
||||||
renderer.PushMatrix();
|
|
||||||
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
|
||||||
renderer.ScaleMatrix(state.modelScale);
|
|
||||||
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
|
||||||
|
|
||||||
renderer.RenderUniformMatrix4fvArray(boneMatricesUniform,
|
renderer.RenderUniformMatrix4fvArray(boneMatricesUniform,
|
||||||
static_cast<int>(anim.gpuSkinningShaderData.skinningMatrices.size()), false,
|
static_cast<int>(anim.gpuSkinningShaderData.skinningMatrices.size()), false,
|
||||||
anim.gpuSkinningShaderData.skinningMatrices[0].data());
|
anim.gpuSkinningShaderData.skinningMatrices[0].data());
|
||||||
@@ -357,37 +348,18 @@ void Character::drawGpuSkinning(Renderer& renderer, const CharacterState& state)
|
|||||||
if (pit == anim.gpuSkinningShaderData.perMesh.end()) continue;
|
if (pit == anim.gpuSkinningShaderData.perMesh.end()) continue;
|
||||||
auto tit = meshTextures.find(name);
|
auto tit = meshTextures.find(name);
|
||||||
if (tit == meshTextures.end() || !tit->second) continue;
|
if (tit == meshTextures.end() || !tit->second) continue;
|
||||||
glBindTexture(GL_TEXTURE_2D, tit->second->getTexID());
|
if (bindTextures) glBindTexture(GL_TEXTURE_2D, tit->second->getTexID());
|
||||||
pit->second.RenderVBO(renderer);
|
pit->second.RenderVBO(renderer);
|
||||||
}
|
}
|
||||||
|
|
||||||
renderer.PopMatrix();
|
|
||||||
|
|
||||||
renderer.shaderManager.PushShader("fog");
|
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosSkin);
|
|
||||||
drawAttachedWeapon(renderer, state);
|
|
||||||
renderer.shaderManager.PopShader();
|
|
||||||
|
|
||||||
renderer.PopProjectionMatrix();
|
|
||||||
renderer.shaderManager.PopShader();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Character::prepareGpuSkinning(const CharacterState& state) {
|
// Draws the weapon with the plain "fog" shader (used after the skinned mesh).
|
||||||
AnimationState drawState = resolveActiveState(state);
|
void Character::drawFogWeapon(Renderer& renderer, const CharacterState& state) {
|
||||||
auto it = animations.find(drawState);
|
renderer.shaderManager.PushShader("fog");
|
||||||
if (it == animations.end()) return false;
|
renderer.RenderUniform1i(textureUniformName, 0);
|
||||||
|
setPlayerEyePos(renderer);
|
||||||
auto& anim = it->second;
|
drawAttachedWeapon(renderer, state);
|
||||||
anim.gpuSkinningShaderData.prepareGpuSkinningVBOs(anim.model);
|
renderer.shaderManager.PopShader();
|
||||||
if (anim.gpuSkinningShaderData.skinningMatrices.empty()) {
|
|
||||||
if (anim.model.animations.empty() || anim.model.animations[0].keyFrames.empty()) return false;
|
|
||||||
anim.gpuSkinningShaderData.ComputeSkinningMatrices(
|
|
||||||
anim.model.startBones, anim.model.animations[0].keyFrames,
|
|
||||||
anim.currentFrame);
|
|
||||||
if (anim.gpuSkinningShaderData.skinningMatrices.empty()) return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Character::drawAttachedWeapon(Renderer& renderer, const CharacterState& state) {
|
void Character::drawAttachedWeapon(Renderer& renderer, const CharacterState& state) {
|
||||||
@@ -407,10 +379,7 @@ void Character::drawAttachedWeapon(Renderer& renderer, const CharacterState& sta
|
|||||||
Eigen::Matrix4f currentBone = anim.gpuSkinningShaderData.skinningMatrices[boneIdx] * bindBone;
|
Eigen::Matrix4f currentBone = anim.gpuSkinningShaderData.skinningMatrices[boneIdx] * bindBone;
|
||||||
|
|
||||||
renderer.PushMatrix();
|
renderer.PushMatrix();
|
||||||
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
applyModelTransform(renderer, state);
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
|
||||||
renderer.ScaleMatrix(state.modelScale);
|
|
||||||
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
|
||||||
renderer.TranslateMatrix(Eigen::Vector3f(currentBone.block<3, 1>(0, 3)));
|
renderer.TranslateMatrix(Eigen::Vector3f(currentBone.block<3, 1>(0, 3)));
|
||||||
renderer.RotateMatrix(Eigen::Matrix3f(currentBone.block<3, 3>(0, 0)));
|
renderer.RotateMatrix(Eigen::Matrix3f(currentBone.block<3, 3>(0, 0)));
|
||||||
renderer.TranslateMatrix(weaponInitialPosition);
|
renderer.TranslateMatrix(weaponInitialPosition);
|
||||||
@@ -421,83 +390,61 @@ void Character::drawAttachedWeapon(Renderer& renderer, const CharacterState& sta
|
|||||||
renderer.PopMatrix();
|
renderer.PopMatrix();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== Main pass ====================
|
||||||
|
|
||||||
|
void Character::draw(Renderer& renderer) {
|
||||||
|
renderer.RenderUniform1f("uAlpha", 1.0f);
|
||||||
|
glDisable(GL_BLEND);
|
||||||
|
|
||||||
|
CharacterState state;
|
||||||
|
if (!prepareForDraw(state)) return;
|
||||||
|
drawHitSparks(renderer);
|
||||||
|
drawGpuSkinning(renderer, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Character::drawGpuSkinning(Renderer& renderer, const CharacterState& state) {
|
||||||
|
BoneAnimationDataNew* anim = prepareGpuSkinning(state);
|
||||||
|
if (!anim) return;
|
||||||
|
|
||||||
|
static const std::string skinningShaderName = "fog_skinning";
|
||||||
|
|
||||||
|
renderer.shaderManager.PushShader(skinningShaderName);
|
||||||
|
renderer.RenderUniform1i(textureUniformName, 0);
|
||||||
|
setPlayerEyePos(renderer);
|
||||||
|
|
||||||
|
pushCharacterProjection(renderer);
|
||||||
|
|
||||||
|
renderer.PushMatrix();
|
||||||
|
applyModelTransform(renderer, state);
|
||||||
|
drawSkinnedMeshes(renderer, *anim, true);
|
||||||
|
renderer.PopMatrix();
|
||||||
|
|
||||||
|
drawFogWeapon(renderer, state);
|
||||||
|
|
||||||
|
renderer.PopProjectionMatrix();
|
||||||
|
renderer.shaderManager.PopShader();
|
||||||
|
}
|
||||||
|
|
||||||
// ==================== Shadow depth pass ====================
|
// ==================== Shadow depth pass ====================
|
||||||
|
|
||||||
void Character::drawShadowDepth(Renderer& renderer) {
|
void Character::drawShadowDepth(Renderer& renderer) {
|
||||||
auto stateSnapshot = this->stateSnapshot();
|
CharacterState state;
|
||||||
if (!stateSnapshot) return;
|
if (!prepareForDraw(state)) return;
|
||||||
CharacterState state = interpolatedState(*stateSnapshot);
|
drawShadowDepthGpuSkinning(renderer, state);
|
||||||
if (!state.enabled) return;
|
|
||||||
updateAnimationForRender(state);
|
|
||||||
if (state.useGpuSkinning) {
|
|
||||||
drawShadowDepthGpuSkinning(renderer, state);
|
|
||||||
} else {
|
|
||||||
drawShadowDepthCpu(renderer, state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Character::drawShadowDepthCpu(Renderer& renderer, const CharacterState& state) {
|
|
||||||
AnimationState drawState = resolveActiveState(state);
|
|
||||||
auto it = animations.find(drawState);
|
|
||||||
if (it == animations.end()) return;
|
|
||||||
|
|
||||||
renderer.PushMatrix();
|
|
||||||
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
|
||||||
renderer.ScaleMatrix(state.modelScale);
|
|
||||||
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
|
||||||
|
|
||||||
auto& anim = it->second;
|
|
||||||
for (const auto& name : anim.model.meshNamesOrdered) {
|
|
||||||
auto mit = anim.model.meshes.find(name);
|
|
||||||
if (mit == anim.model.meshes.end()) continue;
|
|
||||||
auto tit = meshTextures.find(name);
|
|
||||||
if (tit == meshTextures.end() || !tit->second) continue;
|
|
||||||
modelMutable.AssignFrom(mit->second.mesh);
|
|
||||||
modelMutable.RefreshVBO();
|
|
||||||
renderer.DrawVertexRenderStruct(modelMutable);
|
|
||||||
}
|
|
||||||
renderer.PopMatrix();
|
|
||||||
|
|
||||||
drawAttachedWeapon(renderer, state);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Character::drawShadowDepthGpuSkinning(Renderer& renderer, const CharacterState& state) {
|
void Character::drawShadowDepthGpuSkinning(Renderer& renderer, const CharacterState& state) {
|
||||||
CheckGlError(__FILE__, __LINE__);
|
CheckGlError(__FILE__, __LINE__);
|
||||||
AnimationState drawState = resolveActiveState(state);
|
BoneAnimationDataNew* anim = prepareGpuSkinning(state);
|
||||||
auto it = animations.find(drawState);
|
if (!anim) return;
|
||||||
if (it == animations.end()) return;
|
|
||||||
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
|
||||||
if (!prepareGpuSkinning(state)) return;
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
|
||||||
|
|
||||||
static const std::string shadowSkinningShader = "shadow_depth_skinning";
|
static const std::string shadowSkinningShader = "shadow_depth_skinning";
|
||||||
static const std::string boneMatricesUniform = "uBoneMatrices[0]";
|
|
||||||
|
|
||||||
renderer.shaderManager.PushShader(shadowSkinningShader);
|
renderer.shaderManager.PushShader(shadowSkinningShader);
|
||||||
|
|
||||||
renderer.PushMatrix();
|
renderer.PushMatrix();
|
||||||
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
applyModelTransform(renderer, state);
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
drawSkinnedMeshes(renderer, *anim, false);
|
||||||
renderer.ScaleMatrix(state.modelScale);
|
|
||||||
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
|
||||||
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
|
||||||
renderer.RenderUniformMatrix4fvArray(boneMatricesUniform,
|
|
||||||
static_cast<int>(it->second.gpuSkinningShaderData.skinningMatrices.size()), false,
|
|
||||||
it->second.gpuSkinningShaderData.skinningMatrices[0].data());
|
|
||||||
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
|
||||||
for (const auto& name : it->second.model.meshNamesOrdered) {
|
|
||||||
auto pit = it->second.gpuSkinningShaderData.perMesh.find(name);
|
|
||||||
if (pit == it->second.gpuSkinningShaderData.perMesh.end()) continue;
|
|
||||||
auto tit = meshTextures.find(name);
|
|
||||||
if (tit == meshTextures.end() || !tit->second) continue;
|
|
||||||
pit->second.RenderVBO(renderer);
|
|
||||||
}
|
|
||||||
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
|
||||||
renderer.PopMatrix();
|
renderer.PopMatrix();
|
||||||
renderer.shaderManager.PopShader();
|
renderer.shaderManager.PopShader();
|
||||||
|
|
||||||
@@ -508,145 +455,42 @@ void Character::drawShadowDepthGpuSkinning(Renderer& renderer, const CharacterSt
|
|||||||
// ==================== Main pass with shadows ====================
|
// ==================== Main pass with shadows ====================
|
||||||
|
|
||||||
void Character::drawWithShadow(Renderer& renderer, const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex, const Eigen::Vector3f& lightDirCamera) {
|
void Character::drawWithShadow(Renderer& renderer, const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex, const Eigen::Vector3f& lightDirCamera) {
|
||||||
auto stateSnapshot = this->stateSnapshot();
|
CharacterState state;
|
||||||
if (!stateSnapshot) return;
|
if (!prepareForDraw(state)) return;
|
||||||
CharacterState state = interpolatedState(*stateSnapshot);
|
drawHitSparks(renderer);
|
||||||
if (!state.enabled) return;
|
|
||||||
updateAnimationForRender(state);
|
|
||||||
if (hitSparkEmitter.isConfigured() && hitSparkEmitter.getActiveParticleCount() > 0) {
|
|
||||||
hitSparkEmitter.draw(renderer, 1.0f, Environment::width, Environment::height, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderer.RenderUniform1f("uAlpha", 1.0f);
|
renderer.RenderUniform1f("uAlpha", 1.0f);
|
||||||
glDisable(GL_BLEND);
|
glDisable(GL_BLEND);
|
||||||
|
|
||||||
if (state.useGpuSkinning) {
|
drawGpuSkinningWithShadow(renderer, state, lightFromCamera, shadowMapTex, lightDirCamera);
|
||||||
drawGpuSkinningWithShadow(renderer, state, lightFromCamera, shadowMapTex, lightDirCamera);
|
|
||||||
} else {
|
|
||||||
drawCpuWithShadow(renderer, state, lightFromCamera, shadowMapTex, lightDirCamera);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Character::drawCpuWithShadow(Renderer& renderer, const CharacterState& state, const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex, const Eigen::Vector3f& lightDirCamera) {
|
|
||||||
AnimationState drawState = resolveActiveState(state);
|
|
||||||
auto it = animations.find(drawState);
|
|
||||||
if (it == animations.end()) return;
|
|
||||||
|
|
||||||
static const std::string shadowShader = "fog_shadow";
|
|
||||||
|
|
||||||
renderer.shaderManager.PushShader(shadowShader);
|
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
|
||||||
renderer.RenderUniform1i("uShadowMap", 1);
|
|
||||||
renderer.RenderUniformMatrix4fv("uLightFromCamera", false, lightFromCamera.data());
|
|
||||||
renderer.RenderUniform3fv("uLightDir", lightDirCamera.data());
|
|
||||||
const float playerEyePosShadow[3] = { 0.0f, 0.0f, -Environment::zoom };
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosShadow);
|
|
||||||
|
|
||||||
glActiveTexture(GL_TEXTURE1);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, shadowMapTex);
|
|
||||||
glActiveTexture(GL_TEXTURE0);
|
|
||||||
|
|
||||||
renderer.PushPerspectiveProjectionMatrix(1.0 / 1.5,
|
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
|
|
||||||
renderer.PushMatrix();
|
|
||||||
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
|
||||||
renderer.ScaleMatrix(state.modelScale);
|
|
||||||
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
|
||||||
|
|
||||||
auto& anim = it->second;
|
|
||||||
for (const auto& name : anim.model.meshNamesOrdered) {
|
|
||||||
auto mit = anim.model.meshes.find(name);
|
|
||||||
if (mit == anim.model.meshes.end()) continue;
|
|
||||||
auto tit = meshTextures.find(name);
|
|
||||||
if (tit == meshTextures.end() || !tit->second) continue;
|
|
||||||
glBindTexture(GL_TEXTURE_2D, tit->second->getTexID());
|
|
||||||
modelMutable.AssignFrom(mit->second.mesh);
|
|
||||||
modelMutable.RefreshVBO();
|
|
||||||
renderer.DrawVertexRenderStruct(modelMutable);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderer.PopMatrix();
|
|
||||||
|
|
||||||
renderer.shaderManager.PushShader("fog");
|
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosShadow);
|
|
||||||
drawAttachedWeapon(renderer, state);
|
|
||||||
renderer.shaderManager.PopShader();
|
|
||||||
|
|
||||||
renderer.PopProjectionMatrix();
|
|
||||||
renderer.shaderManager.PopShader();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Character::drawGpuSkinningWithShadow(Renderer& renderer, const CharacterState& state, const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex, const Eigen::Vector3f& lightDirCamera) {
|
void Character::drawGpuSkinningWithShadow(Renderer& renderer, const CharacterState& state, const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex, const Eigen::Vector3f& lightDirCamera) {
|
||||||
AnimationState drawState = resolveActiveState(state);
|
|
||||||
auto it = animations.find(drawState);
|
|
||||||
if (it == animations.end()) return;
|
|
||||||
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
|
||||||
if (!prepareGpuSkinning(state)) return;
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
CheckGlError(__FILE__, __LINE__);
|
||||||
|
BoneAnimationDataNew* anim = prepareGpuSkinning(state);
|
||||||
|
if (!anim) return;
|
||||||
|
|
||||||
static const std::string skinningShadowShader = "fog_skinning_shadow";
|
static const std::string skinningShadowShader = "fog_skinning_shadow";
|
||||||
static const std::string boneMatricesUniform = "uBoneMatrices[0]";
|
|
||||||
|
|
||||||
renderer.shaderManager.PushShader(skinningShadowShader);
|
renderer.shaderManager.PushShader(skinningShadowShader);
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
renderer.RenderUniform1i(textureUniformName, 0);
|
||||||
renderer.RenderUniform1i("uShadowMap", 1);
|
renderer.RenderUniform1i("uShadowMap", 1);
|
||||||
renderer.RenderUniformMatrix4fv("uLightFromCamera", false, lightFromCamera.data());
|
renderer.RenderUniformMatrix4fv("uLightFromCamera", false, lightFromCamera.data());
|
||||||
renderer.RenderUniform3fv("uLightDir", lightDirCamera.data());
|
renderer.RenderUniform3fv("uLightDir", lightDirCamera.data());
|
||||||
const float playerEyePosSkinShadow[3] = { 0.0f, 0.0f, -Environment::zoom };
|
setPlayerEyePos(renderer);
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosSkinShadow);
|
bindShadowMap(shadowMapTex);
|
||||||
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
pushCharacterProjection(renderer);
|
||||||
|
|
||||||
glActiveTexture(GL_TEXTURE1);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, shadowMapTex);
|
|
||||||
glActiveTexture(GL_TEXTURE0);
|
|
||||||
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
|
||||||
|
|
||||||
renderer.PushPerspectiveProjectionMatrix(1.0 / 1.5,
|
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
|
|
||||||
renderer.PushMatrix();
|
renderer.PushMatrix();
|
||||||
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
applyModelTransform(renderer, state);
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
drawSkinnedMeshes(renderer, *anim, true);
|
||||||
renderer.ScaleMatrix(state.modelScale);
|
|
||||||
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
|
||||||
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
|
||||||
renderer.RenderUniformMatrix4fvArray(boneMatricesUniform,
|
|
||||||
static_cast<int>(it->second.gpuSkinningShaderData.skinningMatrices.size()), false,
|
|
||||||
it->second.gpuSkinningShaderData.skinningMatrices[0].data());
|
|
||||||
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
|
||||||
|
|
||||||
for (const auto& name : it->second.model.meshNamesOrdered) {
|
|
||||||
auto pit = it->second.gpuSkinningShaderData.perMesh.find(name);
|
|
||||||
if (pit == it->second.gpuSkinningShaderData.perMesh.end()) continue;
|
|
||||||
auto tit = meshTextures.find(name);
|
|
||||||
if (tit == meshTextures.end() || !tit->second) continue;
|
|
||||||
glBindTexture(GL_TEXTURE_2D, tit->second->getTexID());
|
|
||||||
pit->second.RenderVBO(renderer);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderer.PopMatrix();
|
renderer.PopMatrix();
|
||||||
|
|
||||||
renderer.shaderManager.PushShader("fog");
|
drawFogWeapon(renderer, state);
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosSkinShadow);
|
|
||||||
drawAttachedWeapon(renderer, state);
|
|
||||||
renderer.shaderManager.PopShader();
|
|
||||||
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
|
||||||
|
|
||||||
renderer.PopProjectionMatrix();
|
renderer.PopProjectionMatrix();
|
||||||
renderer.shaderManager.PopShader();
|
renderer.shaderManager.PopShader();
|
||||||
|
|
||||||
CheckGlError(__FILE__, __LINE__);
|
CheckGlError(__FILE__, __LINE__);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -659,25 +503,15 @@ void Character::drawNight(Renderer& renderer,
|
|||||||
const Eigen::Matrix4f& cameraViewInverse,
|
const Eigen::Matrix4f& cameraViewInverse,
|
||||||
const float* ambientColor, const float* fogColor)
|
const float* ambientColor, const float* fogColor)
|
||||||
{
|
{
|
||||||
auto stateSnapshot = this->stateSnapshot();
|
CharacterState state;
|
||||||
if (!stateSnapshot) return;
|
if (!prepareForDraw(state)) return;
|
||||||
CharacterState state = interpolatedState(*stateSnapshot);
|
drawHitSparks(renderer);
|
||||||
if (!state.enabled) return;
|
|
||||||
updateAnimationForRender(state);
|
|
||||||
if (hitSparkEmitter.isConfigured() && hitSparkEmitter.getActiveParticleCount() > 0) {
|
|
||||||
hitSparkEmitter.draw(renderer, 1.0f, Environment::width, Environment::height, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderer.RenderUniform1f("uAlpha", 1.0f);
|
renderer.RenderUniform1f("uAlpha", 1.0f);
|
||||||
glDisable(GL_BLEND);
|
glDisable(GL_BLEND);
|
||||||
|
|
||||||
if (state.useGpuSkinning) {
|
drawNightGpuSkinning(renderer, state, pointLightPosEye, pointLightDirEye, pointLightColors, pointLightCount,
|
||||||
drawNightGpuSkinning(renderer, state, pointLightPosEye, pointLightDirEye, pointLightColors, pointLightCount,
|
pointLightWorldXZ, pointLightLimitXZ, cameraViewInverse, ambientColor, fogColor);
|
||||||
pointLightWorldXZ, pointLightLimitXZ, cameraViewInverse, ambientColor, fogColor);
|
|
||||||
} else {
|
|
||||||
drawNightCpu(renderer, state, pointLightPosEye, pointLightDirEye, pointLightColors, pointLightCount,
|
|
||||||
pointLightWorldXZ, pointLightLimitXZ, cameraViewInverse, ambientColor, fogColor);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Character::drawNightGpuSkinning(Renderer& renderer,
|
void Character::drawNightGpuSkinning(Renderer& renderer,
|
||||||
@@ -686,69 +520,25 @@ void Character::drawNightGpuSkinning(Renderer& renderer,
|
|||||||
const float* plWorldXZ, const float* plLimitXZ, const Eigen::Matrix4f& cameraViewInverse,
|
const float* plWorldXZ, const float* plLimitXZ, const Eigen::Matrix4f& cameraViewInverse,
|
||||||
const float* ambientColor, const float* fogColor)
|
const float* ambientColor, const float* fogColor)
|
||||||
{
|
{
|
||||||
AnimationState drawState = resolveActiveState(state);
|
BoneAnimationDataNew* anim = prepareGpuSkinning(state);
|
||||||
auto it = animations.find(drawState);
|
if (!anim) return;
|
||||||
if (it == animations.end()) return;
|
|
||||||
|
|
||||||
if (!prepareGpuSkinning(state)) return;
|
|
||||||
|
|
||||||
|
const NightLights lights{ plPosEye, plDirEye, plColors, plCount, plWorldXZ, plLimitXZ };
|
||||||
static const std::string nightSkinningShader = "night_fog_skinning";
|
static const std::string nightSkinningShader = "night_fog_skinning";
|
||||||
static const std::string boneMatricesUniform = "uBoneMatrices[0]";
|
|
||||||
|
|
||||||
renderer.shaderManager.PushShader(nightSkinningShader);
|
renderer.shaderManager.PushShader(nightSkinningShader);
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
applyNightUniforms(renderer, lights, ambientColor, fogColor);
|
||||||
renderer.RenderUniform3fv("uAmbientColor", ambientColor);
|
|
||||||
renderer.RenderUniform3fv("uFogColor", fogColor);
|
|
||||||
const float playerEyePosNight[3] = { 0.0f, 0.0f, -Environment::zoom };
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosNight);
|
|
||||||
renderer.RenderUniform1i("uPointLightCount", plCount);
|
|
||||||
if (plCount > 0) {
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightPos[0]", plCount, plPosEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightDir[0]", plCount, plDirEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightColor[0]", plCount, plColors);
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightWorldXZ[0]", plCount, plWorldXZ);
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightLimitXZ[0]", plCount, plLimitXZ);
|
|
||||||
}
|
|
||||||
renderer.RenderUniformMatrix4fv("uViewInverse", false, cameraViewInverse.data());
|
renderer.RenderUniformMatrix4fv("uViewInverse", false, cameraViewInverse.data());
|
||||||
|
|
||||||
renderer.PushPerspectiveProjectionMatrix(1.0 / 1.5,
|
pushCharacterProjection(renderer);
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
|
|
||||||
renderer.PushMatrix();
|
renderer.PushMatrix();
|
||||||
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
applyModelTransform(renderer, state);
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
drawSkinnedMeshes(renderer, *anim, true);
|
||||||
renderer.ScaleMatrix(state.modelScale);
|
|
||||||
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
|
||||||
|
|
||||||
renderer.RenderUniformMatrix4fvArray(boneMatricesUniform,
|
|
||||||
static_cast<int>(it->second.gpuSkinningShaderData.skinningMatrices.size()), false,
|
|
||||||
it->second.gpuSkinningShaderData.skinningMatrices[0].data());
|
|
||||||
|
|
||||||
for (const auto& name : it->second.model.meshNamesOrdered) {
|
|
||||||
auto pit = it->second.gpuSkinningShaderData.perMesh.find(name);
|
|
||||||
if (pit == it->second.gpuSkinningShaderData.perMesh.end()) continue;
|
|
||||||
auto tit = meshTextures.find(name);
|
|
||||||
if (tit == meshTextures.end() || !tit->second) continue;
|
|
||||||
glBindTexture(GL_TEXTURE_2D, tit->second->getTexID());
|
|
||||||
pit->second.RenderVBO(renderer);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderer.PopMatrix();
|
renderer.PopMatrix();
|
||||||
|
|
||||||
renderer.shaderManager.PushShader("night_fog");
|
renderer.shaderManager.PushShader("night_fog");
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
applyNightUniforms(renderer, lights, ambientColor, fogColor);
|
||||||
renderer.RenderUniform3fv("uAmbientColor", ambientColor);
|
|
||||||
renderer.RenderUniform3fv("uFogColor", fogColor);
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosNight);
|
|
||||||
renderer.RenderUniform1i("uPointLightCount", plCount);
|
|
||||||
if (plCount > 0) {
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightPos[0]", plCount, plPosEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightDir[0]", plCount, plDirEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightColor[0]", plCount, plColors);
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightWorldXZ[0]", plCount, plWorldXZ);
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightLimitXZ[0]", plCount, plLimitXZ);
|
|
||||||
}
|
|
||||||
drawAttachedWeapon(renderer, state);
|
drawAttachedWeapon(renderer, state);
|
||||||
renderer.shaderManager.PopShader();
|
renderer.shaderManager.PopShader();
|
||||||
|
|
||||||
@@ -756,64 +546,6 @@ void Character::drawNightGpuSkinning(Renderer& renderer,
|
|||||||
renderer.shaderManager.PopShader();
|
renderer.shaderManager.PopShader();
|
||||||
}
|
}
|
||||||
|
|
||||||
void Character::drawNightCpu(Renderer& renderer,
|
|
||||||
const CharacterState& state,
|
|
||||||
const float* plPosEye, const float* plDirEye, const float* plColors, int plCount,
|
|
||||||
const float* plWorldXZ, const float* plLimitXZ, const Eigen::Matrix4f& cameraViewInverse,
|
|
||||||
const float* ambientColor, const float* fogColor)
|
|
||||||
{
|
|
||||||
AnimationState drawState = resolveActiveState(state);
|
|
||||||
auto it = animations.find(drawState);
|
|
||||||
if (it == animations.end()) return;
|
|
||||||
|
|
||||||
static const std::string nightShader = "night_fog";
|
|
||||||
|
|
||||||
renderer.shaderManager.PushShader(nightShader);
|
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
|
||||||
renderer.RenderUniform3fv("uAmbientColor", ambientColor);
|
|
||||||
renderer.RenderUniform3fv("uFogColor", fogColor);
|
|
||||||
const float playerEyePosNight[3] = { 0.0f, 0.0f, -Environment::zoom };
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosNight);
|
|
||||||
renderer.RenderUniform1i("uPointLightCount", plCount);
|
|
||||||
if (plCount > 0) {
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightPos[0]", plCount, plPosEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightDir[0]", plCount, plDirEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightColor[0]", plCount, plColors);
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightWorldXZ[0]", plCount, plWorldXZ);
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightLimitXZ[0]", plCount, plLimitXZ);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderer.PushPerspectiveProjectionMatrix(1.0 / 1.5,
|
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
|
|
||||||
renderer.PushMatrix();
|
|
||||||
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
|
||||||
renderer.ScaleMatrix(state.modelScale);
|
|
||||||
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
|
||||||
|
|
||||||
auto& anim = it->second;
|
|
||||||
for (const auto& name : anim.model.meshNamesOrdered) {
|
|
||||||
auto mit = anim.model.meshes.find(name);
|
|
||||||
if (mit == anim.model.meshes.end()) continue;
|
|
||||||
auto tit = meshTextures.find(name);
|
|
||||||
if (tit == meshTextures.end() || !tit->second) continue;
|
|
||||||
glBindTexture(GL_TEXTURE_2D, tit->second->getTexID());
|
|
||||||
modelMutable.AssignFrom(mit->second.mesh);
|
|
||||||
modelMutable.RefreshVBO();
|
|
||||||
renderer.DrawVertexRenderStruct(modelMutable);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderer.PopMatrix();
|
|
||||||
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosNight);
|
|
||||||
drawAttachedWeapon(renderer, state);
|
|
||||||
|
|
||||||
renderer.PopProjectionMatrix();
|
|
||||||
renderer.shaderManager.PopShader();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ==================== Night pass with spot-light + shadow ====================
|
// ==================== Night pass with spot-light + shadow ====================
|
||||||
|
|
||||||
void Character::drawNightWithShadow(Renderer& renderer,
|
void Character::drawNightWithShadow(Renderer& renderer,
|
||||||
@@ -823,26 +555,15 @@ void Character::drawNightWithShadow(Renderer& renderer,
|
|||||||
const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex,
|
const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex,
|
||||||
const float* ambientColor, const float* fogColor)
|
const float* ambientColor, const float* fogColor)
|
||||||
{
|
{
|
||||||
auto stateSnapshot = this->stateSnapshot();
|
CharacterState state;
|
||||||
if (!stateSnapshot) return;
|
if (!prepareForDraw(state)) return;
|
||||||
CharacterState state = interpolatedState(*stateSnapshot);
|
drawHitSparks(renderer);
|
||||||
if (!state.enabled) return;
|
|
||||||
updateAnimationForRender(state);
|
|
||||||
if (hitSparkEmitter.isConfigured() && hitSparkEmitter.getActiveParticleCount() > 0) {
|
|
||||||
hitSparkEmitter.draw(renderer, 1.0f, Environment::width, Environment::height, false);
|
|
||||||
}
|
|
||||||
renderer.RenderUniform1f("uAlpha", 1.0f);
|
renderer.RenderUniform1f("uAlpha", 1.0f);
|
||||||
glDisable(GL_BLEND);
|
glDisable(GL_BLEND);
|
||||||
|
|
||||||
if (state.useGpuSkinning) {
|
drawNightGpuSkinningWithShadow(renderer, state, plPosEye, plDirEye, plColors, plCount,
|
||||||
drawNightGpuSkinningWithShadow(renderer, state, plPosEye, plDirEye, plColors, plCount,
|
plWorldXZ, plLimitXZ, cameraViewInverse,
|
||||||
plWorldXZ, plLimitXZ, cameraViewInverse,
|
lightFromCamera, shadowMapTex, ambientColor, fogColor);
|
||||||
lightFromCamera, shadowMapTex, ambientColor, fogColor);
|
|
||||||
} else {
|
|
||||||
drawNightCpuWithShadow(renderer, state, plPosEye, plDirEye, plColors, plCount,
|
|
||||||
plWorldXZ, plLimitXZ, cameraViewInverse,
|
|
||||||
lightFromCamera, shadowMapTex, ambientColor, fogColor);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Character::drawNightGpuSkinningWithShadow(Renderer& renderer,
|
void Character::drawNightGpuSkinningWithShadow(Renderer& renderer,
|
||||||
@@ -853,79 +574,26 @@ void Character::drawNightGpuSkinningWithShadow(Renderer& renderer,
|
|||||||
const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex,
|
const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex,
|
||||||
const float* ambientColor, const float* fogColor)
|
const float* ambientColor, const float* fogColor)
|
||||||
{
|
{
|
||||||
AnimationState drawState = resolveActiveState(state);
|
BoneAnimationDataNew* anim = prepareGpuSkinning(state);
|
||||||
auto it = animations.find(drawState);
|
if (!anim) return;
|
||||||
if (it == animations.end()) return;
|
|
||||||
if (!prepareGpuSkinning(state)) return;
|
|
||||||
|
|
||||||
|
const NightLights lights{ plPosEye, plDirEye, plColors, plCount, plWorldXZ, plLimitXZ };
|
||||||
static const std::string nightShadowSkinningShader = "night_fog_skinning_shadow";
|
static const std::string nightShadowSkinningShader = "night_fog_skinning_shadow";
|
||||||
static const std::string boneMatricesUniform = "uBoneMatrices[0]";
|
|
||||||
|
|
||||||
renderer.shaderManager.PushShader(nightShadowSkinningShader);
|
renderer.shaderManager.PushShader(nightShadowSkinningShader);
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
applyNightShadowUniforms(renderer, lights, lightFromCamera, ambientColor, fogColor);
|
||||||
renderer.RenderUniform1i("uShadowMap", 1);
|
|
||||||
renderer.RenderUniform3fv("uAmbientColor", ambientColor);
|
|
||||||
renderer.RenderUniform3fv("uFogColor", fogColor);
|
|
||||||
renderer.RenderUniformMatrix4fv("uLightFromCamera", false, lightFromCamera.data());
|
|
||||||
if (plCount > 0) renderer.RenderUniform3fv("uLightDir", plDirEye);
|
|
||||||
|
|
||||||
const float playerEyePosNightShadow[3] = { 0.0f, 0.0f, -Environment::zoom };
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosNightShadow);
|
|
||||||
renderer.RenderUniform1i("uPointLightCount", plCount);
|
|
||||||
if (plCount > 0) {
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightPos[0]", plCount, plPosEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightDir[0]", plCount, plDirEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightColor[0]", plCount, plColors);
|
|
||||||
}
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightWorldXZ[0]", plCount, plWorldXZ);
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightLimitXZ[0]", plCount, plLimitXZ);
|
|
||||||
renderer.RenderUniformMatrix4fv("uViewInverse", false, cameraViewInverse.data());
|
renderer.RenderUniformMatrix4fv("uViewInverse", false, cameraViewInverse.data());
|
||||||
|
bindShadowMap(shadowMapTex);
|
||||||
|
|
||||||
glActiveTexture(GL_TEXTURE1);
|
pushCharacterProjection(renderer);
|
||||||
glBindTexture(GL_TEXTURE_2D, shadowMapTex);
|
|
||||||
glActiveTexture(GL_TEXTURE0);
|
|
||||||
|
|
||||||
renderer.PushPerspectiveProjectionMatrix(1.0 / 1.5,
|
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
|
|
||||||
renderer.PushMatrix();
|
renderer.PushMatrix();
|
||||||
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
applyModelTransform(renderer, state);
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
drawSkinnedMeshes(renderer, *anim, true);
|
||||||
renderer.ScaleMatrix(state.modelScale);
|
|
||||||
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
|
||||||
|
|
||||||
renderer.RenderUniformMatrix4fvArray(boneMatricesUniform,
|
|
||||||
static_cast<int>(it->second.gpuSkinningShaderData.skinningMatrices.size()), false,
|
|
||||||
it->second.gpuSkinningShaderData.skinningMatrices[0].data());
|
|
||||||
|
|
||||||
for (const auto& name : it->second.model.meshNamesOrdered) {
|
|
||||||
auto pit = it->second.gpuSkinningShaderData.perMesh.find(name);
|
|
||||||
if (pit == it->second.gpuSkinningShaderData.perMesh.end()) continue;
|
|
||||||
auto tit = meshTextures.find(name);
|
|
||||||
if (tit == meshTextures.end() || !tit->second) continue;
|
|
||||||
glBindTexture(GL_TEXTURE_2D, tit->second->getTexID());
|
|
||||||
pit->second.RenderVBO(renderer);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderer.PopMatrix();
|
renderer.PopMatrix();
|
||||||
|
|
||||||
renderer.shaderManager.PushShader("night_fog_shadow");
|
renderer.shaderManager.PushShader("night_fog_shadow");
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
applyNightShadowUniforms(renderer, lights, lightFromCamera, ambientColor, fogColor);
|
||||||
renderer.RenderUniform1i("uShadowMap", 1);
|
|
||||||
renderer.RenderUniform3fv("uAmbientColor", ambientColor);
|
|
||||||
renderer.RenderUniform3fv("uFogColor", fogColor);
|
|
||||||
renderer.RenderUniformMatrix4fv("uLightFromCamera", false, lightFromCamera.data());
|
|
||||||
if (plCount > 0) renderer.RenderUniform3fv("uLightDir", plDirEye);
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosNightShadow);
|
|
||||||
renderer.RenderUniform1i("uPointLightCount", plCount);
|
|
||||||
if (plCount > 0) {
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightPos[0]", plCount, plPosEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightDir[0]", plCount, plDirEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightColor[0]", plCount, plColors);
|
|
||||||
}
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightWorldXZ[0]", plCount, plWorldXZ);
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightLimitXZ[0]", plCount, plLimitXZ);
|
|
||||||
drawAttachedWeapon(renderer, state);
|
drawAttachedWeapon(renderer, state);
|
||||||
renderer.shaderManager.PopShader();
|
renderer.shaderManager.PopShader();
|
||||||
|
|
||||||
@@ -933,74 +601,6 @@ void Character::drawNightGpuSkinningWithShadow(Renderer& renderer,
|
|||||||
renderer.shaderManager.PopShader();
|
renderer.shaderManager.PopShader();
|
||||||
}
|
}
|
||||||
|
|
||||||
void Character::drawNightCpuWithShadow(Renderer& renderer,
|
|
||||||
const CharacterState& state,
|
|
||||||
const float* plPosEye, const float* plDirEye, const float* plColors, int plCount,
|
|
||||||
const float* plWorldXZ, const float* plLimitXZ,
|
|
||||||
const Eigen::Matrix4f& cameraViewInverse,
|
|
||||||
const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex,
|
|
||||||
const float* ambientColor, const float* fogColor)
|
|
||||||
{
|
|
||||||
AnimationState drawState = resolveActiveState(state);
|
|
||||||
auto it = animations.find(drawState);
|
|
||||||
if (it == animations.end()) return;
|
|
||||||
|
|
||||||
static const std::string nightShadowShader = "night_fog_shadow";
|
|
||||||
|
|
||||||
renderer.shaderManager.PushShader(nightShadowShader);
|
|
||||||
renderer.RenderUniform1i(textureUniformName, 0);
|
|
||||||
renderer.RenderUniform1i("uShadowMap", 1);
|
|
||||||
renderer.RenderUniform3fv("uAmbientColor", ambientColor);
|
|
||||||
renderer.RenderUniform3fv("uFogColor", fogColor);
|
|
||||||
renderer.RenderUniformMatrix4fv("uLightFromCamera", false, lightFromCamera.data());
|
|
||||||
if (plCount > 0) renderer.RenderUniform3fv("uLightDir", plDirEye);
|
|
||||||
|
|
||||||
const float playerEyePosNightShadow[3] = { 0.0f, 0.0f, -Environment::zoom };
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosNightShadow);
|
|
||||||
renderer.RenderUniform1i("uPointLightCount", plCount);
|
|
||||||
if (plCount > 0) {
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightPos[0]", plCount, plPosEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightDir[0]", plCount, plDirEye);
|
|
||||||
renderer.RenderUniform3fvArray("uPointLightColor[0]", plCount, plColors);
|
|
||||||
}
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightWorldXZ[0]", plCount, plWorldXZ);
|
|
||||||
renderer.RenderUniform2fvArray("uPointLightLimitXZ[0]", plCount, plLimitXZ);
|
|
||||||
|
|
||||||
glActiveTexture(GL_TEXTURE1);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, shadowMapTex);
|
|
||||||
glActiveTexture(GL_TEXTURE0);
|
|
||||||
|
|
||||||
renderer.PushPerspectiveProjectionMatrix(1.0 / 1.5,
|
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
|
|
||||||
renderer.PushMatrix();
|
|
||||||
renderer.TranslateMatrix({ static_cast<float>(state.position.x), static_cast<float>(state.position.y), static_cast<float>(state.position.z) });
|
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(-static_cast<float>(state.facingAngle), Eigen::Vector3f::UnitY())).toRotationMatrix());
|
|
||||||
renderer.ScaleMatrix(state.modelScale);
|
|
||||||
renderer.RotateMatrix(state.modelCorrectionRotation.toRotationMatrix());
|
|
||||||
|
|
||||||
auto& anim = it->second;
|
|
||||||
for (const auto& name : anim.model.meshNamesOrdered) {
|
|
||||||
auto mit = anim.model.meshes.find(name);
|
|
||||||
if (mit == anim.model.meshes.end()) continue;
|
|
||||||
auto tit = meshTextures.find(name);
|
|
||||||
if (tit == meshTextures.end() || !tit->second) continue;
|
|
||||||
glBindTexture(GL_TEXTURE_2D, tit->second->getTexID());
|
|
||||||
modelMutable.AssignFrom(mit->second.mesh);
|
|
||||||
modelMutable.RefreshVBO();
|
|
||||||
renderer.DrawVertexRenderStruct(modelMutable);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderer.PopMatrix();
|
|
||||||
|
|
||||||
renderer.RenderUniform3fv("uPlayerEyePos", playerEyePosNightShadow);
|
|
||||||
drawAttachedWeapon(renderer, state);
|
|
||||||
|
|
||||||
renderer.PopProjectionMatrix();
|
|
||||||
renderer.shaderManager.PopShader();
|
|
||||||
}
|
|
||||||
|
|
||||||
void Character::setupHitSparks(std::shared_ptr<Texture> sparkTexture) {
|
void Character::setupHitSparks(std::shared_ptr<Texture> sparkTexture) {
|
||||||
hitSparkEmitter.setTexture(sparkTexture);
|
hitSparkEmitter.setTexture(sparkTexture);
|
||||||
hitSparkEmitter.setShaderProgramName("spark");
|
hitSparkEmitter.setShaderProgramName("spark");
|
||||||
|
|||||||
+10
-20
@@ -31,7 +31,6 @@ public:
|
|||||||
// The aliasing shared_ptr keeps the owning GameSnapshot alive for as long
|
// The aliasing shared_ptr keeps the owning GameSnapshot alive for as long
|
||||||
// as the returned CharacterState is being read.
|
// as the returned CharacterState is being read.
|
||||||
std::shared_ptr<const CharacterState> stateSnapshot() const;
|
std::shared_ptr<const CharacterState> stateSnapshot() const;
|
||||||
static constexpr float kAttackRange = 1.25f;
|
|
||||||
|
|
||||||
// ---- Asset loading ----
|
// ---- Asset loading ----
|
||||||
void loadAnimation(AnimationState animState, const std::string& filename, const std::string& zipFile = "");
|
void loadAnimation(AnimationState animState, const std::string& filename, const std::string& zipFile = "");
|
||||||
@@ -43,7 +42,7 @@ public:
|
|||||||
void setTexture(std::shared_ptr<FRG::Texture> texture);
|
void setTexture(std::shared_ptr<FRG::Texture> texture);
|
||||||
|
|
||||||
// Creates a fully-loaded Character from a CharacterState (including its creationInfo).
|
// Creates a fully-loaded Character from a CharacterState (including its creationInfo).
|
||||||
// Loads all animations, textures, and weapon mesh/texture from the paths stored in creationInfo.
|
// Loads all animations and textures from the paths stored in creationInfo.
|
||||||
static std::unique_ptr<Character> createFromState(
|
static std::unique_ptr<Character> createFromState(
|
||||||
const CharacterState& initialState, IGameServer& server,
|
const CharacterState& initialState, IGameServer& server,
|
||||||
const std::string& locationId, const std::string& entityId,
|
const std::string& locationId, const std::string& entityId,
|
||||||
@@ -111,16 +110,12 @@ public:
|
|||||||
private:
|
private:
|
||||||
friend class Game;
|
friend class Game;
|
||||||
friend class Location;
|
friend class Location;
|
||||||
friend class ScriptEngine;
|
|
||||||
friend class LocationEditor;
|
|
||||||
friend class PathVisualization;
|
|
||||||
IGameServer& gameServer_;
|
IGameServer& gameServer_;
|
||||||
std::string locationId_;
|
std::string locationId_;
|
||||||
std::string entityId_;
|
std::string entityId_;
|
||||||
std::function<void()> onDeathAnimComplete;
|
std::function<void()> onDeathAnimComplete;
|
||||||
std::function<void(float, float, const std::string&)> onHpChanged;
|
std::function<void(float, float, const std::string&)> onHpChanged;
|
||||||
std::map<AnimationState, BoneAnimationDataNew> animations;
|
std::map<AnimationState, BoneAnimationDataNew> animations;
|
||||||
VertexRenderStruct modelMutable;
|
|
||||||
VertexRenderStruct healthBarMesh;
|
VertexRenderStruct healthBarMesh;
|
||||||
std::unordered_map<std::string, std::shared_ptr<Texture>> meshTextures;
|
std::unordered_map<std::string, std::shared_ptr<Texture>> meshTextures;
|
||||||
|
|
||||||
@@ -140,34 +135,29 @@ private:
|
|||||||
AnimationState resolveActiveState(const CharacterState& state) const;
|
AnimationState resolveActiveState(const CharacterState& state) const;
|
||||||
CharacterState interpolatedState(const CharacterState& state) const;
|
CharacterState interpolatedState(const CharacterState& state) const;
|
||||||
void updateAnimationForRender(const CharacterState& state);
|
void updateAnimationForRender(const CharacterState& state);
|
||||||
bool prepareGpuSkinning(const CharacterState& state);
|
// Interpolates the state for rendering and refreshes skinning data.
|
||||||
void drawAttachedWeapon(Renderer& renderer, const CharacterState& state);
|
// Returns false when there is nothing to draw (no state / disabled).
|
||||||
|
bool prepareForDraw(CharacterState& state);
|
||||||
|
void drawHitSparks(Renderer& renderer);
|
||||||
|
// Uploads skinning data for the active animation; nullptr if unavailable.
|
||||||
|
BoneAnimationDataNew* prepareGpuSkinning(const CharacterState& state);
|
||||||
|
void drawSkinnedMeshes(Renderer& renderer, BoneAnimationDataNew& anim, bool bindTextures);
|
||||||
|
void drawAttachedWeapon(Renderer& renderer, const CharacterState& state);
|
||||||
|
void drawFogWeapon(Renderer& renderer, const CharacterState& state);
|
||||||
|
|
||||||
void drawGpuSkinning(Renderer& renderer, const CharacterState& state);
|
void drawGpuSkinning(Renderer& renderer, const CharacterState& state);
|
||||||
void drawShadowDepthGpuSkinning(Renderer& renderer, const CharacterState& state);
|
void drawShadowDepthGpuSkinning(Renderer& renderer, const CharacterState& state);
|
||||||
void drawShadowDepthCpu(Renderer& renderer, const CharacterState& state);
|
|
||||||
void drawGpuSkinningWithShadow(Renderer& renderer, const CharacterState& state, const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex, const Eigen::Vector3f& lightDirCamera);
|
void drawGpuSkinningWithShadow(Renderer& renderer, const CharacterState& state, const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex, const Eigen::Vector3f& lightDirCamera);
|
||||||
void drawCpuWithShadow(Renderer& renderer, const CharacterState& state, const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex, const Eigen::Vector3f& lightDirCamera);
|
|
||||||
void drawNightGpuSkinning(Renderer& renderer,
|
void drawNightGpuSkinning(Renderer& renderer,
|
||||||
const CharacterState& state,
|
const CharacterState& state,
|
||||||
const float* plPosEye, const float* plDirEye, const float* plColors, int plCount,
|
const float* plPosEye, const float* plDirEye, const float* plColors, int plCount,
|
||||||
const float* plWorldXZ, const float* plLimitXZ, const Eigen::Matrix4f& cameraViewInverse,
|
const float* plWorldXZ, const float* plLimitXZ, const Eigen::Matrix4f& cameraViewInverse,
|
||||||
const float* ambientColor, const float* fogColor);
|
const float* ambientColor, const float* fogColor);
|
||||||
void drawNightCpu(Renderer& renderer,
|
|
||||||
const CharacterState& state,
|
|
||||||
const float* plPosEye, const float* plDirEye, const float* plColors, int plCount,
|
|
||||||
const float* plWorldXZ, const float* plLimitXZ, const Eigen::Matrix4f& cameraViewInverse,
|
|
||||||
const float* ambientColor, const float* fogColor);
|
|
||||||
void drawNightGpuSkinningWithShadow(Renderer& renderer,
|
void drawNightGpuSkinningWithShadow(Renderer& renderer,
|
||||||
const CharacterState& state,
|
const CharacterState& state,
|
||||||
const float* plPosEye, const float* plDirEye, const float* plColors, int plCount,
|
const float* plPosEye, const float* plDirEye, const float* plColors, int plCount,
|
||||||
const float* plWorldXZ, const float* plLimitXZ, const Eigen::Matrix4f& cameraViewInverse,
|
const float* plWorldXZ, const float* plLimitXZ, const Eigen::Matrix4f& cameraViewInverse,
|
||||||
const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex, const float* ambientColor, const float* fogColor);
|
const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex, const float* ambientColor, const float* fogColor);
|
||||||
void drawNightCpuWithShadow(Renderer& renderer,
|
|
||||||
const CharacterState& state,
|
|
||||||
const float* plPosEye, const float* plDirEye, const float* plColors, int plCount,
|
|
||||||
const float* plWorldXZ, const float* plLimitXZ, const Eigen::Matrix4f& cameraViewInverse,
|
|
||||||
const Eigen::Matrix4f& lightFromCamera, GLuint shadowMapTex, const float* ambientColor, const float* fogColor);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace FRG
|
} // namespace FRG
|
||||||
+81
-114
@@ -7,18 +7,16 @@
|
|||||||
namespace FRG {
|
namespace FRG {
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
constexpr float kPi = 3.14159265358979323846f;
|
||||||
// Tick counts are authoritative and therefore independent of render rate.
|
// Tick counts are authoritative and therefore independent of render rate.
|
||||||
constexpr float ATTACK_COOLDOWN_TIME = 1.6f;
|
constexpr float ATTACK_COOLDOWN_TIME = 1.6f;
|
||||||
constexpr float HOME_DRIFT_CHECK_INTERVAL = 5.0f;
|
constexpr float HOME_DRIFT_CHECK_INTERVAL = 5.0f;
|
||||||
fp HOME_DRIFT_CHECK_INTERVAL_FP = static_cast<fp>(HOME_DRIFT_CHECK_INTERVAL);
|
const fp HOME_DRIFT_CHECK_INTERVAL_FP = static_cast<fp>(HOME_DRIFT_CHECK_INTERVAL);
|
||||||
|
// An NPC farther than this from its home position (squared) walks back.
|
||||||
|
const fp MAX_HOME_DRIFT_SQUARED = static_cast<fp>(3.f * 3.f);
|
||||||
constexpr float TARGET_REPLAN_THRESHOLD = 0.25f;
|
constexpr float TARGET_REPLAN_THRESHOLD = 0.25f;
|
||||||
|
|
||||||
fp TARGET_REPLAN_THRESHOLD_SQUARED = static_cast<fp>(TARGET_REPLAN_THRESHOLD * TARGET_REPLAN_THRESHOLD);
|
const fp TARGET_REPLAN_THRESHOLD_SQUARED = static_cast<fp>(TARGET_REPLAN_THRESHOLD * TARGET_REPLAN_THRESHOLD);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
constexpr float PI = 3.14159265358979323846f;
|
|
||||||
constexpr int BLOCKED_REPLAN_TICKS = 3;
|
|
||||||
|
|
||||||
std::uint32_t stableIdHash(const std::string& value)
|
std::uint32_t stableIdHash(const std::string& value)
|
||||||
{
|
{
|
||||||
@@ -36,10 +34,13 @@ void CharacterState::configureAsPlayer() {
|
|||||||
rotationSpeed = static_cast < fp>(8.0f);
|
rotationSpeed = static_cast < fp>(8.0f);
|
||||||
modelScale = 1.f;
|
modelScale = 1.f;
|
||||||
modelCorrectionRotation = Eigen::Quaternionf(
|
modelCorrectionRotation = Eigen::Quaternionf(
|
||||||
Eigen::AngleAxisf(PI, Eigen::Vector3f::UnitY()) *
|
Eigen::AngleAxisf(kPi, Eigen::Vector3f::UnitY()) *
|
||||||
Eigen::AngleAxisf(-PI * 0.5f, Eigen::Vector3f::UnitX()));
|
Eigen::AngleAxisf(-kPi * 0.5f, Eigen::Vector3f::UnitX()));
|
||||||
canAttack = true;
|
canAttack = true;
|
||||||
isPlayer = true;
|
isPlayer = true;
|
||||||
|
animationPlaybackRates.fill(1.0f);
|
||||||
|
animationPlaybackRates[static_cast<std::size_t>(AnimationState::STAND_TO_ACTION)] = 2.0f;
|
||||||
|
animationPlaybackRates[static_cast<std::size_t>(AnimationState::ACTION_TO_STAND)] = 2.0f;
|
||||||
}
|
}
|
||||||
|
|
||||||
void CharacterState::configureNavigationRetryCooldowns(
|
void CharacterState::configureNavigationRetryCooldowns(
|
||||||
@@ -91,20 +92,47 @@ void CharacterState::stopInPlace() {
|
|||||||
pathWaypoints.clear();
|
pathWaypoints.clear();
|
||||||
currentWaypointIndex = 0;
|
currentWaypointIndex = 0;
|
||||||
onArrivedCallbackName.clear();
|
onArrivedCallbackName.clear();
|
||||||
movementBlockedTicks = 0;
|
navigationOutcome = PathFinder::PathOutcome::ReachedExactGoal;
|
||||||
navigationRetryTicks = 0;
|
navigationRetryTicks = 0;
|
||||||
velocity = Vec2fp(fp(0), fp(0));
|
velocity = Vec2fp(fp(0), fp(0));
|
||||||
preferredVelocity = Vec2fp(fp(0), fp(0));
|
preferredVelocity = Vec2fp(fp(0), fp(0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void CharacterState::applyPathTo(
|
||||||
|
const Vec3fp& target, const LocationNetworkState& location)
|
||||||
|
{
|
||||||
|
if (location.activeNavigationIndex < 0 ||
|
||||||
|
location.activeNavigationIndex >= static_cast<int>(location.navigationMaps.size())) {
|
||||||
|
walkTarget = Vec3fp(position.x, static_cast<fp>(0.f), position.z);
|
||||||
|
navigationOutcome = PathFinder::PathOutcome::NoPath;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto pathResult = location.navigationMaps[location.activeNavigationIndex]
|
||||||
|
.findPathResult(this->position, target);
|
||||||
|
pathWaypoints = pathResult.waypoints;
|
||||||
|
navigationOutcome = pathResult.outcome;
|
||||||
|
|
||||||
|
// Сразу целимся во второй элемент (индекс 1), так как индекс 0 — это точка старта
|
||||||
|
currentWaypointIndex = (pathWaypoints.size() > 1) ? 1 : 0;
|
||||||
|
navigationRetryTicks = 0;
|
||||||
|
|
||||||
|
if (!pathWaypoints.empty()) {
|
||||||
|
for (Vec3fp& waypoint : pathWaypoints)
|
||||||
|
waypoint.y = static_cast<fp>(0.f);
|
||||||
|
walkTarget = pathWaypoints.back();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
walkTarget = Vec3fp(position.x, static_cast<fp>(0.f), position.z);
|
||||||
|
if (!isPlayer) scheduleNextNavigationRetry();
|
||||||
|
}
|
||||||
|
|
||||||
void CharacterState::setTarget(
|
void CharacterState::setTarget(
|
||||||
const Vec3fp& target,
|
const Vec3fp& target,
|
||||||
std::string callbackName,
|
std::string callbackName,
|
||||||
const LocationNetworkState& location,
|
const LocationNetworkState& location)
|
||||||
const std::string& entityId)
|
|
||||||
{
|
{
|
||||||
|
|
||||||
|
|
||||||
const Vec3fp normalizedTarget(target.x, static_cast<fp>(0.f), target.z);
|
const Vec3fp normalizedTarget(target.x, static_cast<fp>(0.f), target.z);
|
||||||
const bool sameRequestedTarget =
|
const bool sameRequestedTarget =
|
||||||
(normalizedTarget - requestedWalkTarget).normSquared() <= TARGET_REPLAN_THRESHOLD_SQUARED;
|
(normalizedTarget - requestedWalkTarget).normSquared() <= TARGET_REPLAN_THRESHOLD_SQUARED;
|
||||||
@@ -121,65 +149,30 @@ void CharacterState::setTarget(
|
|||||||
|
|
||||||
requestedWalkTarget = normalizedTarget;
|
requestedWalkTarget = normalizedTarget;
|
||||||
onArrivedCallbackName = std::move(callbackName);
|
onArrivedCallbackName = std::move(callbackName);
|
||||||
movementBlockedTicks = 0;
|
|
||||||
navigationRetryTicks = 0;
|
navigationRetryTicks = 0;
|
||||||
|
applyPathTo(normalizedTarget, location);
|
||||||
// В setTarget и forceReplan:
|
|
||||||
if (location.activeNavigationIndex < 0 ||
|
|
||||||
location.activeNavigationIndex >= static_cast<int>(location.navigationMaps.size())) {
|
|
||||||
walkTarget = Vec3fp(position.x, static_cast<fp>(0.f), position.z);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
pathWaypoints = location.navigationMaps[location.activeNavigationIndex]
|
|
||||||
.findPathToNearest(this->position, normalizedTarget);
|
|
||||||
|
|
||||||
// Сразу целимся во второй элемент (индекс 1), так как индекс 0 — это точка старта
|
|
||||||
currentWaypointIndex = (pathWaypoints.size() > 1) ? 1 : 0;
|
|
||||||
|
|
||||||
if (!pathWaypoints.empty()) {
|
|
||||||
for (Vec3fp& waypoint : pathWaypoints)
|
|
||||||
{
|
|
||||||
waypoint.y = static_cast<fp>(0.f);
|
|
||||||
}
|
|
||||||
walkTarget = pathWaypoints.back();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
walkTarget = Vec3fp(position.x, static_cast<fp>(0.f), position.z);
|
|
||||||
if (!isPlayer) scheduleNextNavigationRetry();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void CharacterState::forceReplan(
|
void CharacterState::forceReplan(const LocationNetworkState& location)
|
||||||
const LocationNetworkState& location,
|
|
||||||
const std::string& entityId)
|
|
||||||
{
|
{
|
||||||
const Vec3fp normalizedTarget(
|
const Vec3fp normalizedTarget(
|
||||||
requestedWalkTarget.x, static_cast<fp>(0.f), requestedWalkTarget.z);
|
requestedWalkTarget.x, static_cast<fp>(0.f), requestedWalkTarget.z);
|
||||||
|
applyPathTo(normalizedTarget, location);
|
||||||
|
}
|
||||||
|
|
||||||
if (location.activeNavigationIndex < 0 ||
|
void CharacterState::updateFaceTarget(const CharacterObservation* faceTarget)
|
||||||
location.activeNavigationIndex >= static_cast<int>(location.navigationMaps.size())) {
|
{
|
||||||
walkTarget = Vec3fp(position.x, static_cast<fp>(0.f), position.z);
|
if (faceTarget) {
|
||||||
return;
|
Vec3fp toFace = faceTarget->position - position;
|
||||||
|
toFace.y = fp(0);
|
||||||
|
const fp distanceToFace = fpm::sqrt(toFace.normSquared());
|
||||||
|
targetFacingAngle = distanceToFace > static_cast<fp>(1e-3f)
|
||||||
|
? fpm::atan2(toFace.x / distanceToFace, -toFace.z / distanceToFace)
|
||||||
|
: facingAngle;
|
||||||
}
|
}
|
||||||
|
else if (!faceTargetId.empty()) {
|
||||||
pathWaypoints = location.navigationMaps[location.activeNavigationIndex]
|
faceTargetId.clear();
|
||||||
.findPathToNearest(this->position, normalizedTarget);
|
|
||||||
|
|
||||||
currentWaypointIndex = (pathWaypoints.size() > 1) ? 1 : 0;
|
|
||||||
movementBlockedTicks = 0;
|
|
||||||
navigationRetryTicks = 0;
|
|
||||||
|
|
||||||
if (!pathWaypoints.empty()) {
|
|
||||||
for (Vec3fp& waypoint : pathWaypoints) {
|
|
||||||
waypoint.y = static_cast<fp>(0.f);
|
|
||||||
}
|
|
||||||
walkTarget = pathWaypoints.back();
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
walkTarget = Vec3fp(position.x, static_cast<fp>(0.f), position.z);
|
|
||||||
if (!isPlayer) scheduleNextNavigationRetry();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void CharacterState::stopAndRotateToTarget(std::string characterId)
|
void CharacterState::stopAndRotateToTarget(std::string characterId)
|
||||||
@@ -229,9 +222,7 @@ CharacterUpdateEvents CharacterState::update(
|
|||||||
std::int64_t deltaMs, const CharacterUpdateContext& context)
|
std::int64_t deltaMs, const CharacterUpdateContext& context)
|
||||||
{
|
{
|
||||||
CharacterUpdateEvents events;
|
CharacterUpdateEvents events;
|
||||||
movedLastTick = false;
|
|
||||||
if (!enabled) return events;
|
if (!enabled) return events;
|
||||||
bool navigationPausedThisTick = false;
|
|
||||||
|
|
||||||
const CharacterObservation* attackTarget = context.attackTarget;
|
const CharacterObservation* attackTarget = context.attackTarget;
|
||||||
const CharacterObservation* faceTarget = context.faceTarget;
|
const CharacterObservation* faceTarget = context.faceTarget;
|
||||||
@@ -241,27 +232,21 @@ CharacterUpdateEvents CharacterState::update(
|
|||||||
attackTargetId.clear();
|
attackTargetId.clear();
|
||||||
} else {
|
} else {
|
||||||
const fp distanceSquared = (attackTarget->position - position).normSquared();
|
const fp distanceSquared = (attackTarget->position - position).normSquared();
|
||||||
if (distanceSquared >= visibleRange* visibleRange) {
|
if (distanceSquared >= visibleRange * visibleRange ||
|
||||||
|
distanceSquared >= static_cast<fp>(kAttackRange * kAttackRange)) {
|
||||||
|
// Out of attack range: chase the target.
|
||||||
if ((attackTarget->position - requestedWalkTarget).normSquared() >
|
if ((attackTarget->position - requestedWalkTarget).normSquared() >
|
||||||
TARGET_REPLAN_THRESHOLD_SQUARED) {
|
TARGET_REPLAN_THRESHOLD_SQUARED) {
|
||||||
events.navigationRequested = true;
|
events.navigationRequested = true;
|
||||||
events.navigationTarget = attackTarget->position;
|
events.navigationTarget = attackTarget->position;
|
||||||
}
|
}
|
||||||
battle_state = 0;
|
battle_state = 0;
|
||||||
} else if (distanceSquared >= static_cast<fp>(1.25f*1.25f)) {
|
|
||||||
if ((attackTarget->position - requestedWalkTarget).normSquared() > TARGET_REPLAN_THRESHOLD_SQUARED) {
|
|
||||||
events.navigationRequested = true;
|
|
||||||
events.navigationTarget = attackTarget->position;
|
|
||||||
}
|
|
||||||
battle_state = 0;
|
|
||||||
} else {
|
} else {
|
||||||
battle_state = 1;
|
battle_state = 1;
|
||||||
velocity = Vec2fp(fp(0), fp(0));
|
velocity = Vec2fp(fp(0), fp(0));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const Vec3fp activeTarget = getCurrentNavigationTarget();
|
|
||||||
|
|
||||||
preferredVelocity = Vec2fp(fp(0), fp(0));
|
preferredVelocity = Vec2fp(fp(0), fp(0));
|
||||||
|
|
||||||
if (hp > 0.f && battle_state == 0 && !pathWaypoints.empty() &&
|
if (hp > 0.f && battle_state == 0 && !pathWaypoints.empty() &&
|
||||||
@@ -316,25 +301,22 @@ CharacterUpdateEvents CharacterState::update(
|
|||||||
currentWaypointIndex = 0;
|
currentWaypointIndex = 0;
|
||||||
|
|
||||||
if (completedPath &&
|
if (completedPath &&
|
||||||
|
navigationOutcome == PathFinder::PathOutcome::ReachedExactGoal &&
|
||||||
(requestedWalkTarget - position).normSquared() > TARGET_REPLAN_THRESHOLD_SQUARED &&
|
(requestedWalkTarget - position).normSquared() > TARGET_REPLAN_THRESHOLD_SQUARED &&
|
||||||
!isPlayer) {
|
!isPlayer) {
|
||||||
scheduleNextNavigationRetry();
|
scheduleNextNavigationRetry();
|
||||||
}
|
}
|
||||||
if (completedPath && !onArrivedCallbackName.empty()) {
|
if (completedPath &&
|
||||||
|
navigationOutcome == PathFinder::PathOutcome::ReachedExactGoal &&
|
||||||
|
!onArrivedCallbackName.empty()) {
|
||||||
events.arrivedCallbackName = onArrivedCallbackName;
|
events.arrivedCallbackName = onArrivedCallbackName;
|
||||||
onArrivedCallbackName.clear();
|
onArrivedCallbackName.clear();
|
||||||
}
|
}
|
||||||
if (faceTarget) {
|
else if (completedPath &&
|
||||||
Vec3fp toFace = faceTarget->position - position;
|
navigationOutcome != PathFinder::PathOutcome::ReachedExactGoal) {
|
||||||
toFace.y = fp(0);
|
onArrivedCallbackName.clear();
|
||||||
const fp distanceToFace = fpm::sqrt(toFace.normSquared());
|
|
||||||
targetFacingAngle = distanceToFace > static_cast<fp>(1e-3f)
|
|
||||||
? fpm::atan2(toFace.x / distanceToFace, -toFace.z / distanceToFace)
|
|
||||||
: facingAngle;
|
|
||||||
}
|
|
||||||
else if (!faceTargetId.empty()) {
|
|
||||||
faceTargetId.clear();
|
|
||||||
}
|
}
|
||||||
|
updateFaceTarget(faceTarget);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (hp > 0.f && battle_state == 0 && pathWaypoints.empty() &&
|
else if (hp > 0.f && battle_state == 0 && pathWaypoints.empty() &&
|
||||||
@@ -346,21 +328,10 @@ CharacterUpdateEvents CharacterState::update(
|
|||||||
currentState = AnimationState::STAND;
|
currentState = AnimationState::STAND;
|
||||||
resetAnim = true;
|
resetAnim = true;
|
||||||
}
|
}
|
||||||
if (faceTarget) {
|
updateFaceTarget(faceTarget);
|
||||||
Vec3fp toFace = faceTarget->position - position;
|
|
||||||
toFace.y = fp(0);
|
|
||||||
const fp distanceToFace = fpm::sqrt(toFace.normSquared());
|
|
||||||
targetFacingAngle = distanceToFace > static_cast<fp>(1e-3f)
|
|
||||||
? fpm::atan2(toFace.x / distanceToFace, -toFace.z / distanceToFace)
|
|
||||||
: facingAngle;
|
|
||||||
}
|
|
||||||
else if (!faceTargetId.empty()) {
|
|
||||||
faceTargetId.clear();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!isPlayer && pathWaypoints.empty() &&
|
||||||
if (!isPlayer && !navigationPausedThisTick && pathWaypoints.empty() &&
|
|
||||||
(requestedWalkTarget - position).normSquared() > TARGET_REPLAN_THRESHOLD_SQUARED &&
|
(requestedWalkTarget - position).normSquared() > TARGET_REPLAN_THRESHOLD_SQUARED &&
|
||||||
!events.navigationRequested) {
|
!events.navigationRequested) {
|
||||||
if (navigationRetryTicks > 0) --navigationRetryTicks;
|
if (navigationRetryTicks > 0) --navigationRetryTicks;
|
||||||
@@ -407,7 +378,7 @@ CharacterUpdateEvents CharacterState::update(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fp angleDiff = targetFacingAngle - facingAngle;
|
fp angleDiff = targetFacingAngle - facingAngle;
|
||||||
const fp PIfp = static_cast<fp>(PI);
|
const fp PIfp = static_cast<fp>(kPi);
|
||||||
while (angleDiff > PIfp) angleDiff -= static_cast<fp>(2.f) * PIfp;
|
while (angleDiff > PIfp) angleDiff -= static_cast<fp>(2.f) * PIfp;
|
||||||
while (angleDiff < -PIfp) angleDiff += static_cast<fp>(2.f) * PIfp;
|
while (angleDiff < -PIfp) angleDiff += static_cast<fp>(2.f) * PIfp;
|
||||||
const fp rotationStep = rotationSpeed * static_cast<fp>(deltaMs) / static_cast<fp>(1000.f);
|
const fp rotationStep = rotationSpeed * static_cast<fp>(deltaMs) / static_cast<fp>(1000.f);
|
||||||
@@ -418,13 +389,13 @@ CharacterUpdateEvents CharacterState::update(
|
|||||||
facingAngle += angleDiff > static_cast<fp>(0.f) ? rotationStep : -rotationStep;
|
facingAngle += angleDiff > static_cast<fp>(0.f) ? rotationStep : -rotationStep;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isPlayer && hp > 0.f && battle_state == 0 && maxHomeDriftSquared > static_cast<fp>(0.f)) {
|
if (!isPlayer && hp > 0.f && battle_state == 0) {
|
||||||
homeDriftCheckTimer -= static_cast<fp>(deltaMs) / static_cast<fp>(1000.f);
|
homeDriftCheckTimer -= static_cast<fp>(deltaMs) / static_cast<fp>(1000.f);
|
||||||
if (homeDriftCheckTimer <= static_cast <fp>(0.f)) {
|
if (homeDriftCheckTimer <= static_cast <fp>(0.f)) {
|
||||||
homeDriftCheckTimer = HOME_DRIFT_CHECK_INTERVAL_FP;
|
homeDriftCheckTimer = HOME_DRIFT_CHECK_INTERVAL_FP;
|
||||||
Vec3fp toHome = homePosition - position;
|
Vec3fp toHome = homePosition - position;
|
||||||
toHome.y = static_cast<fp>(0.f);
|
toHome.y = static_cast<fp>(0.f);
|
||||||
if (!isMoving() && toHome.normSquared() > maxHomeDriftSquared) {
|
if (!isMoving() && toHome.normSquared() > MAX_HOME_DRIFT_SQUARED) {
|
||||||
events.navigationRequested = true;
|
events.navigationRequested = true;
|
||||||
events.navigationTarget = homePosition;
|
events.navigationTarget = homePosition;
|
||||||
}
|
}
|
||||||
@@ -438,7 +409,11 @@ CharacterUpdateEvents CharacterState::update(
|
|||||||
? static_cast<float>(animationStartFrames[index]) : 0.f;
|
? static_cast<float>(animationStartFrames[index]) : 0.f;
|
||||||
}
|
}
|
||||||
const int previousFrame = static_cast<int>(animationFrame);
|
const int previousFrame = static_cast<int>(animationFrame);
|
||||||
animationFrame += static_cast<float>(deltaMs) / 24.f;
|
const auto animationIndex = static_cast<std::size_t>(currentState);
|
||||||
|
const float playbackRate =
|
||||||
|
animationIndex < animationPlaybackRates.size()
|
||||||
|
? animationPlaybackRates[animationIndex] : 1.0f;
|
||||||
|
animationFrame += static_cast<float>(deltaMs) / 24.f * playbackRate;
|
||||||
|
|
||||||
if (previousFrame < 19 && static_cast<int>(animationFrame) >= 19 &&
|
if (previousFrame < 19 && static_cast<int>(animationFrame) >= 19 &&
|
||||||
(currentState == AnimationState::ACTION_ATTACK ||
|
(currentState == AnimationState::ACTION_ATTACK ||
|
||||||
@@ -468,7 +443,6 @@ CharacterUpdateEvents CharacterState::update(
|
|||||||
currentState == AnimationState::ACTION_ATTACK ||
|
currentState == AnimationState::ACTION_ATTACK ||
|
||||||
currentState == AnimationState::ACTION_IDLE;
|
currentState == AnimationState::ACTION_IDLE;
|
||||||
|
|
||||||
const auto animationIndex = static_cast<std::size_t>(currentState);
|
|
||||||
const int frameCount = animationIndex < animationFrameCounts.size()
|
const int frameCount = animationIndex < animationFrameCounts.size()
|
||||||
? animationFrameCounts[animationIndex] : 1;
|
? animationFrameCounts[animationIndex] : 1;
|
||||||
if (frameCount > 1 && static_cast<int>(animationFrame) >= frameCount - 1) {
|
if (frameCount > 1 && static_cast<int>(animationFrame) >= frameCount - 1) {
|
||||||
@@ -516,10 +490,9 @@ void CharacterState::save(nlohmann::json& out) const
|
|||||||
}
|
}
|
||||||
out["pathWaypoints"] = std::move(wpArr);
|
out["pathWaypoints"] = std::move(wpArr);
|
||||||
out["currentWaypointIndex"] = currentWaypointIndex;
|
out["currentWaypointIndex"] = currentWaypointIndex;
|
||||||
|
out["navigationOutcome"] = static_cast<int>(navigationOutcome);
|
||||||
out["homeDriftCheckTimer"] = static_cast<double>(homeDriftCheckTimer);
|
out["homeDriftCheckTimer"] = static_cast<double>(homeDriftCheckTimer);
|
||||||
out["movementBlockedTicks"] = movementBlockedTicks;
|
|
||||||
out["navigationRetryTicks"] = navigationRetryTicks;
|
out["navigationRetryTicks"] = navigationRetryTicks;
|
||||||
out["movedLastTick"] = movedLastTick;
|
|
||||||
out["velocity"] = {
|
out["velocity"] = {
|
||||||
velocity.x.raw_value(),
|
velocity.x.raw_value(),
|
||||||
velocity.y.raw_value()
|
velocity.y.raw_value()
|
||||||
@@ -535,12 +508,6 @@ void CharacterState::save(nlohmann::json& out) const
|
|||||||
|
|
||||||
void CharacterState::load(const nlohmann::json& in)
|
void CharacterState::load(const nlohmann::json& in)
|
||||||
{
|
{
|
||||||
auto readVec3 = [](const nlohmann::json& j, Eigen::Vector3f def) -> Eigen::Vector3f {
|
|
||||||
if (j.is_array() && j.size() == 3)
|
|
||||||
return { j[0].get<float>(), j[1].get<float>(), j[2].get<float>() };
|
|
||||||
return def;
|
|
||||||
};
|
|
||||||
|
|
||||||
auto readVec3fp = [](const nlohmann::json& j, Vec3fp def) -> Vec3fp {
|
auto readVec3fp = [](const nlohmann::json& j, Vec3fp def) -> Vec3fp {
|
||||||
if (j.is_array() && j.size() == 3)
|
if (j.is_array() && j.size() == 3)
|
||||||
return Vec3fp{ static_cast<fp>(j[0].get<double>()), static_cast<fp>(j[1].get<double>()), static_cast<fp>(j[2].get<double>()) };
|
return Vec3fp{ static_cast<fp>(j[0].get<double>()), static_cast<fp>(j[1].get<double>()), static_cast<fp>(j[2].get<double>()) };
|
||||||
@@ -573,10 +540,10 @@ void CharacterState::load(const nlohmann::json& in)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
currentWaypointIndex = in.value("currentWaypointIndex", currentWaypointIndex);
|
currentWaypointIndex = in.value("currentWaypointIndex", currentWaypointIndex);
|
||||||
|
navigationOutcome = static_cast<PathFinder::PathOutcome>(
|
||||||
|
in.value("navigationOutcome", static_cast<int>(navigationOutcome)));
|
||||||
homeDriftCheckTimer = static_cast<fp>(in.value("homeDriftCheckTimer", static_cast<double>(homeDriftCheckTimer)));
|
homeDriftCheckTimer = static_cast<fp>(in.value("homeDriftCheckTimer", static_cast<double>(homeDriftCheckTimer)));
|
||||||
movementBlockedTicks = in.value("movementBlockedTicks", movementBlockedTicks);
|
|
||||||
navigationRetryTicks = in.value("navigationRetryTicks", navigationRetryTicks);
|
navigationRetryTicks = in.value("navigationRetryTicks", navigationRetryTicks);
|
||||||
movedLastTick = in.value("movedLastTick", movedLastTick);
|
|
||||||
const auto& velocityValue = in.at("velocity");
|
const auto& velocityValue = in.at("velocity");
|
||||||
if (!velocityValue.is_array() || velocityValue.size() != 2 ||
|
if (!velocityValue.is_array() || velocityValue.size() != 2 ||
|
||||||
!velocityValue[0].is_number_integer() ||
|
!velocityValue[0].is_number_integer() ||
|
||||||
|
|||||||
+17
-21
@@ -14,7 +14,12 @@
|
|||||||
namespace FRG {
|
namespace FRG {
|
||||||
|
|
||||||
constexpr float VISIBLE_RANGE = 6.f;
|
constexpr float VISIBLE_RANGE = 6.f;
|
||||||
|
// Distance at which a character starts attacking its target.
|
||||||
|
constexpr float kAttackRange = 1.25f;
|
||||||
|
// How close the player must be to a peaceful NPC to start a conversation.
|
||||||
|
constexpr float kNpcTalkDistance = 1.35f;
|
||||||
|
|
||||||
|
struct CharacterObservation;
|
||||||
struct CharacterUpdateContext;
|
struct CharacterUpdateContext;
|
||||||
struct CharacterUpdateEvents;
|
struct CharacterUpdateEvents;
|
||||||
struct LocationNetworkState;
|
struct LocationNetworkState;
|
||||||
@@ -42,16 +47,6 @@ struct CharacterCreationInfo {
|
|||||||
std::unordered_map<std::string, std::string> meshTexturePaths;
|
std::unordered_map<std::string, std::string> meshTexturePaths;
|
||||||
// Single shared texture path (used when setTexture(shared_ptr) was called on all meshes).
|
// Single shared texture path (used when setTexture(shared_ptr) was called on all meshes).
|
||||||
std::string singleTexturePath;
|
std::string singleTexturePath;
|
||||||
// Weapon asset paths and attachment setup
|
|
||||||
std::string weaponMeshPath;
|
|
||||||
std::string weaponTexturePath;
|
|
||||||
std::string weaponAttachBoneName = "RightHand";
|
|
||||||
Eigen::Vector3f weaponInitialPosition = Eigen::Vector3f::Zero();
|
|
||||||
// Weapon orientation stored as a quaternion (serializable as 4 floats).
|
|
||||||
Eigen::Quaternionf weaponInitialRotation = Eigen::Quaternionf::Identity();
|
|
||||||
// Optional mesh-space transformations applied after loading the weapon mesh.
|
|
||||||
Eigen::Vector3f weaponMeshMove = Eigen::Vector3f::Zero();
|
|
||||||
float weaponMeshScale = 1.0f;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// All serializable authoritative state for a character. GameState or
|
// All serializable authoritative state for a character. GameState or
|
||||||
@@ -99,7 +94,6 @@ public:
|
|||||||
|
|
||||||
// --- Home position for drift recovery ---
|
// --- Home position for drift recovery ---
|
||||||
Vec3fp homePosition;
|
Vec3fp homePosition;
|
||||||
fp maxHomeDriftSquared = static_cast<fp>(3.f*3.f);
|
|
||||||
|
|
||||||
// --- Authoritative logical animation clock ---
|
// --- Authoritative logical animation clock ---
|
||||||
// Frame counts are immutable metadata copied from loaded clips during
|
// Frame counts are immutable metadata copied from loaded clips during
|
||||||
@@ -107,6 +101,9 @@ public:
|
|||||||
float animationFrame = 0.0f;
|
float animationFrame = 0.0f;
|
||||||
std::array<int, 9> animationStartFrames = {{0, 0, 0, 0, 0, 0, 0, 0, 0}};
|
std::array<int, 9> animationStartFrames = {{0, 0, 0, 0, 0, 0, 0, 0, 0}};
|
||||||
std::array<int, 9> animationFrameCounts = {{1, 1, 1, 1, 1, 1, 1, 1, 1}};
|
std::array<int, 9> animationFrameCounts = {{1, 1, 1, 1, 1, 1, 1, 1, 1}};
|
||||||
|
std::array<float, 9> animationPlaybackRates = {{
|
||||||
|
1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
|
||||||
|
1.0f, 1.0f, 1.0f, 1.0f}};
|
||||||
|
|
||||||
// --- Movement / visual parameters ---
|
// --- Movement / visual parameters ---
|
||||||
fp walkSpeed = static_cast<fp>(3.0f);
|
fp walkSpeed = static_cast<fp>(3.0f);
|
||||||
@@ -114,7 +111,6 @@ public:
|
|||||||
|
|
||||||
float modelScale = 0.12f;
|
float modelScale = 0.12f;
|
||||||
Eigen::Quaternionf modelCorrectionRotation = Eigen::Quaternionf::Identity();
|
Eigen::Quaternionf modelCorrectionRotation = Eigen::Quaternionf::Identity();
|
||||||
bool useGpuSkinning = true;
|
|
||||||
|
|
||||||
//fp collisionRadius = static_cast<fp>(0.4f); // Радиус капсулы персонажа
|
//fp collisionRadius = static_cast<fp>(0.4f); // Радиус капсулы персонажа
|
||||||
fp collisionRadius = static_cast<fp>(kCharacterAgentRadius); // Радиус капсулы персонажа
|
fp collisionRadius = static_cast<fp>(kCharacterAgentRadius); // Радиус капсулы персонажа
|
||||||
@@ -125,17 +121,17 @@ public:
|
|||||||
Vec2fp preferredVelocity{ fp(0), fp(0) }; // Желаемая скорость к waypoint'у на текущем тике
|
Vec2fp preferredVelocity{ fp(0), fp(0) }; // Желаемая скорость к waypoint'у на текущем тике
|
||||||
|
|
||||||
fp interactionRadius = static_cast<fp>(0.0f);
|
fp interactionRadius = static_cast<fp>(0.0f);
|
||||||
bool movedLastTick = false;
|
|
||||||
|
|
||||||
// --- Pathfinding data (serializable parts) ---
|
// --- Pathfinding data (serializable parts) ---
|
||||||
Vec3fp walkTarget;
|
Vec3fp walkTarget;
|
||||||
Vec3fp requestedWalkTarget;
|
Vec3fp requestedWalkTarget;
|
||||||
std::vector<Vec3fp> pathWaypoints;
|
std::vector<Vec3fp> pathWaypoints;
|
||||||
size_t currentWaypointIndex = 0;
|
size_t currentWaypointIndex = 0;
|
||||||
|
PathFinder::PathOutcome navigationOutcome =
|
||||||
|
PathFinder::PathOutcome::ReachedExactGoal;
|
||||||
|
|
||||||
// Internal drift-check timer (serializable so it survives save/load).
|
// Internal drift-check timer (serializable so it survives save/load).
|
||||||
fp homeDriftCheckTimer = static_cast<fp>(5.0f);
|
fp homeDriftCheckTimer = static_cast<fp>(5.0f);
|
||||||
int movementBlockedTicks = 0;
|
|
||||||
int navigationRetryTicks = 0;
|
int navigationRetryTicks = 0;
|
||||||
std::vector<int> navigationRetryCooldownTicks;
|
std::vector<int> navigationRetryCooldownTicks;
|
||||||
std::size_t navigationRetryCooldownIndex = 0;
|
std::size_t navigationRetryCooldownIndex = 0;
|
||||||
@@ -153,19 +149,16 @@ public:
|
|||||||
const std::string& entityId,
|
const std::string& entityId,
|
||||||
std::vector<int> cooldownTicks = {});
|
std::vector<int> cooldownTicks = {});
|
||||||
bool isMoving() const;
|
bool isMoving() const;
|
||||||
const Vec3fp& getRequestedWalkTarget() const { return requestedWalkTarget; }
|
PathFinder::PathOutcome getNavigationOutcome() const { return navigationOutcome; }
|
||||||
Vec3fp getCurrentNavigationTarget() const;
|
Vec3fp getCurrentNavigationTarget() const;
|
||||||
void stopInPlace();
|
void stopInPlace();
|
||||||
void setTarget(const Vec3fp& target,
|
void setTarget(const Vec3fp& target,
|
||||||
std::string callbackName,
|
std::string callbackName,
|
||||||
const LocationNetworkState& location,
|
const LocationNetworkState& location);
|
||||||
const std::string& entityId);
|
void forceReplan(const LocationNetworkState& location);
|
||||||
void forceReplan(const LocationNetworkState& location,
|
|
||||||
const std::string& entityId);
|
|
||||||
void stopAndRotateToTarget(std::string characterId);
|
void stopAndRotateToTarget(std::string characterId);
|
||||||
void resetPlayerAfterDeath();
|
void resetPlayerAfterDeath();
|
||||||
void tryAttackCombo();
|
void tryAttackCombo();
|
||||||
float getHp() const { return hp; }
|
|
||||||
void setHp(float newHp);
|
void setHp(float newHp);
|
||||||
CharacterUpdateEvents update(std::int64_t deltaMs, const CharacterUpdateContext& context);
|
CharacterUpdateEvents update(std::int64_t deltaMs, const CharacterUpdateContext& context);
|
||||||
void setAnimationMetadata(AnimationState state, int startFrame, int frameCount);
|
void setAnimationMetadata(AnimationState state, int startFrame, int frameCount);
|
||||||
@@ -175,6 +168,10 @@ public:
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
void scheduleNextNavigationRetry();
|
void scheduleNextNavigationRetry();
|
||||||
|
// Queries the active navigation map for a path to `target` and applies it.
|
||||||
|
void applyPathTo(const Vec3fp& target, const LocationNetworkState& location);
|
||||||
|
// Points targetFacingAngle at `faceTarget`, or clears a stale faceTargetId.
|
||||||
|
void updateFaceTarget(const CharacterObservation* faceTarget);
|
||||||
};
|
};
|
||||||
|
|
||||||
using PlayerStateMap =
|
using PlayerStateMap =
|
||||||
@@ -186,7 +183,6 @@ struct CharacterObservation {
|
|||||||
};
|
};
|
||||||
|
|
||||||
struct CharacterUpdateContext {
|
struct CharacterUpdateContext {
|
||||||
std::string characterId;
|
|
||||||
const CharacterObservation* attackTarget = nullptr;
|
const CharacterObservation* attackTarget = nullptr;
|
||||||
const CharacterObservation* faceTarget = nullptr;
|
const CharacterObservation* faceTarget = nullptr;
|
||||||
};
|
};
|
||||||
|
|||||||
+1
-7
@@ -559,6 +559,7 @@ namespace FRG
|
|||||||
<< "' selected; creating WebSocket client" << std::endl;
|
<< "' selected; creating WebSocket client" << std::endl;
|
||||||
// Use "ws://127.0.0.1:8080/" for a local development server.
|
// Use "ws://127.0.0.1:8080/" for a local development server.
|
||||||
|
|
||||||
|
|
||||||
static const char* const kMultiplayerServerUrl = "wss://api.shadowoverbishkek.com/server001/";
|
static const char* const kMultiplayerServerUrl = "wss://api.shadowoverbishkek.com/server001/";
|
||||||
//static const char* const kMultiplayerServerUrl = "ws://127.0.0.1:8080/";
|
//static const char* const kMultiplayerServerUrl = "ws://127.0.0.1:8080/";
|
||||||
|
|
||||||
@@ -762,16 +763,9 @@ namespace FRG
|
|||||||
std::shared_ptr<Location> Game::createLocation(const LocationConfig& config)
|
std::shared_ptr<Location> Game::createLocation(const LocationConfig& config)
|
||||||
{
|
{
|
||||||
LocationSetup params;
|
LocationSetup params;
|
||||||
params.gameObjectsJsonPath = config.gameObjectsJsonPath;
|
|
||||||
params.interactiveObjectsJsonPath = config.interactiveObjectsJsonPath;
|
|
||||||
params.npcsJsonPath = config.npcsJsonPath;
|
|
||||||
params.dialoguesJsonPath = config.dialoguesJsonPath;
|
params.dialoguesJsonPath = config.dialoguesJsonPath;
|
||||||
//params.navigationJsonPaths = config.navigationJsonPaths;
|
//params.navigationJsonPaths = config.navigationJsonPaths;
|
||||||
params.scriptPath = config.scriptPath;
|
params.scriptPath = config.scriptPath;
|
||||||
params.teleportsJsonPath = config.teleportsJsonPath;
|
|
||||||
params.triggerZonesJsonPath = config.triggerZonesJsonPath;
|
|
||||||
params.lightsJsonPath = config.lightsJsonPath;
|
|
||||||
params.playerPosition = config.playerPosition;
|
|
||||||
params.player = player;
|
params.player = player;
|
||||||
|
|
||||||
auto loc = std::make_shared<Location>(
|
auto loc = std::make_shared<Location>(
|
||||||
|
|||||||
+8
-30
@@ -4,6 +4,7 @@
|
|||||||
#include <iomanip>
|
#include <iomanip>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
namespace FRG {
|
namespace FRG {
|
||||||
|
|
||||||
@@ -14,16 +15,6 @@ bool GameState::completeTutorialStep(TutorialStep step)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
CharacterState* GameState::findCharacter(
|
|
||||||
const std::string& locationId, const std::string& characterId)
|
|
||||||
{
|
|
||||||
auto player = players.find(characterId);
|
|
||||||
if (player != players.end() && player->second) return player->second.get();
|
|
||||||
auto location = locations.find(locationId);
|
|
||||||
return location == locations.end()
|
|
||||||
? nullptr : location->second.findCharacter(characterId, players);
|
|
||||||
}
|
|
||||||
|
|
||||||
const CharacterState* GameState::findCharacter(
|
const CharacterState* GameState::findCharacter(
|
||||||
const std::string& locationId, const std::string& characterId) const
|
const std::string& locationId, const std::string& characterId) const
|
||||||
{
|
{
|
||||||
@@ -34,6 +25,13 @@ const CharacterState* GameState::findCharacter(
|
|||||||
? nullptr : location->second.findCharacter(characterId, players);
|
? nullptr : location->second.findCharacter(characterId, players);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
CharacterState* GameState::findCharacter(
|
||||||
|
const std::string& locationId, const std::string& characterId)
|
||||||
|
{
|
||||||
|
return const_cast<CharacterState*>(
|
||||||
|
std::as_const(*this).findCharacter(locationId, characterId));
|
||||||
|
}
|
||||||
|
|
||||||
void GameState::save(nlohmann::json& out) const
|
void GameState::save(nlohmann::json& out) const
|
||||||
{
|
{
|
||||||
out["schemaVersion"] = kSchemaVersion;
|
out["schemaVersion"] = kSchemaVersion;
|
||||||
@@ -52,8 +50,6 @@ void GameState::save(nlohmann::json& out) const
|
|||||||
out["isDawn"] = isDawn;
|
out["isDawn"] = isDawn;
|
||||||
|
|
||||||
// --- Player resources ---
|
// --- Player resources ---
|
||||||
//out["playerHp"] = playerHp;
|
|
||||||
out["playerMaxHp"] = playerMaxHp;
|
|
||||||
out["money"] = money;
|
out["money"] = money;
|
||||||
|
|
||||||
// --- Script globals ---
|
// --- Script globals ---
|
||||||
@@ -124,7 +120,6 @@ void GameState::load(const nlohmann::json& in)
|
|||||||
throw std::runtime_error(
|
throw std::runtime_error(
|
||||||
"Unsupported game-state schema version: " +
|
"Unsupported game-state schema version: " +
|
||||||
std::to_string(schemaVersion));
|
std::to_string(schemaVersion));
|
||||||
//logger() << "GameState::load step 1" << std::endl;
|
|
||||||
|
|
||||||
// --- World ---
|
// --- World ---
|
||||||
campaignId = in.at("campaignId").get<std::string>();
|
campaignId = in.at("campaignId").get<std::string>();
|
||||||
@@ -133,23 +128,15 @@ void GameState::load(const nlohmann::json& in)
|
|||||||
isNight = in.value("isNight", isNight);
|
isNight = in.value("isNight", isNight);
|
||||||
isDawn = in.value("isDawn", isDawn);
|
isDawn = in.value("isDawn", isDawn);
|
||||||
|
|
||||||
//() << "GameState::load step 2" << std::endl;
|
|
||||||
|
|
||||||
|
|
||||||
// --- Player resources ---
|
// --- Player resources ---
|
||||||
//playerHp = in.value("playerHp", playerHp);
|
|
||||||
playerMaxHp = in.value("playerMaxHp", playerMaxHp);
|
|
||||||
money = in.value("money", money);
|
money = in.value("money", money);
|
||||||
|
|
||||||
//logger() << "GameState::load step 3" << std::endl;
|
|
||||||
|
|
||||||
// --- Script globals ---
|
// --- Script globals ---
|
||||||
globalInts.clear();
|
globalInts.clear();
|
||||||
if (in.contains("globalInts") && in["globalInts"].is_object()) {
|
if (in.contains("globalInts") && in["globalInts"].is_object()) {
|
||||||
for (const auto& [k, v] : in["globalInts"].items())
|
for (const auto& [k, v] : in["globalInts"].items())
|
||||||
globalInts[k] = v.get<int>();
|
globalInts[k] = v.get<int>();
|
||||||
}
|
}
|
||||||
//logger() << "GameState::load step 4" << std::endl;
|
|
||||||
|
|
||||||
globalFloats.clear();
|
globalFloats.clear();
|
||||||
if (in.contains("globalFloats") && in["globalFloats"].is_object()) {
|
if (in.contains("globalFloats") && in["globalFloats"].is_object()) {
|
||||||
@@ -157,7 +144,6 @@ void GameState::load(const nlohmann::json& in)
|
|||||||
globalFloats[k] = v.get<float>();
|
globalFloats[k] = v.get<float>();
|
||||||
}
|
}
|
||||||
|
|
||||||
//logger() << "GameState::load step 5" << std::endl;
|
|
||||||
|
|
||||||
// --- Tutorial ---
|
// --- Tutorial ---
|
||||||
tutorialStep = static_cast<TutorialStep>(
|
tutorialStep = static_cast<TutorialStep>(
|
||||||
@@ -167,20 +153,17 @@ void GameState::load(const nlohmann::json& in)
|
|||||||
tutorialNeedOpenTaxiScreen = in.value("tutorialNeedOpenTaxiScreen", tutorialNeedOpenTaxiScreen);
|
tutorialNeedOpenTaxiScreen = in.value("tutorialNeedOpenTaxiScreen", tutorialNeedOpenTaxiScreen);
|
||||||
tutorialTaxiHintDone = in.value("tutorialTaxiHintDone", false);
|
tutorialTaxiHintDone = in.value("tutorialTaxiHintDone", false);
|
||||||
|
|
||||||
//logger() << "GameState::load step 6" << std::endl;
|
|
||||||
|
|
||||||
// --- Phone / chat ---
|
// --- Phone / chat ---
|
||||||
if (in.contains("chatUnread") && in["chatUnread"].is_array()) {
|
if (in.contains("chatUnread") && in["chatUnread"].is_array()) {
|
||||||
for (int i = 0; i < 3 && i < static_cast<int>(in["chatUnread"].size()); ++i)
|
for (int i = 0; i < 3 && i < static_cast<int>(in["chatUnread"].size()); ++i)
|
||||||
chatUnread[i] = in["chatUnread"][i].get<bool>();
|
chatUnread[i] = in["chatUnread"][i].get<bool>();
|
||||||
}
|
}
|
||||||
//logger() << "GameState::load step 7" << std::endl;
|
|
||||||
|
|
||||||
if (in.contains("chatPreviewMsg") && in["chatPreviewMsg"].is_array()) {
|
if (in.contains("chatPreviewMsg") && in["chatPreviewMsg"].is_array()) {
|
||||||
for (int i = 0; i < 3 && i < static_cast<int>(in["chatPreviewMsg"].size()); ++i)
|
for (int i = 0; i < 3 && i < static_cast<int>(in["chatPreviewMsg"].size()); ++i)
|
||||||
chatPreviewMsg[i] = in["chatPreviewMsg"][i].get<std::string>();
|
chatPreviewMsg[i] = in["chatPreviewMsg"][i].get<std::string>();
|
||||||
}
|
}
|
||||||
//logger() << "GameState::load step 8" << std::endl;
|
|
||||||
|
|
||||||
if (in.contains("chatHistory") && in["chatHistory"].is_array()) {
|
if (in.contains("chatHistory") && in["chatHistory"].is_array()) {
|
||||||
for (int i = 0; i < 3 && i < static_cast<int>(in["chatHistory"].size()); ++i) {
|
for (int i = 0; i < 3 && i < static_cast<int>(in["chatHistory"].size()); ++i) {
|
||||||
@@ -196,17 +179,14 @@ void GameState::load(const nlohmann::json& in)
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
//logger() << "GameState::load step 8" << std::endl;
|
|
||||||
|
|
||||||
// --- Inventory ---
|
// --- Inventory ---
|
||||||
if (in.contains("inventory")) inventory.load(in["inventory"]);
|
if (in.contains("inventory")) inventory.load(in["inventory"]);
|
||||||
|
|
||||||
//logger() << "GameState::load step 9" << std::endl;
|
|
||||||
|
|
||||||
// --- Quest journal ---
|
// --- Quest journal ---
|
||||||
if (in.contains("questJournal")) questJournal.load(in["questJournal"]);
|
if (in.contains("questJournal")) questJournal.load(in["questJournal"]);
|
||||||
|
|
||||||
logger() << "GameState::load step 10" << std::endl;
|
|
||||||
|
|
||||||
// --- Players ---
|
// --- Players ---
|
||||||
const auto& playerValues = in.at("players");
|
const auto& playerValues = in.at("players");
|
||||||
@@ -238,12 +218,10 @@ void GameState::load(const nlohmann::json& in)
|
|||||||
if (!locationValues.contains(it->first)) it = locations.erase(it);
|
if (!locationValues.contains(it->first)) it = locations.erase(it);
|
||||||
else ++it;
|
else ++it;
|
||||||
}
|
}
|
||||||
//logger() << "GameState::load step 11" << std::endl;
|
|
||||||
|
|
||||||
|
|
||||||
// --- Taxi ---
|
// --- Taxi ---
|
||||||
taxiIsCalled = in.value("taxiIsCalled", taxiIsCalled);
|
taxiIsCalled = in.value("taxiIsCalled", taxiIsCalled);
|
||||||
//logger() << "GameState::load step 12" << std::endl;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-3
@@ -33,7 +33,7 @@ struct StoredChatMessage {
|
|||||||
};
|
};
|
||||||
|
|
||||||
struct GameState : public ISaveable {
|
struct GameState : public ISaveable {
|
||||||
static constexpr int kSchemaVersion = 6;
|
static constexpr int kSchemaVersion = 7;
|
||||||
|
|
||||||
// --- World ---
|
// --- World ---
|
||||||
// Campaign being played (see CampaignRegistry).
|
// Campaign being played (see CampaignRegistry).
|
||||||
@@ -50,8 +50,6 @@ struct GameState : public ISaveable {
|
|||||||
|
|
||||||
// --- Player resources ---
|
// --- Player resources ---
|
||||||
Inventory inventory;
|
Inventory inventory;
|
||||||
//float playerHp = 200.f;
|
|
||||||
float playerMaxHp = 200.f;
|
|
||||||
int money = 5500;
|
int money = 5500;
|
||||||
|
|
||||||
// --- Script globals ---
|
// --- Script globals ---
|
||||||
|
|||||||
+72
-313
@@ -11,9 +11,7 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <cfloat>
|
#include <cfloat>
|
||||||
#include <limits>
|
#include <limits>
|
||||||
#include <random>
|
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
#include <unordered_set>
|
|
||||||
#include "GameConstants.h"
|
#include "GameConstants.h"
|
||||||
#include "Character.h"
|
#include "Character.h"
|
||||||
#include "game_server/IGameServer.h"
|
#include "game_server/IGameServer.h"
|
||||||
@@ -24,35 +22,10 @@ namespace FRG
|
|||||||
{
|
{
|
||||||
extern const char* CONST_ZIP_FILE;
|
extern const char* CONST_ZIP_FILE;
|
||||||
|
|
||||||
extern float x;
|
|
||||||
|
|
||||||
constexpr float CONST_TAXI_CAR_SCALE = 0.6f;
|
constexpr float CONST_TAXI_CAR_SCALE = 0.6f;
|
||||||
|
|
||||||
|
|
||||||
static constexpr float CAMERA_FOV_Y = 1.0f / 1.5f;
|
static constexpr float CAMERA_FOV_Y = 1.0f / 1.5f;
|
||||||
// How close the player needs to be to a peaceful NPC before the
|
|
||||||
// on_npc_interact callback fires and the conversation begins.
|
|
||||||
static constexpr float NPC_TALK_DISTANCE = 1.35f;
|
|
||||||
|
|
||||||
static constexpr float RENDER_DISTRANCE = 50.f;
|
|
||||||
|
|
||||||
static float distancePointToSegmentXZ(const Eigen::Vector3f& p,
|
|
||||||
const Eigen::Vector3f& a,
|
|
||||||
const Eigen::Vector3f& b)
|
|
||||||
{
|
|
||||||
const Eigen::Vector2f p2(p.x(), p.z());
|
|
||||||
const Eigen::Vector2f a2(a.x(), a.z());
|
|
||||||
const Eigen::Vector2f b2(b.x(), b.z());
|
|
||||||
const Eigen::Vector2f ab = b2 - a2;
|
|
||||||
const float abLenSq = ab.squaredNorm();
|
|
||||||
if (abLenSq <= 1e-8f) {
|
|
||||||
return (p2 - a2).norm();
|
|
||||||
}
|
|
||||||
const float t = std::clamp((p2 - a2).dot(ab) / abLenSq, 0.0f, 1.0f);
|
|
||||||
const Eigen::Vector2f closest = a2 + ab * t;
|
|
||||||
return (p2 - closest).norm();
|
|
||||||
}
|
|
||||||
|
|
||||||
Location::Location(Renderer& iRenderer, IGameServer& server,
|
Location::Location(Renderer& iRenderer, IGameServer& server,
|
||||||
std::string locationId)
|
std::string locationId)
|
||||||
: renderer(iRenderer)
|
: renderer(iRenderer)
|
||||||
@@ -140,6 +113,8 @@ namespace FRG
|
|||||||
|
|
||||||
void Location::stopCharacter(Character& character)
|
void Location::stopCharacter(Character& character)
|
||||||
{
|
{
|
||||||
|
if (player && character.entityId() == player->entityId())
|
||||||
|
pathVisualization.cancel();
|
||||||
gameServer_.submit(StopCharacterCommand{locationId_, character.entityId()});
|
gameServer_.submit(StopCharacterCommand{locationId_, character.entityId()});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,11 +124,6 @@ namespace FRG
|
|||||||
locationId_, character.entityId(), std::move(targetId)});
|
locationId_, character.entityId(), std::move(targetId)});
|
||||||
}
|
}
|
||||||
|
|
||||||
void Location::replanCharacter(Character& character)
|
|
||||||
{
|
|
||||||
gameServer_.submit(ReplanCharacterCommand{locationId_, character.entityId()});
|
|
||||||
}
|
|
||||||
|
|
||||||
void Location::resetCharacterAfterDeath(Character& character)
|
void Location::resetCharacterAfterDeath(Character& character)
|
||||||
{
|
{
|
||||||
gameServer_.submit(
|
gameServer_.submit(
|
||||||
@@ -587,188 +557,37 @@ namespace FRG
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Location::loadTeleportZones(const std::string& jsonPath, const char* zipFile)
|
void Location::prepareCharacterSparks(const Eigen::Matrix4f& cameraViewMatrix)
|
||||||
{
|
{
|
||||||
if (jsonPath.empty()) return;
|
if (player) player->prepareHitSparksForDraw(cameraViewMatrix);
|
||||||
|
for (auto& [id, remote] : remotePlayers_)
|
||||||
std::string content;
|
if (remote) remote->prepareHitSparksForDraw(cameraViewMatrix);
|
||||||
try {
|
for (auto& npc : npcs) npc->prepareHitSparksForDraw(cameraViewMatrix);
|
||||||
if (!zipFile || zipFile[0] == '\0') {
|
|
||||||
content = readTextFile(jsonPath);
|
|
||||||
} else {
|
|
||||||
auto buf = readFileFromZIP(jsonPath, zipFile);
|
|
||||||
if (buf.empty()) {
|
|
||||||
std::cerr << "[TELEPORT] Failed to read " << jsonPath << " from zip" << std::endl;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
content.assign(buf.begin(), buf.end());
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
std::cerr << "[TELEPORT] Failed to open " << jsonPath << ": " << e.what() << std::endl;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
using json = nlohmann::json;
|
|
||||||
json j;
|
|
||||||
try {
|
|
||||||
j = json::parse(content);
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
std::cerr << "[TELEPORT] JSON parse error in " << jsonPath << ": " << e.what() << std::endl;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!j.contains("teleports") || !j["teleports"].is_array()) return;
|
|
||||||
|
|
||||||
auto activeTex = renderer.textureManager.LoadFromPng("resources/w/star.png", zipFile ? zipFile : "");
|
|
||||||
auto inactiveTex = renderer.textureManager.LoadFromPng("resources/w/star_red.png", zipFile ? zipFile : "");
|
|
||||||
|
|
||||||
std::unordered_set<std::string> ids;
|
|
||||||
for (const auto& item : j["teleports"]) {
|
|
||||||
TeleportZone tz;
|
|
||||||
tz.id = item.at("id").get<std::string>();
|
|
||||||
if (tz.id.empty() || !ids.insert(tz.id).second)
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Missing or duplicate teleport id in " + jsonPath);
|
|
||||||
tz.active = item.value("active", false);
|
|
||||||
tz.position = Eigen::Vector3f(
|
|
||||||
item.value("positionX", 0.0f),
|
|
||||||
item.value("positionY", 0.0f),
|
|
||||||
item.value("positionZ", 0.0f)
|
|
||||||
);
|
|
||||||
tz.radius = item.value("radius", 0.0f);
|
|
||||||
tz.automatic = item.value("automatic", false);
|
|
||||||
tz.automaticRadius = item.value("automaticRadius", tz.radius);
|
|
||||||
tz.destinationLocation = item.value("destinationLocation", "");
|
|
||||||
tz.destinationPosition = Eigen::Vector3f(
|
|
||||||
item.value("destinationPositionX", 0.0f),
|
|
||||||
item.value("destinationPositionY", 0.0f),
|
|
||||||
item.value("destinationPositionZ", 0.0f)
|
|
||||||
);
|
|
||||||
tz.destinationRotationY = item.value("destinationRotationY", 0.0f);
|
|
||||||
tz.initSparks(activeTex, inactiveTex);
|
|
||||||
teleportZones.push_back(std::move(tz));
|
|
||||||
}
|
|
||||||
|
|
||||||
logger() << "[TELEPORT] Loaded " << teleportZones.size() << " teleport(s) from " << jsonPath << std::endl;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Location::loadTriggerZones(const std::string& jsonPath, const char* zipFile)
|
void Location::drawCharacters()
|
||||||
{
|
{
|
||||||
if (jsonPath.empty()) return;
|
if (player) player->draw(renderer);
|
||||||
|
for (auto& [id, remote] : remotePlayers_)
|
||||||
std::string content;
|
if (remote) remote->draw(renderer);
|
||||||
try {
|
for (auto& npc : npcs) npc->draw(renderer);
|
||||||
if (!zipFile || zipFile[0] == '\0') {
|
|
||||||
content = readTextFile(jsonPath);
|
|
||||||
} else {
|
|
||||||
auto buf = readFileFromZIP(jsonPath, zipFile);
|
|
||||||
if (buf.empty()) {
|
|
||||||
std::cerr << "[TRIGGER] Failed to read " << jsonPath << " from zip" << std::endl;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
content.assign(buf.begin(), buf.end());
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
std::cerr << "[TRIGGER] Failed to open " << jsonPath << ": " << e.what() << std::endl;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
using json = nlohmann::json;
|
|
||||||
json j;
|
|
||||||
try {
|
|
||||||
j = json::parse(content);
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
std::cerr << "[TRIGGER] JSON parse error in " << jsonPath << ": " << e.what() << std::endl;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!j.contains("trigger_zones") || !j["trigger_zones"].is_array()) return;
|
|
||||||
|
|
||||||
std::unordered_set<std::string> ids;
|
|
||||||
for (const auto& item : j["trigger_zones"]) {
|
|
||||||
TriggerZone tz;
|
|
||||||
tz.id = item.at("id").get<std::string>();
|
|
||||||
if (tz.id.empty() || !ids.insert(tz.id).second)
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Missing or duplicate trigger-zone id in " + jsonPath);
|
|
||||||
tz.enabled = item.value("enabled", true);
|
|
||||||
tz.radius = item.value("radius", 1.5f);
|
|
||||||
tz.hysteresis = item.value("hysteresis", 0.3f);
|
|
||||||
tz.position = Eigen::Vector3f(
|
|
||||||
item.value("positionX", 0.0f),
|
|
||||||
item.value("positionY", 0.0f),
|
|
||||||
item.value("positionZ", 0.0f)
|
|
||||||
);
|
|
||||||
triggerZones.push_back(std::move(tz));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
logger() << "[TRIGGER] Loaded " << triggerZones.size() << " trigger zone(s) from " << jsonPath << std::endl;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Location::loadPointLights(const std::string& jsonPath, const char* zipFile)
|
void Location::drawCharacterOverlays(const Eigen::Matrix4f& cameraViewMatrix)
|
||||||
{
|
{
|
||||||
if (jsonPath.empty()) return;
|
if (!npcNameText) return;
|
||||||
|
const Eigen::Matrix4f proj = MakePerspectiveMatrix(1.0f / 1.5f,
|
||||||
std::string content;
|
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
||||||
try {
|
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
||||||
if (!zipFile || zipFile[0] == '\0') {
|
drawRemotePlayerNames(cameraViewMatrix, proj);
|
||||||
content = readTextFile(jsonPath);
|
for (auto& npc : npcs) {
|
||||||
} else {
|
if (npc) npc->drawName(*npcNameText, cameraViewMatrix, proj);
|
||||||
auto buf = readFileFromZIP(jsonPath, zipFile);
|
|
||||||
if (buf.empty()) {
|
|
||||||
std::cerr << "[LIGHTS] Failed to read " << jsonPath << " from zip" << std::endl;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
content.assign(buf.begin(), buf.end());
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
std::cerr << "[LIGHTS] Failed to open " << jsonPath << ": " << e.what() << std::endl;
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
if (player) player->drawHealthBar(renderer, cameraViewMatrix, proj);
|
||||||
using json = nlohmann::json;
|
for (auto& npc : npcs) {
|
||||||
json j;
|
if (npc) npc->drawHealthBar(renderer, cameraViewMatrix, proj);
|
||||||
try {
|
|
||||||
j = json::parse(content);
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
std::cerr << "[LIGHTS] JSON parse error in " << jsonPath << ": " << e.what() << std::endl;
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!j.contains("lights") || !j["lights"].is_array()) return;
|
|
||||||
|
|
||||||
for (const auto& item : j["lights"]) {
|
|
||||||
PointLight pl;
|
|
||||||
pl.id = item.value("id", "");
|
|
||||||
pl.autoLight = item.value("autoLight", false);
|
|
||||||
pl.autoLightDistance = item.value("autoLightDistance", -1.0f);
|
|
||||||
pl.limitX = item.value("limitX", 99999.f);
|
|
||||||
pl.limitY = item.value("limitY", 99999.f);
|
|
||||||
pl.autoLightLimitX = item.value("autoLightLimitX", -1.0f);
|
|
||||||
pl.autoLightLimitY = item.value("autoLightLimitY", -1.0f);
|
|
||||||
pl.position = Eigen::Vector3f(
|
|
||||||
item.value("positionX", 0.0f),
|
|
||||||
item.value("positionY", 0.0f),
|
|
||||||
item.value("positionZ", 0.0f)
|
|
||||||
);
|
|
||||||
pl.direction = Eigen::Vector3f(
|
|
||||||
item.value("directionX", 0.0f),
|
|
||||||
item.value("directionY", -1.0f),
|
|
||||||
item.value("directionZ", 0.0f)
|
|
||||||
);
|
|
||||||
pl.color = Eigen::Vector3f(
|
|
||||||
item.value("colorR", 1.0f),
|
|
||||||
item.value("colorG", 1.0f),
|
|
||||||
item.value("colorB", 1.0f)
|
|
||||||
);
|
|
||||||
pointLights.push_back(std::move(pl));
|
|
||||||
}
|
|
||||||
|
|
||||||
logger() << "[LIGHTS] Loaded " << pointLights.size() << " light(s) from " << jsonPath << std::endl;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Location::updateTriggerZones(const Eigen::Vector3f& playerPos)
|
void Location::updateTriggerZones(const Eigen::Vector3f& playerPos)
|
||||||
{
|
{
|
||||||
for (int i = 0; i < static_cast<int>(triggerZones.size()); ++i) {
|
for (int i = 0; i < static_cast<int>(triggerZones.size()); ++i) {
|
||||||
@@ -1017,11 +836,6 @@ namespace FRG
|
|||||||
renderer.shaderManager.PopShader();
|
renderer.shaderManager.PopShader();
|
||||||
}
|
}
|
||||||
|
|
||||||
void Location::setPathVisualizationEnabled(bool enabled)
|
|
||||||
{
|
|
||||||
pathVisualization.setEnabled(enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Location::drawGame()
|
void Location::drawGame()
|
||||||
{
|
{
|
||||||
auto locationState = stateSnapshot();
|
auto locationState = stateSnapshot();
|
||||||
@@ -1074,16 +888,10 @@ namespace FRG
|
|||||||
}
|
}
|
||||||
renderer.RenderUniform1f("uAlpha", 1.0f);
|
renderer.RenderUniform1f("uAlpha", 1.0f);
|
||||||
const Eigen::Matrix4f currentView = renderer.GetCurrentModelViewMatrix();
|
const Eigen::Matrix4f currentView = renderer.GetCurrentModelViewMatrix();
|
||||||
if (player) player->prepareHitSparksForDraw(currentView);
|
prepareCharacterSparks(currentView);
|
||||||
for (auto& [id, remote] : remotePlayers_)
|
|
||||||
if (remote) remote->prepareHitSparksForDraw(currentView);
|
|
||||||
for (auto& npc : npcs) npc->prepareHitSparksForDraw(currentView);
|
|
||||||
for (auto& tz : teleportZones) tz.prepareForDraw(currentView);
|
for (auto& tz : teleportZones) tz.prepareForDraw(currentView);
|
||||||
|
|
||||||
if (player) player->draw(renderer);
|
drawCharacters();
|
||||||
for (auto& [id, remote] : remotePlayers_)
|
|
||||||
if (remote) remote->draw(renderer);
|
|
||||||
for (auto& npc : npcs) npc->draw(renderer);
|
|
||||||
|
|
||||||
drawNpcCar();
|
drawNpcCar();
|
||||||
|
|
||||||
@@ -1104,19 +912,7 @@ namespace FRG
|
|||||||
|
|
||||||
renderer.shaderManager.PopShader();
|
renderer.shaderManager.PopShader();
|
||||||
|
|
||||||
if (npcNameText) {
|
drawCharacterOverlays(currentView);
|
||||||
Eigen::Matrix4f proj = MakePerspectiveMatrix(1.0f / 1.5f,
|
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
drawRemotePlayerNames(currentView, proj);
|
|
||||||
for (auto& npc : npcs) {
|
|
||||||
if (npc) npc->drawName(*npcNameText, currentView, proj);
|
|
||||||
}
|
|
||||||
if (player) player->drawHealthBar(renderer, currentView, proj);
|
|
||||||
for (auto& npc : npcs) {
|
|
||||||
if (npc) npc->drawHealthBar(renderer, currentView, proj);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Location::drawShadowDepthPass()
|
void Location::drawShadowDepthPass()
|
||||||
@@ -1200,6 +996,7 @@ namespace FRG
|
|||||||
glClearColor(0.53, 0.81, 0.92, 1.0f);
|
glClearColor(0.53, 0.81, 0.92, 1.0f);
|
||||||
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
|
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
|
||||||
|
|
||||||
|
Eigen::Matrix4f cameraViewMatrix = Eigen::Matrix4f::Identity();
|
||||||
#ifdef DEBUG_LIGHT
|
#ifdef DEBUG_LIGHT
|
||||||
// Debug mode: render from the light's point of view using the plain
|
// Debug mode: render from the light's point of view using the plain
|
||||||
// textured shader so we can see what the shadow map "sees".
|
// textured shader so we can see what the shadow map "sees".
|
||||||
@@ -1291,24 +1088,15 @@ namespace FRG
|
|||||||
// but from the light's viewpoint — projection/view already on stack).
|
// but from the light's viewpoint — projection/view already on stack).
|
||||||
{
|
{
|
||||||
const Eigen::Matrix4f currentView = renderer.GetCurrentModelViewMatrix();
|
const Eigen::Matrix4f currentView = renderer.GetCurrentModelViewMatrix();
|
||||||
if (player) player->prepareHitSparksForDraw(currentView);
|
prepareCharacterSparks(currentView);
|
||||||
for (auto& [id, remote] : remotePlayers_)
|
|
||||||
if (remote) remote->prepareHitSparksForDraw(currentView);
|
|
||||||
for (auto& npc : npcs) npc->prepareHitSparksForDraw(currentView);
|
|
||||||
}
|
}
|
||||||
if (player) player->draw(renderer);
|
drawCharacters();
|
||||||
for (auto& [id, remote] : remotePlayers_)
|
|
||||||
if (remote) remote->draw(renderer);
|
|
||||||
for (auto& npc : npcs) npc->draw(renderer);
|
|
||||||
drawNpcCar();
|
drawNpcCar();
|
||||||
#else
|
#else
|
||||||
// Characters use their own shadow-aware shaders
|
// Characters use their own shadow-aware shaders
|
||||||
CheckGlError(__FILE__, __LINE__);
|
CheckGlError(__FILE__, __LINE__);
|
||||||
|
|
||||||
if (player) player->prepareHitSparksForDraw(cameraViewMatrix);
|
prepareCharacterSparks(cameraViewMatrix);
|
||||||
for (auto& [id, remote] : remotePlayers_)
|
|
||||||
if (remote) remote->prepareHitSparksForDraw(cameraViewMatrix);
|
|
||||||
for (auto& npc : npcs) npc->prepareHitSparksForDraw(cameraViewMatrix);
|
|
||||||
for (auto& tz : teleportZones) tz.prepareForDraw(cameraViewMatrix);
|
for (auto& tz : teleportZones) tz.prepareForDraw(cameraViewMatrix);
|
||||||
|
|
||||||
if (player) player->drawWithShadow(renderer, lightFromCamera, shadowMap->getDepthTexture(), lightDirCamera);
|
if (player) player->drawWithShadow(renderer, lightFromCamera, shadowMap->getDepthTexture(), lightDirCamera);
|
||||||
@@ -1339,19 +1127,7 @@ namespace FRG
|
|||||||
renderer.PopProjectionMatrix();
|
renderer.PopProjectionMatrix();
|
||||||
renderer.shaderManager.PopShader();
|
renderer.shaderManager.PopShader();
|
||||||
|
|
||||||
if (npcNameText) {
|
drawCharacterOverlays(cameraViewMatrix);
|
||||||
Eigen::Matrix4f proj = MakePerspectiveMatrix(1.0f / 1.5f,
|
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
drawRemotePlayerNames(cameraViewMatrix, proj);
|
|
||||||
for (auto& npc : npcs) {
|
|
||||||
if (npc) npc->drawName(*npcNameText, cameraViewMatrix, proj);
|
|
||||||
}
|
|
||||||
if (player) player->drawHealthBar(renderer, cameraViewMatrix, proj);
|
|
||||||
for (auto& npc : npcs) {
|
|
||||||
if (npc) npc->drawHealthBar(renderer, cameraViewMatrix, proj);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Location::drawGameDarklands()
|
void Location::drawGameDarklands()
|
||||||
@@ -1401,16 +1177,10 @@ namespace FRG
|
|||||||
}
|
}
|
||||||
renderer.RenderUniform1f("uAlpha", 1.0f);
|
renderer.RenderUniform1f("uAlpha", 1.0f);
|
||||||
const Eigen::Matrix4f currentView = renderer.GetCurrentModelViewMatrix();
|
const Eigen::Matrix4f currentView = renderer.GetCurrentModelViewMatrix();
|
||||||
if (player) player->prepareHitSparksForDraw(currentView);
|
prepareCharacterSparks(currentView);
|
||||||
for (auto& [id, remote] : remotePlayers_)
|
|
||||||
if (remote) remote->prepareHitSparksForDraw(currentView);
|
|
||||||
for (auto& npc : npcs) npc->prepareHitSparksForDraw(currentView);
|
|
||||||
for (auto& tz : teleportZones) tz.prepareForDraw(currentView);
|
for (auto& tz : teleportZones) tz.prepareForDraw(currentView);
|
||||||
|
|
||||||
if (player) player->draw(renderer);
|
drawCharacters();
|
||||||
for (auto& [id, remote] : remotePlayers_)
|
|
||||||
if (remote) remote->draw(renderer);
|
|
||||||
for (auto& npc : npcs) npc->draw(renderer);
|
|
||||||
|
|
||||||
//drawNpcCar();
|
//drawNpcCar();
|
||||||
|
|
||||||
@@ -1429,19 +1199,7 @@ namespace FRG
|
|||||||
renderer.PopProjectionMatrix();
|
renderer.PopProjectionMatrix();
|
||||||
renderer.shaderManager.PopShader();
|
renderer.shaderManager.PopShader();
|
||||||
|
|
||||||
if (npcNameText) {
|
drawCharacterOverlays(currentView);
|
||||||
Eigen::Matrix4f proj = MakePerspectiveMatrix(1.0f / 1.5f,
|
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
drawRemotePlayerNames(currentView, proj);
|
|
||||||
for (auto& npc : npcs) {
|
|
||||||
if (npc) npc->drawName(*npcNameText, currentView, proj);
|
|
||||||
}
|
|
||||||
if (player) player->drawHealthBar(renderer, currentView, proj);
|
|
||||||
for (auto& npc : npcs) {
|
|
||||||
if (npc) npc->drawHealthBar(renderer, currentView, proj);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Location::drawNightShadowDepthPass(const PointLight& light)
|
void Location::drawNightShadowDepthPass(const PointLight& light)
|
||||||
@@ -1549,7 +1307,7 @@ namespace FRG
|
|||||||
interpolatedNpcCarPresentation(locationState->taxiCar);
|
interpolatedNpcCarPresentation(locationState->taxiCar);
|
||||||
renderer.PushMatrix();
|
renderer.PushMatrix();
|
||||||
renderer.TranslateMatrix(car.position);
|
renderer.TranslateMatrix(car.position);
|
||||||
renderer.TranslateMatrix({ 0, 0.7f - 0.25f +x, 0 });
|
renderer.TranslateMatrix({ 0, 0.7f - 0.25f, 0 });
|
||||||
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(car.rotation, Eigen::Vector3f::UnitY())).toRotationMatrix());
|
renderer.RotateMatrix(Eigen::Quaternionf(Eigen::AngleAxisf(car.rotation, Eigen::Vector3f::UnitY())).toRotationMatrix());
|
||||||
glBindTexture(GL_TEXTURE_2D, carTexture->getTexID());
|
glBindTexture(GL_TEXTURE_2D, carTexture->getTexID());
|
||||||
renderer.DrawVertexRenderStruct(carMesh);
|
renderer.DrawVertexRenderStruct(carMesh);
|
||||||
@@ -1685,7 +1443,7 @@ namespace FRG
|
|||||||
renderer.TranslateMatrix({ -camTarget.x(), -camTarget.y(), -camTarget.z() });
|
renderer.TranslateMatrix({ -camTarget.x(), -camTarget.y(), -camTarget.z() });
|
||||||
renderer.TranslateMatrix({ 0, -1.f, 0 });
|
renderer.TranslateMatrix({ 0, -1.f, 0 });
|
||||||
|
|
||||||
cameraViewMatrix = renderer.GetCurrentModelViewMatrix();
|
const Eigen::Matrix4f cameraViewMatrix = renderer.GetCurrentModelViewMatrix();
|
||||||
|
|
||||||
// Transform active spot lights to eye space and build uniform arrays
|
// Transform active spot lights to eye space and build uniform arrays
|
||||||
float plPosEye[MAX_POINT_LIGHTS * 3] = {};
|
float plPosEye[MAX_POINT_LIGHTS * 3] = {};
|
||||||
@@ -1770,10 +1528,7 @@ namespace FRG
|
|||||||
}
|
}
|
||||||
|
|
||||||
renderer.RenderUniform1f("uAlpha", 1.0f);
|
renderer.RenderUniform1f("uAlpha", 1.0f);
|
||||||
if (player) player->prepareHitSparksForDraw(cameraViewMatrix);
|
prepareCharacterSparks(cameraViewMatrix);
|
||||||
for (auto& [id, remote] : remotePlayers_)
|
|
||||||
if (remote) remote->prepareHitSparksForDraw(cameraViewMatrix);
|
|
||||||
for (auto& npc : npcs) npc->prepareHitSparksForDraw(cameraViewMatrix);
|
|
||||||
for (auto& tz : teleportZones) tz.prepareForDraw(cameraViewMatrix);
|
for (auto& tz : teleportZones) tz.prepareForDraw(cameraViewMatrix);
|
||||||
|
|
||||||
if (hasShadows) {
|
if (hasShadows) {
|
||||||
@@ -1816,19 +1571,7 @@ namespace FRG
|
|||||||
renderer.PopProjectionMatrix();
|
renderer.PopProjectionMatrix();
|
||||||
renderer.shaderManager.PopShader();
|
renderer.shaderManager.PopShader();
|
||||||
|
|
||||||
if (npcNameText) {
|
drawCharacterOverlays(cameraViewMatrix);
|
||||||
Eigen::Matrix4f proj = MakePerspectiveMatrix(1.0f / 1.5f,
|
|
||||||
static_cast<float>(Environment::width) / static_cast<float>(Environment::height),
|
|
||||||
Environment::CONST_Z_NEAR, Environment::CONST_Z_FAR);
|
|
||||||
drawRemotePlayerNames(cameraViewMatrix, proj);
|
|
||||||
for (auto& npc : npcs) {
|
|
||||||
if (npc) npc->drawName(*npcNameText, cameraViewMatrix, proj);
|
|
||||||
}
|
|
||||||
if (player) player->drawHealthBar(renderer, cameraViewMatrix, proj);
|
|
||||||
for (auto& npc : npcs) {
|
|
||||||
if (npc) npc->drawHealthBar(renderer, cameraViewMatrix, proj);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Location::setNavigationAreaAvailable(const std::string& areaName, bool available)
|
bool Location::setNavigationAreaAvailable(const std::string& areaName, bool available)
|
||||||
@@ -1894,7 +1637,6 @@ namespace FRG
|
|||||||
};
|
};
|
||||||
|
|
||||||
for (const CharacterSimulationEvent& event : events.characters) {
|
for (const CharacterSimulationEvent& event : events.characters) {
|
||||||
Character* character = findRuntimeCharacter(event.characterId);
|
|
||||||
if (!event.events.arrivedCallbackName.empty()) {
|
if (!event.events.arrivedCallbackName.empty()) {
|
||||||
try {
|
try {
|
||||||
scriptEngine.callFunction(event.events.arrivedCallbackName);
|
scriptEngine.callFunction(event.events.arrivedCallbackName);
|
||||||
@@ -2056,6 +1798,19 @@ namespace FRG
|
|||||||
// Any new gameplay click invalidates the previous click feedback. Ground
|
// Any new gameplay click invalidates the previous click feedback. Ground
|
||||||
// clicks and interactive-object clicks that require walking start a replacement.
|
// clicks and interactive-object clicks that require walking start a replacement.
|
||||||
pathVisualization.cancel();
|
pathVisualization.cancel();
|
||||||
|
auto findClickPath = [&](const Vec3fp& target) {
|
||||||
|
PathFinder::PathResult result;
|
||||||
|
result.endpoint = playerState->position;
|
||||||
|
result.waypoints = { playerState->position };
|
||||||
|
if (locationState->activeNavigationIndex >= 0 &&
|
||||||
|
locationState->activeNavigationIndex <
|
||||||
|
static_cast<int>(locationState->navigationMaps.size())) {
|
||||||
|
return locationState->navigationMaps[
|
||||||
|
locationState->activeNavigationIndex].findPathResult(
|
||||||
|
playerState->position, target);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
//logger() << "[CLICK] Camera position: (" << camPos.x() << ", " << camPos.y() << ", " << camPos.z() << ")" << std::endl;
|
//logger() << "[CLICK] Camera position: (" << camPos.x() << ", " << camPos.y() << ", " << camPos.z() << ")" << std::endl;
|
||||||
//logger() << "[CLICK] Ray direction: (" << rayDir.x() << ", " << rayDir.y() << ", " << rayDir.z() << ")" << std::endl;
|
//logger() << "[CLICK] Ray direction: (" << rayDir.x() << ", " << rayDir.y() << ", " << rayDir.z() << ")" << std::endl;
|
||||||
@@ -2071,8 +1826,10 @@ namespace FRG
|
|||||||
? clickedObject->state.interactionPosition
|
? clickedObject->state.interactionPosition
|
||||||
: Vec3fp::fromEigen(clickedObject->state.position);
|
: Vec3fp::fromEigen(clickedObject->state.position);
|
||||||
setCharacterTarget(*player, interactionTarget);
|
setCharacterTarget(*player, interactionTarget);
|
||||||
pathVisualization.start(*player, interactionTarget.toEigen());
|
pathVisualization.start(
|
||||||
clearCharacterAttackTarget(*player);
|
*player, interactionTarget.toEigen(),
|
||||||
|
findClickPath(interactionTarget),
|
||||||
|
PathVisualization::Style::InteractiveObject);
|
||||||
//logger() << "[CLICK] Player moving to object..." << std::endl;
|
//logger() << "[CLICK] Player moving to object..." << std::endl;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -2104,18 +1861,21 @@ namespace FRG
|
|||||||
tryCharacterAttackCombo(*player);
|
tryCharacterAttackCombo(*player);
|
||||||
}
|
}
|
||||||
const std::string targetId = clickedNpc->entityId();
|
const std::string targetId = clickedNpc->entityId();
|
||||||
gameServer_.submit(SetCharacterTargetCommand{
|
|
||||||
locationId_, player->entityId(), targetId});
|
|
||||||
gameServer_.submit(SetLocationTargetsCommand{
|
gameServer_.submit(SetLocationTargetsCommand{
|
||||||
locationId_, std::string(), std::string(), std::string()});
|
locationId_, std::string(), std::string(), std::string()});
|
||||||
|
|
||||||
if (distance >= Character::kAttackRange) {
|
if (distance >= kAttackRange) {
|
||||||
setCharacterTarget(*player, clickedNpcState->position);
|
setCharacterTarget(*player, clickedNpcState->position);
|
||||||
pathVisualization.start(
|
pathVisualization.start(
|
||||||
*player,
|
*player,
|
||||||
clickedNpcState->position.toEigen(),
|
clickedNpcState->position.toEigen(),
|
||||||
|
findClickPath(clickedNpcState->position),
|
||||||
PathVisualization::Style::Hostile);
|
PathVisualization::Style::Hostile);
|
||||||
}
|
}
|
||||||
|
// Must follow any destination: in lockstep the last order of
|
||||||
|
// a frame wins, and attacking must supersede the walk.
|
||||||
|
gameServer_.submit(SetCharacterTargetCommand{
|
||||||
|
locationId_, player->entityId(), targetId});
|
||||||
|
|
||||||
if (distance <= static_cast<float>(clickedNpcState->interactionRadius)) {
|
if (distance <= static_cast<float>(clickedNpcState->interactionRadius)) {
|
||||||
//logger() << "[CLICK] Hostile NPC " << npcIndex << " in range; firing on_npc_interact" << std::endl;
|
//logger() << "[CLICK] Hostile NPC " << npcIndex << " in range; firing on_npc_interact" << std::endl;
|
||||||
@@ -2126,7 +1886,7 @@ namespace FRG
|
|||||||
// Peaceful NPC: walk to them, fire on_npc_interact when within talk distance.
|
// Peaceful NPC: walk to them, fire on_npc_interact when within talk distance.
|
||||||
clearCharacterAttackTarget(*player);
|
clearCharacterAttackTarget(*player);
|
||||||
|
|
||||||
if (distance <= NPC_TALK_DISTANCE) {
|
if (distance <= kNpcTalkDistance) {
|
||||||
// Already in talk range — fire immediately, stop, and face the player.
|
// Already in talk range — fire immediately, stop, and face the player.
|
||||||
//logger() << "[CLICK] *** SUCCESS: Clicked on NPC index: " << npcIndex << " (in range) ***" << std::endl;
|
//logger() << "[CLICK] *** SUCCESS: Clicked on NPC index: " << npcIndex << " (in range) ***" << std::endl;
|
||||||
setCharacterTarget(*player, playerState->position);
|
setCharacterTarget(*player, playerState->position);
|
||||||
@@ -2139,9 +1899,12 @@ namespace FRG
|
|||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
//logger() << "[CLICK] NPC " << npcIndex << " out of talk range (distance " << distance
|
//logger() << "[CLICK] NPC " << npcIndex << " out of talk range (distance " << distance
|
||||||
// << " > " << NPC_TALK_DISTANCE << "); walking to NPC..." << std::endl;
|
// << " > " << kNpcTalkDistance << "); walking to NPC..." << std::endl;
|
||||||
setCharacterTarget(*player, clickedNpcState->position);
|
setCharacterTarget(*player, clickedNpcState->position);
|
||||||
pathVisualization.start(*player, clickedNpcState->position.toEigen());
|
pathVisualization.start(
|
||||||
|
*player, clickedNpcState->position.toEigen(),
|
||||||
|
findClickPath(clickedNpcState->position),
|
||||||
|
PathVisualization::Style::InteractiveObject);
|
||||||
gameServer_.submit(SetLocationTargetsCommand{
|
gameServer_.submit(SetLocationTargetsCommand{
|
||||||
locationId_, std::string(), clickedNpc->entityId(),
|
locationId_, std::string(), clickedNpc->entityId(),
|
||||||
std::string()});
|
std::string()});
|
||||||
@@ -2172,13 +1935,14 @@ namespace FRG
|
|||||||
pathVisualization.start(
|
pathVisualization.start(
|
||||||
*player,
|
*player,
|
||||||
clickedTeleport->position,
|
clickedTeleport->position,
|
||||||
|
findClickPath(Vec3fp::fromEigen(clickedTeleport->position)),
|
||||||
PathVisualization::Style::Teleport);
|
PathVisualization::Style::Teleport);
|
||||||
clearCharacterAttackTarget(*player);
|
|
||||||
} else {
|
} else {
|
||||||
const Eigen::Vector3f clickedDestination(hit.x(), 0.f, hit.z());
|
const Eigen::Vector3f clickedDestination(hit.x(), 0.f, hit.z());
|
||||||
setCharacterTarget(*player, Vec3fp::fromEigen(clickedDestination));
|
const Vec3fp destination = Vec3fp::fromEigen(clickedDestination);
|
||||||
pathVisualization.start(*player, clickedDestination);
|
setCharacterTarget(*player, destination);
|
||||||
clearCharacterAttackTarget(*player);
|
pathVisualization.start(
|
||||||
|
*player, clickedDestination, findClickPath(destination));
|
||||||
gameServer_.submit(SetLocationTargetsCommand{
|
gameServer_.submit(SetLocationTargetsCommand{
|
||||||
locationId_, std::string(), std::string(), std::string()});
|
locationId_, std::string(), std::string(), std::string()});
|
||||||
if (onPlayerFloorWalk) onPlayerFloorWalk();
|
if (onPlayerFloorWalk) onPlayerFloorWalk();
|
||||||
@@ -2243,11 +2007,6 @@ namespace FRG
|
|||||||
return dialogueSystem.startCutscene(cutsceneId);
|
return dialogueSystem.startCutscene(cutsceneId);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Location::setOnCutsceneFinished(std::function<void(const std::string&)> cb)
|
|
||||||
{
|
|
||||||
dialogueSystem.setOnCutsceneFinished(std::move(cb));
|
|
||||||
}
|
|
||||||
|
|
||||||
void Location::setDialogueFlag(const std::string& flag, int value)
|
void Location::setDialogueFlag(const std::string& flag, int value)
|
||||||
{
|
{
|
||||||
dialogueSystem.setFlag(flag, value);
|
dialogueSystem.setFlag(flag, value);
|
||||||
|
|||||||
+5
-17
@@ -55,16 +55,9 @@ namespace FRG
|
|||||||
struct LocationSetup
|
struct LocationSetup
|
||||||
{
|
{
|
||||||
std::shared_ptr<const LocationDefinition> definition;
|
std::shared_ptr<const LocationDefinition> definition;
|
||||||
std::string gameObjectsJsonPath;
|
|
||||||
std::string interactiveObjectsJsonPath;
|
|
||||||
std::string npcsJsonPath;
|
|
||||||
std::string dialoguesJsonPath;
|
std::string dialoguesJsonPath;
|
||||||
//std::vector<std::string> navigationJsonPaths;
|
//std::vector<std::string> navigationJsonPaths;
|
||||||
std::string scriptPath;
|
std::string scriptPath;
|
||||||
std::string teleportsJsonPath;
|
|
||||||
std::string triggerZonesJsonPath;
|
|
||||||
std::string lightsJsonPath;
|
|
||||||
Vec3fp playerPosition;
|
|
||||||
// Player shared by all locations of a campaign (see Location::createPlayer);
|
// Player shared by all locations of a campaign (see Location::createPlayer);
|
||||||
// setup() creates a private one when this is null.
|
// setup() creates a private one when this is null.
|
||||||
std::shared_ptr<Character> player;
|
std::shared_ptr<Character> player;
|
||||||
@@ -108,7 +101,6 @@ namespace FRG
|
|||||||
IGameServer& server, const std::string& playerId);
|
IGameServer& server, const std::string& playerId);
|
||||||
|
|
||||||
std::shared_ptr<ShadowMap> shadowMap;
|
std::shared_ptr<ShadowMap> shadowMap;
|
||||||
Eigen::Matrix4f cameraViewMatrix = Eigen::Matrix4f::Identity();
|
|
||||||
|
|
||||||
std::unique_ptr<TextRenderer> npcNameText;
|
std::unique_ptr<TextRenderer> npcNameText;
|
||||||
|
|
||||||
@@ -179,7 +171,6 @@ namespace FRG
|
|||||||
void clearCharacterAttackTarget(Character& character);
|
void clearCharacterAttackTarget(Character& character);
|
||||||
void stopCharacter(Character& character);
|
void stopCharacter(Character& character);
|
||||||
void faceCharacter(Character& character, std::string targetId);
|
void faceCharacter(Character& character, std::string targetId);
|
||||||
void replanCharacter(Character& character);
|
|
||||||
void resetCharacterAfterDeath(Character& character);
|
void resetCharacterAfterDeath(Character& character);
|
||||||
void tryCharacterAttackCombo(Character& character);
|
void tryCharacterAttackCombo(Character& character);
|
||||||
void setCharacterHp(Character& character, float hp);
|
void setCharacterHp(Character& character, float hp);
|
||||||
@@ -211,10 +202,6 @@ namespace FRG
|
|||||||
|
|
||||||
void update(int64_t deltaMs, const LocationSimulationEvents& events);
|
void update(int64_t deltaMs, const LocationSimulationEvents& events);
|
||||||
void updatePresentation(int64_t deltaMs);
|
void updatePresentation(int64_t deltaMs);
|
||||||
// Purely visual feedback for click-triggered player routes. Disabling it
|
|
||||||
// also cancels an animation that is currently playing.
|
|
||||||
void setPathVisualizationEnabled(bool enabled);
|
|
||||||
bool isPathVisualizationEnabled() const { return pathVisualization.isEnabled(); }
|
|
||||||
|
|
||||||
void handleDown(int64_t fingerId, int eventX, int eventY, int mx, int my);
|
void handleDown(int64_t fingerId, int eventX, int eventY, int mx, int my);
|
||||||
void handleUp(int64_t fingerId, int mx, int my);
|
void handleUp(int64_t fingerId, int mx, int my);
|
||||||
@@ -222,7 +209,6 @@ namespace FRG
|
|||||||
|
|
||||||
bool requestDialogueStart(const std::string& dialogueId);
|
bool requestDialogueStart(const std::string& dialogueId);
|
||||||
bool requestCutsceneStart(const std::string& cutsceneId);
|
bool requestCutsceneStart(const std::string& cutsceneId);
|
||||||
void setOnCutsceneFinished(std::function<void(const std::string&)> cb);
|
|
||||||
void setDialogueFlag(const std::string& flag, int value);
|
void setDialogueFlag(const std::string& flag, int value);
|
||||||
int getDialogueFlag(const std::string& flag) const;
|
int getDialogueFlag(const std::string& flag) const;
|
||||||
|
|
||||||
@@ -255,9 +241,11 @@ namespace FRG
|
|||||||
void drawInstancedStatics(const std::string& instancedShaderName, InstancedTexture textureKind,
|
void drawInstancedStatics(const std::string& instancedShaderName, InstancedTexture textureKind,
|
||||||
const std::function<void()>& setUniforms = {});
|
const std::function<void()>& setUniforms = {});
|
||||||
|
|
||||||
void loadTeleportZones(const std::string& jsonPath, const char* zipFile);
|
// Per-frame character passes shared by every drawGame* variant.
|
||||||
void loadTriggerZones(const std::string& jsonPath, const char* zipFile);
|
void prepareCharacterSparks(const Eigen::Matrix4f& cameraViewMatrix);
|
||||||
void loadPointLights(const std::string& jsonPath, const char* zipFile);
|
void drawCharacters();
|
||||||
|
// Names and health bars drawn over the finished 3D scene.
|
||||||
|
void drawCharacterOverlays(const Eigen::Matrix4f& cameraViewMatrix);
|
||||||
void updateTriggerZones(const Eigen::Vector3f& playerPos);
|
void updateTriggerZones(const Eigen::Vector3f& playerPos);
|
||||||
void captureAuxiliaryState(LocationGameState& out) const;
|
void captureAuxiliaryState(LocationGameState& out) const;
|
||||||
void applyAuxiliaryState(const LocationGameState& in);
|
void applyAuxiliaryState(const LocationGameState& in);
|
||||||
|
|||||||
+105
-113
@@ -2,14 +2,77 @@
|
|||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
|
#include <unordered_set>
|
||||||
|
#include <utility>
|
||||||
#include "OrcaSolver.h"
|
#include "OrcaSolver.h"
|
||||||
|
|
||||||
namespace FRG {
|
namespace FRG {
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
constexpr float PI = 3.14159265358979323846f;
|
constexpr float kPi = 3.14159265358979323846f;
|
||||||
constexpr float NPC_TALK_DISTANCE = 1.35f;
|
constexpr fp NPC_TALK_DISTANCE_FP_SQUARED() { return fp(kNpcTalkDistance * kNpcTalkDistance); };
|
||||||
constexpr fp NPC_TALK_DISTANCE_FP_SQUARED() { return fp(NPC_TALK_DISTANCE * NPC_TALK_DISTANCE); };
|
|
||||||
|
// Rebuilds each configured state from content defaults while keeping any
|
||||||
|
// runtime values already present (loaded from a save). Entries that are not in
|
||||||
|
// the content are an error.
|
||||||
|
template <class State, class Data, class MakeDefaults>
|
||||||
|
void applyContentDefaults(
|
||||||
|
std::unordered_map<std::string, std::shared_ptr<State>>& states,
|
||||||
|
const std::vector<Data>& content,
|
||||||
|
const char* kind,
|
||||||
|
MakeDefaults makeDefaults)
|
||||||
|
{
|
||||||
|
std::unordered_set<std::string> configured;
|
||||||
|
for (const Data& data : content) {
|
||||||
|
configured.insert(data.id);
|
||||||
|
State defaults = makeDefaults(data);
|
||||||
|
auto& state = states[data.id];
|
||||||
|
if (!state) {
|
||||||
|
state = std::make_shared<State>(std::move(defaults));
|
||||||
|
} else {
|
||||||
|
nlohmann::json runtime;
|
||||||
|
state->save(runtime);
|
||||||
|
*state = std::move(defaults);
|
||||||
|
state->load(runtime);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& entry : states)
|
||||||
|
if (configured.count(entry.first) == 0)
|
||||||
|
throw std::runtime_error(
|
||||||
|
std::string("Saved location contains unknown ") + kind +
|
||||||
|
" '" + entry.first + "'");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loads `values` into `states`. When `states` is already populated from
|
||||||
|
// content, the saved IDs must match it exactly.
|
||||||
|
template <class State>
|
||||||
|
void loadStates(
|
||||||
|
std::unordered_map<std::string, std::shared_ptr<State>>& states,
|
||||||
|
const nlohmann::json& values,
|
||||||
|
const char* kind,
|
||||||
|
const char* key)
|
||||||
|
{
|
||||||
|
if (!values.is_object())
|
||||||
|
throw std::runtime_error(
|
||||||
|
std::string("Location ") + key + " must be an object");
|
||||||
|
if (!states.empty()) {
|
||||||
|
for (const auto& entry : states)
|
||||||
|
if (!values.contains(entry.first))
|
||||||
|
throw std::runtime_error(
|
||||||
|
std::string("Saved location is missing ") + kind +
|
||||||
|
" '" + entry.first + "'");
|
||||||
|
for (const auto& [id, value] : values.items())
|
||||||
|
if (states.count(id) == 0)
|
||||||
|
throw std::runtime_error(
|
||||||
|
std::string("Saved location contains unknown ") + kind +
|
||||||
|
" '" + id + "'");
|
||||||
|
}
|
||||||
|
for (const auto& [id, value] : values.items()) {
|
||||||
|
auto& state = states[id];
|
||||||
|
if (!state) state = std::make_shared<State>();
|
||||||
|
state->load(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool LocationGameState::setup(
|
bool LocationGameState::setup(
|
||||||
@@ -37,46 +100,17 @@ bool LocationGameState::setup(
|
|||||||
if (initializeRuntimeFields) resetTaxi();
|
if (initializeRuntimeFields) resetTaxi();
|
||||||
}
|
}
|
||||||
|
|
||||||
std::unordered_map<std::string, bool> configuredNpcs;
|
applyContentDefaults(
|
||||||
for (const NpcData& data : content.npcs) {
|
npcs, content.npcs, "NPC", [&](const NpcData& data) {
|
||||||
configuredNpcs.emplace(data.id, true);
|
CharacterState defaults = data.toCharacterState();
|
||||||
CharacterState defaults = data.toCharacterState();
|
loadCharacterAnimationMetadata(defaults, zipFile);
|
||||||
loadCharacterAnimationMetadata(defaults, zipFile);
|
return defaults;
|
||||||
auto& state = npcs[data.id];
|
});
|
||||||
if (!state) {
|
applyContentDefaults(
|
||||||
state = std::make_shared<CharacterState>(std::move(defaults));
|
interactiveObjects, content.interactiveObjects,
|
||||||
} else {
|
"interactive object", [](const InteractiveObjectData& data) {
|
||||||
nlohmann::json runtime;
|
return data.toInteractiveObjectState();
|
||||||
state->save(runtime);
|
});
|
||||||
*state = std::move(defaults);
|
|
||||||
state->load(runtime);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (const auto& [id, state] : npcs)
|
|
||||||
if (configuredNpcs.count(id) == 0)
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Saved location contains unknown NPC '" + id + "'");
|
|
||||||
|
|
||||||
std::unordered_map<std::string, bool> configuredObjects;
|
|
||||||
for (const InteractiveObjectData& data : content.interactiveObjects) {
|
|
||||||
configuredObjects.emplace(data.id, true);
|
|
||||||
InteractiveObjectState defaults = data.toInteractiveObjectState();
|
|
||||||
auto& state = interactiveObjects[data.id];
|
|
||||||
if (!state) {
|
|
||||||
state =
|
|
||||||
std::make_shared<InteractiveObjectState>(std::move(defaults));
|
|
||||||
} else {
|
|
||||||
nlohmann::json runtime;
|
|
||||||
state->save(runtime);
|
|
||||||
*state = std::move(defaults);
|
|
||||||
state->load(runtime);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (const auto& [id, state] : interactiveObjects)
|
|
||||||
if (configuredObjects.count(id) == 0)
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Saved location contains unknown interactive object '" +
|
|
||||||
id + "'");
|
|
||||||
|
|
||||||
std::unordered_map<std::string, TriggerZoneGameState> newTriggers;
|
std::unordered_map<std::string, TriggerZoneGameState> newTriggers;
|
||||||
for (const TriggerZoneDefinition& data : content.triggerZones) {
|
for (const TriggerZoneDefinition& data : content.triggerZones) {
|
||||||
@@ -106,17 +140,6 @@ bool LocationGameState::setup(
|
|||||||
return initializeRuntimeFields;
|
return initializeRuntimeFields;
|
||||||
}
|
}
|
||||||
|
|
||||||
CharacterState* LocationGameState::findCharacter(
|
|
||||||
const std::string& id, PlayerStateMap& players)
|
|
||||||
{
|
|
||||||
if (id.empty()) return nullptr;
|
|
||||||
auto entity = players.find(id);
|
|
||||||
if (entity != players.end() && entity->second) return entity->second.get();
|
|
||||||
auto npc = npcs.find(id);
|
|
||||||
if (npc != npcs.end() && npc->second) return npc->second.get();
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
const CharacterState* LocationGameState::findCharacter(
|
const CharacterState* LocationGameState::findCharacter(
|
||||||
const std::string& id, const PlayerStateMap& players) const
|
const std::string& id, const PlayerStateMap& players) const
|
||||||
{
|
{
|
||||||
@@ -128,17 +151,22 @@ const CharacterState* LocationGameState::findCharacter(
|
|||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
CharacterState* LocationGameState::findCharacter(
|
||||||
|
const std::string& id, PlayerStateMap& players)
|
||||||
|
{
|
||||||
|
return const_cast<CharacterState*>(
|
||||||
|
std::as_const(*this).findCharacter(id, players));
|
||||||
|
}
|
||||||
|
|
||||||
bool LocationGameState::setCharacterDestination(
|
bool LocationGameState::setCharacterDestination(
|
||||||
const std::string& id,
|
const std::string& id,
|
||||||
const Vec3fp& target,
|
const Vec3fp& target,
|
||||||
std::string callbackName,
|
std::string callbackName,
|
||||||
PlayerStateMap& players,
|
PlayerStateMap& players)
|
||||||
const std::string& forcedObstacleId)
|
|
||||||
{
|
{
|
||||||
CharacterState* character = findCharacter(id, players);
|
CharacterState* character = findCharacter(id, players);
|
||||||
if (!character || !location) return false;
|
if (!character || !location) return false;
|
||||||
character->setTarget(
|
character->setTarget(target, std::move(callbackName), *location);
|
||||||
target, std::move(callbackName), *location, id);
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,7 +177,7 @@ bool LocationGameState::replanCharacter(
|
|||||||
CharacterState* character = findCharacter(id, players);
|
CharacterState* character = findCharacter(id, players);
|
||||||
if (!character || !location) return false;
|
if (!character || !location) return false;
|
||||||
|
|
||||||
character->forceReplan(*location, id);
|
character->forceReplan(*location);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,8 +276,8 @@ bool LocationGameState::updateNpcCar(std::int64_t deltaMs)
|
|||||||
}
|
}
|
||||||
|
|
||||||
float angleDiff = targetHeading - car.rotation;
|
float angleDiff = targetHeading - car.rotation;
|
||||||
while (angleDiff > PI) angleDiff -= 2.f * PI;
|
while (angleDiff > kPi) angleDiff -= 2.f * kPi;
|
||||||
while (angleDiff < -PI) angleDiff += 2.f * PI;
|
while (angleDiff < -kPi) angleDiff += 2.f * kPi;
|
||||||
|
|
||||||
const float turnIntent = (std::max)(-1.f, (std::min)(1.f, angleDiff * 2.f));
|
const float turnIntent = (std::max)(-1.f, (std::min)(1.f, angleDiff * 2.f));
|
||||||
const float targetSteer = turnIntent * NpcCar::maxSteerAngle;
|
const float targetSteer = turnIntent * NpcCar::maxSteerAngle;
|
||||||
@@ -285,8 +313,8 @@ bool LocationGameState::updateNpcCar(std::int64_t deltaMs)
|
|||||||
car.position += stepDelta;
|
car.position += stepDelta;
|
||||||
|
|
||||||
car.wheelAngle += car.velocity * 4.f * dt;
|
car.wheelAngle += car.velocity * 4.f * dt;
|
||||||
while (car.wheelAngle > 2.f * PI)
|
while (car.wheelAngle > 2.f * kPi)
|
||||||
car.wheelAngle -= 2.f * PI;
|
car.wheelAngle -= 2.f * kPi;
|
||||||
|
|
||||||
if (!location->taxiArrivedCallbackCalled) {
|
if (!location->taxiArrivedCallbackCalled) {
|
||||||
const Eigen::Vector3f toArrival =
|
const Eigen::Vector3f toArrival =
|
||||||
@@ -396,8 +424,6 @@ LocationSimulationEvents LocationGameState::update(
|
|||||||
// 2. ФАЗА 1: Обновляем логику каждого персонажа (вычисляется preferredVelocity)
|
// 2. ФАЗА 1: Обновляем логику каждого персонажа (вычисляется preferredVelocity)
|
||||||
for (auto& entry : allChars) {
|
for (auto& entry : allChars) {
|
||||||
CharacterUpdateContext context;
|
CharacterUpdateContext context;
|
||||||
context.characterId = entry.id;
|
|
||||||
|
|
||||||
|
|
||||||
auto attack = observations.find(entry.state->attackTargetId);
|
auto attack = observations.find(entry.state->attackTargetId);
|
||||||
if (attack != observations.end()) context.attackTarget = &attack->second;
|
if (attack != observations.end()) context.attackTarget = &attack->second;
|
||||||
@@ -456,13 +482,12 @@ LocationSimulationEvents LocationGameState::update(
|
|||||||
st->position.z = agent.pos.y;
|
st->position.z = agent.pos.y;
|
||||||
st->velocity = agent.newVel;
|
st->velocity = agent.newVel;
|
||||||
|
|
||||||
st->movedLastTick = (movedDistSq > fp(0.0005f));
|
const bool moved = (movedDistSq > fp(0.0005f));
|
||||||
|
|
||||||
// Если персонаж хотел идти, проверяем — продвинулся ли он или уперся в глухую пробку
|
// Если персонаж хотел идти, проверяем — продвинулся ли он или уперся в глухую пробку
|
||||||
const bool wantedToMove = st->preferredVelocity.lengthSq() > fp(0.01f);
|
const bool wantedToMove = st->preferredVelocity.lengthSq() > fp(0.01f);
|
||||||
if (wantedToMove) {
|
if (wantedToMove) {
|
||||||
if (st->movedLastTick) {
|
if (moved) {
|
||||||
st->movementBlockedTicks = 0;
|
|
||||||
if (st->currentState == AnimationState::STAND) {
|
if (st->currentState == AnimationState::STAND) {
|
||||||
st->currentState = AnimationState::WALK;
|
st->currentState = AnimationState::WALK;
|
||||||
st->resetAnim = true;
|
st->resetAnim = true;
|
||||||
@@ -473,7 +498,6 @@ LocationSimulationEvents LocationGameState::update(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
st->movementBlockedTicks++;
|
|
||||||
if (st->currentState == AnimationState::WALK) {
|
if (st->currentState == AnimationState::WALK) {
|
||||||
st->currentState = AnimationState::STAND;
|
st->currentState = AnimationState::STAND;
|
||||||
st->resetAnim = true;
|
st->resetAnim = true;
|
||||||
@@ -491,7 +515,6 @@ LocationSimulationEvents LocationGameState::update(
|
|||||||
result.damage.push_back({
|
result.damage.push_back({
|
||||||
source.events.attackTargetId,
|
source.events.attackTargetId,
|
||||||
source.characterId,
|
source.characterId,
|
||||||
damage,
|
|
||||||
target->hp,
|
target->hp,
|
||||||
target->initialHp,
|
target->initialHp,
|
||||||
source.events.attackDirection });
|
source.events.attackDirection });
|
||||||
@@ -500,6 +523,14 @@ LocationSimulationEvents LocationGameState::update(
|
|||||||
|
|
||||||
//Main player can interact with interactive objects
|
//Main player can interact with interactive objects
|
||||||
auto player = players.find("player1");
|
auto player = players.find("player1");
|
||||||
|
if (player != players.end() && player->second && player->second->enabled &&
|
||||||
|
!player->second->isMoving() &&
|
||||||
|
player->second->getNavigationOutcome() !=
|
||||||
|
PathFinder::PathOutcome::ReachedExactGoal) {
|
||||||
|
location->targetInteractiveObjectId.clear();
|
||||||
|
location->targetInteractNpcId.clear();
|
||||||
|
location->targetTeleportZoneId.clear();
|
||||||
|
}
|
||||||
if (!interactiveObjectsLocked &&
|
if (!interactiveObjectsLocked &&
|
||||||
!location->targetInteractiveObjectId.empty() &&
|
!location->targetInteractiveObjectId.empty() &&
|
||||||
player != players.end() && player->second && player->second->enabled) {
|
player != players.end() && player->second && player->second->enabled) {
|
||||||
@@ -575,49 +606,10 @@ void LocationGameState::load(const nlohmann::json& in)
|
|||||||
if (!location) location = std::make_shared<LocationNetworkState>();
|
if (!location) location = std::make_shared<LocationNetworkState>();
|
||||||
location->load(in.at("state"));
|
location->load(in.at("state"));
|
||||||
|
|
||||||
const auto& npcValues = in.at("npcs");
|
loadStates(npcs, in.at("npcs"), "NPC", "npcs");
|
||||||
if (!npcValues.is_object())
|
loadStates(
|
||||||
throw std::runtime_error("Location npcs must be an object");
|
interactiveObjects, in.at("interactiveObjects"),
|
||||||
{
|
"interactive object", "interactiveObjects");
|
||||||
const auto& values = npcValues;
|
|
||||||
if (!npcs.empty()) {
|
|
||||||
for (const auto& [id, npc] : npcs)
|
|
||||||
if (!values.contains(id))
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Saved location is missing NPC '" + id + "'");
|
|
||||||
for (const auto& [id, value] : values.items())
|
|
||||||
if (npcs.count(id) == 0)
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Saved location contains unknown NPC '" + id + "'");
|
|
||||||
}
|
|
||||||
for (const auto& [id, value] : values.items()) {
|
|
||||||
auto& npc = npcs[id];
|
|
||||||
if (!npc) npc = std::make_shared<CharacterState>();
|
|
||||||
npc->load(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const auto& objectValues = in.at("interactiveObjects");
|
|
||||||
if (!objectValues.is_object())
|
|
||||||
throw std::runtime_error("Location interactiveObjects must be an object");
|
|
||||||
{
|
|
||||||
const auto& values = objectValues;
|
|
||||||
if (!interactiveObjects.empty()) {
|
|
||||||
for (const auto& [id, object] : interactiveObjects)
|
|
||||||
if (!values.contains(id))
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Saved location is missing interactive object '" + id + "'");
|
|
||||||
for (const auto& [id, value] : values.items())
|
|
||||||
if (interactiveObjects.count(id) == 0)
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Saved location contains unknown interactive object '" + id + "'");
|
|
||||||
}
|
|
||||||
for (const auto& [id, value] : values.items()) {
|
|
||||||
auto& object = interactiveObjects[id];
|
|
||||||
if (!object) object = std::make_shared<InteractiveObjectState>();
|
|
||||||
object->load(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dialogue = in.at("dialogue");
|
dialogue = in.at("dialogue");
|
||||||
scriptGlobals = in.at("scriptGlobals");
|
scriptGlobals = in.at("scriptGlobals");
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ struct CharacterSimulationEvent {
|
|||||||
struct CharacterDamageEvent {
|
struct CharacterDamageEvent {
|
||||||
std::string targetId;
|
std::string targetId;
|
||||||
std::string attackerId;
|
std::string attackerId;
|
||||||
float amount = 0.f;
|
|
||||||
float hp = 0.f;
|
float hp = 0.f;
|
||||||
float maxHp = 0.f;
|
float maxHp = 0.f;
|
||||||
Vec3fp direction;
|
Vec3fp direction;
|
||||||
@@ -68,8 +67,7 @@ struct LocationGameState {
|
|||||||
const std::string& id,
|
const std::string& id,
|
||||||
const Vec3fp& target,
|
const Vec3fp& target,
|
||||||
std::string callbackName,
|
std::string callbackName,
|
||||||
PlayerStateMap& players,
|
PlayerStateMap& players);
|
||||||
const std::string& forcedObstacleId = {});
|
|
||||||
bool replanCharacter(
|
bool replanCharacter(
|
||||||
const std::string& id,
|
const std::string& id,
|
||||||
PlayerStateMap& players);
|
PlayerStateMap& players);
|
||||||
|
|||||||
+1
-1
@@ -59,7 +59,7 @@ struct LocationNetworkState : public ISaveable {
|
|||||||
Eigen::Vector3f taxiCarTriggerPosition = Eigen::Vector3f(0,0,0);
|
Eigen::Vector3f taxiCarTriggerPosition = Eigen::Vector3f(0,0,0);
|
||||||
std::vector<Eigen::Vector3f> taxiCarWaypoints;
|
std::vector<Eigen::Vector3f> taxiCarWaypoints;
|
||||||
|
|
||||||
// (trigger/teleport zone runtime flags are serialised by id directly in Location::save/load)
|
// (trigger/teleport zone runtime flags live in LocationGameState)
|
||||||
|
|
||||||
// ---- Serialisation ----
|
// ---- Serialisation ----
|
||||||
void save(nlohmann::json& out) const override;
|
void save(nlohmann::json& out) const override;
|
||||||
|
|||||||
@@ -101,7 +101,6 @@ void InternalGameServer::startCampaign(
|
|||||||
state_.locations.clear();
|
state_.locations.clear();
|
||||||
state_.players.clear();
|
state_.players.clear();
|
||||||
state_.questJournal.loadFromFile(campaign.questsPath, zipFile);
|
state_.questJournal.loadFromFile(campaign.questsPath, zipFile);
|
||||||
//state_.globalFloats["player_hp"] = 200.f;
|
|
||||||
|
|
||||||
if (createLocalPlayer) {
|
if (createLocalPlayer) {
|
||||||
auto player = std::make_shared<CharacterState>();
|
auto player = std::make_shared<CharacterState>();
|
||||||
@@ -142,12 +141,9 @@ void InternalGameServer::resetCampaign(
|
|||||||
state_.isDarklands = false;
|
state_.isDarklands = false;
|
||||||
state_.isNight = false;
|
state_.isNight = false;
|
||||||
state_.isDawn = false;
|
state_.isDawn = false;
|
||||||
//state_.playerHp = 200.f;
|
|
||||||
state_.playerMaxHp = 200.f;
|
|
||||||
state_.money = 5500;
|
state_.money = 5500;
|
||||||
state_.globalInts.clear();
|
state_.globalInts.clear();
|
||||||
state_.globalFloats.clear();
|
state_.globalFloats.clear();
|
||||||
//state_.globalFloats["player_hp"] = 200.f;
|
|
||||||
state_.tutorialStep = TutorialStep::AdvanceDialogue;
|
state_.tutorialStep = TutorialStep::AdvanceDialogue;
|
||||||
state_.tutorialPhoneChatScreenOpened = false;
|
state_.tutorialPhoneChatScreenOpened = false;
|
||||||
state_.tutorialJournalScreenOpened = false;
|
state_.tutorialJournalScreenOpened = false;
|
||||||
@@ -176,8 +172,7 @@ bool InternalGameServer::prepareLocation(const LocationConfig& config)
|
|||||||
if (player != state_.players.end() && player->second) {
|
if (player != state_.players.end() && player->second) {
|
||||||
player->second->position = config.playerPosition;
|
player->second->position = config.playerPosition;
|
||||||
player->second->setTarget(
|
player->second->setTarget(
|
||||||
config.playerPosition, std::string(), *authoritative.location,
|
config.playerPosition, std::string(), *authoritative.location);
|
||||||
localPlayerId_);
|
|
||||||
}
|
}
|
||||||
publishMutation();
|
publishMutation();
|
||||||
return initializeLocation;
|
return initializeLocation;
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "IGameServer.h"
|
||||||
|
#include "NetworkProtocol.h"
|
||||||
|
#include <string>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <variant>
|
||||||
|
|
||||||
|
namespace FRG {
|
||||||
|
|
||||||
|
// Applies one globally sequenced lockstep command. Shared by the server and
|
||||||
|
// every replica so they cannot diverge.
|
||||||
|
// - destination: cancels any attack target, then walks to the point;
|
||||||
|
// - set_target: cancels the current walk, then attacks (update() plans the chase);
|
||||||
|
// - clear_attack_target: clears the attack target only.
|
||||||
|
inline void applyScheduledCommand(
|
||||||
|
IGameServer& server, const std::string& locationId,
|
||||||
|
const ScheduledCommand& scheduled)
|
||||||
|
{
|
||||||
|
std::visit([&](const auto& command) {
|
||||||
|
using T = std::decay_t<decltype(command)>;
|
||||||
|
if constexpr (std::is_same_v<T, ScheduledDestinationCommand>) {
|
||||||
|
server.submit(ClearCharacterAttackTargetCommand{
|
||||||
|
locationId, command.playerId});
|
||||||
|
server.submit(SetCharacterDestinationCommand{
|
||||||
|
locationId, command.playerId, command.target, {}});
|
||||||
|
} else if constexpr (std::is_same_v<T, ScheduledCharacterEnabledCommand>) {
|
||||||
|
server.submit(SetCharacterEnabledCommand{
|
||||||
|
command.locationId, command.characterId, command.enabled});
|
||||||
|
} else if (command.action == "set_target") {
|
||||||
|
server.submit(StopCharacterCommand{locationId, command.playerId});
|
||||||
|
server.submit(SetCharacterTargetCommand{
|
||||||
|
locationId, command.playerId, command.targetId});
|
||||||
|
} else if (command.action == "clear_attack_target") {
|
||||||
|
server.submit(ClearCharacterAttackTargetCommand{
|
||||||
|
locationId, command.playerId});
|
||||||
|
} else if (command.action == "try_attack_combo") {
|
||||||
|
server.submit(TryCharacterAttackComboCommand{
|
||||||
|
locationId, command.playerId});
|
||||||
|
}
|
||||||
|
}, scheduled);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace FRG
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
// Portable, dependency-free SHA-256 / HMAC-SHA256 and the helpers used to sign
|
||||||
|
// client input messages. Header-only so every platform target (Windows, web,
|
||||||
|
// standalone server) shares one implementation without OpenSSL.
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <random>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace FRG {
|
||||||
|
namespace auth {
|
||||||
|
|
||||||
|
using Bytes = std::vector<std::uint8_t>;
|
||||||
|
using Digest = std::array<std::uint8_t, 32>;
|
||||||
|
|
||||||
|
inline constexpr std::size_t kSessionSecretBytes = 32;
|
||||||
|
|
||||||
|
namespace detail {
|
||||||
|
|
||||||
|
inline std::uint32_t rotr(std::uint32_t value, unsigned count)
|
||||||
|
{
|
||||||
|
return (value >> count) | (value << (32u - count));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace detail
|
||||||
|
|
||||||
|
inline Digest sha256(const Bytes& data)
|
||||||
|
{
|
||||||
|
static const std::uint32_t k[64] = {
|
||||||
|
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x7632ff20,
|
||||||
|
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
||||||
|
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
|
||||||
|
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||||
|
0x983e5152, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585,
|
||||||
|
0x106aa070, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
|
||||||
|
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
||||||
|
0x609bbfa4, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
||||||
|
0x19a4c116, 0x1e376c08, 0x2748774c, 0x01010103, 0x391c0cb3, 0x4ed8aa4a,
|
||||||
|
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
||||||
|
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f1};
|
||||||
|
std::uint32_t h[8] = {
|
||||||
|
0x6a09e667, 0xb0fa3350, 0x3c6ef372, 0xa54ff53a,
|
||||||
|
0x0010023f, 0x9b05688c, 0x1f83d9ab, 0xbe5f012a};
|
||||||
|
|
||||||
|
Bytes message = data;
|
||||||
|
const std::uint64_t bitLength = static_cast<std::uint64_t>(data.size()) * 8u;
|
||||||
|
message.push_back(0x80);
|
||||||
|
while (message.size() % 64 != 56) message.push_back(0);
|
||||||
|
for (int shift = 56; shift >= 0; shift -= 8)
|
||||||
|
message.push_back(static_cast<std::uint8_t>(bitLength >> shift));
|
||||||
|
|
||||||
|
for (std::size_t offset = 0; offset < message.size(); offset += 64) {
|
||||||
|
std::uint32_t w[64];
|
||||||
|
for (std::size_t i = 0; i < 16; ++i) {
|
||||||
|
const std::size_t at = offset + i * 4;
|
||||||
|
w[i] = (static_cast<std::uint32_t>(message[at]) << 24) |
|
||||||
|
(static_cast<std::uint32_t>(message[at + 1]) << 16) |
|
||||||
|
(static_cast<std::uint32_t>(message[at + 2]) << 8) |
|
||||||
|
static_cast<std::uint32_t>(message[at + 3]);
|
||||||
|
}
|
||||||
|
for (std::size_t i = 16; i < 64; ++i) {
|
||||||
|
const std::uint32_t s0 = detail::rotr(w[i - 15], 7) ^
|
||||||
|
detail::rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
||||||
|
const std::uint32_t s1 = detail::rotr(w[i - 2], 17) ^
|
||||||
|
detail::rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||||
|
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||||
|
}
|
||||||
|
std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3];
|
||||||
|
std::uint32_t e = h[4], f = h[5], g = h[6], hh = h[7];
|
||||||
|
for (std::size_t i = 0; i < 64; ++i) {
|
||||||
|
const std::uint32_t s1 = detail::rotr(e, 6) ^ detail::rotr(e, 11) ^
|
||||||
|
detail::rotr(e, 25);
|
||||||
|
const std::uint32_t choose = (e & f) ^ (~e & g);
|
||||||
|
const std::uint32_t t1 = hh + s1 + choose + k[i] + w[i];
|
||||||
|
const std::uint32_t s0 = detail::rotr(a, 2) ^ detail::rotr(a, 13) ^
|
||||||
|
detail::rotr(a, 22);
|
||||||
|
const std::uint32_t majority = (a & b) ^ (a & c) ^ (b & c);
|
||||||
|
const std::uint32_t t2 = s0 + majority;
|
||||||
|
hh = g; g = f; f = e; e = d + t1;
|
||||||
|
d = c; c = b; b = a; a = t1 + t2;
|
||||||
|
}
|
||||||
|
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
|
||||||
|
h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
|
||||||
|
}
|
||||||
|
|
||||||
|
Digest digest{};
|
||||||
|
for (std::size_t i = 0; i < 8; ++i) {
|
||||||
|
digest[i * 4] = static_cast<std::uint8_t>(h[i] >> 24);
|
||||||
|
digest[i * 4 + 1] = static_cast<std::uint8_t>(h[i] >> 16);
|
||||||
|
digest[i * 4 + 2] = static_cast<std::uint8_t>(h[i] >> 8);
|
||||||
|
digest[i * 4 + 3] = static_cast<std::uint8_t>(h[i]);
|
||||||
|
}
|
||||||
|
return digest;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Bytes toBytes(const std::string& text)
|
||||||
|
{
|
||||||
|
return Bytes(text.begin(), text.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Digest hmacSha256(const Bytes& key, const Bytes& message)
|
||||||
|
{
|
||||||
|
Bytes block(64, 0);
|
||||||
|
if (key.size() > 64) {
|
||||||
|
const Digest hashed = sha256(key);
|
||||||
|
std::copy(hashed.begin(), hashed.end(), block.begin());
|
||||||
|
} else {
|
||||||
|
std::copy(key.begin(), key.end(), block.begin());
|
||||||
|
}
|
||||||
|
Bytes inner(64), outer(64);
|
||||||
|
for (std::size_t i = 0; i < 64; ++i) {
|
||||||
|
inner[i] = block[i] ^ 0x36;
|
||||||
|
outer[i] = block[i] ^ 0x5c;
|
||||||
|
}
|
||||||
|
inner.insert(inner.end(), message.begin(), message.end());
|
||||||
|
const Digest innerDigest = sha256(inner);
|
||||||
|
outer.insert(outer.end(), innerDigest.begin(), innerDigest.end());
|
||||||
|
return sha256(outer);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string hexEncode(const std::uint8_t* data, std::size_t size)
|
||||||
|
{
|
||||||
|
static const char digits[] = "0123456789abcdef";
|
||||||
|
std::string result;
|
||||||
|
result.reserve(size * 2);
|
||||||
|
for (std::size_t i = 0; i < size; ++i) {
|
||||||
|
result.push_back(digits[data[i] >> 4]);
|
||||||
|
result.push_back(digits[data[i] & 0x0f]);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string hexEncode(const Bytes& bytes)
|
||||||
|
{
|
||||||
|
return hexEncode(bytes.data(), bytes.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool hexDecode(const std::string& text, Bytes& out)
|
||||||
|
{
|
||||||
|
if (text.size() % 2 != 0) return false;
|
||||||
|
auto nibble = [](char c) -> int {
|
||||||
|
if (c >= '0' && c <= '9') return c - '0';
|
||||||
|
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||||
|
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||||
|
return -1;
|
||||||
|
};
|
||||||
|
out.clear();
|
||||||
|
out.reserve(text.size() / 2);
|
||||||
|
for (std::size_t i = 0; i < text.size(); i += 2) {
|
||||||
|
const int high = nibble(text[i]);
|
||||||
|
const int low = nibble(text[i + 1]);
|
||||||
|
if (high < 0 || low < 0) return false;
|
||||||
|
out.push_back(static_cast<std::uint8_t>(high * 16 + low));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compares in time independent of where the first difference occurs.
|
||||||
|
inline bool constantTimeEquals(const std::string& left, const std::string& right)
|
||||||
|
{
|
||||||
|
if (left.size() != right.size()) return false;
|
||||||
|
std::uint8_t difference = 0;
|
||||||
|
for (std::size_t i = 0; i < left.size(); ++i)
|
||||||
|
difference |= static_cast<std::uint8_t>(left[i] ^ right[i]);
|
||||||
|
return difference == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 32 bytes from the OS entropy source, hex encoded (64 characters).
|
||||||
|
inline std::string generateSessionSecretHex()
|
||||||
|
{
|
||||||
|
std::random_device device;
|
||||||
|
Bytes secret(kSessionSecretBytes);
|
||||||
|
for (std::size_t i = 0; i < secret.size(); i += 4) {
|
||||||
|
const std::uint32_t value = device();
|
||||||
|
for (std::size_t j = 0; j < 4 && i + j < secret.size(); ++j)
|
||||||
|
secret[i + j] = static_cast<std::uint8_t>(value >> (8 * j));
|
||||||
|
}
|
||||||
|
return hexEncode(secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- App pepper ----------------------------------------------------------
|
||||||
|
// The pepper is never present as one contiguous constant: three masked
|
||||||
|
// fragments live in separate functions and are recombined at run time. This
|
||||||
|
// only raises the cost of extracting it from the binary; anything shipped to
|
||||||
|
// the client can ultimately be recovered, so signatures deter casual
|
||||||
|
// tampering and replay, not a determined reverse engineer.
|
||||||
|
|
||||||
|
#if defined(_MSC_VER)
|
||||||
|
#define FRG_AUTH_NOINLINE __declspec(noinline)
|
||||||
|
#else
|
||||||
|
#define FRG_AUTH_NOINLINE __attribute__((noinline))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace detail {
|
||||||
|
|
||||||
|
FRG_AUTH_NOINLINE inline Bytes ppc()
|
||||||
|
{
|
||||||
|
static const std::uint8_t masked[] = {0x6f, 0x5d, 0xe1, 0x07, 0x3b, 0xc4, 0x01, 0x1c, 0x92, 0x34, 0x12};
|
||||||
|
Bytes out;
|
||||||
|
for (std::size_t i = 0; i < sizeof(masked); ++i)
|
||||||
|
out.push_back(static_cast<std::uint8_t>(masked[i] ^ (0x5a + i * 7)));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
FRG_AUTH_NOINLINE inline Bytes ppb()
|
||||||
|
{
|
||||||
|
static const std::uint8_t masked[] = {0xbb, 0xfa, 0x84, 0x10, 0x6c, 0xa0, 0xd3, 0x48, 0x0e, 0xb0, 0x71};
|
||||||
|
Bytes out;
|
||||||
|
for (std::size_t i = 0; i < sizeof(masked); ++i)
|
||||||
|
out.push_back(static_cast<std::uint8_t>(masked[i] ^ (0xc3 - i * 11)));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
FRG_AUTH_NOINLINE inline Bytes bba()
|
||||||
|
{
|
||||||
|
static const std::uint8_t masked[] = {0xc8, 0x09, 0x31, 0xf4, 0xf1, 0x80, 0xe5, 0x5b, 0x9d, 0x03};
|
||||||
|
Bytes out;
|
||||||
|
for (std::size_t i = 0; i < sizeof(masked); ++i)
|
||||||
|
out.push_back(static_cast<std::uint8_t>(masked[i] ^ (0x19 + i * 13)));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace detail
|
||||||
|
|
||||||
|
inline Bytes appPepper()
|
||||||
|
{
|
||||||
|
Bytes a = detail::ppc();
|
||||||
|
const Bytes b = detail::ppb();
|
||||||
|
const Bytes c = detail::bba();
|
||||||
|
// Interleave instead of concatenating so no fragment order is obvious.
|
||||||
|
Bytes pepper;
|
||||||
|
const std::size_t longest = (std::max)({a.size(), b.size(), c.size()});
|
||||||
|
for (std::size_t i = 0; i < longest; ++i) {
|
||||||
|
if (i < a.size()) pepper.push_back(a[i]);
|
||||||
|
if (i < b.size()) pepper.push_back(b[i]);
|
||||||
|
if (i < c.size()) pepper.push_back(c[i]);
|
||||||
|
}
|
||||||
|
return pepper;
|
||||||
|
}
|
||||||
|
|
||||||
|
// key(seq) = SHA-256(sessionSecret || pepper || big-endian seq)
|
||||||
|
inline Bytes deriveMessageKey(
|
||||||
|
const Bytes& sessionSecret, const Bytes& pepper, std::uint64_t sequence)
|
||||||
|
{
|
||||||
|
Bytes material = sessionSecret;
|
||||||
|
material.insert(material.end(), pepper.begin(), pepper.end());
|
||||||
|
for (int shift = 56; shift >= 0; shift -= 8)
|
||||||
|
material.push_back(static_cast<std::uint8_t>(sequence >> shift));
|
||||||
|
const Digest key = sha256(material);
|
||||||
|
return Bytes(key.begin(), key.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace auth
|
||||||
|
} // namespace FRG
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
#include "NetworkProtocol.h"
|
#include "NetworkProtocol.h"
|
||||||
|
#include "MessageAuth.h"
|
||||||
|
#include <algorithm>
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
#include <exception>
|
#include <exception>
|
||||||
#include <iomanip>
|
#include <iomanip>
|
||||||
@@ -165,10 +167,79 @@ std::string makeInitialStateMessage(const InitialStateMessage& message)
|
|||||||
{"snapshotTick", message.snapshotTick},
|
{"snapshotTick", message.snapshotTick},
|
||||||
{"tickMs", message.tickMs},
|
{"tickMs", message.tickMs},
|
||||||
{"inputDelayTicks", message.inputDelayTicks},
|
{"inputDelayTicks", message.inputDelayTicks},
|
||||||
{"compatibilityFingerprint", message.compatibilityFingerprint}
|
{"compatibilityFingerprint", message.compatibilityFingerprint},
|
||||||
|
{"sessionSecret", message.sessionSecret}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
std::string signedText(
|
||||||
|
const std::string& type, std::uint64_t sequence,
|
||||||
|
const nlohmann::json& payload)
|
||||||
|
{
|
||||||
|
return type + "|" + std::to_string(sequence) + "|" + payload.dump();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string computeSignature(
|
||||||
|
const std::string& sessionSecretHex, std::uint64_t sequence,
|
||||||
|
const std::string& text)
|
||||||
|
{
|
||||||
|
auth::Bytes secret;
|
||||||
|
if (!auth::hexDecode(sessionSecretHex, secret) ||
|
||||||
|
secret.size() != auth::kSessionSecretBytes)
|
||||||
|
return {};
|
||||||
|
const auth::Bytes key =
|
||||||
|
auth::deriveMessageKey(secret, auth::appPepper(), sequence);
|
||||||
|
const auth::Digest mac = auth::hmacSha256(key, auth::toBytes(text));
|
||||||
|
return auth::hexEncode(mac.data(), mac.size());
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::string signInputMessage(
|
||||||
|
const std::string& unsignedMessage, const std::string& sessionSecretHex)
|
||||||
|
{
|
||||||
|
nlohmann::json message = nlohmann::json::parse(unsignedMessage);
|
||||||
|
const nlohmann::json& payload = message.at("payload");
|
||||||
|
const std::uint64_t sequence = payload.at("clientSequence").get<std::uint64_t>();
|
||||||
|
message["signature"] = computeSignature(
|
||||||
|
sessionSecretHex, sequence,
|
||||||
|
signedText(message.at("type").get<std::string>(), sequence, payload));
|
||||||
|
return message.dump();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool verifyInputMessage(
|
||||||
|
const std::string& text, const std::string& sessionSecretHex,
|
||||||
|
std::uint64_t& clientSequence, std::string& error)
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
const nlohmann::json message = nlohmann::json::parse(text);
|
||||||
|
if (!message.is_object() || !message.contains("payload") ||
|
||||||
|
!message["payload"].is_object() || !message.contains("type") ||
|
||||||
|
!message["type"].is_string() || !message.contains("signature") ||
|
||||||
|
!message["signature"].is_string()) {
|
||||||
|
error = "unsigned or malformed message";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const nlohmann::json& payload = message["payload"];
|
||||||
|
if (!readTick(payload, "clientSequence", clientSequence, error))
|
||||||
|
return false;
|
||||||
|
const std::string expected = computeSignature(
|
||||||
|
sessionSecretHex, clientSequence,
|
||||||
|
signedText(message["type"].get<std::string>(), clientSequence, payload));
|
||||||
|
if (expected.empty() ||
|
||||||
|
!auth::constantTimeEquals(
|
||||||
|
expected, message["signature"].get<std::string>())) {
|
||||||
|
error = "invalid signature";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
error.clear();
|
||||||
|
return true;
|
||||||
|
} catch (const std::exception& exception) {
|
||||||
|
error = exception.what();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
bool parseInitialStateMessage(
|
bool parseInitialStateMessage(
|
||||||
const std::string& text, InitialStateMessage& message, std::string& error)
|
const std::string& text, InitialStateMessage& message, std::string& error)
|
||||||
{
|
{
|
||||||
@@ -191,6 +262,20 @@ bool parseInitialStateMessage(
|
|||||||
error = "unsupported lockstep timing";
|
error = "unsupported lockstep timing";
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
if (!payload.contains("sessionSecret") ||
|
||||||
|
!payload["sessionSecret"].is_string()) {
|
||||||
|
error = "initial state is missing the session secret";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
message.sessionSecret = payload["sessionSecret"].get<std::string>();
|
||||||
|
{
|
||||||
|
auth::Bytes decoded;
|
||||||
|
if (!auth::hexDecode(message.sessionSecret, decoded) ||
|
||||||
|
decoded.size() != auth::kSessionSecretBytes) {
|
||||||
|
error = "invalid session secret";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
message.state = payload["state"];
|
message.state = payload["state"];
|
||||||
message.assignedPlayerId = payload["assignedPlayerId"].get<std::string>();
|
message.assignedPlayerId = payload["assignedPlayerId"].get<std::string>();
|
||||||
message.compatibilityFingerprint =
|
message.compatibilityFingerprint =
|
||||||
@@ -198,10 +283,37 @@ bool parseInitialStateMessage(
|
|||||||
return !message.assignedPlayerId.empty();
|
return !message.assignedPlayerId.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
bool isOrderCommand(const ScheduledCommand& command, const std::string& playerId)
|
||||||
|
{
|
||||||
|
if (const auto* destination = std::get_if<ScheduledDestinationCommand>(&command))
|
||||||
|
return destination->playerId == playerId;
|
||||||
|
if (const auto* action = std::get_if<ScheduledCharacterActionCommand>(&command))
|
||||||
|
return action->playerId == playerId &&
|
||||||
|
(action->action == "set_target" ||
|
||||||
|
action->action == "clear_attack_target");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Within one tick only the player's last order (destination, set_target or
|
||||||
|
// clear_attack_target) survives; combos and presence commands are untouched.
|
||||||
|
void dropSupersededOrders(
|
||||||
|
std::vector<ScheduledCommand>& commands, const std::string& playerId)
|
||||||
|
{
|
||||||
|
commands.erase(
|
||||||
|
std::remove_if(commands.begin(), commands.end(),
|
||||||
|
[&](const ScheduledCommand& command) {
|
||||||
|
return isOrderCommand(command, playerId);
|
||||||
|
}),
|
||||||
|
commands.end());
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
std::uint64_t LockstepTimeline::schedule(
|
std::uint64_t LockstepTimeline::schedule(
|
||||||
const std::string& playerId, const Vec3fp& target)
|
const std::string& playerId, const Vec3fp& target)
|
||||||
{
|
{
|
||||||
const std::uint64_t sequence = nextCommandSequence_++;
|
const std::uint64_t sequence = nextCommandSequence_++;
|
||||||
|
dropSupersededOrders(pending_[currentTick_ + inputDelayTicks_], playerId);
|
||||||
pending_[currentTick_ + inputDelayTicks_].push_back(
|
pending_[currentTick_ + inputDelayTicks_].push_back(
|
||||||
ScheduledDestinationCommand{sequence, playerId, target});
|
ScheduledDestinationCommand{sequence, playerId, target});
|
||||||
return sequence;
|
return sequence;
|
||||||
@@ -222,6 +334,8 @@ std::uint64_t LockstepTimeline::scheduleCharacterAction(
|
|||||||
const std::string& playerId, std::string action, std::string targetId)
|
const std::string& playerId, std::string action, std::string targetId)
|
||||||
{
|
{
|
||||||
const std::uint64_t sequence = nextCommandSequence_++;
|
const std::uint64_t sequence = nextCommandSequence_++;
|
||||||
|
if (action == "set_target" || action == "clear_attack_target")
|
||||||
|
dropSupersededOrders(pending_[currentTick_ + inputDelayTicks_], playerId);
|
||||||
pending_[currentTick_ + inputDelayTicks_].push_back(
|
pending_[currentTick_ + inputDelayTicks_].push_back(
|
||||||
ScheduledCharacterActionCommand{
|
ScheduledCharacterActionCommand{
|
||||||
sequence, playerId, std::move(action), std::move(targetId)});
|
sequence, playerId, std::move(action), std::move(targetId)});
|
||||||
|
|||||||
@@ -22,8 +22,14 @@ struct InitialStateMessage {
|
|||||||
std::int64_t tickMs = kSimulationTickMs;
|
std::int64_t tickMs = kSimulationTickMs;
|
||||||
std::uint32_t inputDelayTicks = kDefaultInputDelayTicks;
|
std::uint32_t inputDelayTicks = kDefaultInputDelayTicks;
|
||||||
std::string compatibilityFingerprint;
|
std::string compatibilityFingerprint;
|
||||||
|
// 32 random bytes (64 hex chars) issued per connection; used with the app
|
||||||
|
// pepper to derive per-message HMAC keys.
|
||||||
|
std::string sessionSecret;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Server-side limit on client messages; exceeding it gets the player kicked.
|
||||||
|
inline constexpr std::size_t kMaxCommandsPerSecond = 40;
|
||||||
|
|
||||||
struct DestinationInputMessage {
|
struct DestinationInputMessage {
|
||||||
std::uint64_t clientSequence = 0;
|
std::uint64_t clientSequence = 0;
|
||||||
Vec3fp target;
|
Vec3fp target;
|
||||||
@@ -101,6 +107,18 @@ std::string makeCharacterActionInputMessage(
|
|||||||
bool parseCharacterActionInputMessage(
|
bool parseCharacterActionInputMessage(
|
||||||
const std::string& text, CharacterActionInputMessage& message,
|
const std::string& text, CharacterActionInputMessage& message,
|
||||||
std::string& error);
|
std::string& error);
|
||||||
|
// Adds an HMAC-SHA256 "signature" to a client input envelope. The key is
|
||||||
|
// SHA-256(sessionSecret || appPepper || clientSequence); the signed text is
|
||||||
|
// "type|clientSequence|payload". Unsigned make*InputMessage output is what the
|
||||||
|
// parse* functions consume, so signing is layered on top.
|
||||||
|
std::string signInputMessage(
|
||||||
|
const std::string& unsignedMessage, const std::string& sessionSecretHex);
|
||||||
|
// Verifies the signature and extracts the clientSequence. Returns false (with
|
||||||
|
// an error) for a missing/invalid signature or malformed envelope.
|
||||||
|
bool verifyInputMessage(
|
||||||
|
const std::string& text, const std::string& sessionSecretHex,
|
||||||
|
std::uint64_t& clientSequence, std::string& error);
|
||||||
|
|
||||||
std::string makeTickMessage(const TickMessage& message);
|
std::string makeTickMessage(const TickMessage& message);
|
||||||
bool parseTickMessage(
|
bool parseTickMessage(
|
||||||
const std::string& text, TickMessage& message, std::string& error);
|
const std::string& text, TickMessage& message, std::string& error);
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
#include "WebsocketGameClient.h"
|
#include "WebsocketGameClient.h"
|
||||||
#include "NetworkProtocol.h"
|
#include "NetworkProtocol.h"
|
||||||
|
#include "LockstepApply.h"
|
||||||
|
#include "../utils/Utils.h"
|
||||||
#ifdef __EMSCRIPTEN__
|
#ifdef __EMSCRIPTEN__
|
||||||
#include <emscripten/websocket.h>
|
#include <emscripten/websocket.h>
|
||||||
#else
|
#else
|
||||||
@@ -407,8 +409,14 @@ private:
|
|||||||
buffer_,
|
buffer_,
|
||||||
[this](beast::error_code error, std::size_t) {
|
[this](beast::error_code error, std::size_t) {
|
||||||
if (error) {
|
if (error) {
|
||||||
connected_.store(false);
|
// A clean close is also a lost connection for the game.
|
||||||
if (error != websocket::error::closed) fail("read", error);
|
if (error == websocket::error::closed) {
|
||||||
|
connected_.store(false);
|
||||||
|
connectionFailed_.store(true);
|
||||||
|
std::cerr << "[network] Server closed the connection\n";
|
||||||
|
} else {
|
||||||
|
fail("read", error);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
std::string message = beast::buffers_to_string(buffer_.data());
|
std::string message = beast::buffers_to_string(buffer_.data());
|
||||||
@@ -496,18 +504,18 @@ void WebsocketGameClient::submit(const GameCommand& command)
|
|||||||
if (!initialized_) return;
|
if (!initialized_) return;
|
||||||
if (const auto* destination =
|
if (const auto* destination =
|
||||||
std::get_if<SetCharacterDestinationCommand>(&command)) {
|
std::get_if<SetCharacterDestinationCommand>(&command)) {
|
||||||
impl_->send(makeDestinationInputMessage(
|
impl_->send(signInputMessage(makeDestinationInputMessage(
|
||||||
{nextClientSequence_++, destination->target}));
|
{nextClientSequence_++, destination->target}), sessionSecret_));
|
||||||
} else if (const auto* target =
|
} else if (const auto* target =
|
||||||
std::get_if<SetCharacterTargetCommand>(&command)) {
|
std::get_if<SetCharacterTargetCommand>(&command)) {
|
||||||
impl_->send(makeCharacterActionInputMessage(
|
impl_->send(signInputMessage(makeCharacterActionInputMessage(
|
||||||
{nextClientSequence_++, "set_target", target->targetId}));
|
{nextClientSequence_++, "set_target", target->targetId}), sessionSecret_));
|
||||||
} else if (std::holds_alternative<ClearCharacterAttackTargetCommand>(command)) {
|
} else if (std::holds_alternative<ClearCharacterAttackTargetCommand>(command)) {
|
||||||
impl_->send(makeCharacterActionInputMessage(
|
impl_->send(signInputMessage(makeCharacterActionInputMessage(
|
||||||
{nextClientSequence_++, "clear_attack_target", {}}));
|
{nextClientSequence_++, "clear_attack_target", {}}), sessionSecret_));
|
||||||
} else if (std::holds_alternative<TryCharacterAttackComboCommand>(command)) {
|
} else if (std::holds_alternative<TryCharacterAttackComboCommand>(command)) {
|
||||||
impl_->send(makeCharacterActionInputMessage(
|
impl_->send(signInputMessage(makeCharacterActionInputMessage(
|
||||||
{nextClientSequence_++, "try_attack_combo", {}}));
|
{nextClientSequence_++, "try_attack_combo", {}}), sessionSecret_));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -525,28 +533,32 @@ void WebsocketGameClient::update(std::int64_t)
|
|||||||
std::string error;
|
std::string error;
|
||||||
InitialStateMessage initial;
|
InitialStateMessage initial;
|
||||||
if (parseInitialStateMessage(text, initial, error)) {
|
if (parseInitialStateMessage(text, initial, error)) {
|
||||||
|
//logger() << text << std::endl;
|
||||||
if (!expectedCompatibilityFingerprint_.empty() &&
|
if (!expectedCompatibilityFingerprint_.empty() &&
|
||||||
initial.compatibilityFingerprint !=
|
initial.compatibilityFingerprint !=
|
||||||
expectedCompatibilityFingerprint_) {
|
expectedCompatibilityFingerprint_) {
|
||||||
std::cerr << "[network] Incompatible server content: expected "
|
logger() << "[network] Incompatible server content: expected "
|
||||||
<< expectedCompatibilityFingerprint_ << ", received "
|
<< expectedCompatibilityFingerprint_ << ", received "
|
||||||
<< initial.compatibilityFingerprint << '\n';
|
<< initial.compatibilityFingerprint << '\n';
|
||||||
|
rejected_ = true;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
replica_.load(initial.state);
|
replica_.load(initial.state);
|
||||||
replica_.setLocalPlayerId(initial.assignedPlayerId);
|
replica_.setLocalPlayerId(initial.assignedPlayerId);
|
||||||
nextExpectedTick_ = initial.snapshotTick + 1;
|
nextExpectedTick_ = initial.snapshotTick + 1;
|
||||||
|
sessionSecret_ = std::move(initial.sessionSecret);
|
||||||
|
nextClientSequence_ = 1;
|
||||||
compatibilityFingerprint_ =
|
compatibilityFingerprint_ =
|
||||||
std::move(initial.compatibilityFingerprint);
|
std::move(initial.compatibilityFingerprint);
|
||||||
pendingTicks_.clear();
|
pendingTicks_.clear();
|
||||||
initialized_ = true;
|
initialized_ = true;
|
||||||
std::cout << "[network] Applied initial state at tick "
|
logger() << "[network] Applied initial state at tick "
|
||||||
<< initial.snapshotTick << " as player '"
|
<< initial.snapshotTick << " as player '"
|
||||||
<< initial.assignedPlayerId << "' (delay "
|
<< initial.assignedPlayerId << "' (delay "
|
||||||
<< initial.inputDelayTicks << " ticks)" << std::endl;
|
<< initial.inputDelayTicks << " ticks)" << std::endl;
|
||||||
} catch (const std::exception& exception) {
|
} catch (const std::exception& exception) {
|
||||||
std::cerr << "[network] Invalid initial state: "
|
logger() << "[network] Invalid initial state: "
|
||||||
<< exception.what() << '\n';
|
<< exception.what() << '\n';
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
@@ -555,7 +567,7 @@ void WebsocketGameClient::update(std::int64_t)
|
|||||||
if (parseTickMessage(text, tick, error)) {
|
if (parseTickMessage(text, tick, error)) {
|
||||||
if (initialized_ && tick.tickId >= nextExpectedTick_) {
|
if (initialized_ && tick.tickId >= nextExpectedTick_) {
|
||||||
if (!loggedFirstTick_) {
|
if (!loggedFirstTick_) {
|
||||||
std::cout << "[network] Received first lockstep tick "
|
logger() << "[network] Received first lockstep tick "
|
||||||
<< tick.tickId << std::endl;
|
<< tick.tickId << std::endl;
|
||||||
loggedFirstTick_ = true;
|
loggedFirstTick_ = true;
|
||||||
}
|
}
|
||||||
@@ -566,14 +578,15 @@ void WebsocketGameClient::update(std::int64_t)
|
|||||||
std::string errorCode;
|
std::string errorCode;
|
||||||
std::string errorDetail;
|
std::string errorDetail;
|
||||||
if (parseErrorMessage(text, errorCode, errorDetail)) {
|
if (parseErrorMessage(text, errorCode, errorDetail)) {
|
||||||
std::cerr << "[network] Server rejected request (" << errorCode
|
logger() << "[network] Server rejected request (" << errorCode
|
||||||
<< "): " << errorDetail << '\n';
|
<< "): " << errorDetail << '\n';
|
||||||
if (errorCode == "server_full" ||
|
// Everything except a recoverable malformed-input report ends the
|
||||||
errorCode == "incompatible")
|
// session (server_full, incompatible, rate_limited, kicked, ...).
|
||||||
|
if (errorCode != "invalid_input")
|
||||||
rejected_ = true;
|
rejected_ = true;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
std::cerr << "[network] Ignoring WebSocket message: "
|
logger() << "[network] Ignoring WebSocket message: "
|
||||||
<< error << '\n';
|
<< error << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -585,25 +598,7 @@ void WebsocketGameClient::update(std::int64_t)
|
|||||||
const std::string locationId =
|
const std::string locationId =
|
||||||
replica_.snapshot()->currentLocationId;
|
replica_.snapshot()->currentLocationId;
|
||||||
for (const ScheduledCommand& scheduled : tick.commands) {
|
for (const ScheduledCommand& scheduled : tick.commands) {
|
||||||
std::visit([&](const auto& command) {
|
applyScheduledCommand(replica_, locationId, scheduled);
|
||||||
using T = std::decay_t<decltype(command)>;
|
|
||||||
if constexpr (std::is_same_v<T, ScheduledDestinationCommand>) {
|
|
||||||
replica_.submit(SetCharacterDestinationCommand{
|
|
||||||
locationId, command.playerId, command.target, {}});
|
|
||||||
} else if constexpr (std::is_same_v<T, ScheduledCharacterEnabledCommand>) {
|
|
||||||
replica_.submit(SetCharacterEnabledCommand{
|
|
||||||
command.locationId, command.characterId, command.enabled});
|
|
||||||
} else if (command.action == "set_target") {
|
|
||||||
replica_.submit(SetCharacterTargetCommand{
|
|
||||||
locationId, command.playerId, command.targetId});
|
|
||||||
} else if (command.action == "clear_attack_target") {
|
|
||||||
replica_.submit(ClearCharacterAttackTargetCommand{
|
|
||||||
locationId, command.playerId});
|
|
||||||
} else if (command.action == "try_attack_combo") {
|
|
||||||
replica_.submit(TryCharacterAttackComboCommand{
|
|
||||||
locationId, command.playerId});
|
|
||||||
}
|
|
||||||
}, scheduled);
|
|
||||||
}
|
}
|
||||||
replica_.update(kSimulationTickMs);
|
replica_.update(kSimulationTickMs);
|
||||||
completedSimulationTicks_.push_back({
|
completedSimulationTicks_.push_back({
|
||||||
@@ -619,7 +614,7 @@ void WebsocketGameClient::update(std::int64_t)
|
|||||||
replica_.save(state);
|
replica_.save(state);
|
||||||
const std::string localHash = canonicalStateHash(std::move(state));
|
const std::string localHash = canonicalStateHash(std::move(state));
|
||||||
if (localHash != tick.stateHash) {
|
if (localHash != tick.stateHash) {
|
||||||
std::cerr << "[network] Lockstep divergence at tick "
|
logger() << "[network] Lockstep divergence at tick "
|
||||||
<< tick.tickId << ": server=" << tick.stateHash
|
<< tick.tickId << ": server=" << tick.stateHash
|
||||||
<< ", client=" << localHash << '\n';
|
<< ", client=" << localHash << '\n';
|
||||||
}
|
}
|
||||||
@@ -653,7 +648,8 @@ bool WebsocketGameClient::connected() const
|
|||||||
|
|
||||||
bool WebsocketGameClient::connectionFailed() const
|
bool WebsocketGameClient::connectionFailed() const
|
||||||
{
|
{
|
||||||
return impl_->connectionFailed();
|
// Rejection (server full / incompatible content) is also a failed connection.
|
||||||
|
return rejected_ || impl_->connectionFailed();
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace FRG
|
} // namespace FRG
|
||||||
@@ -68,6 +68,7 @@ private:
|
|||||||
std::uint64_t nextExpectedTick_ = 0;
|
std::uint64_t nextExpectedTick_ = 0;
|
||||||
std::uint64_t nextClientSequence_ = 1;
|
std::uint64_t nextClientSequence_ = 1;
|
||||||
std::string compatibilityFingerprint_;
|
std::string compatibilityFingerprint_;
|
||||||
|
std::string sessionSecret_;
|
||||||
std::string expectedCompatibilityFingerprint_;
|
std::string expectedCompatibilityFingerprint_;
|
||||||
bool initialized_ = false;
|
bool initialized_ = false;
|
||||||
bool rejected_ = false;
|
bool rejected_ = false;
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
#include "WebsocketGameServer.h"
|
#include "WebsocketGameServer.h"
|
||||||
#include "InternalGameServer.h"
|
#include "InternalGameServer.h"
|
||||||
#include "NetworkProtocol.h"
|
#include "NetworkProtocol.h"
|
||||||
|
#include "LockstepApply.h"
|
||||||
#include <boost/asio.hpp>
|
#include <boost/asio.hpp>
|
||||||
#include <boost/beast.hpp>
|
#include <boost/beast.hpp>
|
||||||
|
#include "MessageAuth.h"
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <chrono>
|
||||||
#include <deque>
|
#include <deque>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <map>
|
#include <map>
|
||||||
@@ -30,16 +33,53 @@ public:
|
|||||||
std::function<void(const std::shared_ptr<ServerSession>&)>;
|
std::function<void(const std::shared_ptr<ServerSession>&)>;
|
||||||
|
|
||||||
ServerSession(
|
ServerSession(
|
||||||
tcp::socket socket, std::string playerId,
|
tcp::socket socket, std::string playerId, std::string sessionSecret,
|
||||||
InputHandler inputHandler, CloseHandler closeHandler)
|
InputHandler inputHandler, CloseHandler closeHandler)
|
||||||
: socket_(std::move(socket))
|
: socket_(std::move(socket))
|
||||||
, playerId_(std::move(playerId))
|
, playerId_(std::move(playerId))
|
||||||
|
, sessionSecret_(std::move(sessionSecret))
|
||||||
, inputHandler_(std::move(inputHandler))
|
, inputHandler_(std::move(inputHandler))
|
||||||
, closeHandler_(std::move(closeHandler))
|
, closeHandler_(std::move(closeHandler))
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
const std::string& playerId() const { return playerId_; }
|
const std::string& playerId() const { return playerId_; }
|
||||||
|
const std::string& sessionSecret() const { return sessionSecret_; }
|
||||||
|
bool kicked() const { return kicked_; }
|
||||||
|
|
||||||
|
// Counts one received message in a sliding one-second window. Returns false
|
||||||
|
// once the player exceeds kMaxCommandsPerSecond.
|
||||||
|
bool allowMessage()
|
||||||
|
{
|
||||||
|
const auto now = std::chrono::steady_clock::now();
|
||||||
|
while (!recentMessages_.empty() &&
|
||||||
|
now - recentMessages_.front() > std::chrono::seconds(1))
|
||||||
|
recentMessages_.pop_front();
|
||||||
|
recentMessages_.push_back(now);
|
||||||
|
return recentMessages_.size() <= kMaxCommandsPerSecond;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accepts only strictly increasing sequence numbers (replay protection).
|
||||||
|
bool acceptSequence(std::uint64_t sequence)
|
||||||
|
{
|
||||||
|
if (sequence <= lastSequence_) return false;
|
||||||
|
lastSequence_ = sequence;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sends a final error, ignores all further input and ticks, then closes.
|
||||||
|
// Closing releases the slot, so the character is disabled for everyone.
|
||||||
|
void kick(const std::string& code, const std::string& detail)
|
||||||
|
{
|
||||||
|
if (kicked_ || closed_) return;
|
||||||
|
kicked_ = true;
|
||||||
|
std::cout << "[network] Kicking player slot '" << playerId_ << "' ("
|
||||||
|
<< code << "): " << detail << std::endl;
|
||||||
|
closeAfterWrite_ = true;
|
||||||
|
const bool writeInProgress = !outbound_.empty();
|
||||||
|
outbound_.push_back(makeErrorMessage(code, detail));
|
||||||
|
if (!writeInProgress) write();
|
||||||
|
}
|
||||||
|
|
||||||
void start(std::string initialState, bool closeAfterWrite = false)
|
void start(std::string initialState, bool closeAfterWrite = false)
|
||||||
{
|
{
|
||||||
@@ -62,6 +102,7 @@ public:
|
|||||||
|
|
||||||
void send(std::string message)
|
void send(std::string message)
|
||||||
{
|
{
|
||||||
|
if (closed_ || kicked_) return;
|
||||||
const bool writeInProgress = !outbound_.empty();
|
const bool writeInProgress = !outbound_.empty();
|
||||||
outbound_.push_back(std::move(message));
|
outbound_.push_back(std::move(message));
|
||||||
if (!writeInProgress) write();
|
if (!writeInProgress) write();
|
||||||
@@ -83,7 +124,9 @@ private:
|
|||||||
const std::string message =
|
const std::string message =
|
||||||
beast::buffers_to_string(self->inbound_.data());
|
beast::buffers_to_string(self->inbound_.data());
|
||||||
self->inbound_.consume(self->inbound_.size());
|
self->inbound_.consume(self->inbound_.size());
|
||||||
|
if (self->kicked_) return;
|
||||||
self->inputHandler_(self, message);
|
self->inputHandler_(self, message);
|
||||||
|
if (self->kicked_) return;
|
||||||
self->read();
|
self->read();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -96,6 +139,11 @@ private:
|
|||||||
if (error) {
|
if (error) {
|
||||||
std::cerr << "[network] WebSocket write failed: "
|
std::cerr << "[network] WebSocket write failed: "
|
||||||
<< error.message() << '\n';
|
<< error.message() << '\n';
|
||||||
|
// Release the slot and stop queueing ticks for a dead peer.
|
||||||
|
self->outbound_.clear();
|
||||||
|
beast::error_code ignored;
|
||||||
|
beast::get_lowest_layer(self->socket_).close(ignored);
|
||||||
|
self->notifyClosed();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
self->outbound_.pop_front();
|
self->outbound_.pop_front();
|
||||||
@@ -120,10 +168,14 @@ private:
|
|||||||
beast::flat_buffer inbound_;
|
beast::flat_buffer inbound_;
|
||||||
std::deque<std::string> outbound_;
|
std::deque<std::string> outbound_;
|
||||||
std::string playerId_;
|
std::string playerId_;
|
||||||
|
std::string sessionSecret_;
|
||||||
|
std::deque<std::chrono::steady_clock::time_point> recentMessages_;
|
||||||
|
std::uint64_t lastSequence_ = 0;
|
||||||
InputHandler inputHandler_;
|
InputHandler inputHandler_;
|
||||||
CloseHandler closeHandler_;
|
CloseHandler closeHandler_;
|
||||||
bool closeAfterWrite_ = false;
|
bool closeAfterWrite_ = false;
|
||||||
bool closed_ = false;
|
bool closed_ = false;
|
||||||
|
bool kicked_ = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace
|
} // namespace
|
||||||
@@ -224,11 +276,30 @@ private:
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const std::string sessionSecret = auth::generateSessionSecretHex();
|
||||||
auto session =
|
auto session =
|
||||||
std::make_shared<ServerSession>(
|
std::make_shared<ServerSession>(
|
||||||
std::move(socket), playerId,
|
std::move(socket), playerId, sessionSecret,
|
||||||
[this](const std::shared_ptr<ServerSession>& source,
|
[this](const std::shared_ptr<ServerSession>& source,
|
||||||
const std::string& message) {
|
const std::string& message) {
|
||||||
|
if (!source->allowMessage()) {
|
||||||
|
source->kick("rate_limited",
|
||||||
|
"Too many commands per second");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::uint64_t signedSequence = 0;
|
||||||
|
std::string authError;
|
||||||
|
if (!verifyInputMessage(
|
||||||
|
message, source->sessionSecret(),
|
||||||
|
signedSequence, authError)) {
|
||||||
|
source->kick("invalid_signature", authError);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!source->acceptSequence(signedSequence)) {
|
||||||
|
source->kick("replayed_message",
|
||||||
|
"Message sequence did not increase");
|
||||||
|
return;
|
||||||
|
}
|
||||||
DestinationInputMessage destination;
|
DestinationInputMessage destination;
|
||||||
std::string destinationError;
|
std::string destinationError;
|
||||||
if (parseDestinationInputMessage(
|
if (parseDestinationInputMessage(
|
||||||
@@ -283,6 +354,7 @@ private:
|
|||||||
initial.snapshotTick = latestTick_;
|
initial.snapshotTick = latestTick_;
|
||||||
initial.compatibilityFingerprint =
|
initial.compatibilityFingerprint =
|
||||||
compatibilityFingerprint_;
|
compatibilityFingerprint_;
|
||||||
|
initial.sessionSecret = sessionSecret;
|
||||||
session->start(makeInitialStateMessage(initial));
|
session->start(makeInitialStateMessage(initial));
|
||||||
std::cout << "[network] Initial state queued for player '"
|
std::cout << "[network] Initial state queued for player '"
|
||||||
<< playerId << "'" << std::endl;
|
<< playerId << "'" << std::endl;
|
||||||
@@ -341,6 +413,11 @@ void WebsocketGameServer::update()
|
|||||||
lastClientSequences_.erase(playerId);
|
lastClientSequences_.erase(playerId);
|
||||||
for (const Impl::PendingInput& pending : impl_->takeInputs()) {
|
for (const Impl::PendingInput& pending : impl_->takeInputs()) {
|
||||||
std::uint64_t& previous = lastClientSequences_[pending.playerId];
|
std::uint64_t& previous = lastClientSequences_[pending.playerId];
|
||||||
|
// Input queued before the slot was released must not reach a disabled
|
||||||
|
// character.
|
||||||
|
if (std::find(releasedPlayers.begin(), releasedPlayers.end(),
|
||||||
|
pending.playerId) != releasedPlayers.end())
|
||||||
|
continue;
|
||||||
const std::uint64_t sequence = std::visit(
|
const std::uint64_t sequence = std::visit(
|
||||||
[](const auto& input) { return input.clientSequence; },
|
[](const auto& input) { return input.clientSequence; },
|
||||||
pending.input);
|
pending.input);
|
||||||
@@ -359,29 +436,8 @@ void WebsocketGameServer::update()
|
|||||||
|
|
||||||
TickMessage tick = timeline_.advance();
|
TickMessage tick = timeline_.advance();
|
||||||
for (const ScheduledCommand& scheduled : tick.commands) {
|
for (const ScheduledCommand& scheduled : tick.commands) {
|
||||||
std::visit([this](const auto& command) {
|
applyScheduledCommand(
|
||||||
using T = std::decay_t<decltype(command)>;
|
gameServer_, gameServer_.snapshot()->currentLocationId, scheduled);
|
||||||
if constexpr (std::is_same_v<T, ScheduledDestinationCommand>) {
|
|
||||||
gameServer_.submit(SetCharacterDestinationCommand{
|
|
||||||
gameServer_.snapshot()->currentLocationId,
|
|
||||||
command.playerId, command.target, {}});
|
|
||||||
} else if constexpr (std::is_same_v<T, ScheduledCharacterEnabledCommand>) {
|
|
||||||
gameServer_.submit(SetCharacterEnabledCommand{
|
|
||||||
command.locationId, command.characterId, command.enabled});
|
|
||||||
} else if (command.action == "set_target") {
|
|
||||||
gameServer_.submit(SetCharacterTargetCommand{
|
|
||||||
gameServer_.snapshot()->currentLocationId,
|
|
||||||
command.playerId, command.targetId});
|
|
||||||
} else if (command.action == "clear_attack_target") {
|
|
||||||
gameServer_.submit(ClearCharacterAttackTargetCommand{
|
|
||||||
gameServer_.snapshot()->currentLocationId,
|
|
||||||
command.playerId});
|
|
||||||
} else if (command.action == "try_attack_combo") {
|
|
||||||
gameServer_.submit(TryCharacterAttackComboCommand{
|
|
||||||
gameServer_.snapshot()->currentLocationId,
|
|
||||||
command.playerId});
|
|
||||||
}
|
|
||||||
}, scheduled);
|
|
||||||
}
|
}
|
||||||
gameServer_.update(kSimulationTickMs);
|
gameServer_.update(kSimulationTickMs);
|
||||||
nlohmann::json state;
|
nlohmann::json state;
|
||||||
|
|||||||
@@ -257,8 +257,14 @@ namespace FRG {
|
|||||||
ready = !navMesh.empty();
|
ready = !navMesh.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<Vec3fp> PathFinder::findPathToNearest(const Vec3fp& start3D, const Vec3fp& end3D) const {
|
PathFinder::PathResult PathFinder::findPathResult(
|
||||||
if (!ready || !area.available) return { start3D };
|
const Vec3fp& start3D, const Vec3fp& end3D) const {
|
||||||
|
PathResult result;
|
||||||
|
result.endpoint = start3D;
|
||||||
|
if (!ready || !area.available) {
|
||||||
|
result.waypoints = { start3D };
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
Vec2fp startPt(start3D.x, start3D.z);
|
Vec2fp startPt(start3D.x, start3D.z);
|
||||||
Vec2fp targetPt(end3D.x, end3D.z);
|
Vec2fp targetPt(end3D.x, end3D.z);
|
||||||
@@ -268,7 +274,10 @@ namespace FRG {
|
|||||||
if (startTri == -1) {
|
if (startTri == -1) {
|
||||||
startPt = findClosestPointOnNavMesh(startPt, startTri, -1);
|
startPt = findClosestPointOnNavMesh(startPt, startTri, -1);
|
||||||
}
|
}
|
||||||
if (startTri == -1) return { start3D };
|
if (startTri == -1) {
|
||||||
|
result.waypoints = { start3D };
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
const int startComponent = navMesh[startTri].componentId;
|
const int startComponent = navMesh[startTri].componentId;
|
||||||
|
|
||||||
@@ -276,36 +285,59 @@ namespace FRG {
|
|||||||
// Если точка попала в препятствие ИЛИ в изолированную зону (другой остров),
|
// Если точка попала в препятствие ИЛИ в изолированную зону (другой остров),
|
||||||
// ищем ближайшую доступную точку именно на границе острова startComponent!
|
// ищем ближайшую доступную точку именно на границе острова startComponent!
|
||||||
int endTri = findTriangleContaining(targetPt);
|
int endTri = findTriangleContaining(targetPt);
|
||||||
|
const bool exactTargetIsWalkable =
|
||||||
|
endTri != -1 && navMesh[endTri].componentId == startComponent;
|
||||||
if (endTri == -1 || navMesh[endTri].componentId != startComponent) {
|
if (endTri == -1 || navMesh[endTri].componentId != startComponent) {
|
||||||
targetPt = findClosestPointOnNavMesh(targetPt, endTri, startComponent);
|
targetPt = findClosestPointOnNavMesh(targetPt, endTri, startComponent);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (endTri == -1) return { start3D };
|
if (endTri == -1) {
|
||||||
|
result.waypoints = { start3D };
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
// Если старт и конец оказались в одном треугольнике — идем по прямой
|
// Если старт и конец оказались в одном треугольнике — идем по прямой
|
||||||
if (startTri == endTri) {
|
if (startTri == endTri) {
|
||||||
return {
|
result.waypoints = {
|
||||||
start3D,
|
start3D,
|
||||||
Vec3fp(targetPt.x, floorY, targetPt.y)
|
Vec3fp(targetPt.x, floorY, targetPt.y)
|
||||||
};
|
};
|
||||||
|
result.endpoint = result.waypoints.back();
|
||||||
|
result.outcome = exactTargetIsWalkable
|
||||||
|
? PathOutcome::ReachedExactGoal
|
||||||
|
: PathOutcome::NearestReachable;
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Поиск коридора из треугольников через A*
|
// 3. Поиск коридора из треугольников через A*
|
||||||
std::vector<int> triangleCorridor = runAStar(startTri, endTri, startPt, targetPt);
|
std::vector<int> triangleCorridor = runAStar(startTri, endTri, startPt, targetPt);
|
||||||
if (triangleCorridor.empty()) return { start3D };
|
if (triangleCorridor.empty()) {
|
||||||
|
result.waypoints = { start3D };
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
// 4. Сглаживание пути через Funnel Algorithm (Натянутая нить)
|
// 4. Сглаживание пути через Funnel Algorithm (Натянутая нить)
|
||||||
std::vector<Vec2fp> smoothPath2D = stringPullFunnel(startPt, targetPt, triangleCorridor);
|
std::vector<Vec2fp> smoothPath2D = stringPullFunnel(startPt, targetPt, triangleCorridor);
|
||||||
|
|
||||||
// 5. Формируем выходной массив 3D точек
|
// 5. Формируем выходной массив 3D точек
|
||||||
std::vector<Vec3fp> result;
|
result.waypoints.reserve(smoothPath2D.size());
|
||||||
result.reserve(smoothPath2D.size());
|
|
||||||
for (const auto& pt : smoothPath2D) {
|
for (const auto& pt : smoothPath2D) {
|
||||||
result.emplace_back(pt.x, floorY, pt.y);
|
result.waypoints.emplace_back(pt.x, floorY, pt.y);
|
||||||
|
}
|
||||||
|
if (!result.waypoints.empty()) {
|
||||||
|
result.endpoint = result.waypoints.back();
|
||||||
|
result.outcome = exactTargetIsWalkable
|
||||||
|
? PathOutcome::ReachedExactGoal
|
||||||
|
: PathOutcome::NearestReachable;
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::vector<Vec3fp> PathFinder::findPathToNearest(
|
||||||
|
const Vec3fp& start3D, const Vec3fp& end3D) const {
|
||||||
|
return findPathResult(start3D, end3D).waypoints;
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<Eigen::Vector3f> PathFinder::findPathToNearest(const Eigen::Vector3f& start, const Eigen::Vector3f& end) const {
|
std::vector<Eigen::Vector3f> PathFinder::findPathToNearest(const Eigen::Vector3f& start, const Eigen::Vector3f& end) const {
|
||||||
auto pathFp = findPathToNearest(Vec3fp::fromEigen(start), Vec3fp::fromEigen(end));
|
auto pathFp = findPathToNearest(Vec3fp::fromEigen(start), Vec3fp::fromEigen(end));
|
||||||
std::vector<Eigen::Vector3f> out;
|
std::vector<Eigen::Vector3f> out;
|
||||||
|
|||||||
@@ -18,6 +18,22 @@ namespace FRG {
|
|||||||
|
|
||||||
class PathFinder {
|
class PathFinder {
|
||||||
public:
|
public:
|
||||||
|
enum class PathOutcome {
|
||||||
|
ReachedExactGoal,
|
||||||
|
NearestReachable,
|
||||||
|
NoPath
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PathResult {
|
||||||
|
std::vector<Vec3fp> waypoints;
|
||||||
|
Vec3fp endpoint;
|
||||||
|
PathOutcome outcome = PathOutcome::NoPath;
|
||||||
|
|
||||||
|
bool reachedGoal() const {
|
||||||
|
return outcome == PathOutcome::ReachedExactGoal;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
struct NavigationArea {
|
struct NavigationArea {
|
||||||
std::string name;
|
std::string name;
|
||||||
bool available = true;
|
bool available = true;
|
||||||
@@ -52,6 +68,7 @@ namespace FRG {
|
|||||||
void generateNavMesh();
|
void generateNavMesh();
|
||||||
|
|
||||||
// Основной метод поиска пути (плоскость XZ, Y — высота)
|
// Основной метод поиска пути (плоскость XZ, Y — высота)
|
||||||
|
PathResult findPathResult(const Vec3fp& start3D, const Vec3fp& end3D) const;
|
||||||
std::vector<Vec3fp> findPathToNearest(const Vec3fp& start3D, const Vec3fp& end3D) const;
|
std::vector<Vec3fp> findPathToNearest(const Vec3fp& start3D, const Vec3fp& end3D) const;
|
||||||
|
|
||||||
// Перегрузка для совместимости со старым Eigen-интерфейсом
|
// Перегрузка для совместимости со старым Eigen-интерфейсом
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ namespace FRG {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void PathVisualization::start(const Character& player, const Eigen::Vector3f& clickedDestination,
|
void PathVisualization::start(const Character& player, const Eigen::Vector3f& clickedDestination,
|
||||||
Style style)
|
const PathFinder::PathResult& pathResult, Style style)
|
||||||
{
|
{
|
||||||
cancel();
|
cancel();
|
||||||
if (!enabled) return;
|
if (!enabled) return;
|
||||||
@@ -92,6 +92,9 @@ namespace FRG {
|
|||||||
case Style::Hostile:
|
case Style::Hostile:
|
||||||
color = Eigen::Vector3f(1.0f, 0.20f, 0.03f);
|
color = Eigen::Vector3f(1.0f, 0.20f, 0.03f);
|
||||||
break;
|
break;
|
||||||
|
case Style::InteractiveObject:
|
||||||
|
color = Eigen::Vector3f(1.0f, 0.90f, 0.05f);
|
||||||
|
break;
|
||||||
case Style::Teleport:
|
case Style::Teleport:
|
||||||
color = Eigen::Vector3f(1.0f, 0.90f, 0.05f);
|
color = Eigen::Vector3f(1.0f, 0.90f, 0.05f);
|
||||||
break;
|
break;
|
||||||
@@ -99,33 +102,27 @@ namespace FRG {
|
|||||||
color = Eigen::Vector3f(0.08f, 1.0f, 0.25f);
|
color = Eigen::Vector3f(0.08f, 1.0f, 0.25f);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
destinationColor = color;
|
||||||
|
|
||||||
auto state = player.stateSnapshot();
|
auto state = player.stateSnapshot();
|
||||||
if (!state) return;
|
if (!state) return;
|
||||||
std::vector<Eigen::Vector3f> route;
|
std::vector<Eigen::Vector3f> route;
|
||||||
route.reserve(state->pathWaypoints.size() + 1);
|
route.reserve(pathResult.waypoints.size() + 1);
|
||||||
const Eigen::Vector3f renderPosition = player.renderPosition();
|
const Eigen::Vector3f renderPosition = player.renderPosition();
|
||||||
route.push_back(Eigen::Vector3f(renderPosition.x(), 0.0f, renderPosition.z()));
|
route.push_back(Eigen::Vector3f(renderPosition.x(), 0.0f, renderPosition.z()));
|
||||||
const size_t firstWaypoint = (std::min)(
|
for (const Vec3fp& waypointFp : pathResult.waypoints) {
|
||||||
state->currentWaypointIndex, state->pathWaypoints.size());
|
const Eigen::Vector3f waypoint = waypointFp.toEigen();
|
||||||
for (size_t i = firstWaypoint; i < state->pathWaypoints.size(); ++i) {
|
|
||||||
const Eigen::Vector3f& waypoint = state->pathWaypoints[i].toEigen();
|
|
||||||
route.push_back(Eigen::Vector3f(waypoint.x(), 0.0f, waypoint.z()));
|
route.push_back(Eigen::Vector3f(waypoint.x(), 0.0f, waypoint.z()));
|
||||||
}
|
}
|
||||||
const Eigen::Vector3f clickedPosition(
|
const Eigen::Vector3f clickedPosition(
|
||||||
clickedDestination.x(), 0.0f, clickedDestination.z());
|
clickedDestination.x(), 0.0f, clickedDestination.z());
|
||||||
if (route.size() == 1 ||
|
|
||||||
(route.back() - clickedPosition).norm() > 0.5f) {
|
|
||||||
// A remote destination is not present in the replica yet, or the
|
|
||||||
// replica still contains the route for a previous click. Preview
|
|
||||||
// the new intent directly until authoritative waypoints catch up.
|
|
||||||
route.clear();
|
|
||||||
route.push_back(Eigen::Vector3f(
|
|
||||||
renderPosition.x(), 0.0f, renderPosition.z()));
|
|
||||||
route.push_back(clickedPosition);
|
|
||||||
}
|
|
||||||
|
|
||||||
destination = clickedPosition;
|
destination = clickedPosition;
|
||||||
|
if (pathResult.outcome != PathFinder::PathOutcome::ReachedExactGoal &&
|
||||||
|
style != Style::Hostile &&
|
||||||
|
style != Style::InteractiveObject) {
|
||||||
|
destinationColor = Eigen::Vector3f(1.0f, 0.20f, 0.03f);
|
||||||
|
}
|
||||||
|
|
||||||
float totalLength = 0.0f;
|
float totalLength = 0.0f;
|
||||||
for (size_t i = 1; i < route.size(); ++i) {
|
for (size_t i = 1; i < route.size(); ++i) {
|
||||||
@@ -232,7 +229,10 @@ namespace FRG {
|
|||||||
}
|
}
|
||||||
if (markerAlpha > 0.001f) {
|
if (markerAlpha > 0.001f) {
|
||||||
const float markerScale = 0.72f + 0.28f * smoothStep(elapsedMs / kMarkerFadeInMs);
|
const float markerScale = 0.72f + 0.28f * smoothStep(elapsedMs / kMarkerFadeInMs);
|
||||||
const float rgba[4] = { color.x(), color.y(), color.z(), markerAlpha * kMaxOpacity };
|
const float rgba[4] = {
|
||||||
|
destinationColor.x(), destinationColor.y(), destinationColor.z(),
|
||||||
|
markerAlpha * kMaxOpacity
|
||||||
|
};
|
||||||
renderer.RenderUniform4fv("uColor", rgba);
|
renderer.RenderUniform4fv("uColor", rgba);
|
||||||
renderer.PushMatrix();
|
renderer.PushMatrix();
|
||||||
renderer.TranslateMatrix(destination + Eigen::Vector3f(0.0f, 0.05f, 0.0f));
|
renderer.TranslateMatrix(destination + Eigen::Vector3f(0.0f, 0.05f, 0.0f));
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include "navigation/PathFinder.h"
|
||||||
#include "render/Renderer.h"
|
#include "render/Renderer.h"
|
||||||
|
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
@@ -15,6 +16,7 @@ namespace FRG {
|
|||||||
enum class Style {
|
enum class Style {
|
||||||
Movement,
|
Movement,
|
||||||
Hostile,
|
Hostile,
|
||||||
|
InteractiveObject,
|
||||||
Teleport
|
Teleport
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -23,6 +25,7 @@ namespace FRG {
|
|||||||
bool isEnabled() const { return enabled; }
|
bool isEnabled() const { return enabled; }
|
||||||
|
|
||||||
void start(const Character& player, const Eigen::Vector3f& clickedDestination,
|
void start(const Character& player, const Eigen::Vector3f& clickedDestination,
|
||||||
|
const PathFinder::PathResult& pathResult,
|
||||||
Style style = Style::Movement);
|
Style style = Style::Movement);
|
||||||
void cancel();
|
void cancel();
|
||||||
void update(int64_t deltaMs);
|
void update(int64_t deltaMs);
|
||||||
@@ -41,6 +44,7 @@ namespace FRG {
|
|||||||
float durationMs = 0.0f;
|
float durationMs = 0.0f;
|
||||||
Eigen::Vector3f destination = Eigen::Vector3f::Zero();
|
Eigen::Vector3f destination = Eigen::Vector3f::Zero();
|
||||||
Eigen::Vector3f color = Eigen::Vector3f(0.08f, 1.0f, 0.25f);
|
Eigen::Vector3f color = Eigen::Vector3f(0.08f, 1.0f, 0.25f);
|
||||||
|
Eigen::Vector3f destinationColor = color;
|
||||||
std::vector<Dot> dots;
|
std::vector<Dot> dots;
|
||||||
VertexRenderStruct dotMesh;
|
VertexRenderStruct dotMesh;
|
||||||
VertexRenderStruct destinationMesh;
|
VertexRenderStruct destinationMesh;
|
||||||
|
|||||||
Reference in new issue
Block a user