Skip to content

An OpenMW mod that lets you play the whole Elder Scrolls III: Morrowind as a top-down isometric game — with full online co-op or MMO modes.

C++

Companion and NPC following fixes

pw-tf1d94acfb9648
diff --git a/.gitignore b/.gitignore
index ff6da27..092ea2c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -39,6 +39,8 @@ resources
/*.cfg
/*.desktop
/*.install
+/mods
+/mod
## binaries
/esmtool
diff --git a/apps/openmw-mp/Script/Functions/Actors.cpp b/apps/openmw-mp/Script/Functions/Actors.cpp
index abe09d7..f64f6d0 100644
--- a/apps/openmw-mp/Script/Functions/Actors.cpp
+++ b/apps/openmw-mp/Script/Functions/Actors.cpp
@@ -202,6 +202,21 @@ int ActorFunctions::GetActorKillerPid(unsigned int index) noexcept
return -1;
}
+int ActorFunctions::GetActorAIAction(unsigned int index) noexcept
+{
+ return readActorList->baseActors.at(index).aiAction;
+}
+
+int ActorFunctions::GetActorAITargetPid(unsigned int index) noexcept
+{
+ const BaseActor& actor = readActorList->baseActors.at(index);
+ if (!actor.hasAiTarget || !actor.aiTarget.isPlayer)
+ return -1;
+
+ Player *player = Players::getPlayer(actor.aiTarget.guid);
+ return player != nullptr ? player->getId() : -1;
+}
+
const char *ActorFunctions::GetActorKillerRefId(unsigned int index) noexcept
{
return readActorList->baseActors.at(index).killer.refId.c_str();
diff --git a/apps/openmw-mp/Script/Functions/Actors.hpp b/apps/openmw-mp/Script/Functions/Actors.hpp
index 09f5381..b336f90 100644
--- a/apps/openmw-mp/Script/Functions/Actors.hpp
+++ b/apps/openmw-mp/Script/Functions/Actors.hpp
@@ -42,6 +42,8 @@
\
{"DoesActorHavePlayerKiller", ActorFunctions::DoesActorHavePlayerKiller},\
{"GetActorKillerPid", ActorFunctions::GetActorKillerPid},\
+ {"GetActorAIAction", ActorFunctions::GetActorAIAction},\
+ {"GetActorAITargetPid", ActorFunctions::GetActorAITargetPid},\
{"GetActorKillerRefId", ActorFunctions::GetActorKillerRefId},\
{"GetActorKillerRefNum", ActorFunctions::GetActorKillerRefNum},\
{"GetActorKillerMpNum", ActorFunctions::GetActorKillerMpNum},\
@@ -397,6 +399,24 @@ public:
*/
static int GetActorKillerPid(unsigned int index) noexcept;
+ /**
+ * rief Isowind: get the AI action of the actor at a certain index in the read actor list (an ID_ACTOR_AI
+ * packet's), as in enumerations.ai (CANCEL 0, ACTIVATE 1, COMBAT 2, ESCORT 3, FOLLOW 4, TRAVEL 5, WANDER 6).
+ *
+ * \param index The index of the actor.
+ * eturn The AI action.
+ */
+ static int GetActorAIAction(unsigned int index) noexcept;
+
+ /**
+ * rief Isowind: get the player ID of the target of the AI of the actor at a certain index in the read actor
+ * list (who it follows, escorts, fights or activates), if that is a player.
+ *
+ * \param index The index of the actor.
+ * eturn The player ID of the target, or -1 if the target isn't a player (or there is none).
+ */
+ static int GetActorAITargetPid(unsigned int index) noexcept;
+
/**
* \brief Get the refId of the actor killer of the actor at a certain index in the read actor list.
*
diff --git a/apps/openmw-mp/processors/ActorProcessor.hpp b/apps/openmw-mp/processors/ActorProcessor.hpp
index 03e6e7d..b4f4770 100644
--- a/apps/openmw-mp/processors/ActorProcessor.hpp
+++ b/apps/openmw-mp/processors/ActorProcessor.hpp
@@ -18,6 +18,19 @@ namespace mwmp
virtual void Do(ActorPacket &packet, Player &player, BaseActorList &actorList);
static bool Process(RakNet::Packet &packet, BaseActorList &actorList) noexcept;
+
+ // Isowind MMO: only the copies of the player's own followers (FOLLOWER_COPY_BASE), which their game moves
+ // whoever has authority over the cell
+ static bool isOwnFollowerCopies(Player &player, const BaseActorList &actorList)
+ {
+ const unsigned int first = FOLLOWER_COPY_BASE + player.getId() * FOLLOWER_COPIES_PER_PLAYER;
+ if (actorList.baseActors.empty())
+ return false;
+ for (const auto &actor : actorList.baseActors)
+ if (actor.refNum != 0 || actor.mpNum < first || actor.mpNum >= first + FOLLOWER_COPIES_PER_PLAYER)
+ return false;
+ return true;
+ }
};
}
diff --git a/apps/openmw-mp/processors/actor/ProcessorActorAnimFlags.hpp b/apps/openmw-mp/processors/actor/ProcessorActorAnimFlags.hpp
index 7a9441a..4b2eff2 100644
--- a/apps/openmw-mp/processors/actor/ProcessorActorAnimFlags.hpp
+++ b/apps/openmw-mp/processors/actor/ProcessorActorAnimFlags.hpp
@@ -18,7 +18,8 @@ namespace mwmp
// Send only to players who have the cell loaded
Cell *serverCell = CellController::get()->getCell(&actorList.cell);
- if (serverCell != nullptr && *serverCell->getAuthority() == actorList.guid)
+ if (serverCell != nullptr
+ && (*serverCell->getAuthority() == actorList.guid || isOwnFollowerCopies(player, actorList)))
serverCell->sendToLoaded(&packet, &actorList);
}
};
diff --git a/apps/openmw-mp/processors/actor/ProcessorActorAnimPlay.hpp b/apps/openmw-mp/processors/actor/ProcessorActorAnimPlay.hpp
index 445ee8e..06d298e 100644
--- a/apps/openmw-mp/processors/actor/ProcessorActorAnimPlay.hpp
+++ b/apps/openmw-mp/processors/actor/ProcessorActorAnimPlay.hpp
@@ -18,7 +18,8 @@ namespace mwmp
// Send only to players who have the cell loaded
Cell *serverCell = CellController::get()->getCell(&actorList.cell);
- if (serverCell != nullptr && *serverCell->getAuthority() == actorList.guid)
+ if (serverCell != nullptr
+ && (*serverCell->getAuthority() == actorList.guid || isOwnFollowerCopies(player, actorList)))
serverCell->sendToLoaded(&packet, &actorList);
}
};
diff --git a/apps/openmw-mp/processors/actor/ProcessorActorAttack.hpp b/apps/openmw-mp/processors/actor/ProcessorActorAttack.hpp
index 9da7271..70376b8 100644
--- a/apps/openmw-mp/processors/actor/ProcessorActorAttack.hpp
+++ b/apps/openmw-mp/processors/actor/ProcessorActorAttack.hpp
@@ -18,7 +18,8 @@ namespace mwmp
// Send only to players who have the cell loaded
Cell *serverCell = CellController::get()->getCell(&actorList.cell);
- if (serverCell != nullptr && *serverCell->getAuthority() == actorList.guid)
+ if (serverCell != nullptr
+ && (*serverCell->getAuthority() == actorList.guid || isOwnFollowerCopies(player, actorList)))
serverCell->sendToLoaded(&packet, &actorList);
}
};
diff --git a/apps/openmw-mp/processors/actor/ProcessorActorCast.hpp b/apps/openmw-mp/processors/actor/ProcessorActorCast.hpp
index 864135f..2fe4882 100644
--- a/apps/openmw-mp/processors/actor/ProcessorActorCast.hpp
+++ b/apps/openmw-mp/processors/actor/ProcessorActorCast.hpp
@@ -18,7 +18,8 @@ namespace mwmp
// Send only to players who have the cell loaded
Cell *serverCell = CellController::get()->getCell(&actorList.cell);
- if (serverCell != nullptr && *serverCell->getAuthority() == actorList.guid)
+ if (serverCell != nullptr
+ && (*serverCell->getAuthority() == actorList.guid || isOwnFollowerCopies(player, actorList)))
serverCell->sendToLoaded(&packet, &actorList);
}
};
diff --git a/apps/openmw-mp/processors/actor/ProcessorActorPosition.hpp b/apps/openmw-mp/processors/actor/ProcessorActorPosition.hpp
index 05133b4..15bebdf 100644
--- a/apps/openmw-mp/processors/actor/ProcessorActorPosition.hpp
+++ b/apps/openmw-mp/processors/actor/ProcessorActorPosition.hpp
@@ -18,7 +18,8 @@ namespace mwmp
// Send only to players who have the cell loaded
Cell *serverCell = CellController::get()->getCell(&actorList.cell);
- if (serverCell != nullptr && *serverCell->getAuthority() == actorList.guid)
+ if (serverCell != nullptr
+ && (*serverCell->getAuthority() == actorList.guid || isOwnFollowerCopies(player, actorList)))
{
serverCell->readActorList(packetID, &actorList);
serverCell->sendToLoaded(&packet, &actorList);
diff --git a/apps/openmw-mp/processors/actor/ProcessorActorSpeech.hpp b/apps/openmw-mp/processors/actor/ProcessorActorSpeech.hpp
index f5de44f..8e743cf 100644
--- a/apps/openmw-mp/processors/actor/ProcessorActorSpeech.hpp
+++ b/apps/openmw-mp/processors/actor/ProcessorActorSpeech.hpp
@@ -18,7 +18,8 @@ namespace mwmp
// Send only to players who have the cell loaded
Cell *serverCell = CellController::get()->getCell(&actorList.cell);
- if (serverCell != nullptr && *serverCell->getAuthority() == actorList.guid)
+ if (serverCell != nullptr
+ && (*serverCell->getAuthority() == actorList.guid || isOwnFollowerCopies(player, actorList)))
serverCell->sendToLoaded(&packet, &actorList);
}
};
diff --git a/apps/openmw/mwclass/creature.cpp b/apps/openmw/mwclass/creature.cpp
index 25d7e70..71a2104 100644
--- a/apps/openmw/mwclass/creature.cpp
+++ b/apps/openmw/mwclass/creature.cpp
@@ -360,6 +360,27 @@ namespace MWClass
void Creature::onHit(const MWWorld::Ptr& ptr, const std::map<std::string, float>& damages, ESM::RefId object,
const MWWorld::Ptr& attacker, bool successful, const MWMechanics::DamageSourceType sourceType) const
{
+ // Isowind multiplayer: as for Npc::onHit (here, someone's follower as this game shows it)
+ if (mwmp::hooks::isPvpBlocked(attacker, ptr))
+ {
+ if (sourceType != MWMechanics::DamageSourceType::Magical)
+ mwmp::hooks::finishLocalHit(attacker, ptr, 0.f, false);
+ return;
+ }
+
+ // Isowind MMO: someone's follower as this game shows it takes no hits here: a local attacker's hit goes to its
+ // owner's game (MechanicsHelper::getTargetPtr), where the follower is
+ if (mwmp::hooks::isFollowerCopy(ptr))
+ {
+ if (sourceType != MWMechanics::DamageSourceType::Magical)
+ {
+ const auto health = damages.find("health");
+ mwmp::hooks::finishLocalHit(attacker, ptr,
+ successful && health != damages.end() ? health->second : 0.f, successful);
+ }
+ return;
+ }
+
MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
// Self defense
@@ -475,6 +496,15 @@ namespace MWClass
std::unique_ptr<MWWorld::Action> Creature::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
+ // Isowind MMO: someone's follower as this game shows it (a pack guar's packs are its owner's; a party member's
+ // comes over to this player's game, the server decides)
+ if (mwmp::hooks::isFollowerCopy(ptr))
+ {
+ if (actor == MWMechanics::getPlayer())
+ mwmp::hooks::requestFollowerCopy(ptr);
+ return std::make_unique<MWWorld::FailedAction>();
+ }
+
if (actor.getClass().isNpc() && actor.getClass().getNpcStats(actor).isWerewolf())
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
diff --git a/apps/openmw/mwclass/npc.cpp b/apps/openmw/mwclass/npc.cpp
index d07336e..c4ac600 100644
--- a/apps/openmw/mwclass/npc.cpp
+++ b/apps/openmw/mwclass/npc.cpp
@@ -727,6 +727,19 @@ namespace MWClass
return;
}
+ // Isowind MMO: someone's follower as this game shows it takes no hits here: a local attacker's hit goes to its
+ // owner's game (MechanicsHelper::getTargetPtr), where the follower is
+ if (mwmp::hooks::isFollowerCopy(ptr))
+ {
+ if (sourceType != MWMechanics::DamageSourceType::Magical)
+ {
+ const auto health = damages.find("health");
+ mwmp::hooks::finishLocalHit(attacker, ptr,
+ successful && health != damages.end() ? health->second : 0.f, successful);
+ }
+ return;
+ }
+
MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
bool wasDead = stats.isDead();
@@ -870,9 +883,16 @@ namespace MWClass
{
if (mwmp::hooks::isMultiplayer())
{
- // Isowind multiplayer: no dialogue between two players
+ // Isowind multiplayer: no dialogue between two players, nor with someone's follower as this game shows it
if (actor == MWMechanics::getPlayer() && mwmp::hooks::isDedicatedPlayer(ptr))
return std::make_unique<MWWorld::FailedAction>();
+ if (mwmp::hooks::isFollowerCopy(ptr))
+ {
+ // (a party member's comes over to this player's game, where it's talked to: the server decides)
+ if (actor == MWMechanics::getPlayer())
+ mwmp::hooks::requestFollowerCopy(ptr);
+ return std::make_unique<MWWorld::FailedAction>();
+ }
// nor for NPCs activating each other (the dialogue would open for the local player)
if (ptr != MWMechanics::getPlayer() && actor != MWMechanics::getPlayer())
return std::make_unique<MWWorld::FailedAction>();
diff --git a/apps/openmw/mwmp/ActorList.cpp b/apps/openmw/mwmp/ActorList.cpp
index 9d89e3a..db3dc9b 100644
--- a/apps/openmw/mwmp/ActorList.cpp
+++ b/apps/openmw/mwmp/ActorList.cpp
@@ -98,6 +98,7 @@ void ActorList::addAiActor(const MWWorld::Ptr& actorPtr, const MWWorld::Ptr& tar
baseActor.refNum = actorPtr.getCellRef().getMpRefNum();
baseActor.mpNum = actorPtr.getCellRef().getMpNum();
baseActor.aiAction = aiAction;
+ baseActor.hasAiTarget = true;
baseActor.aiTarget = MechanicsHelper::getTarget(targetPtr);
LOG_MESSAGE_SIMPLE(TimedLog::LOG_INFO, "Preparing to send ID_ACTOR_AI about %s %i-%i\n- action: %i",
@@ -265,8 +266,9 @@ void ActorList::sendActorsInCell(MWWorld::CellStore* cellStore)
if (ptr.getCellRef().getMpRefNum() == 0 && ptr.getCellRef().getMpNum() == 0)
return true;
- // Isowind MMO: nor one this client runs for itself only (a one-off event's)
- if (Main::get().getCellController()->isClientLocalActor(ptr))
+ // Isowind MMO: nor one this client runs for itself only (a one-off event's), nor someone's follower as
+ // this game shows it
+ if (Main::get().getCellController()->isClientLocalActor(ptr) || MechanicsHelper::isFollowerCopy(ptr))
return true;
BaseActor actor;
diff --git a/apps/openmw/mwmp/Cell.cpp b/apps/openmw/mwmp/Cell.cpp
index 5892ff4..4e9fe30 100644
--- a/apps/openmw/mwmp/Cell.cpp
+++ b/apps/openmw/mwmp/Cell.cpp
@@ -125,7 +125,7 @@ void Cell::updateDedicated(float dt)
// Are we the authority over this cell? If so, uninitialize DedicatedActors
// after the above update
if (hasLocalAuthority())
- uninitializeDedicatedActors();
+ uninitializeDedicatedActors(true);
}
void Cell::readPositions(ActorList& actorList)
@@ -480,8 +480,9 @@ void Cell::readCellChange(ActorList& actorList)
void Cell::initializeLocalActor(const MWWorld::Ptr& ptr)
{
- // Isowind MMO: one this client runs for itself only (a one-off event's), not for the others
- if (Main::get().getCellController()->isClientLocalActor(ptr))
+ // Isowind MMO: one this client runs for itself only (a one-off event's), not for the others, nor someone's
+ // follower as this game shows it (moved by its owner's game)
+ if (Main::get().getCellController()->isClientLocalActor(ptr) || MechanicsHelper::isFollowerCopy(ptr))
return;
std::string mapIndex = Main::get().getCellController()->generateMapIndex(ptr);
@@ -538,6 +539,8 @@ void Cell::initializeDedicatedActor(const MWWorld::Ptr& ptr)
DedicatedActor *actor = new DedicatedActor();
actor->cell = store->getCell()->getEsm3();
actor->setPtr(ptr);
+ // Standing where it is (setPtr) until its movement comes
+ actor->direction = ESM::Position();
dedicatedActors[mapIndex] = actor;
@@ -556,7 +559,10 @@ void Cell::initializeDedicatedActors(ActorList& actorList)
if (dedicatedActors.count(mapIndex) == 0
&& !Main::get().getCellController()->isClientLocalActor(baseActor.refNum, baseActor.mpNum))
{
- MWWorld::Ptr ptrFound = store->searchExact(baseActor.refNum, baseActor.mpNum, refId(baseActor.refId), true);
+ // (Isowind MMO: someone's follower as this game shows it, made or brought here as it comes)
+ MWWorld::Ptr ptrFound = baseActor.mpNum >= FOLLOWER_COPY_BASE
+ ? MechanicsHelper::getFollowerCopy(store, baseActor.mpNum)
+ : store->searchExact(baseActor.refNum, baseActor.mpNum, refId(baseActor.refId), true);
if (ptrFound.isEmpty()) continue;
@@ -583,7 +589,7 @@ void Cell::uninitializeDedicatedActors(ActorList& actorList)
std::string mapIndex = Main::get().getCellController()->generateMapIndex(baseActor);
// (none for the actors this client runs itself)
auto it = dedicatedActors.find(mapIndex);
- if (it == dedicatedActors.end())
+ if (it == dedicatedActors.end() || baseActor.mpNum >= FOLLOWER_COPY_BASE)
continue;
Main::get().getCellController()->removeDedicatedActorRecord(mapIndex);
delete it->second;
@@ -591,15 +597,19 @@ void Cell::uninitializeDedicatedActors(ActorList& actorList)
}
}
-void Cell::uninitializeDedicatedActors()
+void Cell::uninitializeDedicatedActors(bool keepFollowerCopies)
{
- for (const auto &actor : dedicatedActors)
+ for (auto it = dedicatedActors.begin(); it != dedicatedActors.end();)
{
- Main::get().getCellController()->removeDedicatedActorRecord(actor.first);
- delete actor.second;
+ if (keepFollowerCopies && it->second->mpNum >= FOLLOWER_COPY_BASE)
+ {
+ ++it;
+ continue;
+ }
+ Main::get().getCellController()->removeDedicatedActorRecord(it->first);
+ delete it->second;
+ it = dedicatedActors.erase(it);
}
-
- dedicatedActors.clear();
}
LocalActor *Cell::getLocalActor(std::string actorIndex)
diff --git a/apps/openmw/mwmp/Cell.hpp b/apps/openmw/mwmp/Cell.hpp
index 8bf432e..e590c2d 100644
--- a/apps/openmw/mwmp/Cell.hpp
+++ b/apps/openmw/mwmp/Cell.hpp
@@ -38,8 +38,10 @@ namespace mwmp
void initializeDedicatedActors(ActorList& actorList);
void uninitializeLocalActors();
+ /// (Under this client's authority: they're LocalActors here. Not someone's follower as this game shows it,
+ /// which only its owner's game moves, whoever has authority)
void uninitializeDedicatedActors(ActorList& actorList);
- void uninitializeDedicatedActors();
+ void uninitializeDedicatedActors(bool keepFollowerCopies = false);
virtual LocalActor *getLocalActor(std::string actorIndex);
virtual DedicatedActor *getDedicatedActor(std::string actorIndex);
diff --git a/apps/openmw/mwmp/CellController.cpp b/apps/openmw/mwmp/CellController.cpp
index 538b7eb..924c0c0 100644
--- a/apps/openmw/mwmp/CellController.cpp
+++ b/apps/openmw/mwmp/CellController.cpp
@@ -392,6 +392,13 @@ void CellController::setClientLocalActor(int refNum, int mpNum)
TimedLog::LOG_INFO, "Running actor %s here, whoever has authority over its cell", actorIndex.c_str());
// No longer sent about as a LocalActor, or moved by what another client sends as a DedicatedActor
+ forgetActor(refNum, mpNum);
+}
+
+void CellController::forgetActor(int refNum, int mpNum)
+{
+ std::string actorIndex = generateMapIndex(refNum, mpNum);
+
auto localIt = localActorsToCells.find(actorIndex);
if (localIt != localActorsToCells.end())
{
diff --git a/apps/openmw/mwmp/CellController.hpp b/apps/openmw/mwmp/CellController.hpp
index 48ed901..38a8edf 100644
--- a/apps/openmw/mwmp/CellController.hpp
+++ b/apps/openmw/mwmp/CellController.hpp
@@ -63,6 +63,8 @@ namespace mwmp
// them and ignoring what others send (a one-off event's people, each player's own: "isowind local" from the
// server, see MechanicsHelper::runClientLocalCommand). They stay so for the session.
void setClientLocalActor(int refNum, int mpNum);
+ /// No longer a LocalActor or DedicatedActor here (it's gone, or now run otherwise)
+ void forgetActor(int refNum, int mpNum);
bool isClientLocalActor(const MWWorld::Ptr& ptr);
bool isClientLocalActor(int refNum, int mpNum);
diff --git a/apps/openmw/mwmp/Hooks.cpp b/apps/openmw/mwmp/Hooks.cpp
index a7b7f11..8320e3c 100644
--- a/apps/openmw/mwmp/Hooks.cpp
+++ b/apps/openmw/mwmp/Hooks.cpp
@@ -1,5 +1,7 @@
#include "Hooks.hpp"
+#include <algorithm>
+
#include <components/esm/util.hpp>
#include "../mwbase/environment.hpp"
@@ -299,6 +301,9 @@ namespace mwmp::hooks
cellController->getDedicatedActor(oldPtr)->setPtr(newPtr);
else if (DedicatedPlayer* player = PlayerList::getPlayer(oldPtr))
player->setPtr(newPtr);
+ // Isowind MMO: this player's own followers (what the others see of them goes with them)
+ else if (MechanicsHelper::isPrivateFollower(newPtr))
+ MechanicsHelper::onPrivateFollowerMoved(newPtr);
}
ServerChange::ServerChange()
@@ -587,8 +592,13 @@ namespace mwmp::hooks
bool isPvpBlocked(const MWWorld::Ptr& attacker, const MWWorld::Ptr& victim)
{
- return isMultiplayer() && !sPvp && !attacker.isEmpty() && !victim.isEmpty() && attacker != victim
- && isPlayer(attacker) && isPlayer(victim);
+ if (!isMultiplayer() || attacker.isEmpty() || victim.isEmpty() || attacker == victim || !isPlayer(attacker))
+ return false;
+ // Isowind MMO: someone's follower as this game shows it can't be hurt by a player (the real one is in its
+ // owner's game)
+ if (MechanicsHelper::isFollowerCopy(victim))
+ return true;
+ return !sPvp && isPlayer(victim);
}
bool isMmoMode()
@@ -596,6 +606,17 @@ namespace mwmp::hooks
return isMultiplayer() && sMmo;
}
+ bool isFollowerCopy(const MWWorld::Ptr& ptr)
+ {
+ return isMultiplayer() && MechanicsHelper::isFollowerCopy(ptr);
+ }
+
+ void requestFollowerCopy(const MWWorld::Ptr& ptr)
+ {
+ if (isMultiplayer())
+ MechanicsHelper::requestFollowerCopy(ptr);
+ }
+
void sendSummonRemoval(const MWWorld::Ptr& creature)
{
if (!isLoggedIn() || creature.isEmpty())
@@ -1194,6 +1215,31 @@ namespace mwmp::hooks
actorList->sendAiActors();
}
+ void sendScriptEscort(const MWWorld::Ptr& actor, const MWWorld::Ptr& target, int duration, float x, float y, float z)
+ {
+ if (!isLoggedIn() || actor.isEmpty() || target.isEmpty() || !actor.isInCell()
+ || actor.getCell()->getCell()->isEsm4())
+ return;
+ // Isowind MMO: as for sendScriptAi
+ if (Main::get().getCellController()->isClientLocalActor(actor))
+ return;
+ ActorList* actorList = Main::get().getNetworking()->getActorList();
+ actorList->reset();
+ actorList->cell = actor.getCell()->getCell()->getEsm3();
+ BaseActor escort;
+ escort.refNum = actor.getCellRef().getMpRefNum();
+ escort.mpNum = actor.getCellRef().getMpNum();
+ escort.aiAction = BaseActorList::ESCORT;
+ escort.hasAiTarget = true;
+ escort.aiTarget = MechanicsHelper::getTarget(target);
+ escort.aiDuration = static_cast<unsigned int>(std::max(duration, 0));
+ escort.aiCoordinates.pos[0] = x;
+ escort.aiCoordinates.pos[1] = y;
+ escort.aiCoordinates.pos[2] = z;
+ actorList->addAiActor(escort);
+ actorList->sendAiActors();
+ }
+
void sendScriptAnimation(const Interpreter::Context& context, const MWWorld::Ptr& ptr, const std::string& group,
int mode)
{
diff --git a/apps/openmw/mwmp/Hooks.hpp b/apps/openmw/mwmp/Hooks.hpp
index 98ee59c..681cbb7 100644
--- a/apps/openmw/mwmp/Hooks.hpp
+++ b/apps/openmw/mwmp/Hooks.hpp
@@ -166,9 +166,14 @@ namespace mwmp::hooks
/// for other settings
bool applyServerRule(const std::string& name, const std::string& value);
/// Whether this is a hit or harmful spell from one player on another while the server has PvP off
+ /// (Also true for a player's hits on someone's follower as this game shows it, PvP or not)
bool isPvpBlocked(const MWWorld::Ptr& attacker, const MWWorld::Ptr& victim);
/// Whether the server is in MMO mode (everyone loots and quests for themselves)
bool isMmoMode();
+ /// Isowind MMO: someone's follower as this game shows it (a look-alike, moved by its owner's game)
+ bool isFollowerCopy(const MWWorld::Ptr& ptr);
+ /// The local player used one: the server may hand the follower over (a party member's)
+ void requestFollowerCopy(const MWWorld::Ptr& ptr);
/// A summoned creature going away: the server removes it for everyone, when this client is the one to say so
void sendSummonRemoval(const MWWorld::Ptr& creature);
@@ -268,6 +273,8 @@ namespace mwmp::hooks
/// AI given by scripts (combat with the player, following, StartCombat): the client with authority over the actor
/// is told, through the server. aiAction: mwmp::BaseActorList::COMBAT or FOLLOW
void sendScriptAi(const MWWorld::Ptr& actor, const MWWorld::Ptr& target, int aiAction);
+ /// AiEscort / AiEscortCell: the actor leads the target to a place, as for sendScriptAi
+ void sendScriptEscort(const MWWorld::Ptr& actor, const MWWorld::Ptr& target, int duration, float x, float y, float z);
/// PlayGroup on an object, by a script the server hears from: other clients play it too
void sendScriptAnimation(const Interpreter::Context& context, const MWWorld::Ptr& ptr, const std::string& group,
int mode);
diff --git a/apps/openmw/mwmp/LocalActor.cpp b/apps/openmw/mwmp/LocalActor.cpp
index 0793d6c..65f1c57 100644
--- a/apps/openmw/mwmp/LocalActor.cpp
+++ b/apps/openmw/mwmp/LocalActor.cpp
@@ -58,8 +58,11 @@ LocalActor::~LocalActor()
void LocalActor::update(bool forceUpdate)
{
- updateStatsDynamic(forceUpdate);
- updateEquipment(forceUpdate, false);
+ if (!isFollowerCopy)
+ {
+ updateStatsDynamic(forceUpdate);
+ updateEquipment(forceUpdate, false);
+ }
if (forceUpdate || !creatureStats.mDeathAnimationFinished)
{
diff --git a/apps/openmw/mwmp/LocalActor.hpp b/apps/openmw/mwmp/LocalActor.hpp
index 271cd10..8ee67ef 100644
--- a/apps/openmw/mwmp/LocalActor.hpp
+++ b/apps/openmw/mwmp/LocalActor.hpp
@@ -36,6 +36,9 @@ namespace mwmp
void setPtr(const MWWorld::Ptr& newPtr);
bool hasSentData;
+ // Isowind MMO: the copy of this player's own follower that the others see (MechanicsHelper's): only how it
+ // moves, attacks and casts
+ bool isFollowerCopy = false;
private:
MWWorld::Ptr ptr;
diff --git a/apps/openmw/mwmp/Main.cpp b/apps/openmw/mwmp/Main.cpp
index cd23f4a..c26dd4c 100644
--- a/apps/openmw/mwmp/Main.cpp
+++ b/apps/openmw/mwmp/Main.cpp
@@ -176,6 +176,7 @@ void Main::updateWorld(float dt) const
{
mLocalPlayer->update();
mCellController->updateLocal(false);
+ MechanicsHelper::updatePrivateFollowers(dt);
}
}
diff --git a/apps/openmw/mwmp/MechanicsHelper.cpp b/apps/openmw/mwmp/MechanicsHelper.cpp
index b82c6d5..6f622a4 100644
--- a/apps/openmw/mwmp/MechanicsHelper.cpp
+++ b/apps/openmw/mwmp/MechanicsHelper.cpp
@@ -1,4 +1,7 @@
+#include <cstdio>
#include <locale>
+#include <map>
+#include <memory>
#include <sstream>
#include <components/openmw-mp/TimedLog.hpp>
@@ -24,6 +27,8 @@
#include "../mwmechanics/activespells.hpp"
#include "../mwmechanics/actorutil.hpp"
+#include "../mwmechanics/aifollow.hpp"
+#include "../mwmechanics/aisequence.hpp"
#include "../mwmechanics/combat.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/damagesourcetype.hpp"
@@ -37,6 +42,7 @@
#include "../mwworld/esmstore.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/manualref.hpp"
+#include "../mwworld/worldmodel.hpp"
#include "MechanicsHelper.hpp"
#include "Main.hpp"
@@ -47,6 +53,7 @@
#include "ObjectList.hpp"
#include "CellController.hpp"
#include "Ids.hpp"
+#include "LocalActor.hpp"
using namespace mwmp;
@@ -158,6 +165,9 @@ bool MechanicsHelper::respawnActor(const MWWorld::Ptr& ptr)
bool MechanicsHelper::runClientLocalCommand(const std::string& command, MWWorld::CellStore* cellStore,
unsigned int refNum, unsigned int mpNum, const std::string& refIdString)
{
+ if (runPrivateFollowerCommand(command, cellStore, refNum, mpNum, refIdString))
+ return true;
+
static const std::string deadPrefix = "isowind local dead ";
const bool dead = command.rfind(deadPrefix, 0) == 0;
if (command != "isowind local" && !dead)
@@ -228,6 +238,9 @@ void MechanicsHelper::sendClientLocalDeath(const MWWorld::Ptr& actor)
{
if (!mwmp::hooks::isLoggedIn() || actor.isEmpty() || !actor.isInCell() || actor.getCell()->getCell()->isEsm4())
return;
+ // (A private follower's death is told with the rest about it: updatePrivateFollowers)
+ if (isPrivateFollower(actor))
+ return;
LOG_MESSAGE_SIMPLE(TimedLog::LOG_INFO, "Sending the death of %s %i-%i, which this client runs itself",
idString(actor.getCellRef().getRefId()).c_str(), actor.getCellRef().getMpRefNum(),
@@ -252,6 +265,577 @@ void MechanicsHelper::sendClientLocalDeath(const MWWorld::Ptr& actor)
objectList->sendClientScriptLocal();
}
+namespace
+{
+ enum PrivateFollowerState
+ {
+ FOLLOWING = 1,
+ STAYING = 2,
+ DEAD = 3,
+ // (asked of the server about someone's follower as this game shows it: requestFollowerCopy)
+ WANTED = 4
+ };
+
+ // Where each private follower was last found, what the server was last told of it, and what's sent about it as
+ // the others' copy of it while it follows
+ struct PrivateFollower
+ {
+ unsigned int refNum = 0;
+ unsigned int mpNum = 0;
+ ESM::RefId refId;
+ MWWorld::CellStore* cell = nullptr;
+ int reportedState = 0;
+ MWWorld::CellStore* reportedCell = nullptr;
+ osg::Vec3f reportedPosition;
+ unsigned int copyMpNum = 0;
+ std::unique_ptr<LocalActor> mirror;
+ // Gone to another member of the player's party ("isowind release"): out of this game, kept for if it comes
+ // back
+ bool released = false;
+ };
+
+ std::map<std::string, PrivateFollower> privateFollowers;
+ float privateFollowerTimer = 0.f;
+ float mirrorTimer = 0.f;
+
+ // The others' followers as this game shows them, by their mpNum: who they look like, and where the server last
+ // said they were (cell: where the look-alike is, once made)
+ struct FollowerCopy
+ {
+ ESM::RefId originalId;
+ ESM::Position position;
+ MWWorld::CellStore* cell = nullptr;
+ };
+
+ std::map<unsigned int, FollowerCopy> followerCopies;
+ // The look-alikes' records, one for each actor they look like: the same but with no script (so nothing a quest
+ // does by the actor's id happens to them)
+ std::map<ESM::RefId, ESM::RefId> copyRecords;
+
+ std::string followerIndex(unsigned int refNum, unsigned int mpNum)
+ {
+ return Main::get().getCellController()->generateMapIndex(refNum, mpNum);
+ }
+
+ // Where it was last found, else in the cells around the player (it walked or went through a door with them)
+ MWWorld::Ptr findPrivateFollower(PrivateFollower& follower)
+ {
+ MWWorld::Ptr ptr = follower.cell->searchExact(follower.refNum, follower.mpNum, follower.refId, true);
+ if (ptr.isEmpty())
+ {
+ for (MWWorld::CellStore* cell : MWBase::Environment::get().getWorldScene()->getActiveCells())
+ {
+ ptr = cell->searchExact(follower.refNum, follower.mpNum, follower.refId, true);
+ if (!ptr.isEmpty())
+ break;
+ }
+ }
+ if (!ptr.isEmpty())
+ follower.cell = ptr.getCell();
+ return ptr;
+ }
+
+ // As the game counts a follower (MWMechanics::Actors::getActorsFollowing): following the player, with only
+ // fighting or wandering before that
+ bool isFollowingPlayer(const MWWorld::Ptr& ptr)
+ {
+ const MWWorld::Ptr player = MWMechanics::getPlayer();
+ for (const auto& package : ptr.getClass().getCreatureStats(ptr).getAiSequence())
+ {
+ if (package->followTargetThroughDoors() && package->targetIs(player))
+ return true;
+ if (package->getTypeId() != MWMechanics::AiPackageTypeId::Combat
+ && package->getTypeId() != MWMechanics::AiPackageTypeId::Wander)
+ return false;
+ }
+ return false;
+ }
+
+ // What's sent about a private follower as its copy, while it follows (its attacks and casts go with it)
+ LocalActor* getMirror(const MWWorld::Ptr& ptr)
+ {
+ if (privateFollowers.empty() || ptr.isEmpty() || ptr.mRef == nullptr)
+ return nullptr;
+ auto found
+ = privateFollowers.find(followerIndex(ptr.getCellRef().getMpRefNum(), ptr.getCellRef().getMpNum()));
+ return found != privateFollowers.end() ? found->second.mirror.get() : nullptr;
+ }
+
+ void followPlayer(const MWWorld::Ptr& ptr)
+ {
+ MWMechanics::AiFollow package(MWMechanics::getPlayer());
+ package.allowAnyDistance(true);
+ ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(package, ptr);
+ }
+
+ // What's sent about the follower goes as about its copy
+ void setMirrorPtr(PrivateFollower& follower, const MWWorld::Ptr& ptr)
+ {
+ follower.mirror->setPtr(ptr);
+ follower.mirror->refNum = 0;
+ follower.mirror->mpNum = follower.copyMpNum;
+ follower.mirror->cell = ptr.getCell()->getCell()->getEsm3();
+ }
+
+ // A cell as the server describes it: "<x>, <y>" outdoors, its name indoors
+ MWWorld::CellStore* getCellStoreFromDescription(const std::string& description)
+ {
+ MWWorld::WorldModel* worldModel = MWBase::Environment::get().getWorldModel();
+ int x = 0;
+ int y = 0;
+ int length = 0;
+ if (std::sscanf(description.c_str(), "%d, %d%n", &x, &y, &length) == 2
+ && length == static_cast<int>(description.size()))
+ return &worldModel->getExterior(ESM::ExteriorCellLocation(x, y, ESM::Cell::sDefaultWorldspaceId));
+ try
+ {
+ return worldModel->findInterior(description);
+ }
+ catch (std::exception&)
+ {
+ return nullptr;
+ }
+ }
+
+ // A command's words after its name, or false if it isn't that command
+ bool takeCommand(const std::string& command, const std::string& name, std::string& rest)
+ {
+ if (command == name)
+ {
+ rest.clear();
+ return true;
+ }
+ if (command.rfind(name + " ", 0) != 0)
+ return false;
+ rest = command.substr(name.size() + 1);
+ return true;
+ }
+
+ void sendPrivateFollower(const MWWorld::Ptr& ptr, int state)
+ {
+ const osg::Vec3f position = ptr.getRefData().getPosition().asVec3();
+ ObjectList* objectList = Main::get().getNetworking()->getObjectList();
+ objectList->reset();
+ objectList->packetOrigin = CLIENT_GAMEPLAY;
+ objectList->cell = ptr.getCell()->getCell()->getEsm3();
+ BaseObject baseObject = objectList->getBaseObjectFromPtr(ptr);
+ for (int i = 0; i < 3; ++i)
+ {
+ ClientVariable place;
+ place.internalIndex = i;
+ place.variableType = VARIABLE_TYPE::FLOAT;
+ place.intValue = 0;
+ place.floatValue = position[i];
+ baseObject.clientLocals.push_back(place);
+ }
+ ClientVariable stateVariable;
+ stateVariable.internalIndex = 0;
+ stateVariable.variableType = VARIABLE_TYPE::SHORT;
+ stateVariable.intValue = state;
+ stateVariable.floatValue = 0.f;
+ baseObject.clientLocals.push_back(stateVariable);
+ objectList->addBaseObject(baseObject);
+ objectList->sendClientScriptLocal();
+ }
+
+ ESM::RefId getCopyRecord(const ESM::RefId& originalId)
+ {
+ auto found = copyRecords.find(originalId);
+ if (found != copyRecords.end())
+ return found->second;
+ MWWorld::ESMStore& store = MWBase::Environment::get().getWorld()->getStore();
+ ESM::RefId recordId;
+ if (const ESM::NPC* npc = store.get<ESM::NPC>().search(originalId))
+ {
+ ESM::NPC record = *npc;
+ record.mScript = ESM::RefId();
+ recordId = store.insert(record)->mId;
+ }
+ else if (const ESM::Creature* creature = store.get<ESM::Creature>().search(originalId))
+ {
+ ESM::Creature record = *creature;
+ record.mScript = ESM::RefId();
+ recordId = store.insert(record)->mId;
+ }
+ copyRecords[originalId] = recordId;
+ return recordId;
+ }
+
+ MWWorld::Ptr findFollowerCopy(unsigned int mpNum, FollowerCopy& copy)
+ {
+ if (copy.cell == nullptr)
+ return {};
+ MWWorld::Ptr ptr = copy.cell->searchExact(0, mpNum, {}, true);
+ if (ptr.isEmpty())
+ copy.cell = nullptr;
+ return ptr;
+ }
+
+ void removeFollowerCopy(unsigned int mpNum, FollowerCopy& copy)
+ {
+ MWWorld::Ptr ptr = findFollowerCopy(mpNum, copy);
+ Main::get().getCellController()->forgetActor(0, mpNum);
+ if (!ptr.isEmpty())
+ MWBase::Environment::get().getWorld()->deleteObject(ptr);
+ copy.cell = nullptr;
+ }
+
+ // The look-alike in a cell in use here: made, or brought over from the cell it was in
+ MWWorld::Ptr placeFollowerCopy(
+ unsigned int mpNum, FollowerCopy& copy, MWWorld::CellStore* store, const ESM::Position& position)
+ {
+ MWBase::World* world = MWBase::Environment::get().getWorld();
+ MWWorld::Ptr ptr = findFollowerCopy(mpNum, copy);
+ if (!ptr.isEmpty())
+ {
+ if (ptr.getCell() == store)
+ return ptr;
+ Main::get().getCellController()->forgetActor(0, mpNum);
+ ptr = world->moveObject(ptr, store, position.asVec3());
+ copy.cell = ptr.getCell();
+ return ptr;
+ }
+
+ const ESM::RefId recordId = getCopyRecord(copy.originalId);
+ if (recordId.empty())
+ return {};
+ MWWorld::ManualRef manualRef(world->getStore(), recordId);
+ manualRef.getPtr().getCellRef().setMpNum(mpNum);
+ ptr = world->placeObject(manualRef.getPtr(), store, position);
+ // Moved only by what its owner's game sends, not by AI of its own here
+ MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr);
+ stats.getAiSequence().clear();
+ stats.setAiSetting(MWMechanics::AiSetting::Fight, 0);
+ stats.setAiSetting(MWMechanics::AiSetting::Hello, 0);
+ copy.cell = ptr.getCell();
+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_INFO, "Showing someone's %s as 0-%u in %s", idString(copy.originalId).c_str(),
+ mpNum, std::string(store->getCell()->getDescription()).c_str());
+ return ptr;
+ }
+
+ // "isowind copy <x> <y> <z>" (someone's follower is there: the look-alike, if this game has the cell in use, else
+ // later when what its owner's game sends about it comes) and "isowind uncopy" (it no longer follows them)
+ bool runFollowerCopyCommand(const std::string& command, MWWorld::CellStore* cellStore, unsigned int mpNum,
+ const std::string& refIdString)
+ {
+ std::string rest;
+ if (takeCommand(command, "isowind uncopy", rest))
+ {
+ auto found = followerCopies.find(mpNum);
+ if (found != followerCopies.end())
+ {
+ removeFollowerCopy(mpNum, found->second);
+ followerCopies.erase(found);
+ }
+ return true;
+ }
+ if (!takeCommand(command, "isowind copy", rest))
+ return false;
+ if (mpNum < FOLLOWER_COPY_BASE)
+ return true;
+
+ FollowerCopy& copy = followerCopies[mpNum];
+ copy.originalId = refId(refIdString);
+ std::istringstream stream(rest);
+ stream.imbue(std::locale::classic());
+ copy.position = ESM::Position();
+ stream >> copy.position.pos[0] >> copy.position.pos[1] >> copy.position.pos[2];
+
+ if (cellStore != nullptr && cellStore->getState() == MWWorld::CellStore::State_Loaded
+ && MWBase::Environment::get().getWorldScene()->isCellActive(*cellStore))
+ placeFollowerCopy(mpNum, copy, cellStore, copy.position);
+ else
+ {
+ // Gone where this game doesn't show
+ MWWorld::Ptr ptr = findFollowerCopy(mpNum, copy);
+ if (!ptr.isEmpty())
+ removeFollowerCopy(mpNum, copy);
+ }
+ return true;
+ }
+}
+
+bool MechanicsHelper::runPrivateFollowerCommand(const std::string& command, MWWorld::CellStore* cellStore,
+ unsigned int refNum, unsigned int mpNum, const std::string& refIdString)
+{
+ if (runFollowerCopyCommand(command, cellStore, mpNum, refIdString))
+ return true;
+
+ std::string rest;
+ const bool own = takeCommand(command, "isowind own", rest);
+ const bool follow = !own && takeCommand(command, "isowind follow", rest);
+ const bool stay = !own && !follow && takeCommand(command, "isowind stay", rest);
+ const bool take = !own && !follow && !stay && takeCommand(command, "isowind take", rest);
+ const bool release = !own && !follow && !stay && !take && takeCommand(command, "isowind release", rest);
+ if (!own && !follow && !stay && !take && !release)
+ return false;
+
+ const std::string index = followerIndex(refNum, mpNum);
+ auto known = privateFollowers.find(index);
+ const bool wasPrivate = known != privateFollowers.end();
+
+ // It went to another member of the player's party: out of this game (they have it; this player sees its copy)
+ if (release)
+ {
+ if (!wasPrivate)
+ return true;
+ PrivateFollower& follower = known->second;
+ MWWorld::Ptr ptr = findPrivateFollower(follower);
+ follower.mirror.reset();
+ follower.released = true;
+ follower.reportedState = 0;
+ if (!ptr.isEmpty() && ptr.getRefData().isEnabled())
+ MWBase::Environment::get().getWorld()->disable(ptr);
+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_INFO, "%s %s went to another member of the party", refIdString.c_str(),
+ index.c_str());
+ return true;
+ }
+ MWWorld::Ptr ptr;
+ if (wasPrivate)
+ ptr = findPrivateFollower(known->second);
+ else if (cellStore != nullptr)
+ {
+ // Where the game's files have it, which the player's game may not have loaded (they logged in elsewhere)
+ if (cellStore->getState() != MWWorld::CellStore::State_Loaded)
+ cellStore->load();
+ ptr = cellStore->searchExact(refNum, mpNum, refId(refIdString), true);
+ }
+ if (ptr.isEmpty())
+ {
+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_WARN, "No actor %s %s for \"%s\"", refIdString.c_str(), index.c_str(),
+ command.c_str());
+ return true;
+ }
+
+ Main::get().getCellController()->setClientLocalActor(refNum, mpNum);
+ PrivateFollower& follower = privateFollowers[index];
+ follower.refNum = refNum;
+ follower.mpNum = mpNum;
+ follower.refId = ptr.getCellRef().getRefId();
+ follower.cell = ptr.getCell();
+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_INFO, "%s %s is this player's own follower (\"%s\")", refIdString.c_str(),
+ index.c_str(), command.c_str());
+
+ // "own", "follow" and "take" come with the number of its copy for the others; "take" then with what to do with it
+ // (1: follow the player, 2: talk to it, as the player did to its copy) and where it is
+ int takeFlags = 0;
+ if (own || follow || take)
+ {
+ std::istringstream stream(rest);
+ unsigned int copyMpNum = 0;
+ if (stream >> copyMpNum && copyMpNum >= FOLLOWER_COPY_BASE)
+ follower.copyMpNum = copyMpNum;
+ if (take)
+ {
+ stream >> takeFlags;
+ std::getline(stream >> std::ws, rest);
+ }
+ }
+
+ // Back from another member of the party
+ if (follower.released)
+ {
+ follower.released = false;
+ MWBase::Environment::get().getWorld()->enable(ptr);
+ }
+
+ // Just told to follow here, as it is (the follow order normally already stacked: stacked again in case what the
+ // game running its cell sent undid it)
+ if (own)
+ {
+ if (!isFollowingPlayer(ptr))
+ followPlayer(ptr);
+ return true;
+ }
+
+ // At login: as the game's files have it, undoing what the world's (others') sent about it
+ if (!wasPrivate && respawnActor(ptr))
+ {
+ ptr = cellStore->searchExact(refNum, mpNum, refId(refIdString), true);
+ if (ptr.isEmpty())
+ return true;
+ }
+
+ MWBase::World* world = MWBase::Environment::get().getWorld();
+ if (follow)
+ {
+ // Where the player is, as followers come through a door with them (MWWorld::ActionTeleport)
+ const MWWorld::Ptr player = world->getPlayerPtr();
+ ptr = world->moveObject(ptr, player.getCell(), player.getRefData().getPosition().asVec3());
+ follower.cell = ptr.getCell();
+ if (!isFollowingPlayer(ptr))
+ followPlayer(ptr);
+ return true;
+ }
+
+ static const std::string deadPrefix = "dead ";
+ std::string place = rest;
+ const bool dead = place.rfind(deadPrefix, 0) == 0;
+ if (dead)
+ place = place.substr(deadPrefix.size());
+ osg::Vec3f position;
+ std::istringstream stream(place);
+ stream.imbue(std::locale::classic());
+ if (!(stream >> position.x() >> position.y() >> position.z()))
+ return true;
+ std::string cellDescription;
+ std::getline(stream >> std::ws, cellDescription);
+ MWWorld::CellStore* destination = getCellStoreFromDescription(cellDescription);
+ if (destination == nullptr)
+ {
+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_WARN, "No cell %s for \"%s\"", cellDescription.c_str(), command.c_str());
+ return true;
+ }
+ if (destination->getState() != MWWorld::CellStore::State_Loaded)
+ destination->load();
+ ptr = world->moveObject(ptr, destination, position);
+ follower.cell = ptr.getCell();
+
+ if (dead)
+ {
+ // Dead already, its death not played again (as for an event's person: runClientLocalCommand)
+ MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr);
+ if (!stats.isDead())
+ {
+ MWMechanics::DynamicStat<float> health = stats.getHealth();
+ health.setCurrent(0.f);
+ stats.setHealth(health);
+ stats.setDeathAnimationFinished(true);
+ }
+ world->enableActorCollision(ptr, false);
+ }
+ if (takeFlags & 1)
+ followPlayer(ptr);
+ if (takeFlags & 2)
+ MWBase::Environment::get().getLuaManager()->objectActivated(ptr, world->getPlayerPtr());
+ return true;
+}
+
+void MechanicsHelper::requestFollowerCopy(const MWWorld::Ptr& copy)
+{
+ if (!mwmp::hooks::isLoggedIn() || !isFollowerCopy(copy) || !copy.isInCell() || copy.getCell()->getCell()->isEsm4())
+ return;
+ sendPrivateFollower(copy, WANTED);
+}
+
+bool MechanicsHelper::isPrivateFollower(const MWWorld::Ptr& ptr)
+{
+ if (privateFollowers.empty() || ptr.isEmpty() || ptr.mRef == nullptr)
+ return false;
+ return privateFollowers.count(followerIndex(ptr.getCellRef().getMpRefNum(), ptr.getCellRef().getMpNum())) > 0;
+}
+
+void MechanicsHelper::onPrivateFollowerMoved(const MWWorld::Ptr& ptr)
+{
+ auto found
+ = privateFollowers.find(followerIndex(ptr.getCellRef().getMpRefNum(), ptr.getCellRef().getMpNum()));
+ if (found == privateFollowers.end() || !ptr.isInCell() || ptr.getCell()->getCell()->isEsm4())
+ return;
+ found->second.cell = ptr.getCell();
+ if (found->second.mirror != nullptr)
+ setMirrorPtr(found->second, ptr);
+}
+
+bool MechanicsHelper::isFollowerCopy(const MWWorld::Ptr& ptr)
+{
+ return !ptr.isEmpty() && ptr.mRef != nullptr && ptr.getCellRef().getMpNum() >= FOLLOWER_COPY_BASE;
+}
+
+MWWorld::Ptr MechanicsHelper::getPrivateFollowerByCopy(unsigned int mpNum)
+{
+ for (auto& [index, follower] : privateFollowers)
+ if (follower.copyMpNum == mpNum)
+ return findPrivateFollower(follower);
+ return {};
+}
+
+MWWorld::Ptr MechanicsHelper::getFollowerCopy(MWWorld::CellStore* store, unsigned int mpNum)
+{
+ auto found = followerCopies.find(mpNum);
+ if (found == followerCopies.end() || store == nullptr || store->getState() != MWWorld::CellStore::State_Loaded
+ || !MWBase::Environment::get().getWorldScene()->isCellActive(*store))
+ return {};
+ MWWorld::Ptr ptr = findFollowerCopy(mpNum, found->second);
+ return placeFollowerCopy(
+ mpNum, found->second, store, ptr.isEmpty() ? found->second.position : ptr.getRefData().getPosition());
+}
+
+void MechanicsHelper::updatePrivateFollowers(float dt)
+{
+ if (privateFollowers.empty() || !mwmp::hooks::isLoggedIn())
+ return;
+
+ // What the others' copies do, as often as what's sent about the actors this game runs (Cell::updateLocal)
+ mirrorTimer += dt;
+ if (mirrorTimer >= 0.025f)
+ {
+ mirrorTimer = 0.f;
+ ActorList* actorList = Main::get().getNetworking()->getActorList();
+ for (auto& [index, follower] : privateFollowers)
+ {
+ if (follower.mirror == nullptr)
+ continue;
+ actorList->reset();
+ actorList->cell = follower.mirror->cell;
+ follower.mirror->update(!follower.mirror->hasSentData);
+ actorList->sendPositionActors();
+ actorList->sendAnimFlagsActors();
+ actorList->sendAnimPlayActors();
+ actorList->sendSpeechActors();
+ actorList->sendAttackActors();
+ actorList->sendCastActors();
+ }
+ }
+
+ privateFollowerTimer += dt;
+ if (privateFollowerTimer < 1.f)
+ return;
+ privateFollowerTimer = 0.f;
+
+ for (auto& [index, follower] : privateFollowers)
+ {
+ if (follower.released)
+ continue;
+ MWWorld::Ptr ptr = findPrivateFollower(follower);
+ if (ptr.isEmpty() || !ptr.isInCell() || ptr.getCell()->getCell()->isEsm4())
+ continue;
+ int state = STAYING;
+ if (ptr.getClass().getCreatureStats(ptr).isDead())
+ state = DEAD;
+ else if (isFollowingPlayer(ptr))
+ state = FOLLOWING;
+
+ // The others see it only while it follows
+ if (state == FOLLOWING && follower.copyMpNum != 0)
+ {
+ if (follower.mirror == nullptr)
+ {
+ follower.mirror = std::make_unique<LocalActor>();
+ follower.mirror->isFollowerCopy = true;
+ setMirrorPtr(follower, ptr);
+ }
+ else if (follower.mirror->getPtr().getCell() != ptr.getCell())
+ setMirrorPtr(follower, ptr);
+ }
+ else
+ follower.mirror.reset();
+
+ const osg::Vec3f position = ptr.getRefData().getPosition().asVec3();
+ // Where it stays or lies matters to the server; where it follows, roughly (where the others' games first
+ // show it: their copy then goes by what's sent about it as it moves)
+ const float far = state == FOLLOWING ? 1024.f : 128.f;
+ const bool moved = ptr.getCell() != follower.reportedCell
+ || (position - follower.reportedPosition).length2() > far * far;
+ if (state == follower.reportedState && !moved)
+ continue;
+
+ sendPrivateFollower(ptr, state);
+ follower.reportedState = state;
+ follower.reportedCell = ptr.getCell();
+ follower.reportedPosition = position;
+ }
+}
+
bool MechanicsHelper::isUsingRangedWeapon(const MWWorld::Ptr& ptr)
{
if (ptr.getClass().hasInventoryStore(ptr))
@@ -278,6 +862,8 @@ Attack *MechanicsHelper::getLocalAttack(const MWWorld::Ptr& ptr)
return &mwmp::Main::get().getLocalPlayer()->attack;
else if (mwmp::Main::get().getCellController()->isLocalActor(ptr))
return &mwmp::Main::get().getCellController()->getLocalActor(ptr)->attack;
+ else if (LocalActor* mirror = getMirror(ptr))
+ return &mirror->attack;
return nullptr;
}
@@ -298,6 +884,8 @@ Cast *MechanicsHelper::getLocalCast(const MWWorld::Ptr& ptr)
return &mwmp::Main::get().getLocalPlayer()->cast;
else if (mwmp::Main::get().getCellController()->isLocalActor(ptr))
return &mwmp::Main::get().getCellController()->getLocalActor(ptr)->cast;
+ else if (LocalActor* mirror = getMirror(ptr))
+ return &mirror->cast;
return nullptr;
}
@@ -336,6 +924,10 @@ MWWorld::Ptr MechanicsHelper::getTargetPtr(const mwmp::Target& target)
if (target.isPlayer)
return getPlayerPtr(target);
+ // Isowind MMO: this player's own follower, as the others' games know it (its copy)
+ if (target.refNum == 0 && target.mpNum >= FOLLOWER_COPY_BASE)
+ return getPrivateFollowerByCopy(target.mpNum);
+
auto controller = mwmp::Main::get().getCellController();
if (controller->isLocalActor(target.refNum, target.mpNum))
return controller->getLocalActor(target.refNum, target.mpNum)->getPtr();
diff --git a/apps/openmw/mwmp/MechanicsHelper.hpp b/apps/openmw/mwmp/MechanicsHelper.hpp
index 8d800f1..898bc41 100644
--- a/apps/openmw/mwmp/MechanicsHelper.hpp
+++ b/apps/openmw/mwmp/MechanicsHelper.hpp
@@ -29,6 +29,32 @@ namespace MechanicsHelper
/// with where the body lies, as that player's (a ClientScriptLocal packet as gameplay, floats 0 to 2 the place)
void sendClientLocalDeath(const MWWorld::Ptr& actor);
+ /// Isowind MMO: someone from the world told to follow this player, who has their own of it (the others keep the
+ /// world's at its post): the server's commands "isowind own <n>" (just told to follow here: this client's from now
+ /// on, as it is), "isowind follow <n>" (at the player's side, following, after logging in) and "isowind stay <x> <y> <z>
+ /// <cell>" / "isowind stay dead <x> <y> <z> <cell>" (where it stopped following, or its body), the objects' cell
+ /// being where the game's files have it. Returns false for other commands.
+ bool runPrivateFollowerCommand(const std::string& command, MWWorld::CellStore* cellStore, unsigned int refNum,
+ unsigned int mpNum, const std::string& refId);
+ bool isPrivateFollower(const MWWorld::Ptr& ptr);
+ /// One of them went to another cell (mwmp::hooks::updatePtr)
+ void onPrivateFollowerMoved(const MWWorld::Ptr& ptr);
+ /// Someone else's follower as this game shows it: a look-alike (a record like the actor's, with no script) that
+ /// can't be talked to or hurt here, moved by what its owner's game sends about it (as about a copy numbered 0-<n>,
+ /// n from mwmp::FOLLOWER_COPY_BASE); the server's commands "isowind copy <x> <y> <z>" (it's there; the objects'
+ /// refId the actor it looks like) and "isowind uncopy" (it no longer follows them)
+ bool isFollowerCopy(const MWWorld::Ptr& ptr);
+ /// The player used someone's follower as this game shows it: the server hands it over if they're in the player's
+ /// party ("isowind take <n> <flags> <x> <y> <z> <cell>", and "isowind release" to the game that had it)
+ void requestFollowerCopy(const MWWorld::Ptr& copy);
+ /// This player's own follower whose copy the others' games know by that number (what they send about hitting it)
+ MWWorld::Ptr getPrivateFollowerByCopy(unsigned int mpNum);
+ /// The look-alike in a cell this game has in use, made or brought there, for what's sent about it there
+ MWWorld::Ptr getFollowerCopy(MWWorld::CellStore* store, unsigned int mpNum);
+ /// Tells the server, every few seconds, of the private followers that changed: following, staying (and where) or
+ /// dead (and where the body lies), as for sendClientLocalDeath with short 0 the state
+ void updatePrivateFollowers(float dt);
+
bool isUsingRangedWeapon(const MWWorld::Ptr& ptr);
mwmp::Attack *getLocalAttack(const MWWorld::Ptr& ptr);
diff --git a/apps/openmw/mwscript/aiextensions.cpp b/apps/openmw/mwscript/aiextensions.cpp
index f2e2ff3..59c7c58 100644
--- a/apps/openmw/mwscript/aiextensions.cpp
+++ b/apps/openmw/mwscript/aiextensions.cpp
@@ -128,6 +128,9 @@ namespace MWScript
MWMechanics::AiEscort escortPackage(actorID, {}, static_cast<int>(duration), x, y, z, repeat);
ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(escortPackage, ptr);
+ // Isowind multiplayer: wherever the actor's AI runs
+ mwmp::hooks::sendScriptEscort(ptr, MWBase::Environment::get().getWorld()->searchPtr(actorID, true),
+ static_cast<int>(duration), x, y, z);
Log(Debug::Info) << "AiEscort: " << x << ", " << y << ", " << z << ", " << duration;
}
@@ -175,6 +178,9 @@ namespace MWScript
MWMechanics::AiEscort escortPackage(actorID, cellID, static_cast<int>(duration), x, y, z, repeat);
ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(escortPackage, ptr);
+ // Isowind multiplayer: wherever the actor's AI runs
+ mwmp::hooks::sendScriptEscort(ptr, MWBase::Environment::get().getWorld()->searchPtr(actorID, true),
+ static_cast<int>(duration), x, y, z);
Log(Debug::Info) << "AiEscort: " << x << ", " << y << ", " << z << ", " << duration;
}
diff --git a/components/openmw-mp/Base/BaseActor.hpp b/components/openmw-mp/Base/BaseActor.hpp
index 9488e3e..73db120 100644
--- a/components/openmw-mp/Base/BaseActor.hpp
+++ b/components/openmw-mp/Base/BaseActor.hpp
@@ -9,6 +9,12 @@
namespace mwmp
{
+ // Isowind MMO: a player's own follower as the other players see it (a look-alike their games make,
+ // MechanicsHelper::isFollowerCopy): numbered 0-<mpNum>, the mpNum being this base plus its owner's player id times
+ // FOLLOWER_COPIES_PER_PLAYER plus which of their followers it is. Only the owner's game moves it.
+ const unsigned int FOLLOWER_COPY_BASE = 0x40000000;
+ const unsigned int FOLLOWER_COPIES_PER_PLAYER = 256;
+
class BaseActor
{
public:
@@ -44,14 +50,14 @@ namespace mwmp
Target killer;
- bool isFollowerCellChange;
+ bool isFollowerCellChange = false;
- bool hasAiTarget;
+ bool hasAiTarget = false;
Target aiTarget;
- unsigned int aiAction;
- unsigned int aiDistance;
- unsigned int aiDuration;
- bool aiShouldRepeat;
+ unsigned int aiAction = 0;
+ unsigned int aiDistance = 0;
+ unsigned int aiDuration = 0;
+ bool aiShouldRepeat = false;
ESM::Position aiCoordinates;
bool hasPositionData;
diff --git a/isowind/README.txt b/isowind/README.txt
index 29f4245..0e29836 100644
--- a/isowind/README.txt
+++ b/isowind/README.txt
@@ -58,6 +58,11 @@ Hosting a server
disarmed or set off is still there for them.
Quests that count kills (like the Fighters Guild's rats) count the kills you made yourself,
or your party made; someone else killing them first doesn't take them from you, they come back.
+ Someone who follows you (an escort, a companion, a pack guar) is your own: they stay at their
+ post for everyone else, who can each take them along too. Others see yours walking and
+ fighting with you, but can't talk to it or hurt it. Log out while they follow and they're at
+ your side when you're back; once they stop following they stay where they stopped, for you.
+ If they die, they're dead for you only.
- PvP (whether players can hurt each other), difficulty and how fast the time of day goes.
Then the server's window opens; it runs the server, and closing it stops the server (saved). It shows:
- The players in the world, their staff rank, ping, level and cell. Pick one to change their staff rank
@@ -90,7 +95,10 @@ When you die you wake up at the nearest temple.
Parties (MMO servers): players in a party share their quests as on a co-op server - journal,
topics, quest progress, kill credit and what quests change in the world - and the locks and traps
-they open, from when they joined, while each keeps their own loot. Type in the chat:
+they open, from when they joined, while each keeps their own loot. Sharing never sets anyone back
+in a quest they're further along in. A party has one of each companion: use a member's companion
+(talk to it) and it comes over to you; if the member it follows logs out or leaves the party, it
+follows another member. Type in the chat:
/party invite NAME invite a player (their name, or the number before it in the player list)
/party accept join the party you were invited to (or /party decline)
/party who is in your party
diff --git a/isowind/server/CoreScripts/scripts/custom/isowindFollowers.lua b/isowind/server/CoreScripts/scripts/custom/isowindFollowers.lua
new file mode 100644
index 0000000..835229b
--- /dev/null
+++ b/isowind/server/CoreScripts/scripts/custom/isowindFollowers.lua
@@ -0,0 +1,548 @@
+-- Isowind MMO mode: followers of one's own.
+--
+-- Someone from the world (an NPC or creature from the game's files, not a summon) told to follow or escort a player
+-- becomes that player's own: their game runs it for them alone from then on (the server's "isowind own", a console
+-- command packet the game handles itself, mwmp::MechanicsHelper::runPrivateFollowerCommand), and the follow order goes
+-- no further, so the world's stays at its post for everyone else, who can each have their own of it the same way.
+-- Quest scripts and dialogue find it as ever: it's the same one in the player's game.
+--
+-- What the player's game tells of it (a ClientScriptLocal packet as gameplay: floats 0 to 2 the place, short 0 the
+-- state, mwmp::MechanicsHelper::updatePrivateFollowers) is kept with the player (isowindFollowers):
+-- * Following: after logging in, it's at their side again ("isowind follow").
+-- * Staying (it stopped following): it stays where it stopped, for them ("isowind stay <x> <y> <z> <cell>").
+-- * Dead: for them only, and it doesn't come back; its body lies where it fell ("isowind stay dead ...").
+--
+-- While it follows, the other players see it with them: their games make a look-alike of it ("isowind copy <x> <y>
+-- <z>", "isowind uncopy" once it no longer follows) that can't be talked to or hurt, moved by what the owner's game
+-- sends about it as about a copy numbered 0-<n> (n = FOLLOWER_COPY_BASE + pid * FOLLOWER_COPIES_PER_PLAYER + which of
+-- the player's followers it is this session; the server takes those from that player's game alone, whoever has
+-- authority over the cell). The owner's game learns the number with "isowind own <n>" / "isowind follow <n>".
+--
+-- A party has one of each (isowindParty.lua keeps which member holds it), for every member to use: one who uses its
+-- copy (their game asks: state 4 in the same kind of packet), or who tells the same NPC to follow them, takes it over
+-- ("isowind take <n> <flags> <x> <y> <z> <cell>" to their game, "isowind release" to the one that had it). If the
+-- member it follows logs out or leaves the party, it goes to another member who is on, at their side.
+--
+-- Before followers were each player's own, a follow order moved the world's own NPC for everyone (Din, taken to the
+-- Gnisis temple, was no longer at his post for anyone). Actors from the game's files that were moved out of their cell
+-- before this script was there are put back at their post when either cell loads: what the server kept of them goes,
+-- from both cells. Actors moved since are left as they are (isowindMovedSince, kept from the first start with this
+-- script). Players with journal entries from one of them (who took it there) keep their own of it where it was
+-- (isowindDisplacedReset, looked at once for each player).
+
+if not IsowindHost.IsMmo() then
+ return
+end
+
+local isowindFollowers = {}
+IsowindFollowers = isowindFollowers
+
+local state = { FOLLOWING = 1, STAYING = 2, DEAD = 3, WANTED = 4 }
+
+-- This session's players (by name) whose game has been told where their followers are
+local placed = {}
+
+-- The numbers of this session's copies, by player name: { pid, slots = { uniqueIndex = slot }, count }
+local copyNumbers = {}
+
+local FOLLOWER_COPY_BASE = 1073741824 -- 0x40000000, components/openmw-mp/Base/BaseActor.hpp
+local FOLLOWER_COPIES_PER_PLAYER = 256
+
+local function playerKey(pid)
+ return string.lower(Players[pid].accountName)
+end
+
+-- A player's followers: { uniqueIndex = { refId, postCell, state, cell, posX, posY, posZ } }, postCell being where the
+-- game's files have it (where their game finds it after logging in)
+local function followersOf(pid)
+ local data = Players[pid].data
+ data.customVariables = data.customVariables or {}
+ data.customVariables.isowindFollowers = data.customVariables.isowindFollowers or {}
+ return data.customVariables.isowindFollowers
+end
+
+-- A command the game handles itself (mwmp::ObjectList::runConsoleCommands), to one player, about one actor
+local function sendCommand(pid, cellDescription, command, uniqueIndex, refId)
+ local parts = uniqueIndex:split("-")
+ tes3mp.ClearObjectList()
+ tes3mp.SetObjectListPid(pid)
+ tes3mp.SetObjectListCell(cellDescription)
+ tes3mp.SetObjectListConsoleCommand(command)
+ tes3mp.SetObjectRefNum(tonumber(parts[1]))
+ tes3mp.SetObjectMpNum(tonumber(parts[2]))
+ tes3mp.SetObjectRefId(refId)
+ tes3mp.AddObject()
+ tes3mp.SendConsoleCommand(false, false)
+end
+
+-- The number of a player's follower's copy, for this session
+local function copyMpNum(pid, uniqueIndex)
+ local name = playerKey(pid)
+ local numbers = copyNumbers[name]
+ if numbers == nil or numbers.pid ~= pid then
+ numbers = { pid = pid, slots = {}, count = 0 }
+ copyNumbers[name] = numbers
+ end
+ if numbers.slots[uniqueIndex] == nil then
+ if numbers.count >= FOLLOWER_COPIES_PER_PLAYER then
+ return nil
+ end
+ numbers.slots[uniqueIndex] = numbers.count
+ numbers.count = numbers.count + 1
+ end
+ return FOLLOWER_COPY_BASE + pid * FOLLOWER_COPIES_PER_PLAYER + numbers.slots[uniqueIndex]
+end
+
+local function withCopyNumber(command, pid, uniqueIndex)
+ local mpNum = copyMpNum(pid, uniqueIndex)
+ return mpNum ~= nil and (command .. " " .. mpNum) or command
+end
+
+-- The others' games are told of a player's follower's copy: where it is ("isowind copy"), or that it's gone
+local function sendCopy(ownerPid, uniqueIndex, follower, toPids, gone)
+ local mpNum = copyMpNum(ownerPid, uniqueIndex)
+ if mpNum == nil or follower.cell == nil then
+ return
+ end
+ local command = gone and "isowind uncopy" or string.format("isowind copy %.2f %.2f %.2f", follower.posX or 0,
+ follower.posY or 0, follower.posZ or 0)
+ for _, pid in ipairs(toPids) do
+ sendCommand(pid, follower.cell, command, "0-" .. mpNum, follower.refId)
+ end
+end
+
+local function otherPids(pid)
+ local pids = {}
+ for otherPid, player in pairs(Players) do
+ if otherPid ~= pid and player:IsLoggedIn() then
+ table.insert(pids, otherPid)
+ end
+ end
+ return pids
+end
+
+local function holderOf(name, uniqueIndex)
+ return IsowindParty ~= nil and IsowindParty.GetFollowerHolder(name, uniqueIndex) or nil
+end
+
+local function setHolder(name, uniqueIndex, holder)
+ if IsowindParty ~= nil then
+ IsowindParty.SetFollowerHolder(name, uniqueIndex, holder)
+ end
+end
+
+-- A follower goes from one member of a party to another: out of the first one's game, into the other's, at their side
+-- following them (place nil), or where it is (place: x, y, z, cell; talk: as they used its copy)
+local function handOver(fromPid, uniqueIndex, toPid, place)
+ local fromFollowers = followersOf(fromPid)
+ local follower = fromFollowers[uniqueIndex]
+ if follower == nil then
+ return
+ end
+ if follower.state == state.FOLLOWING then
+ sendCopy(fromPid, uniqueIndex, follower, otherPids(fromPid), true)
+ end
+ sendCommand(fromPid, follower.cell or follower.postCell, "isowind release", uniqueIndex, follower.refId)
+ fromFollowers[uniqueIndex] = nil
+ followersOf(toPid)[uniqueIndex] = follower
+
+ local mpNum = copyMpNum(toPid, uniqueIndex) or 0
+ if place == nil then
+ follower.state = state.FOLLOWING
+ sendCommand(toPid, follower.postCell, "isowind follow " .. mpNum, uniqueIndex, follower.refId)
+ else
+ local flags = (follower.state == state.FOLLOWING and 1 or 0) + (place.talk and 2 or 0)
+ follower.cell = place.cell
+ follower.posX, follower.posY, follower.posZ = place.x, place.y, place.z
+ sendCommand(toPid, follower.postCell, string.format("isowind take %d %d %.2f %.2f %.2f %s", mpNum, flags,
+ place.x, place.y, place.z, place.cell), uniqueIndex, follower.refId)
+ end
+ setHolder(playerKey(toPid), uniqueIndex, playerKey(toPid))
+ Players[fromPid]:QuicksaveToDrive()
+ Players[toPid]:QuicksaveToDrive()
+ tes3mp.LogMessage(enumerations.log.INFO, "[Isowind] " .. follower.refId .. " " .. uniqueIndex .. " went from " ..
+ playerKey(fromPid) .. " to " .. playerKey(toPid))
+end
+
+-- The followers following a player who goes (logs out, leaves the party) go to another member of their party who is
+-- on; the rest stay theirs
+local function handOverFollowing(pid)
+ local others = IsowindParty ~= nil and IsowindParty.GetOnlineMemberPids(playerKey(pid)) or {}
+ for uniqueIndex, follower in pairs(followersOf(pid)) do
+ if follower.state == state.FOLLOWING and others[1] ~= nil and
+ holderOf(playerKey(pid), uniqueIndex) == playerKey(pid) then
+ handOver(pid, uniqueIndex, others[1], nil)
+ end
+ end
+end
+
+function isowindFollowers.OnLeavingParty(pid)
+ handOverFollowing(pid)
+end
+
+-- A player used a party member's follower's copy: it comes to them, there, and they talk to it
+local function onWanted(pid, cellDescription, uniqueIndex, x, y, z)
+ local _, mpNum = uniqueIndex:match("^(%d+)-(%d+)$")
+ mpNum = tonumber(mpNum)
+ if mpNum == nil or mpNum < FOLLOWER_COPY_BASE or x == nil then
+ return
+ end
+ local ownerPid = math.floor((mpNum - FOLLOWER_COPY_BASE) / FOLLOWER_COPIES_PER_PLAYER)
+ local slot = (mpNum - FOLLOWER_COPY_BASE) % FOLLOWER_COPIES_PER_PLAYER
+ local owner = Players[ownerPid]
+ if owner == nil or not owner:IsLoggedIn() or ownerPid == pid then
+ return
+ end
+ local numbers = copyNumbers[playerKey(ownerPid)]
+ local followerIndex = nil
+ if numbers ~= nil and numbers.pid == ownerPid then
+ for index, number in pairs(numbers.slots) do
+ if number == slot then
+ followerIndex = index
+ end
+ end
+ end
+ local follower = followerIndex ~= nil and followersOf(ownerPid)[followerIndex] or nil
+ if follower == nil then
+ return
+ end
+ local members = IsowindParty ~= nil and IsowindParty.GetMemberNames(playerKey(ownerPid)) or {}
+ if not tableHelper.containsValue(members, playerKey(pid)) then
+ tes3mp.SendMessage(pid, color.White .. "That's " .. owner.accountName .. "'s companion.\n", false)
+ return
+ end
+ handOver(ownerPid, followerIndex, pid, { x = x, y = y, z = z, cell = cellDescription, talk = true })
+end
+
+-- Where the game's files have an actor now in a cell: there, unless it moved there from another (the cell keeps where
+-- from, cell/base.lua's SaveActorCellChanges)
+local function postCellOf(cellDescription, uniqueIndex)
+ local cell = LoadedCells[cellDescription]
+ if cell ~= nil and tableHelper.containsValue(cell.data.packets.cellChangeFrom or {}, uniqueIndex) then
+ local objectData = cell.data.objectData[uniqueIndex]
+ if objectData ~= nil and objectData.cellChangeFrom ~= nil then
+ return objectData.cellChangeFrom
+ end
+ end
+ return cellDescription
+end
+
+-- A follow or escort order toward the player who gave it (their game sends the order: a dialogue result or script)
+-- makes the actor theirs, and doesn't reach the game running its cell
+local function onActorAI(eventStatus, pid, cellDescription)
+ if eventStatus.validDefaultHandler == false then
+ return
+ end
+ tes3mp.ReadReceivedActorList()
+ local followers = followersOf(pid)
+ local taken = false
+ for index = 0, tes3mp.GetActorListSize() - 1 do
+ local action = tes3mp.GetActorAIAction(index)
+ local mpNum = tes3mp.GetActorMpNum(index)
+ if (action == enumerations.ai.FOLLOW or action == enumerations.ai.ESCORT) and mpNum == 0 and
+ tes3mp.GetActorAITargetPid(index) == pid then
+ local uniqueIndex = tes3mp.GetActorRefNum(index) .. "-" .. mpNum
+ local refId = tes3mp.GetActorRefId(index)
+ -- One of each for a party: another member's comes to this one (the one they told to follow, in their game)
+ local holder = holderOf(playerKey(pid), uniqueIndex)
+ if holder ~= nil and holder ~= playerKey(pid) and followers[uniqueIndex] == nil then
+ for holderPid, player in pairs(Players) do
+ if player:IsLoggedIn() and string.lower(player.accountName) == holder then
+ local held = followersOf(holderPid)[uniqueIndex]
+ if held ~= nil and held.state == state.FOLLOWING then
+ sendCopy(holderPid, uniqueIndex, held, otherPids(holderPid), true)
+ end
+ if held ~= nil then
+ sendCommand(holderPid, held.cell or held.postCell, "isowind release", uniqueIndex, refId)
+ followersOf(holderPid)[uniqueIndex] = nil
+ player:QuicksaveToDrive()
+ end
+ end
+ end
+ tes3mp.LogMessage(enumerations.log.INFO, "[Isowind] " .. refId .. " " .. uniqueIndex .. " went from " ..
+ holder .. " to " .. playerKey(pid) .. ", who told it to follow them")
+ end
+ setHolder(playerKey(pid), uniqueIndex, playerKey(pid))
+ if followers[uniqueIndex] == nil then
+ followers[uniqueIndex] = { refId = refId, postCell = postCellOf(cellDescription, uniqueIndex),
+ state = state.FOLLOWING, cell = cellDescription }
+ tes3mp.LogMessage(enumerations.log.INFO, "[Isowind] " .. refId .. " " .. uniqueIndex .. " follows " ..
+ playerKey(pid) .. ", who has their own of it from now on (its post: " ..
+ followers[uniqueIndex].postCell .. ")")
+ end
+ sendCommand(pid, cellDescription, withCopyNumber("isowind own", pid, uniqueIndex), uniqueIndex, refId)
+ taken = true
+ end
+ end
+ if taken then
+ Players[pid]:QuicksaveToDrive()
+ return customEventHooks.makeEventStatus(false, false)
+ end
+end
+
+-- What a player's game tells of its own followers (and only those: anything else in such a packet is the MMO's,
+-- isowindMmo.lua's event deaths, which have no state)
+local function onClientScriptLocal(eventStatus, pid, cellDescription, objects)
+ if eventStatus.validDefaultHandler == false or
+ tes3mp.GetObjectListOrigin() ~= enumerations.packetOrigin.CLIENT_GAMEPLAY then
+ return
+ end
+ local followers = followersOf(pid)
+ local told = false
+ for uniqueIndex, object in pairs(objects) do
+ local variables = object.variables or {}
+ local shorts = variables[enumerations.variableType.SHORT] or {}
+ local floats = variables[enumerations.variableType.FLOAT] or {}
+ local newState = tonumber(shorts[0])
+ if newState == state.WANTED then
+ told = true
+ onWanted(pid, cellDescription, uniqueIndex, tonumber(floats[0]), tonumber(floats[1]), tonumber(floats[2]))
+ elseif newState ~= nil then
+ told = true
+ local follower = followers[uniqueIndex]
+ local x, y, z = tonumber(floats[0]), tonumber(floats[1]), tonumber(floats[2])
+ if follower == nil or x == nil or y == nil or z == nil then
+ tes3mp.LogMessage(enumerations.log.WARN, "[Isowind] Ignored news of " .. tostring(object.refId) ..
+ " " .. uniqueIndex .. " from " .. playerKey(pid) .. ": not their follower")
+ else
+ local wasFollowing = follower.state == state.FOLLOWING
+ -- Dead stays dead (its body can still be moved)
+ if follower.state ~= state.DEAD then
+ if newState ~= follower.state then
+ tes3mp.LogMessage(enumerations.log.INFO, "[Isowind] " .. playerKey(pid) .. "'s " ..
+ follower.refId .. " " .. uniqueIndex .. " is " ..
+ (tableHelper.getIndexByValue(state, newState) or tostring(newState)) .. " in " ..
+ cellDescription)
+ end
+ follower.state = newState
+ -- Dead for the party too: a member can have the world's own again
+ if newState == state.DEAD then
+ setHolder(playerKey(pid), uniqueIndex, nil)
+ end
+ end
+ follower.cell = cellDescription
+ follower.posX, follower.posY, follower.posZ = x, y, z
+ -- The others see it while it follows
+ if follower.state == state.FOLLOWING then
+ sendCopy(pid, uniqueIndex, follower, otherPids(pid), false)
+ elseif wasFollowing then
+ sendCopy(pid, uniqueIndex, follower, otherPids(pid), true)
+ end
+ end
+ end
+ end
+ if told then
+ Players[pid]:QuicksaveToDrive()
+ return customEventHooks.makeEventStatus(false, false)
+ end
+end
+
+-- --- The world's actors that follow orders took away before ----------------------------------------------------------
+
+local function withCell(cellDescription, callback)
+ local temporary = LoadedCells[cellDescription] == nil
+ if temporary then
+ logicHandler.LoadCell(cellDescription)
+ end
+ local result = callback(LoadedCells[cellDescription])
+ if temporary then
+ logicHandler.UnloadCell(cellDescription)
+ end
+ return result
+end
+
+local function forgetInCell(cell, uniqueIndex)
+ cell.data.objectData[uniqueIndex] = nil
+ for _, list in pairs(cell.data.packets) do
+ if type(list) == "table" and tableHelper.containsValue(list, uniqueIndex) then
+ tableHelper.removeValue(list, uniqueIndex)
+ tableHelper.cleanNils(list)
+ end
+ end
+ cell:QuicksaveToDrive()
+end
+
+-- Back at its post: the cell it was moved to and its own cell forget it was moved
+local function putBack(uniqueIndex, postCell, movedTo)
+ local record = withCell(movedTo, function(cell)
+ local objectData = cell.data.objectData[uniqueIndex] or {}
+ local location = objectData.location or {}
+ forgetInCell(cell, uniqueIndex)
+ return { refId = objectData.refId, postCell = postCell, cell = movedTo, posX = location.posX,
+ posY = location.posY, posZ = location.posZ, dead = objectData.deathState ~= nil, checked = {} }
+ end)
+ withCell(postCell, function(cell)
+ if record.refId == nil and cell.data.objectData[uniqueIndex] ~= nil then
+ record.refId = cell.data.objectData[uniqueIndex].refId
+ end
+ forgetInCell(cell, uniqueIndex)
+ end)
+ WorldInstance.data.isowindDisplacedReset = WorldInstance.data.isowindDisplacedReset or {}
+ WorldInstance.data.isowindDisplacedReset[uniqueIndex] = record
+ WorldInstance:QuicksaveToDrive()
+ tes3mp.LogMessage(enumerations.log.INFO, "[Isowind] Put " .. tostring(record.refId) .. " " .. uniqueIndex ..
+ " back in " .. postCell .. " (it had been taken to " .. movedTo .. ")")
+end
+
+-- Before a cell's state goes to the player's game: the world's actors moved to or from it before
+local function putBackDisplaced(eventStatus, pid, cellDescription)
+ local movedSince = WorldInstance.data.isowindMovedSince or {}
+ local moves = withCell(cellDescription, function(cell)
+ local found = {}
+ for _, uniqueIndex in pairs(cell.data.packets.cellChangeFrom or {}) do
+ local objectData = cell.data.objectData[uniqueIndex]
+ if uniqueIndex:match("^%d+%-0$") and not movedSince[uniqueIndex] and objectData ~= nil and
+ objectData.cellChangeFrom ~= nil then
+ table.insert(found, { uniqueIndex, objectData.cellChangeFrom, cellDescription })
+ end
+ end
+ for _, uniqueIndex in pairs(cell.data.packets.cellChangeTo or {}) do
+ local objectData = cell.data.objectData[uniqueIndex]
+ if uniqueIndex:match("^%d+%-0$") and not movedSince[uniqueIndex] and objectData ~= nil and
+ objectData.cellChangeTo ~= nil then
+ table.insert(found, { uniqueIndex, cellDescription, objectData.cellChangeTo })
+ end
+ end
+ return found
+ end)
+ for _, move in ipairs(moves) do
+ putBack(move[1], move[2], move[3])
+ end
+ if #moves > 0 then
+ -- The players on who took them there keep theirs there
+ for otherPid, player in pairs(Players) do
+ if player:IsLoggedIn() and placed[playerKey(otherPid)] then
+ isowindFollowers.KeepDisplaced(otherPid, true)
+ end
+ end
+ end
+end
+
+-- The world's actors moved since this script was there are left where they're moved to
+local function onActorCellChange(eventStatus, pid, cellDescription)
+ if eventStatus.validDefaultHandler == false then
+ return
+ end
+ tes3mp.ReadReceivedActorList()
+ local movedSince = WorldInstance.data.isowindMovedSince
+ local added = false
+ for index = 0, tes3mp.GetActorListSize() - 1 do
+ local uniqueIndex = tes3mp.GetActorRefNum(index) .. "-" .. tes3mp.GetActorMpNum(index)
+ if tes3mp.GetActorMpNum(index) == 0 and not movedSince[uniqueIndex] then
+ movedSince[uniqueIndex] = true
+ added = true
+ end
+ end
+ if added then
+ WorldInstance:QuicksaveToDrive()
+ end
+end
+
+-- A player gets their own of each actor put back that has spoken their journal entries (looked at once for each
+-- player, so the ones who talk to it later at its post don't), where it was; placed now if their game is already told
+-- where their followers are
+local placeFollower
+
+function isowindFollowers.KeepDisplaced(pid, placeNow)
+ local name = playerKey(pid)
+ local followers = followersOf(pid)
+ local spokenBy = {}
+ for _, item in ipairs(Players[pid].data.journal or {}) do
+ if item.actorRefId ~= nil then
+ spokenBy[string.lower(item.actorRefId)] = true
+ end
+ end
+ local changed = false
+ for uniqueIndex, record in pairs(WorldInstance.data.isowindDisplacedReset or {}) do
+ record.checked = record.checked or {}
+ if not record.checked[name] then
+ record.checked[name] = true
+ changed = true
+ if record.refId ~= nil and record.posX ~= nil and spokenBy[string.lower(record.refId)] and
+ followers[uniqueIndex] == nil then
+ followers[uniqueIndex] = { refId = record.refId, postCell = record.postCell,
+ state = record.dead and state.DEAD or state.STAYING, cell = record.cell, posX = record.posX,
+ posY = record.posY, posZ = record.posZ }
+ tes3mp.LogMessage(enumerations.log.INFO, "[Isowind] " .. name .. " keeps their own " .. record.refId ..
+ " " .. uniqueIndex .. " in " .. record.cell)
+ if placeNow then
+ placeFollower(pid, uniqueIndex, followers[uniqueIndex])
+ end
+ end
+ end
+ end
+ if changed then
+ WorldInstance:QuicksaveToDrive()
+ Players[pid]:QuicksaveToDrive()
+ end
+end
+
+-- A player's game is told where one of their followers is: at their side, where it stayed, or dead where it fell
+function placeFollower(pid, uniqueIndex, follower)
+ local command = withCopyNumber("isowind follow", pid, uniqueIndex)
+ if follower.state ~= state.FOLLOWING and follower.posX ~= nil then
+ command = string.format("isowind stay %s%.2f %.2f %.2f %s", follower.state == state.DEAD and "dead " or "",
+ follower.posX, follower.posY, follower.posZ, follower.cell)
+ end
+ sendCommand(pid, follower.postCell, command, uniqueIndex, follower.refId)
+end
+
+-- A player's game loading a cell gets the copies of the others' followers there. Once it has loaded the world after
+-- logging in, it's told where the player's own followers are: at their side, where they stayed, or dead where they fell.
+local function onCellLoad(eventStatus, pid, cellDescription)
+ if Players[pid] == nil or not Players[pid]:IsLoggedIn() then
+ return
+ end
+ for otherPid, player in pairs(Players) do
+ if otherPid ~= pid and player:IsLoggedIn() then
+ for uniqueIndex, follower in pairs(followersOf(otherPid)) do
+ if follower.state == state.FOLLOWING and follower.cell == cellDescription then
+ sendCopy(otherPid, uniqueIndex, follower, { pid }, false)
+ end
+ end
+ end
+ end
+
+ local name = playerKey(pid)
+ if placed[name] then
+ return
+ end
+ placed[name] = true
+ isowindFollowers.KeepDisplaced(pid, false)
+ local followers = followersOf(pid)
+ for uniqueIndex, follower in pairs(followers) do
+ -- Another member of their party has it now
+ local holder = holderOf(name, uniqueIndex)
+ if holder ~= nil and holder ~= name then
+ followers[uniqueIndex] = nil
+ Players[pid]:QuicksaveToDrive()
+ else
+ placeFollower(pid, uniqueIndex, follower)
+ end
+ end
+end
+
+-- Before isowindMmo.lua's (required after this), whose OnClientScriptLocal takes the rest of the gameplay ones
+customEventHooks.registerHandler("OnServerPostInit", function(eventStatus)
+ WorldInstance.data.isowindMovedSince = WorldInstance.data.isowindMovedSince or {}
+ customEventHooks.registerValidator("OnCellLoad", putBackDisplaced)
+ customEventHooks.registerHandler("OnActorCellChange", onActorCellChange)
+ customEventHooks.registerValidator("OnActorAI", onActorAI)
+ customEventHooks.registerValidator("OnClientScriptLocal", onClientScriptLocal)
+ customEventHooks.registerHandler("OnCellLoad", onCellLoad)
+ -- Their followers' copies go from the others' games
+ customEventHooks.registerValidator("OnPlayerDisconnect", function(eventStatus, pid)
+ if Players[pid] ~= nil then
+ for uniqueIndex, follower in pairs(followersOf(pid)) do
+ if follower.state == state.FOLLOWING then
+ sendCopy(pid, uniqueIndex, follower, otherPids(pid), true)
+ end
+ end
+ handOverFollowing(pid)
+ placed[playerKey(pid)] = nil
+ copyNumbers[playerKey(pid)] = nil
+ end
+ end)
+end)
+
+return isowindFollowers
diff --git a/isowind/server/CoreScripts/scripts/custom/isowindParty.lua b/isowind/server/CoreScripts/scripts/custom/isowindParty.lua
index a772199..adc6db3 100644
--- a/isowind/server/CoreScripts/scripts/custom/isowindParty.lua
+++ b/isowind/server/CoreScripts/scripts/custom/isowindParty.lua
@@ -9,7 +9,11 @@
-- /p <message> talk to your party
--
-- Kept in the world's data (isowindParties): members, and the party's journal, topics and quest variables, so
--- members who were offline catch up when they log in.
+-- members who were offline catch up when they log in. What's shared only ever moves a member forward in a quest: an
+-- earlier stage than the one they're at isn't given to them.
+--
+-- A party has one of each follower (isowindFollowers.lua), held by one member at a time (followers: uniqueIndex ->
+-- that member's name).
if not IsowindHost.IsMmo() then
return
@@ -72,6 +76,37 @@ function IsowindParty.GetMemberNames(name)
return { name }
end
+-- The pids of a player's party's other members who are on
+function IsowindParty.GetOnlineMemberPids(name)
+ local pids = {}
+ local _, party = partyOf(name)
+ if party ~= nil then
+ for _, member in ipairs(party.members) do
+ local pid = onlinePid(member)
+ if member ~= name and pid ~= nil then
+ table.insert(pids, pid)
+ end
+ end
+ end
+ return pids
+end
+
+-- Which member of a player's party holds one of its followers (nil: none, or no party)
+function IsowindParty.GetFollowerHolder(name, uniqueIndex)
+ local _, party = partyOf(name)
+ return party ~= nil and party.followers ~= nil and party.followers[uniqueIndex] or nil
+end
+
+function IsowindParty.SetFollowerHolder(name, uniqueIndex, holder)
+ local _, party = partyOf(name)
+ if party == nil then
+ return
+ end
+ party.followers = party.followers or {}
+ party.followers[uniqueIndex] = holder
+ WorldInstance:QuicksaveToDrive()
+end
+
-- --- Sharing ----------------------------------------------------------------------------------------------------
local function journalKey(item)
@@ -82,17 +117,24 @@ local function isQuestVariable(id)
return tableHelper.containsCaseInsensitiveString(clientVariableScopes.globals.quest, id)
end
--- Journal entries a member doesn't have yet: saved for them, and sent if they're on
+-- Journal entries a member doesn't have yet: saved for them, and sent if they're on. Only those that move them forward:
+-- an entry or index below the stage they're at in that quest would set them back (the game takes an entry's index as
+-- the quest's).
local function giveJournal(player, items)
player.data.journal = player.data.journal or {}
local have = {}
+ local reached = {}
for _, item in ipairs(player.data.journal) do
have[journalKey(item)] = true
+ local quest = lower(item.quest)
+ reached[quest] = math.max(reached[quest] or item.index, item.index)
end
local missing = {}
for _, item in ipairs(items) do
- if not have[journalKey(item)] then
+ local quest = lower(item.quest)
+ if not have[journalKey(item)] and (reached[quest] == nil or item.index >= reached[quest]) then
have[journalKey(item)] = true
+ reached[quest] = item.index
table.insert(missing, item)
end
end
@@ -347,6 +389,15 @@ local function leave(pid)
message(pid, "You're not in a party.")
return
end
+ -- The party's followers this member had that follow them go to another member who is on, or else stay theirs
+ if IsowindFollowers ~= nil then
+ IsowindFollowers.OnLeavingParty(pid)
+ end
+ for uniqueIndex, holder in pairs(party.followers or {}) do
+ if holder == name then
+ party.followers[uniqueIndex] = nil
+ end
+ end
tableHelper.removeValue(party.members, name)
tableHelper.cleanNils(party.members)
forOtherMembers(party, name, function(member)
diff --git a/isowind/server/CoreScripts/scripts/customScripts.lua b/isowind/server/CoreScripts/scripts/customScripts.lua
index 429aa7e..2d8db72 100644
--- a/isowind/server/CoreScripts/scripts/customScripts.lua
+++ b/isowind/server/CoreScripts/scripts/customScripts.lua
@@ -7,6 +7,7 @@
require("custom/isowindHost")
+require("custom/isowindFollowers")
require("custom/isowindMmo")
require("custom/isowindParty")
require("custom/isowindLocks")