Files
DarkflameServer/dGame/dComponents/MovingPlatformComponent.cpp
Aaron Kimbrell 87e3e9b38d fix(platforms): a time based mover turned round restarts the stretch's clock, as the client
Turned round between two waypoints, the client's platform calls ProcessStateChange for the waypoint it was heading
to, which zeroes the time travelled: it then takes the whole stretch's time at the whole stretch's speed from where it
is, going past the waypoint by as far as it had come. DLU kept the time already travelled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 00:53:40 -06:00

1151 lines
55 KiB
C++

/*
* Darkflame Universe
* Copyright 2019
*/
#include "MovingPlatformComponent.h"
#include <cmath>
#include "BitStream.h"
#include "GeneralUtils.h"
#include "dZoneManager.h"
#include "EntityManager.h"
#include "Logger.h"
#include "GameMessages.h"
#include "CppScripts.h"
#include "SimplePhysicsComponent.h"
#include "Zone.h"
#include "CDClientDatabase.h"
#include "MovementMessages.h"
#include <glm/gtc/quaternion.hpp>
#include "Entity.h"
#include "ObjectLoadState.h"
#include "MovementAIComponent.h"
#include "QuickBuildComponent.h"
#include "PhantomPhysicsComponent.h"
#include "eQuickBuildState.h"
void PlatformSubComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) {
outBitStream.Write<bool>(true);
outBitStream.Write<uint32_t>(mState);
outBitStream.Write<int32_t>(mDesiredWaypointIndex);
outBitStream.Write(mShouldStopAtDesiredWaypoint);
outBitStream.Write(mInReverse);
outBitStream.Write<float_t>(mPercentBetweenPoints);
outBitStream.Write<float_t>(mPosition.x);
outBitStream.Write<float_t>(mPosition.y);
outBitStream.Write<float_t>(mPosition.z);
outBitStream.Write<uint32_t>(mCurrentWaypointIndex);
outBitStream.Write<uint32_t>(mNextWaypointIndex);
outBitStream.Write<float_t>(mIdleTimeElapsed);
outBitStream.Write<float_t>(mMoveTimeElapsed);
}
//------------- SimpleMoverSubComponent below --------------
// A dirty bit, then whether there is a starting point with its position and rotation (w, x, y, z); a dirty bit, then
// the state, the current waypoint and whether it is reversing
void SimpleMoverSubComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) {
outBitStream.Write(bIsInitialUpdate || mDirtyStartingPoint);
if (bIsInitialUpdate || mDirtyStartingPoint) {
outBitStream.Write1();
outBitStream.Write(mStartPosition.x);
outBitStream.Write(mStartPosition.y);
outBitStream.Write(mStartPosition.z);
outBitStream.Write(mStartRotation.w);
outBitStream.Write(mStartRotation.x);
outBitStream.Write(mStartRotation.y);
outBitStream.Write(mStartRotation.z);
if (!bIsInitialUpdate) mDirtyStartingPoint = false;
}
outBitStream.Write(bIsInitialUpdate || mDirtyState);
if (bIsInitialUpdate || mDirtyState) {
outBitStream.Write<uint32_t>(mState);
outBitStream.Write<int32_t>(static_cast<int32_t>(mCurrentWaypointIndex));
outBitStream.Write(mInReverse);
if (!bIsInitialUpdate) mDirtyState = false;
}
}
NiPoint3 SimpleMoverSubComponent::GetWaypointPosition(const int32_t index) const {
if (index <= 0) return mStartPosition;
const glm::vec3 moved = mStartRotation * glm::vec3(mMove.x, mMove.y, mMove.z);
return mStartPosition + NiPoint3(moved.x, moved.y, moved.z);
}
SimpleMoverSubComponent::SimpleMoverSubComponent() = default;
SimpleMoverSubComponent::~SimpleMoverSubComponent() = default;
// As the client builds it from the starting point it is constructed with: a path run once, from the start to the start
// moved by platformMove (in the start's rotation), both waypoints with the start's rotation and the speed that covers
// the way in platformMoveTime (none without a way or a time)
void SimpleMoverSubComponent::GeneratePath() {
mOwnPath = std::make_unique<Path>();
mOwnPath->pathType = PathType::MovingPlatform;
mOwnPath->pathName = "SimpleMoverPath";
mOwnPath->pathBehavior = PathBehavior::Once;
const float distance = mMove.Length();
const float speed = distance != 0.0f && mMoveTime != 0.0f ? distance / mMoveTime : 0.0f;
for (int32_t index = 0; index < 2; index++) {
PathWaypoint waypoint;
waypoint.position = GetWaypointPosition(index);
waypoint.rotation = mStartRotation;
waypoint.speed = speed;
mOwnPath->pathWaypoints.push_back(waypoint);
}
mOwnPath->waypointCount = 2;
mPath = mOwnPath.get();
}
std::vector<eMoverSubComponentType> ChooseSubComponentTypes(const int32_t componentID, const Entity& entity) {
const bool setRotater = entity.HasVar(u"platformIsRotater");
const bool setMover = entity.HasVar(u"platformIsMover");
const bool setSimpleMover = entity.HasVar(u"platformIsSimpleMover");
if (!setRotater && !setMover && !setSimpleMover) {
return { componentID < 1 ? eMoverSubComponentType::mover : eMoverSubComponentType::simpleMover };
}
std::vector<eMoverSubComponentType> types;
if (setMover && entity.GetVar<bool>(u"platformIsMover")) types.push_back(eMoverSubComponentType::mover);
if (setSimpleMover && entity.GetVar<bool>(u"platformIsSimpleMover")) types.push_back(eMoverSubComponentType::simpleMover);
if (setRotater && entity.GetVar<bool>(u"platformIsRotater")) types.push_back(eMoverSubComponentType::rotater);
// All set false: rotate_while_idle makes it a rotater, or a mover when false
if (types.empty() && entity.HasVar(u"rotate_while_idle")) {
types.push_back(entity.GetVar<bool>(u"rotate_while_idle") ? eMoverSubComponentType::rotater : eMoverSubComponentType::mover);
}
return types;
}
eMoverSubComponentType ChooseMoverSubComponentType(const int32_t componentID, const Entity& entity) {
const auto types = ChooseSubComponentTypes(componentID, entity);
return types.empty() ? eMoverSubComponentType::none : types.front();
}
//------------- MovingPlatformComponent below --------------
MovingPlatformComponent::MovingPlatformComponent(Entity* parent, const int32_t componentID, const std::string& pathName) : Component(parent, componentID) {
m_PathName = GeneralUtils::ASCIIToUTF16(pathName);
m_NoAutoStart = false;
}
// The subcomponents (one per type, in the client's order)
void MovingPlatformComponent::LoadDataFromTemplate() {
for (const auto type : ChooseSubComponentTypes(m_ComponentID, *m_Parent)) {
if (type == eMoverSubComponentType::simpleMover) {
auto simpleMover = std::make_unique<SimpleMoverSubComponent>();
simpleMover->mStartPosition = m_Parent->GetDefaultPosition();
simpleMover->mStartRotation = m_Parent->GetDefaultRotation();
m_SubComponents.push_back(std::move(simpleMover));
} else if (type == eMoverSubComponentType::rotater) {
m_SubComponents.push_back(std::make_unique<RotatorSubComponent>());
} else {
m_SubComponents.push_back(std::make_unique<MoverSubComponent>());
}
}
m_MoverSubComponentType = m_SubComponents.empty() ? eMoverSubComponentType::none : m_SubComponents.front()->GetType();
}
using namespace ePlatformStateFlag;
namespace {
void StartTravelling(PlatformSubComponent& platform) {
platform.mState = (platform.mState & ~(Waiting | Stopped)) | Travelling;
}
void StopTravelling(PlatformSubComponent& platform) {
platform.mState = (platform.mState & ~(Waiting | Travelling)) | Stopped;
}
void StartWaiting(PlatformSubComponent& platform) {
platform.mState = (platform.mState & ~(Travelling | Stopped)) | Waiting;
}
bool IsSimpleMover(const PlatformSubComponent& platform) {
return platform.GetType() == eMoverSubComponentType::simpleMover;
}
}
// The client's platform takes away both of its object's velocities
void MovingPlatformComponent::ResetVelocities(PlatformSubComponent& platform) {
platform.mVelocity = NiPoint3Constant::ZERO;
m_AngularVelocity = NiPoint3Constant::ZERO;
}
// The level config: the path, a simple mover's settings, and where and whether each platform starts
void MovingPlatformComponent::LoadConfigData() {
const auto pathName = GeneralUtils::UTF16ToWTF8(m_PathName);
m_Path = Game::zoneManager->GetZone()->GetPath(pathName);
if (m_Path == nullptr) {
LOG("Path not found: %s", pathName.c_str());
}
const auto start = m_Parent->HasVar(u"attached_path_start") ? m_Parent->GetVar<int32_t>(u"attached_path_start") : 0;
m_StartWaypoint = start >= 0 ? start : 0;
if (m_Path != nullptr && static_cast<size_t>(m_StartWaypoint) >= m_Path->pathWaypoints.size()) m_StartWaypoint = 0;
for (const auto& subComponent : m_SubComponents) {
if (IsSimpleMover(*subComponent)) SetupSimpleMover(static_cast<SimpleMoverSubComponent&>(*subComponent));
else if (subComponent->GetType() == eMoverSubComponentType::rotater) SetupRotator(static_cast<RotatorSubComponent&>(*subComponent));
else SetupMoverPath(*subComponent);
}
// Live constructed every moving platform with simple physics as keyframed
auto* const simplePhysics = m_Parent->GetComponent<SimplePhysicsComponent>();
if (simplePhysics && !m_Parent->HasVar(u"motionType")) simplePhysics->SetPhysicsMotionState(SimplePhysicsComponent::MOTION_TYPE_KEYFRAMED);
}
bool MovingPlatformComponent::StartsOnLoad() const {
return !m_Parent->HasVar(u"startPathingOnLoad") || m_Parent->GetVar<bool>(u"startPathingOnLoad");
}
// A simple mover's settings, read in the client's order: the object's own first (not its platformMove ones when it
// has a MovingPlatforms row and is db only), then the row's platformMove and platformMoveTime over them, unless the
// object sets dbonly false. So with a row the object's own only count with dbonly false, and without a row dbonly
// means nothing. Whether it starts at its end only comes from the object.
// The simple mover then gets its own path, between its two ends, and is at the end it starts at: a platform like any
// other on a path run once. Made stopped at its waypoint (12), it waits there (9, as live constructed the NJ
// counterweights) unless startPathingOnLoad is false, for the shortest wait as its waypoints have none, and sets off
// for its other end. Live's scripts for the NJ spinners, which are simple movers that only move when used, stop them
// when they start up, and the simple movers that wait for an event without such a script have startPathingOnLoad 0.
void MovingPlatformComponent::SetupSimpleMover(SimpleMoverSubComponent& simpleMover) {
const bool hasRow = m_ComponentID > 0;
const bool dbOnly = hasRow && m_Parent->GetVar<bool>(u"dbonly");
if (m_Parent->HasVar(u"attached_path_start")) simpleMover.mStartAtEnd = m_Parent->GetVar<int32_t>(u"attached_path_start") != 0;
if (m_Parent->HasVar(u"platformStartAtEnd")) simpleMover.mStartAtEnd = m_Parent->GetVar<bool>(u"platformStartAtEnd");
if (!dbOnly) {
if (m_Parent->HasVar(u"platformMoveX")) simpleMover.mMove.x = m_Parent->GetVar<float>(u"platformMoveX");
if (m_Parent->HasVar(u"platformMoveY")) simpleMover.mMove.y = m_Parent->GetVar<float>(u"platformMoveY");
if (m_Parent->HasVar(u"platformMoveZ")) simpleMover.mMove.z = m_Parent->GetVar<float>(u"platformMoveZ");
if (m_Parent->HasVar(u"platformMoveTime")) simpleMover.mMoveTime = m_Parent->GetVar<float>(u"platformMoveTime");
}
if (hasRow && (!m_Parent->HasVar(u"dbonly") || dbOnly)) {
auto query = CDClientDatabase::CreatePreppedStmt(
"SELECT platformMoveX, platformMoveY, platformMoveZ, platformMoveTime FROM MovingPlatforms WHERE id = ?;");
query.bind(1, m_ComponentID);
auto result = query.execQuery();
if (!result.eof()) {
simpleMover.mMove = NiPoint3(result.getFloatField(0), result.getFloatField(1), result.getFloatField(2));
simpleMover.mMoveTime = result.getFloatField(3);
} else {
LOG("LOT %i couldn't find simple mover %i in MovingPlatforms", m_Parent->GetLOT(), m_ComponentID);
}
}
simpleMover.GeneratePath();
// One that starts at its end goes back from there: the client takes the direction it is constructed with
simpleMover.mInReverse = simpleMover.mStartAtEnd;
PlatformProcessStateChange(simpleMover, simpleMover.mStartAtEnd ? 1 : 0);
if (StartsOnLoad()) PlatformResumeTravelling(simpleMover, false);
}
// A mover is at its starting waypoint, stopped (12, as live constructed movers nothing had started). Unless
// startPathingOnLoad is false it then waits the waypoint's wait and leaves (live: 9). Live constructed a mover without
// a path waiting too (9), at waypoint 0 and at no position (0, 0, 0): it has nowhere to go.
void MovingPlatformComponent::SetupMoverPath(PlatformSubComponent& mover) {
mover.mPath = m_Path != nullptr && !m_Path->pathWaypoints.empty() ? m_Path : nullptr;
if (mover.mPath == nullptr) {
if (StartsOnLoad()) StartWaiting(mover);
return;
}
mover.mTimeBased = m_Path->movingPlatform.timeBasedMovement != 0;
mover.mInReverse = m_PathReverse;
PlatformProcessStateChange(mover, m_StartWaypoint);
if (StartsOnLoad()) PlatformResumeTravelling(mover, false);
}
// A rotator does not move along its path: it only turns (rotX/rotY/rotZ in half turns, at rate) while travelling, and
// never arrives anywhere. Only one on a path runs, and the client reads a platform that is not at a waypoint from its
// path, so one without a path stays as it was made (12). The client's rotator starts turning when it is sent
// travelling.
void MovingPlatformComponent::SetupRotator(RotatorSubComponent& rotator) {
constexpr float pi = 3.14159265358979323846f;
if (m_Parent->HasVar(u"rotX")) rotator.mRotationX = m_Parent->GetVarAs<float>(u"rotX") * pi;
if (m_Parent->HasVar(u"rotY")) rotator.mRotationY = m_Parent->GetVarAs<float>(u"rotY") * pi;
if (m_Parent->HasVar(u"rotZ")) rotator.mRotationZ = m_Parent->GetVarAs<float>(u"rotZ") * pi;
rotator.mRate = m_Parent->GetVarAs<float>(u"rate");
rotator.mPath = m_Path != nullptr && !m_Path->pathWaypoints.empty() ? m_Path : nullptr;
if (rotator.mPath == nullptr) return;
rotator.mTimeBased = m_Path->movingPlatform.timeBasedMovement != 0;
rotator.mInReverse = m_PathReverse;
PlatformProcessStateChange(rotator, m_StartWaypoint);
if (StartsOnLoad()) rotator.mState = Travelling;
}
// The SetCurrentPath game message: the path, the waypoint it starts at and its direction, then the client makes its
// subcomponents anew and a mover takes the path. Live wrote the path to the clients with the mover (the GF shooting
// gallery's targets), which do the same there. A simple mover keeps its own path.
bool MovingPlatformComponent::SetCurrentPath(const std::string& pathName, const uint32_t startPoint, const bool reverse) {
m_PathName = GeneralUtils::ASCIIToUTF16(pathName);
m_Path = Game::zoneManager->GetZone()->GetPath(pathName);
m_PathReverse = reverse;
m_DirtyPath = true;
// Whatever is running a platform of before now stops looking at it
m_SetupGeneration++;
// The new platforms of a quick build run once it is built
m_CheckedQuickBuild = false;
m_StartWaypoint = m_Path != nullptr && static_cast<size_t>(startPoint) >= m_Path->pathWaypoints.size() ? 0 : startPoint;
for (auto& subComponent : m_SubComponents) {
if (subComponent->GetType() == eMoverSubComponentType::mover) {
subComponent = std::make_unique<MoverSubComponent>();
SetupMoverPath(*subComponent);
} else if (subComponent->GetType() == eMoverSubComponentType::rotater) {
subComponent = std::make_unique<RotatorSubComponent>();
SetupRotator(static_cast<RotatorSubComponent&>(*subComponent));
}
}
const bool mover = IsMover();
if (mover) MoveObject(*GetSubComponent(eMoverSubComponentType::mover));
else if (m_Path == nullptr) LOG("Cannot setup platform on path %s", pathName.c_str());
Game::entityManager->SerializeEntity(m_Parent);
return mover;
}
MovingPlatformComponent::~MovingPlatformComponent() = default;
void MovingPlatformComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) {
// Live always constructed a simple mover with its starting point (the client builds its path from it), and
// serialized it only when its state changed: no path, then the one subcomponent and the 0 bit ending the list
if (m_SubComponents.size() == 1 && m_MoverSubComponentType == eMoverSubComponentType::simpleMover) {
auto* const simpleMover = GetSimpleMoverSubComponent();
const bool dirty = bIsInitialUpdate || simpleMover->mDirtyStartingPoint || simpleMover->mDirtyState;
outBitStream.Write(dirty);
outBitStream.Write(bIsInitialUpdate);
if (bIsInitialUpdate) outBitStream.Write0();
if (dirty) {
outBitStream.Write1();
outBitStream.Write(m_MoverSubComponentType);
simpleMover->Serialize(outBitStream, bIsInitialUpdate);
outBitStream.Write0();
}
return;
}
// Whether subcomponents follow, whether the path changed (then whether there is one: its name, starting waypoint
// and reverse), then the subcomponents. Live wrote the path with the construction and the mover's state with every
// serialization; a path set later (SetCurrentPath) is written once.
outBitStream.Write<bool>(true);
const bool writePath = bIsInitialUpdate || m_DirtyPath;
outBitStream.Write(writePath);
if (writePath) {
if (!bIsInitialUpdate) m_DirtyPath = false;
const auto hasPath = !m_PathName.empty() && m_Path != nullptr;
outBitStream.Write(hasPath);
if (hasPath) {
outBitStream.Write<uint16_t>(m_PathName.size());
for (const auto& c : m_PathName) {
outBitStream.Write<uint16_t>(c);
}
outBitStream.Write<uint32_t>(m_StartWaypoint);
outBitStream.Write<bool>(m_PathReverse);
}
}
// The subcomponents, each after a 1 bit with its type (a rotater sends a mover's data); a 0 bit
// ends the list. A platform the client made none for gets none: it could not read one.
for (const auto& subComponent : m_SubComponents) {
outBitStream.Write1();
outBitStream.Write(subComponent->GetType());
subComponent->Serialize(outBitStream, bIsInitialUpdate);
}
outBitStream.Write0();
}
void MovingPlatformComponent::OnQuickBuildInitilized() {
for (size_t i = 0; i < m_SubComponents.size(); i++) {
auto& platform = *m_SubComponents[i];
// Live left a quick built simple mover (the NJ counterweights) where it was, only resending its state
if (IsSimpleMover(platform)) static_cast<SimpleMoverSubComponent&>(platform).mDirtyState = true;
else PlatformStop(platform);
}
}
void MovingPlatformComponent::OnCompleteQuickBuild() {
for (size_t i = 0; i < m_SubComponents.size(); i++) {
auto& platform = *m_SubComponents[i];
// Live (the NJ counterweights, LOT 16141): the built simple mover is serialized waiting at its waypoint (9) and
// about 0.1 s later travelling (2) to its other end, where it stops without a serialization and
// PlatformAtLastWaypoint tells the scripts. A quick build's platform runs once the quick build is complete: it
// then waits the shortest wait and sets off.
if (IsSimpleMover(platform)) static_cast<SimpleMoverSubComponent&>(platform).mDirtyState = true;
else if (!m_NoAutoStart) PlatformStart(platform);
}
}
// A serialization with the platform's state in it: a simple mover only writes its state when it changed
void MovingPlatformComponent::SerializePlatform(PlatformSubComponent& platform) {
if (IsSimpleMover(platform)) static_cast<SimpleMoverSubComponent&>(platform).mDirtyState = true;
Game::entityManager->SerializeEntity(m_Parent);
}
void MovingPlatformComponent::SetMovementState(eMovementPlatformState value) {
for (const auto& subComponent : m_SubComponents) {
if (subComponent->GetType() == eMoverSubComponentType::rotater || subComponent->mPath == nullptr) continue;
subComponent->mState = static_cast<uint32_t>(value);
SerializePlatform(*subComponent);
}
}
// What the object is told goes to each of its platforms, as the client's component passes its messages on to every
// subcomponent
void MovingPlatformComponent::GotoWaypoint(uint32_t index, bool stopAtWaypoint) {
const auto generation = m_SetupGeneration;
for (size_t i = 0; i < m_SubComponents.size() && generation == m_SetupGeneration; i++) {
PlatformGotoWaypoint(*m_SubComponents[i], index, stopAtWaypoint);
}
}
// Sends a platform to a waypoint, stopping there when stopAtWaypoint: it turns round if the waypoint is behind it. Live
// (the NJ falling tiles): a mover at a waypoint first waits there (9, or 25 at an end, with the desired waypoint), then
// leaves (2).
void MovingPlatformComponent::PlatformGotoWaypoint(PlatformSubComponent& platform, const uint32_t index, const bool stopAtWaypoint) {
if (platform.mPath == nullptr || index >= platform.mPath->pathWaypoints.size()) return;
if (platform.GetType() == eMoverSubComponentType::rotater) {
platform.mDesiredWaypointIndex = static_cast<int32_t>(index);
platform.mShouldStopAtDesiredWaypoint = stopAtWaypoint;
RotatorSetMoving(static_cast<RotatorSubComponent&>(platform), index < platform.mCurrentWaypointIndex);
return;
}
const auto& waypoints = platform.mPath->pathWaypoints;
const bool atWaypoint = (platform.mState & ReachedDesiredWaypoint) != 0;
if (atWaypoint && platform.mCurrentWaypointIndex == index) {
// Already there. A simple mover stays as it is.
if (IsSimpleMover(platform)) return;
platform.mDesiredWaypointIndex = -1;
platform.mShouldStopAtDesiredWaypoint = false;
if (stopAtWaypoint) {
StopTravelling(platform);
ResetVelocities(platform);
}
FireArrivalHooks(index, true, index == waypoints.size() - 1);
return;
}
platform.mDesiredWaypointIndex = static_cast<int32_t>(index);
platform.mShouldStopAtDesiredWaypoint = stopAtWaypoint;
// At a waypoint it sets off in the waypoint's direction. Between two a mover carries on if the waypoint is ahead,
// else turns round (the waypoint it was heading to becomes the one it comes from).
if (atWaypoint) {
const bool reverse = index < platform.mCurrentWaypointIndex;
if (reverse != platform.mInReverse) {
platform.mInReverse = reverse;
PlatformProcessStateChange(platform, platform.mCurrentWaypointIndex);
}
} else if (IsSimpleMover(platform)) {
// The client's simple mover only takes a new direction at a waypoint: on its way it goes on to the end it was
// heading for, and sets off for the waypoint it was sent to once it has stopped there
return;
} else {
const bool ahead = platform.mInReverse ? index <= platform.mNextWaypointIndex : index >= platform.mNextWaypointIndex;
if (!ahead) {
const float percent = platform.mPercentBetweenPoints;
const auto heading = platform.mNextWaypointIndex;
platform.mInReverse = !platform.mInReverse;
platform.mNextWaypointIndex = platform.mCurrentWaypointIndex;
platform.mCurrentWaypointIndex = heading;
platform.mPercentBetweenPoints = 1.0f - std::min(percent, 1.0f);
platform.mSegmentLength = Vector3::Distance(waypoints[platform.mCurrentWaypointIndex].position, waypoints[platform.mNextWaypointIndex].position);
platform.mWaitTime = waypoints[platform.mCurrentWaypointIndex].movingPlatform.wait;
if (platform.mTimeBased) {
// The client's turn round (ProcessStateChange of the waypoint it was heading to, not moving there) starts
// the stretch's clock again: from where it is, it takes the whole stretch's time at the whole stretch's
// speed, so it goes past the waypoint by as far as it had come
platform.mMoveTimeElapsed = 0.0f;
platform.mPercentBetweenPoints = 0.0f;
} else {
std::swap(platform.mCurrentSpeed, platform.mNextSpeed);
}
}
}
PlatformResumeTravelling(platform, false);
SerializePlatform(platform);
}
// A rotator sent forwards or backwards, as the client's rotator has it (nothing in the client sends it either way: the
// client has no handler for GoToWaypoint, the server sends platforms on). It travels; set the way it already turns
// it starts turning, and set the other way it turns round and turns at the same rate the other way. It never gets to a
// waypoint: one ahead of where it is on its path sends it forwards, one behind backwards.
// The client's rotator only takes its direction from its path or from a PlatformResync, never from a serialization, so
// a rotator that turned round is resynced: the client's platform then puts its object in the waypoint's rotation and
// turns from there, as the object here is. An object's resync goes to all of its platforms, so one that also has a
// mover is not resynced: its clients keep the rotator's old direction.
void MovingPlatformComponent::RotatorSetMoving(RotatorSubComponent& rotator, const bool reverse) {
if (rotator.mPath == nullptr) return;
StartTravelling(rotator);
if (rotator.mInReverse != reverse) {
rotator.mInReverse = reverse;
if (m_SubComponents.size() == 1) {
SetObjectTransform(m_Parent->GetPosition(), rotator.mPath->pathWaypoints[rotator.mCurrentWaypointIndex].rotation);
GameMessages::PlatformResync resync;
resync.target = m_Parent->GetObjectID();
if (FillResync(resync)) resync.Send(UNASSIGNED_SYSTEM_ADDRESS);
}
} else {
// Setting off drops the two "reached" bits
rotator.mState &= MovementMask;
}
Game::entityManager->SerializeEntity(m_Parent);
}
void MovingPlatformComponent::StartPathing() {
for (size_t i = 0; i < m_SubComponents.size(); i++) PlatformStart(*m_SubComponents[i]);
}
void MovingPlatformComponent::PlatformStart(PlatformSubComponent& platform) {
if (platform.mPath == nullptr) return;
if (platform.GetType() == eMoverSubComponentType::rotater) {
// A rotator on a path spins again
platform.mState = Travelling;
Game::entityManager->SerializeEntity(m_Parent);
return;
}
if ((platform.mState & Travelling) != 0) return;
// Stopped between two waypoints it carries on; at a waypoint it first waits there for the waypoint's wait (issue
// 964: the AG monument elevator waited about 2 s before rising). A simple mover's path is start to end: from one
// it sets off for the other.
PlatformResumeTravelling(platform, false);
SerializePlatform(platform);
}
void MovingPlatformComponent::StopPathing() {
for (size_t i = 0; i < m_SubComponents.size(); i++) PlatformStop(*m_SubComponents[i]);
}
void MovingPlatformComponent::PlatformStop(PlatformSubComponent& platform) {
if (IsSimpleMover(platform)) {
// At an end it is stopped; on its way it goes on to the end it was heading for, to stop there (where its path,
// run once, stops it anyway)
if ((platform.mState & ReachedDesiredWaypoint) == 0) {
platform.mDesiredWaypointIndex = static_cast<int32_t>(platform.mNextWaypointIndex);
platform.mShouldStopAtDesiredWaypoint = true;
return;
}
StopTravelling(platform);
ResetVelocities(platform);
SerializePlatform(platform);
return;
}
if (platform.GetType() == eMoverSubComponentType::rotater) {
// No longer spinning
StopTravelling(platform);
m_AngularVelocity = NiPoint3Constant::ZERO;
Game::entityManager->SerializeEntity(m_Parent);
return;
}
if (platform.mPath == nullptr) return;
// Stopped where it is (the client stops on the stopped bit, 4)
StopTravelling(platform);
ResetVelocities(platform);
platform.mDesiredWaypointIndex = -1;
platform.mShouldStopAtDesiredWaypoint = false;
Game::entityManager->SerializeEntity(m_Parent);
}
bool MovingPlatformComponent::IsMover() const {
const auto* const mover = GetSubComponent(eMoverSubComponentType::mover);
return mover != nullptr && mover->mPath != nullptr;
}
// The waypoint becomes the platform's current one, where it now is. The next follows from the path's behavior and the
// direction (a bounce turns round at either end), with the two waypoints' speeds.
void MovingPlatformComponent::PlatformProcessStateChange(PlatformSubComponent& platform, const uint32_t index) {
const auto& waypoints = platform.mPath->pathWaypoints;
const auto count = static_cast<int32_t>(waypoints.size());
const auto behavior = static_cast<PathBehavior>(platform.mPath->pathBehavior);
const auto current = std::min<int32_t>(static_cast<int32_t>(index), count - 1);
int32_t next{};
if (!platform.mInReverse) {
next = current + 1;
if (next >= count) {
if (behavior == PathBehavior::Once) next = count - 1;
else if (behavior == PathBehavior::Bounce) {
next = count - 2;
platform.mInReverse = true;
} else next = 0;
}
} else {
next = current - 1;
if (next < 0) {
if (behavior == PathBehavior::Once) next = 0;
else if (behavior == PathBehavior::Bounce) {
next = 1;
platform.mInReverse = false;
} else next = count - 1;
}
}
next = std::clamp(next, 0, count - 1);
platform.mCurrentWaypointIndex = current;
platform.mNextWaypointIndex = next;
platform.mWaitTime = waypoints[current].movingPlatform.wait;
platform.mPercentBetweenPoints = 0.0f;
platform.mMoveTimeElapsed = 0.0f;
platform.mPosition = waypoints[current].position;
platform.mSegmentLength = Vector3::Distance(waypoints[current].position, waypoints[next].position);
if (current == next) {
platform.mCurrentSpeed = platform.mNextSpeed = 0.0f;
} else if (platform.mTimeBased) {
platform.mCurrentSpeed = waypoints[std::min(current, next)].speed;
platform.mNextSpeed = 0.0f;
} else {
platform.mCurrentSpeed = waypoints[current].speed;
platform.mNextSpeed = waypoints[next].speed;
}
}
// Starts a wait of at least 0.1 s
void MovingPlatformComponent::PlatformSetWaitingTime(PlatformSubComponent& platform, const float waitTime, const float idleTimeElapsed) {
platform.mTimeToWait = std::max(0.1f, waitTime);
platform.mIdleTimeElapsed = idleTimeElapsed;
platform.mWaitSet = true;
// Only at an end of the path, or stopped, does the object lose its velocities here. Waiting at a waypoint in between
// it keeps them: live's platforms went on as they came for the wait (the GF shooting gallery subs 2 units past each
// waypoint, the FV dragons 5.33; a dragon met 2.2 s into a 5 s wait was 88 past its waypoint).
if ((platform.mState & (ReachedFinalDestination | Stopped)) != 0) ResetVelocities(platform);
}
// The velocity towards the next waypoint at the speed for where the platform is; setting off drops the two "reached"
// bits of its state
void MovingPlatformComponent::PlatformUpdateVelocities(PlatformSubComponent& platform) {
const auto& waypoints = platform.mPath->pathWaypoints;
auto direction = waypoints[platform.mNextWaypointIndex].position - waypoints[platform.mCurrentWaypointIndex].position;
const float distance = direction.Length();
if (distance > 0.0f) direction = direction / distance;
// A time based path's mCurrentSpeed is the seconds to the next waypoint; else the speed goes from the waypoint's to
// the next one's along the way
float speed{};
if (platform.mTimeBased) speed = platform.mCurrentSpeed > 0.0f ? distance / platform.mCurrentSpeed : 0.0f;
else speed = platform.mCurrentSpeed + (platform.mNextSpeed - platform.mCurrentSpeed) * platform.mPercentBetweenPoints;
platform.mVelocity = direction * speed;
// The object turns at its angular velocity only where it has a rotator on a path; else it is turned between the
// two waypoints' rotations as it goes (MoveObject)
if (platform.GetType() != eMoverSubComponentType::rotater && HasRotatorOnPath()) PlatformSetAngularVelocity(platform);
platform.mState &= MovementMask;
}
// Stopped between two waypoints the platform travels on; at a waypoint it first waits there. A simple mover only does
// either at a waypoint or stopped, unless forced.
void MovingPlatformComponent::PlatformResumeTravelling(PlatformSubComponent& platform, const bool force) {
if (IsSimpleMover(platform) && !force && (platform.mState & (ReachedDesiredWaypoint | Stopped)) == 0) return;
if ((platform.mState & Stopped) != 0 && (platform.mState & ReachedDesiredWaypoint) == 0) StartTravelling(platform);
if ((platform.mState & Travelling) != 0) {
PlatformUpdateVelocities(platform);
} else {
StartWaiting(platform);
PlatformSetWaitingTime(platform, platform.mWaitTime, 0.0f);
}
}
// Once the platform is at its next waypoint: it is there (8), at an end of the path (16) if it is one, where a path
// run once turns it round. It stops there if it was sent there to stop or turned at the end of a path run once; else
// it travels on, after the waypoint's wait. False when a script told of it put the platform on another path.
bool MovingPlatformComponent::PlatformArrivedAtWaypoint(PlatformSubComponent& platform) {
const auto& waypoints = platform.mPath->pathWaypoints;
const auto& next = waypoints[platform.mNextWaypointIndex].position;
bool closeEnough{};
if (platform.mTimeBased) {
// The time to the next waypoint is up
closeEnough = std::abs(platform.mCurrentSpeed - platform.mMoveTimeElapsed) < 0.02f;
} else {
// Within 0.01 of the next waypoint, or past it
const auto offset = next - platform.mPosition;
const auto direction = next - waypoints[platform.mCurrentWaypointIndex].position;
closeEnough = offset.SquaredLength() <= 0.0001f || direction.DotProduct(offset) <= 0.0f;
}
if (!closeEnough) return true;
// What the clients were last sent, to know whether an arrival while waiting changes it
const auto sentState = platform.mState;
const auto sentCurrent = platform.mCurrentWaypointIndex;
const auto sentNext = platform.mNextWaypointIndex;
const bool sentReverse = platform.mInReverse;
const auto arrived = platform.mNextWaypointIndex;
const bool atLastWaypoint = arrived == static_cast<uint32_t>(waypoints.size() - 1);
bool atDesiredWaypoint = false;
bool stopAtDesiredWaypoint = false;
bool turnedAtEnd = false;
platform.mState = ReachedDesiredWaypoint;
if (platform.mDesiredWaypointIndex == static_cast<int32_t>(arrived)) {
atDesiredWaypoint = true;
stopAtDesiredWaypoint = platform.mShouldStopAtDesiredWaypoint;
platform.mShouldStopAtDesiredWaypoint = false;
platform.mDesiredWaypointIndex = -1;
}
if (arrived == 0 || atLastWaypoint) {
platform.mState |= ReachedFinalDestination;
if (static_cast<PathBehavior>(platform.mPath->pathBehavior) == PathBehavior::Once) {
turnedAtEnd = true;
platform.mInReverse = !platform.mInReverse;
}
}
if (stopAtDesiredWaypoint || turnedAtEnd) {
StopTravelling(platform);
ResetVelocities(platform);
} else {
StartTravelling(platform);
}
PlatformProcessStateChange(platform, arrived);
MoveObject(platform, true);
if (!PlatformHandleWaypointArrived(platform, arrived, atDesiredWaypoint, atLastWaypoint)) return false;
// Live serialized a platform that waits at the waypoint it arrived at (it leaves again), not one that stopped there.
// A platform kept at one waypoint by its path (a path of one waypoint) arrives every frame of its wait without
// anything to send.
const bool unchanged = (sentState & Waiting) != 0 && platform.mState == sentState && platform.mCurrentWaypointIndex == sentCurrent
&& platform.mNextWaypointIndex == sentNext && platform.mInReverse == sentReverse;
if ((platform.mState & Stopped) == 0 && !unchanged) SerializePlatform(platform);
// A simple mover sent elsewhere on its way (it cannot turn between its ends) sets off from where it stopped
if (IsSimpleMover(platform) && (platform.mState & Stopped) != 0 && platform.mDesiredWaypointIndex >= 0
&& platform.mDesiredWaypointIndex != static_cast<int32_t>(platform.mCurrentWaypointIndex)) {
PlatformGotoWaypoint(platform, static_cast<uint32_t>(platform.mDesiredWaypointIndex), platform.mShouldStopAtDesiredWaypoint);
}
return true;
}
// Tells the scripts, then a platform that travels on waits at the waypoint. False when a script put the platform on
// another path.
bool MovingPlatformComponent::PlatformHandleWaypointArrived(PlatformSubComponent& platform, const uint32_t index, const bool atDesiredWaypoint, const bool atLastWaypoint) {
const auto generation = m_SetupGeneration;
FireArrivalHooks(index, atDesiredWaypoint, atLastWaypoint);
if (generation != m_SetupGeneration) return false;
if ((platform.mState & Travelling) != 0) {
StartWaiting(platform);
PlatformSetWaitingTime(platform, platform.mWaitTime, 0.0f);
}
return true;
}
// The client's platform moves its object ignoring the dirty flags, and its physics carry it between waypoints: live
// did not serialize a mover's physics for it, each client moves its own. The server's object goes with the platform,
// turned between the two waypoints' rotations. Where the object has a rotator on the path as well, the rotator turns
// it (the client's rotator puts its own angular velocity back on the object every frame), so the object keeps the
// rotation it has; only at a waypoint it arrives at is it put in the waypoint's rotation.
void MovingPlatformComponent::MoveObject(const PlatformSubComponent& platform, const bool atWaypoint) {
const auto& from = platform.mPath->pathWaypoints[platform.mCurrentWaypointIndex].rotation;
if (!atWaypoint) {
const auto* const rotator = GetSubComponent(eMoverSubComponentType::rotater);
if (rotator != nullptr && rotator->mPath != nullptr) {
SetObjectTransform(platform.mPosition, m_Parent->GetRotation());
return;
}
}
const auto& to = platform.mPath->pathWaypoints[platform.mNextWaypointIndex].rotation;
const auto rotation = from == to ? from : glm::slerp(from, to, std::min(platform.mPercentBetweenPoints, 1.0f));
SetObjectTransform(platform.mPosition, rotation);
}
void MovingPlatformComponent::SetObjectTransform(const NiPoint3& position, const NiQuaternion& rotation) {
if (auto* const simplePhysics = m_Parent->GetComponent<SimplePhysicsComponent>()) {
simplePhysics->SetPositionAndRotationIgnoringDirtyFlags(position, rotation);
}
if (auto* const phantomPhysics = m_Parent->GetComponent<PhantomPhysicsComponent>()) {
phantomPhysics->SetPositionAndRotationIgnoringDirtyFlags(position, rotation);
}
}
// A quick build's platforms do not run until it is built, nor once the quick build is open again
void MovingPlatformComponent::UpdateActive() {
if (!m_CheckedQuickBuild) {
m_CheckedQuickBuild = true;
m_QuickBuild = m_Parent->GetComponent<QuickBuildComponent>();
if (m_QuickBuild) for (const auto& subComponent : m_SubComponents) subComponent->mActive = false;
}
if (!m_QuickBuild) return;
const auto quickBuildState = m_QuickBuild->GetState();
if (quickBuildState != eQuickBuildState::OPEN && quickBuildState != eQuickBuildState::COMPLETED) return;
for (const auto& subComponent : m_SubComponents) subComponent->mActive = quickBuildState == eQuickBuildState::COMPLETED;
}
NiPoint3 CalcRotatorAngularVelocity(const float rotX, const float rotY, const float rotZ, const float rate, const bool reverse) {
// The client's rotations about x, y and z: each turns the other way round than the usual right-handed one
const float sx = static_cast<float>(std::sin(static_cast<double>(rotX))), cx = static_cast<float>(std::cos(static_cast<double>(rotX)));
const float sy = static_cast<float>(std::sin(static_cast<double>(rotY))), cy = static_cast<float>(std::cos(static_cast<double>(rotY)));
const float sz = static_cast<float>(std::sin(static_cast<double>(rotZ))), cz = static_cast<float>(std::cos(static_cast<double>(rotZ)));
const float x[3][3] = { { 1.0f, 0.0f, 0.0f }, { 0.0f, cx, sx }, { 0.0f, -sx, cx } };
const float y[3][3] = { { cy, 0.0f, -sy }, { 0.0f, 1.0f, 0.0f }, { sy, 0.0f, cy } };
const float z[3][3] = { { cz, sz, 0.0f }, { -sz, cz, 0.0f }, { 0.0f, 0.0f, 1.0f } };
// The three as one: x * (y * z)
float yz[3][3]{};
float m[3][3]{};
for (int32_t i = 0; i < 3; i++) for (int32_t j = 0; j < 3; j++) for (int32_t k = 0; k < 3; k++) yz[i][j] += y[i][k] * z[k][j];
for (int32_t i = 0; i < 3; i++) for (int32_t j = 0; j < 3; j++) for (int32_t k = 0; k < 3; k++) m[i][j] += x[i][k] * yz[k][j];
// The matrix as a quaternion
float q[4]{}; // x, y, z, w
const float trace = m[0][0] + m[1][1] + m[2][2];
if (trace > 0.0f) {
float root = std::sqrt(trace + 1.0f);
q[3] = 0.5f * root;
root = 0.5f / root;
q[0] = (m[2][1] - m[1][2]) * root;
q[1] = (m[0][2] - m[2][0]) * root;
q[2] = (m[1][0] - m[0][1]) * root;
} else {
constexpr int32_t next[3] = { 1, 2, 0 };
int32_t i = 0;
if (m[1][1] > m[0][0]) i = 1;
if (m[2][2] > m[i][i]) i = 2;
const int32_t j = next[i];
const int32_t k = next[j];
float root = std::sqrt(m[i][i] - m[j][j] - m[k][k] + 1.0f);
q[i] = 0.5f * root;
root = 0.5f / root;
q[3] = (m[k][j] - m[j][k]) * root;
q[j] = (m[j][i] + m[i][j]) * root;
q[k] = (m[k][i] + m[i][k]) * root;
}
// From no rotation to it (from it to none in reverse) in half the rate
const NiQuaternion rotation(q[3], q[0], q[1], q[2]);
if (rate == 0.0f) return NiPoint3Constant::ZERO;
const float time = rate * 0.5f;
return reverse ? CalcAngularVelocity(rotation, QuatUtils::IDENTITY, time) : CalcAngularVelocity(QuatUtils::IDENTITY, rotation, time);
}
// The rotation from the first to the second (the second times the inverse of the first), normalized; without an axis
// there is no velocity; else the axis (the other way for a negative w) times twice the arc cosine of |w| over the time
NiPoint3 CalcAngularVelocity(const NiQuaternion& from, const NiQuaternion& to, const float time) {
if (!(time > 0.0f)) return NiPoint3Constant::ZERO;
auto diff = to * glm::inverse(from);
const float length = std::sqrt(diff.x * diff.x + diff.y * diff.y + diff.z * diff.z + diff.w * diff.w);
if (!(length > 0.0f)) return NiPoint3Constant::ZERO;
diff = NiQuaternion(diff.w / length, diff.x / length, diff.y / length, diff.z / length);
const float axisLength = std::sqrt(diff.x * diff.x + diff.y * diff.y + diff.z * diff.z);
if (!(axisLength > std::numeric_limits<float>::epsilon())) return NiPoint3Constant::ZERO;
const float angle = 2.0f * std::acos(std::min(std::abs(diff.w), 1.0f));
const float scale = (diff.w < 0.0f ? -1.0f : 1.0f) / axisLength * angle * (1.0f / time);
return NiPoint3(diff.x * scale, diff.y * scale, diff.z * scale);
}
// Even acceleration from one speed to the other over the way; the time at that acceleration, or the way over the
// speed without one
float CalcPlatformTravelTime(const NiPoint3& start, const NiPoint3& end, const float startSpeed, const float endSpeed) {
constexpr float minDistance = 0.00001f;
const float distance = Vector3::Distance(start, end);
if (distance < minDistance) return 0.0f;
float acceleration = 0.0f;
if (startSpeed != endSpeed) acceleration = static_cast<float>((endSpeed * endSpeed - startSpeed * startSpeed) / (distance * 2.0));
if (acceleration != 0.0f) {
const double root = std::sqrt(startSpeed * startSpeed + acceleration * 2.0 * distance);
return static_cast<float>(-startSpeed + root) / acceleration;
}
return startSpeed == 0.0f ? 0.0f : distance / startSpeed;
}
// A rotator's wait never ends and it never arrives; it has no linear velocity. The client's physics turn the object at
// its angular velocity, which a rotator that has not stopped puts back to its own whenever it differs (so a mover on
// the same object only turns it while the rotator is stopped). The server turns its object in TurnObject, without a
// serialization of its physics, as a mover's.
void MovingPlatformComponent::RunRotator(RotatorSubComponent& rotator, const float deltaTime) {
if (rotator.mPath == nullptr) return;
if (!rotator.mPlaced) {
// The object is put at its waypoint when the rotator is set up on its path
rotator.mPlaced = true;
SetObjectTransform(rotator.mPosition, rotator.mPath->pathWaypoints[rotator.mCurrentWaypointIndex].rotation);
}
// An open quick build's platforms do not turn it
if (!rotator.mActive) m_AngularVelocity = NiPoint3Constant::ZERO;
else if (rotator.mState != 0 && (rotator.mState & Stopped) == 0) m_AngularVelocity = rotator.GetAngularVelocity();
}
bool MovingPlatformComponent::HasRotatorOnPath() const {
const auto* const rotator = GetSubComponent(eMoverSubComponentType::rotater);
return rotator != nullptr && rotator->mPath != nullptr;
}
void MovingPlatformComponent::TurnObject(const float deltaTime) {
const float speed = m_AngularVelocity.Length();
if (!(speed > 0.0f) || !std::isfinite(speed)) return;
const glm::vec3 axis(m_AngularVelocity.x / speed, m_AngularVelocity.y / speed, m_AngularVelocity.z / speed);
SetObjectTransform(m_Parent->GetPosition(), glm::normalize(glm::angleAxis(speed * deltaTime, axis) * m_Parent->GetRotation()));
}
// The client's mover sets off (and, between waypoints of different speeds, goes on) turned towards the next
// waypoint's rotation: at a waypoint from that waypoint's rotation; between two from the rotation for how far it is
// (or its own, when that is within 8 degrees of it, then timed from where it is at the speed for there), at the
// angular velocity that gets it there with the next waypoint. With both waypoints in one rotation it is put in it and
// does not turn.
void MovingPlatformComponent::PlatformSetAngularVelocity(PlatformSubComponent& platform) {
constexpr float closeAngle = 0.13962634f;
constexpr float minStretchSquared = 0.00001f;
const auto& waypoints = platform.mPath->pathWaypoints;
const auto& currentRotation = waypoints[platform.mCurrentWaypointIndex].rotation;
const auto& nextRotation = waypoints[platform.mNextWaypointIndex].rotation;
if (currentRotation == nextRotation) {
SetObjectTransform(platform.mPosition, currentRotation);
m_AngularVelocity = NiPoint3Constant::ZERO;
return;
}
bool closeToRotation = false;
auto rotation = currentRotation;
if ((platform.mState & ReachedDesiredWaypoint) == 0) {
rotation = glm::slerp(currentRotation, nextRotation, platform.mPercentBetweenPoints);
const auto current = m_Parent->GetRotation();
const float dot = std::abs(glm::dot(rotation, current));
if (std::acos(std::min(dot, 1.0f)) < closeAngle) {
closeToRotation = true;
rotation = current;
}
}
if (!closeToRotation) SetObjectTransform(platform.mPosition, rotation);
float time = platform.mTimeBased ? platform.mCurrentSpeed - platform.mMoveTimeElapsed : 0.0f;
if (!platform.mTimeBased) {
auto start = waypoints[platform.mCurrentWaypointIndex].position;
auto startSpeed = platform.mCurrentSpeed;
if (closeToRotation) {
start = platform.mPosition;
startSpeed = platform.mCurrentSpeed + (platform.mNextSpeed - platform.mCurrentSpeed) * platform.mPercentBetweenPoints;
}
const auto& end = waypoints[platform.mNextWaypointIndex].position;
if ((start - end).SquaredLength() > minStretchSquared) time = CalcPlatformTravelTime(start, end, startSpeed, platform.mNextSpeed);
}
if (time > 0.0f) m_AngularVelocity = CalcAngularVelocity(rotation, nextRotation, time);
}
// A platform on its path. The client's is moved by its physics, at the velocity the platform gives its object; the
// server moves it here by the same speed. False when a script told of an arrival put the platform on another path.
bool MovingPlatformComponent::RunPlatform(PlatformSubComponent& platform, const float deltaTime, const float stepTime) {
if (platform.mPath == nullptr) return true;
if (!platform.mActive) {
// An open quick build's platform loses its velocities
ResetVelocities(platform);
return true;
}
if (platform.mState == 0) return true;
const bool travelling = (platform.mState & Travelling) != 0;
if (platform.mTimeBased && travelling) platform.mMoveTimeElapsed += deltaTime;
// The object's physics: it goes at its velocity, travelling or not, in whole physics steps
platform.mPosition = platform.mPosition + platform.mVelocity * stepTime;
if (platform.mTimeBased) {
// mCurrentSpeed is the seconds to the next waypoint
platform.mMoveTimeElapsed = std::min(platform.mMoveTimeElapsed, platform.mCurrentSpeed);
platform.mPercentBetweenPoints = platform.mCurrentSpeed > 0.0f ? platform.mMoveTimeElapsed / platform.mCurrentSpeed : 1.0f;
} else {
// How far the object is from the current waypoint, over the way to the next (live sent 1.219 for a dragon that
// far past its waypoint)
const auto& from = platform.mPath->pathWaypoints[platform.mCurrentWaypointIndex].position;
platform.mPercentBetweenPoints = platform.mSegmentLength > 0.0f ? Vector3::Distance(from, platform.mPosition) / platform.mSegmentLength : 0.0f;
}
MoveObject(platform);
const bool stopped = (platform.mState & Stopped) != 0;
bool doneWaiting = false;
if ((platform.mState & Waiting) != 0 && platform.mWaitSet) {
platform.mIdleTimeElapsed += deltaTime;
if (platform.mIdleTimeElapsed >= platform.mTimeToWait) {
platform.mIdleTimeElapsed = 0.0f;
doneWaiting = true;
}
}
if (doneWaiting) {
StartTravelling(platform);
} else if (!stopped) {
// A platform that has not stopped looks whether it arrived, also while it waits. Live's FV dragons, going on as
// they came through the 5 s wait at their waypoint 4, were at waypoint 5 (waiting there, then going on in the
// direction they came to 4 in) without ever having left 4. Where the next waypoint is in the same place (two
// waypoints in one place, a path of one waypoint) it is there at once: it arrives in the first frame of the
// wait, and on a path that keeps it there, every frame, as the client's.
if (!PlatformArrivedAtWaypoint(platform)) return false;
}
if ((platform.mState & Travelling) != 0 && (doneWaiting || platform.mCurrentSpeed != platform.mNextSpeed)) {
// The client's platform sends Departed as it leaves a waypoint it waited at
if (doneWaiting && !FireDeparted(platform.mCurrentWaypointIndex)) return false;
PlatformUpdateVelocities(platform);
// Live serialized a platform leaving its waypoint, where it then was: as far past the waypoint as the wait took it
if (doneWaiting) SerializePlatform(platform);
}
MoveObject(platform);
return true;
}
// Every platform of the object runs, in the client's order: a mover or simple mover moves the object, a rotator turns it
void MovingPlatformComponent::Run(const float deltaTime) {
if (m_SubComponents.empty()) return;
// The physics steps that fall in this frame (several in a long frame, none in most short ones)
m_StepTimeLeft += deltaTime;
// (a frame of exactly one step must not lose it to rounding)
const float steps = std::floor(m_StepTimeLeft / PhysicsStep + 0.0001f);
const float stepTime = steps * PhysicsStep;
m_StepTimeLeft = std::max(0.0f, m_StepTimeLeft - stepTime);
UpdateActive();
const auto generation = m_SetupGeneration;
for (size_t i = 0; i < m_SubComponents.size(); i++) {
auto& platform = *m_SubComponents[i];
if (platform.GetType() == eMoverSubComponentType::rotater) RunRotator(static_cast<RotatorSubComponent&>(platform), deltaTime);
else if (!RunPlatform(platform, deltaTime, stepTime)) return;
// A script told of an arrival may have put the platforms on another path
if (generation != m_SetupGeneration) return;
}
if (HasRotatorOnPath() && stepTime > 0.0f) TurnObject(stepTime);
}
// What live answered a client's request with: the state of the platform (a mover's, a simple mover's on its own path,
// or a mover's without a path: waiting at waypoint 0 of none, at no position and with no rotation), where it is, and
// the rotation between its two waypoints'. The client gives the message to every platform of the object; the first
// one's state is sent.
bool MovingPlatformComponent::FillResync(GameMessages::PlatformResync& resync) const {
if (m_SubComponents.empty()) return false;
const auto& platform = *m_SubComponents.front();
resync.bReverse = platform.mInReverse;
resync.bStopAtDesiredWaypoint = platform.mShouldStopAtDesiredWaypoint;
resync.eState = static_cast<eMovementPlatformState>(platform.mState);
resync.fIdleTimeElapsed = platform.mIdleTimeElapsed;
resync.fMoveTimeElapsed = platform.mMoveTimeElapsed;
resync.fPercentBetweenPoints = std::min(platform.mPercentBetweenPoints, 1.0f);
resync.iDesiredWaypointIndex = platform.mDesiredWaypointIndex;
resync.iIndex = static_cast<int32_t>(platform.mCurrentWaypointIndex);
resync.iNextIndex = static_cast<int32_t>(platform.mNextWaypointIndex);
resync.ptUnexpectedLocation = platform.mPosition;
resync.qUnexpectedRotation = QuatUtils::IDENTITY;
if (platform.mPath != nullptr) {
const auto& from = platform.mPath->pathWaypoints[platform.mCurrentWaypointIndex].rotation;
const auto& to = platform.mPath->pathWaypoints[platform.mNextWaypointIndex].rotation;
resync.qUnexpectedRotation = from == to ? from : glm::slerp(from, to, resync.fPercentBetweenPoints);
}
return true;
}
void MovingPlatformComponent::SetSerialized(bool value) {
m_Serialize = value;
}
bool MovingPlatformComponent::GetNoAutoStart() const {
return m_NoAutoStart;
}
void MovingPlatformComponent::SetNoAutoStart(const bool value) {
m_NoAutoStart = value;
}
void MovingPlatformComponent::WarpToWaypoint(size_t index) {
for (size_t i = 0; i < m_SubComponents.size(); i++) PlatformWarpToWaypoint(*m_SubComponents[i], index);
}
void MovingPlatformComponent::PlatformWarpToWaypoint(PlatformSubComponent& platform, size_t index) {
if (platform.GetType() == eMoverSubComponentType::rotater || platform.mPath == nullptr) return;
const auto& waypoints = platform.mPath->pathWaypoints;
if (IsSimpleMover(platform)) {
// Either end: at its end it goes back from there
index = index == 0 ? 0 : 1;
platform.mInReverse = index == 1;
}
if (index >= waypoints.size()) return;
PlatformProcessStateChange(platform, static_cast<uint32_t>(index));
const bool atEnd = index == 0 || index == waypoints.size() - 1;
platform.mState = Stopped | ReachedDesiredWaypoint | (atEnd ? ReachedFinalDestination : 0);
ResetVelocities(platform);
m_Parent->SetPosition(waypoints[index].position);
m_Parent->SetRotation(waypoints[index].rotation);
SerializePlatform(platform);
}
size_t MovingPlatformComponent::GetLastWaypointIndex() const {
for (const auto& subComponent : m_SubComponents) {
if (subComponent->mPath != nullptr) return subComponent->mPath->pathWaypoints.size() - 1;
}
return 0;
}
PlatformSubComponent* MovingPlatformComponent::GetSubComponent(const eMoverSubComponentType type) const {
for (const auto& subComponent : m_SubComponents) {
if (subComponent->GetType() == type) return subComponent.get();
}
return nullptr;
}
PlatformSubComponent* MovingPlatformComponent::GetMoverSubComponent() const {
auto* const mover = GetSubComponent(eMoverSubComponentType::mover);
return mover != nullptr ? mover : GetSubComponent(eMoverSubComponentType::rotater);
}
SimpleMoverSubComponent* MovingPlatformComponent::GetSimpleMoverSubComponent() const {
return static_cast<SimpleMoverSubComponent*>(GetSubComponent(eMoverSubComponentType::simpleMover));
}
// The client's arrival messages: Arrived, then ArrivedAtDesiredWaypoint at the waypoint it was sent to, then
// PlatformAtLastWaypoint at the last waypoint of the path
void MovingPlatformComponent::FireArrivalHooks(const uint32_t index, const bool atDesiredWaypoint, const bool atLastWaypoint) {
auto* const script = m_Parent->GetScript();
script->OnWaypointReached(m_Parent, index);
if (atDesiredWaypoint) script->OnArrivedAtDesiredWaypoint(m_Parent, index);
if (atLastWaypoint) {
script->OnPlatformAtLastWaypoint(m_Parent);
// A callback may add another
const auto callbacks = m_AtLastWaypointCallbacks;
for (const auto& callback : callbacks) callback();
}
}
bool MovingPlatformComponent::FireDeparted(const uint32_t index) {
const auto generation = m_SetupGeneration;
m_Parent->GetScript()->OnDeparted(m_Parent, index);
return generation == m_SetupGeneration;
}
void MovingPlatformComponent::AddPlatformAtLastWaypointCallback(const std::function<void()>& callback) {
m_AtLastWaypointCallbacks.push_back(callback);
}
void MovingPlatformComponent::Allocator(Entity& entity, ObjectLoadState& state) {
const std::string pathName = entity.GetVarAsString(u"attached_path");
const Path* const path = Game::zoneManager->GetZone()->GetPath(pathName);
//Check to see if we have an attached path and add the appropiate component to handle it:
if (path) {
// if we have a moving platform path, then we need a moving platform component
if (path->pathType == PathType::MovingPlatform) {
// The registry component ID picks the subcomponent (a simple mover when it has one), path or not
entity.AddComponent<MovingPlatformComponent>(state.GetComponentID(eReplicaComponentType::MOVING_PLATFORM, -1), pathName);
} else if (path->pathType == PathType::Movement) {
auto* const movementAIcomponent = entity.GetComponent<MovementAIComponent>();
if (movementAIcomponent && state.GetComponentID(eReplicaComponentType::BASE_COMBAT_AI) == 0) {
movementAIcomponent->SetPath(pathName);
} else {
MovementAIInfo moveInfo{
.movementType = "",
.wanderRadius = 16,
.wanderSpeed = 2.5f,
.wanderChance = 0,
.wanderDelayMin = 2,
.wanderDelayMax = 5,
};
entity.AddComponent<MovementAIComponent>(-1, moveInfo);
}
}
} else {
// else we still need to setup moving platform if it has a moving platform comp but no path
const auto movingPlatformComponentID = state.GetComponentID(eReplicaComponentType::MOVING_PLATFORM, -1);
if (movingPlatformComponentID >= 0) {
entity.AddComponent<MovingPlatformComponent>(movingPlatformComponentID, pathName);
}
}
}