id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35,426
|
soundextensions.cpp
|
OpenMW_openmw/apps/openmw/mwscript/soundextensions.cpp
|
#include "soundextensions.hpp"
#include <components/compiler/opcodes.hpp>
#include <components/interpreter/interpreter.hpp>
#include <components/interpreter/opcodes.hpp>
#include <components/interpreter/runtime.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/inventorystore.hpp"
#include "interpretercontext.hpp"
#include "ref.hpp"
namespace MWScript
{
namespace Sound
{
template <class R>
class OpSay : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&>(runtime.getContext());
VFS::Path::Normalized file{ runtime.getStringLiteral(runtime[0].mInteger) };
runtime.pop();
std::string_view text = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
MWBase::Environment::get().getSoundManager()->say(ptr, Misc::ResourceHelpers::correctSoundPath(file));
if (Settings::gui().mSubtitles)
context.messageBox(text);
}
};
template <class R>
class OpSayDone : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
runtime.push(MWBase::Environment::get().getSoundManager()->sayDone(ptr));
}
};
class OpStreamMusic : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
const VFS::Path::Normalized music(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
MWBase::Environment::get().getSoundManager()->streamMusic(
Misc::ResourceHelpers::correctMusicPath(music), MWSound::MusicType::MWScript);
}
};
class OpPlaySound : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
ESM::RefId sound = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
MWBase::Environment::get().getSoundManager()->playSound(
sound, 1.0, 1.0, MWSound::Type::Sfx, MWSound::PlayMode::NoEnv);
}
};
class OpPlaySoundVP : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
ESM::RefId sound = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
Interpreter::Type_Float volume = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float pitch = runtime[0].mFloat;
runtime.pop();
MWBase::Environment::get().getSoundManager()->playSound(
sound, volume, pitch, MWSound::Type::Sfx, MWSound::PlayMode::NoEnv);
}
};
template <class R, bool TLoop>
class OpPlaySound3D : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId sound = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
MWBase::Environment::get().getSoundManager()->playSound3D(ptr, sound, 1.0, 1.0, MWSound::Type::Sfx,
TLoop ? MWSound::PlayMode::LoopRemoveAtDistance : MWSound::PlayMode::Normal);
}
};
template <class R, bool TLoop>
class OpPlaySoundVP3D : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId sound = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
Interpreter::Type_Float volume = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float pitch = runtime[0].mFloat;
runtime.pop();
MWBase::Environment::get().getSoundManager()->playSound3D(ptr, sound, volume, pitch, MWSound::Type::Sfx,
TLoop ? MWSound::PlayMode::LoopRemoveAtDistance : MWSound::PlayMode::Normal);
}
};
template <class R>
class OpStopSound : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId sound = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
MWBase::Environment::get().getSoundManager()->stopSound3D(ptr, sound);
}
};
template <class R>
class OpGetSoundPlaying : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
int index = runtime[0].mInteger;
runtime.pop();
bool ret = MWBase::Environment::get().getSoundManager()->getSoundPlaying(
ptr, ESM::RefId::stringRefId(runtime.getStringLiteral(index)));
// GetSoundPlaying called on an equipped item should also look for sounds played by the equipping actor.
if (!ret && ptr.getContainerStore())
{
MWWorld::Ptr cont = MWBase::Environment::get().getWorld()->findContainer(ptr);
if (!cont.isEmpty() && cont.getClass().hasInventoryStore(cont)
&& cont.getClass().getInventoryStore(cont).isEquipped(ptr))
{
ret = MWBase::Environment::get().getSoundManager()->getSoundPlaying(
cont, ESM::RefId::stringRefId(runtime.getStringLiteral(index)));
}
}
runtime.push(ret);
}
};
void installOpcodes(Interpreter::Interpreter& interpreter)
{
interpreter.installSegment5<OpSay<ImplicitRef>>(Compiler::Sound::opcodeSay);
interpreter.installSegment5<OpSayDone<ImplicitRef>>(Compiler::Sound::opcodeSayDone);
interpreter.installSegment5<OpStreamMusic>(Compiler::Sound::opcodeStreamMusic);
interpreter.installSegment5<OpPlaySound>(Compiler::Sound::opcodePlaySound);
interpreter.installSegment5<OpPlaySoundVP>(Compiler::Sound::opcodePlaySoundVP);
interpreter.installSegment5<OpPlaySound3D<ImplicitRef, false>>(Compiler::Sound::opcodePlaySound3D);
interpreter.installSegment5<OpPlaySoundVP3D<ImplicitRef, false>>(Compiler::Sound::opcodePlaySound3DVP);
interpreter.installSegment5<OpPlaySound3D<ImplicitRef, true>>(Compiler::Sound::opcodePlayLoopSound3D);
interpreter.installSegment5<OpPlaySoundVP3D<ImplicitRef, true>>(Compiler::Sound::opcodePlayLoopSound3DVP);
interpreter.installSegment5<OpStopSound<ImplicitRef>>(Compiler::Sound::opcodeStopSound);
interpreter.installSegment5<OpGetSoundPlaying<ImplicitRef>>(Compiler::Sound::opcodeGetSoundPlaying);
interpreter.installSegment5<OpSay<ExplicitRef>>(Compiler::Sound::opcodeSayExplicit);
interpreter.installSegment5<OpSayDone<ExplicitRef>>(Compiler::Sound::opcodeSayDoneExplicit);
interpreter.installSegment5<OpPlaySound3D<ExplicitRef, false>>(Compiler::Sound::opcodePlaySound3DExplicit);
interpreter.installSegment5<OpPlaySoundVP3D<ExplicitRef, false>>(
Compiler::Sound::opcodePlaySound3DVPExplicit);
interpreter.installSegment5<OpPlaySound3D<ExplicitRef, true>>(
Compiler::Sound::opcodePlayLoopSound3DExplicit);
interpreter.installSegment5<OpPlaySoundVP3D<ExplicitRef, true>>(
Compiler::Sound::opcodePlayLoopSound3DVPExplicit);
interpreter.installSegment5<OpStopSound<ExplicitRef>>(Compiler::Sound::opcodeStopSoundExplicit);
interpreter.installSegment5<OpGetSoundPlaying<ExplicitRef>>(Compiler::Sound::opcodeGetSoundPlayingExplicit);
}
}
}
| 8,900
|
C++
|
.cpp
| 177
| 37.440678
| 120
| 0.615225
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,427
|
cellextensions.cpp
|
OpenMW_openmw/apps/openmw/mwscript/cellextensions.cpp
|
#include "cellextensions.hpp"
#include <limits>
#include <components/compiler/opcodes.hpp>
#include <components/interpreter/context.hpp>
#include <components/interpreter/interpreter.hpp>
#include <components/interpreter/opcodes.hpp>
#include <components/interpreter/runtime.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/esm/util.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/statemanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/actionteleport.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/scene.hpp"
#include "../mwmechanics/actorutil.hpp"
namespace MWScript
{
namespace Cell
{
class OpCellChanged : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
runtime.push(MWBase::Environment::get().getWorldScene()->hasCellChanged() ? 1 : 0);
}
};
class OpTestCells : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
if (MWBase::Environment::get().getStateManager()->getState() != MWBase::StateManager::State_NoGame)
{
runtime.getContext().report(
"Use TestCells from the main menu, when there is no active game session.");
return;
}
bool wasConsole = MWBase::Environment::get().getWindowManager()->isConsoleMode();
if (wasConsole)
MWBase::Environment::get().getWindowManager()->toggleConsole();
MWBase::Environment::get().getWorldScene()->testExteriorCells();
if (wasConsole)
MWBase::Environment::get().getWindowManager()->toggleConsole();
}
};
class OpTestInteriorCells : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
if (MWBase::Environment::get().getStateManager()->getState() != MWBase::StateManager::State_NoGame)
{
runtime.getContext().report(
"Use TestInteriorCells from the main menu, when there is no active game session.");
return;
}
bool wasConsole = MWBase::Environment::get().getWindowManager()->isConsoleMode();
if (wasConsole)
MWBase::Environment::get().getWindowManager()->toggleConsole();
MWBase::Environment::get().getWorldScene()->testInteriorCells();
if (wasConsole)
MWBase::Environment::get().getWindowManager()->toggleConsole();
}
};
class OpCOC : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
std::string_view cell = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
ESM::Position pos;
MWBase::World* world = MWBase::Environment::get().getWorld();
MWWorld::Ptr playerPtr = world->getPlayerPtr();
if (const ESM::RefId refId = world->findExteriorPosition(cell, pos); !refId.empty())
{
MWWorld::ActionTeleport(refId, pos, false).execute(playerPtr);
playerPtr = world->getPlayerPtr(); // could be changed by ActionTeleport
world->adjustPosition(playerPtr, false);
return;
}
if (const ESM::RefId refId = world->findInteriorPosition(cell, pos); !refId.empty())
{
MWWorld::ActionTeleport(refId, pos, false).execute(playerPtr);
return;
}
throw std::runtime_error("Cell " + std::string(cell) + " is not found");
}
};
class OpCOE : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
Interpreter::Type_Integer x = runtime[0].mInteger;
runtime.pop();
Interpreter::Type_Integer y = runtime[0].mInteger;
runtime.pop();
ESM::Position pos;
MWBase::World* world = MWBase::Environment::get().getWorld();
MWWorld::Ptr playerPtr = world->getPlayerPtr();
const osg::Vec2f posFromIndex
= ESM::indexToPosition(ESM::ExteriorCellLocation(x, y, ESM::Cell::sDefaultWorldspaceId), true);
pos.pos[0] = posFromIndex.x();
pos.pos[1] = posFromIndex.y();
pos.pos[2] = 0;
pos.rot[0] = pos.rot[1] = pos.rot[2] = 0;
MWWorld::ActionTeleport(ESM::RefId::esm3ExteriorCell(x, y), pos, false).execute(playerPtr);
playerPtr = world->getPlayerPtr(); // could be changed by ActionTeleport
world->adjustPosition(playerPtr, false);
}
};
class OpGetInterior : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
if (!MWMechanics::getPlayer().isInCell())
{
runtime.push(0);
return;
}
bool interior = !MWMechanics::getPlayer().getCell()->getCell()->isExterior();
runtime.push(interior ? 1 : 0);
}
};
class OpGetPCCell : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
std::string_view name = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
if (!MWMechanics::getPlayer().isInCell())
{
runtime.push(0);
return;
}
const MWWorld::CellStore* cell = MWMechanics::getPlayer().getCell();
std::string_view current = MWBase::Environment::get().getWorld()->getCellName(cell);
bool match = Misc::StringUtils::ciCompareLen(name, current, name.length()) == 0;
runtime.push(match ? 1 : 0);
}
};
class OpGetWaterLevel : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
if (!MWMechanics::getPlayer().isInCell())
{
runtime.push(0.f);
return;
}
MWWorld::CellStore* cell = MWMechanics::getPlayer().getCell();
if (cell->isExterior())
runtime.push(0.f); // vanilla oddity, return 0 even though water is actually at -1
else if (cell->getCell()->hasWater())
runtime.push(cell->getWaterLevel());
else
runtime.push(-std::numeric_limits<float>::max());
}
};
class OpSetWaterLevel : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
Interpreter::Type_Float level = runtime[0].mFloat;
runtime.pop();
if (!MWMechanics::getPlayer().isInCell())
{
return;
}
MWWorld::CellStore* cell = MWMechanics::getPlayer().getCell();
if (cell->getCell()->isExterior())
throw std::runtime_error("Can't set water level in exterior cell");
cell->setWaterLevel(level);
MWBase::Environment::get().getWorld()->setWaterHeight(cell->getWaterLevel());
}
};
class OpModWaterLevel : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
Interpreter::Type_Float level = runtime[0].mFloat;
runtime.pop();
if (!MWMechanics::getPlayer().isInCell())
{
return;
}
MWWorld::CellStore* cell = MWMechanics::getPlayer().getCell();
if (cell->getCell()->isExterior())
throw std::runtime_error("Can't set water level in exterior cell");
cell->setWaterLevel(cell->getWaterLevel() + level);
MWBase::Environment::get().getWorld()->setWaterHeight(cell->getWaterLevel());
}
};
void installOpcodes(Interpreter::Interpreter& interpreter)
{
interpreter.installSegment5<OpCellChanged>(Compiler::Cell::opcodeCellChanged);
interpreter.installSegment5<OpTestCells>(Compiler::Cell::opcodeTestCells);
interpreter.installSegment5<OpTestInteriorCells>(Compiler::Cell::opcodeTestInteriorCells);
interpreter.installSegment5<OpCOC>(Compiler::Cell::opcodeCOC);
interpreter.installSegment5<OpCOE>(Compiler::Cell::opcodeCOE);
interpreter.installSegment5<OpGetInterior>(Compiler::Cell::opcodeGetInterior);
interpreter.installSegment5<OpGetPCCell>(Compiler::Cell::opcodeGetPCCell);
interpreter.installSegment5<OpGetWaterLevel>(Compiler::Cell::opcodeGetWaterLevel);
interpreter.installSegment5<OpSetWaterLevel>(Compiler::Cell::opcodeSetWaterLevel);
interpreter.installSegment5<OpModWaterLevel>(Compiler::Cell::opcodeModWaterLevel);
}
}
}
| 9,870
|
C++
|
.cpp
| 217
| 31.654378
| 115
| 0.558123
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,428
|
ref.cpp
|
OpenMW_openmw/apps/openmw/mwscript/ref.cpp
|
#include "ref.hpp"
#include <components/interpreter/runtime.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp"
#include "interpretercontext.hpp"
MWWorld::Ptr MWScript::ExplicitRef::operator()(Interpreter::Runtime& runtime, bool required, bool activeOnly) const
{
ESM::RefId id = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
if (required)
return MWBase::Environment::get().getWorld()->getPtr(id, activeOnly);
else
return MWBase::Environment::get().getWorld()->searchPtr(id, activeOnly);
}
MWWorld::Ptr MWScript::ImplicitRef::operator()(Interpreter::Runtime& runtime, bool required, bool activeOnly) const
{
MWScript::InterpreterContext& context = static_cast<MWScript::InterpreterContext&>(runtime.getContext());
return context.getReference(required);
}
| 864
|
C++
|
.cpp
| 19
| 42
| 115
| 0.752983
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,429
|
scriptmanagerimp.cpp
|
OpenMW_openmw/apps/openmw/mwscript/scriptmanagerimp.cpp
|
#include "scriptmanagerimp.hpp"
#include <algorithm>
#include <cassert>
#include <exception>
#include <sstream>
#include <components/debug/debuglog.hpp>
#include <components/esm/refid.hpp>
#include <components/esm3/loadscpt.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/compiler/context.hpp>
#include <components/compiler/exception.hpp>
#include <components/compiler/quickfileparser.hpp>
#include <components/compiler/scanner.hpp>
#include "../mwworld/esmstore.hpp"
#include "extensions.hpp"
#include "interpretercontext.hpp"
namespace MWScript
{
ScriptManager::ScriptManager(const MWWorld::ESMStore& store, Compiler::Context& compilerContext, int warningsMode)
: mErrorHandler()
, mStore(store)
, mCompilerContext(compilerContext)
, mParser(mErrorHandler, mCompilerContext)
, mGlobalScripts(store)
{
installOpcodes(mInterpreter);
mErrorHandler.setWarningsMode(warningsMode);
}
bool ScriptManager::compile(const ESM::RefId& name)
{
mParser.reset();
mErrorHandler.reset();
if (const ESM::Script* script = mStore.get<ESM::Script>().find(name))
{
mErrorHandler.setContext(script->mId.getRefIdString());
bool Success = true;
try
{
std::istringstream input(script->mScriptText);
Compiler::Scanner scanner(mErrorHandler, input, mCompilerContext.getExtensions());
scanner.scan(mParser);
if (!mErrorHandler.isGood())
Success = false;
}
catch (const Compiler::SourceException&)
{
// error has already been reported via error handler
Success = false;
}
catch (const std::exception& error)
{
Log(Debug::Error) << "Error: An exception has been thrown: " << error.what();
Success = false;
}
if (!Success)
{
Log(Debug::Error) << "Error: script compiling failed: " << name;
}
if (Success)
{
mScripts.emplace(name, CompiledScript(mParser.getProgram(), mParser.getLocals()));
return true;
}
}
return false;
}
bool ScriptManager::run(const ESM::RefId& name, Interpreter::Context& interpreterContext)
{
// compile script
auto iter = mScripts.find(name);
if (iter == mScripts.end())
{
if (!compile(name))
{
// failed -> ignore script from now on.
mScripts.emplace(name, CompiledScript({}, Compiler::Locals()));
return false;
}
iter = mScripts.find(name);
assert(iter != mScripts.end());
}
// execute script
const auto& target = interpreterContext.getTarget();
if (!iter->second.mProgram.mInstructions.empty()
&& iter->second.mInactive.find(target) == iter->second.mInactive.end())
{
try
{
mInterpreter.run(iter->second.mProgram, interpreterContext);
return true;
}
catch (const MissingImplicitRefError& e)
{
Log(Debug::Error) << "Execution of script " << name << " failed: " << e.what();
}
catch (const std::exception& e)
{
Log(Debug::Error) << "Execution of script " << name << " failed: " << e.what();
iter->second.mInactive.insert(target); // don't execute again.
}
}
return false;
}
void ScriptManager::clear()
{
for (auto& script : mScripts)
{
script.second.mInactive.clear();
}
mGlobalScripts.clear();
}
std::pair<int, int> ScriptManager::compileAll()
{
int count = 0;
int success = 0;
for (auto& script : mStore.get<ESM::Script>())
{
++count;
if (compile(script.mId))
++success;
}
return std::make_pair(count, success);
}
const Compiler::Locals& ScriptManager::getLocals(const ESM::RefId& name)
{
{
auto iter = mScripts.find(name);
if (iter != mScripts.end())
return iter->second.mLocals;
}
{
auto iter = mOtherLocals.find(name);
if (iter != mOtherLocals.end())
return iter->second;
}
if (const ESM::Script* script = mStore.get<ESM::Script>().search(name))
{
Compiler::Locals locals;
const Compiler::ContextOverride override(mErrorHandler, name.getRefIdString() + "[local variables]");
std::istringstream stream(script->mScriptText);
Compiler::QuickFileParser parser(mErrorHandler, mCompilerContext, locals);
Compiler::Scanner scanner(mErrorHandler, stream, mCompilerContext.getExtensions());
try
{
scanner.scan(parser);
}
catch (const Compiler::SourceException&)
{
// error has already been reported via error handler
locals.clear();
}
catch (const std::exception& error)
{
Log(Debug::Error) << "Error: An exception has been thrown: " << error.what();
locals.clear();
}
auto iter = mOtherLocals.emplace(name, locals).first;
return iter->second;
}
throw std::logic_error("script " + name.toDebugString() + " does not exist");
}
GlobalScripts& ScriptManager::getGlobalScripts()
{
return mGlobalScripts;
}
const Compiler::Extensions& ScriptManager::getExtensions() const
{
return *mCompilerContext.getExtensions();
}
}
| 6,031
|
C++
|
.cpp
| 170
| 25.052941
| 118
| 0.56264
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,430
|
transformationextensions.cpp
|
OpenMW_openmw/apps/openmw/mwscript/transformationextensions.cpp
|
#include <components/debug/debuglog.hpp>
#include <components/sceneutil/positionattitudetransform.hpp>
#include <components/esm3/loadcell.hpp>
#include <components/esm/util.hpp>
#include <components/compiler/opcodes.hpp>
#include <components/interpreter/interpreter.hpp>
#include <components/interpreter/opcodes.hpp>
#include <components/interpreter/runtime.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/luamanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/manualref.hpp"
#include "../mwworld/player.hpp"
#include "../mwworld/scene.hpp"
#include "../mwworld/worldmodel.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "interpretercontext.hpp"
#include "ref.hpp"
namespace MWScript
{
namespace Transformation
{
void moveStandingActors(const MWWorld::Ptr& ptr, const osg::Vec3f& diff)
{
std::vector<MWWorld::Ptr> actors;
MWBase::Environment::get().getWorld()->getActorsStandingOn(ptr, actors);
for (auto& actor : actors)
MWBase::Environment::get().getWorld()->moveObjectBy(actor, diff, false);
}
template <class R>
class OpGetDistance : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr from = R()(runtime, !R::implicit);
ESM::RefId name = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
if (from.isEmpty())
{
std::string error = "Missing implicit ref";
runtime.getContext().report(error);
Log(Debug::Error) << error;
runtime.push(0.f);
return;
}
if (from.getContainerStore()) // is the object contained?
{
MWWorld::Ptr container = MWBase::Environment::get().getWorld()->findContainer(from);
if (!container.isEmpty())
from = container;
else
{
const std::string error
= "Failed to find the container of object " + from.getCellRef().getRefId().toDebugString();
runtime.getContext().report(error);
Log(Debug::Error) << error;
runtime.push(0.f);
return;
}
}
const MWWorld::Ptr to = MWBase::Environment::get().getWorld()->searchPtr(name, false);
if (to.isEmpty())
{
const std::string error = "Failed to find an instance of object " + name.toDebugString();
runtime.getContext().report(error);
Log(Debug::Error) << error;
runtime.push(0.f);
return;
}
float distance;
// If the objects are in different worldspaces, return a large value (just like vanilla)
if (!to.isInCell() || !from.isInCell()
|| to.getCell()->getCell()->getWorldSpace() != from.getCell()->getCell()->getWorldSpace())
distance = std::numeric_limits<float>::max();
else
{
double diff[3];
const float* const pos1 = to.getRefData().getPosition().pos;
const float* const pos2 = from.getRefData().getPosition().pos;
for (int i = 0; i < 3; ++i)
diff[i] = pos1[i] - pos2[i];
distance = static_cast<float>(std::sqrt(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]));
}
runtime.push(distance);
}
};
template <class R>
class OpSetScale : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Float scale = runtime[0].mFloat;
runtime.pop();
MWBase::Environment::get().getWorld()->scaleObject(ptr, scale);
}
};
template <class R>
class OpGetScale : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
runtime.push(ptr.getCellRef().getScale());
}
};
template <class R>
class OpModScale : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Float scale = runtime[0].mFloat;
runtime.pop();
// add the parameter to the object's scale.
MWBase::Environment::get().getWorld()->scaleObject(ptr, ptr.getCellRef().getScale() + scale);
}
};
template <class R>
class OpSetAngle : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
std::string_view axis = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Float angle = osg::DegreesToRadians(runtime[0].mFloat);
runtime.pop();
float ax = ptr.getRefData().getPosition().rot[0];
float ay = ptr.getRefData().getPosition().rot[1];
float az = ptr.getRefData().getPosition().rot[2];
// XYZ axis use the inverse (XYZ) rotation order like vanilla SetAngle.
// UVW axis use the standard (ZYX) rotation order like TESCS/OpenMW-CS and the rest of the game.
if (axis == "x")
MWBase::Environment::get().getWorld()->rotateObject(
ptr, osg::Vec3f(angle, ay, az), MWBase::RotationFlag_inverseOrder);
else if (axis == "y")
MWBase::Environment::get().getWorld()->rotateObject(
ptr, osg::Vec3f(ax, angle, az), MWBase::RotationFlag_inverseOrder);
else if (axis == "z")
MWBase::Environment::get().getWorld()->rotateObject(
ptr, osg::Vec3f(ax, ay, angle), MWBase::RotationFlag_inverseOrder);
else if (axis == "u")
MWBase::Environment::get().getWorld()->rotateObject(
ptr, osg::Vec3f(angle, ay, az), MWBase::RotationFlag_none);
else if (axis == "v")
MWBase::Environment::get().getWorld()->rotateObject(
ptr, osg::Vec3f(ax, angle, az), MWBase::RotationFlag_none);
else if (axis == "w")
MWBase::Environment::get().getWorld()->rotateObject(
ptr, osg::Vec3f(ax, ay, angle), MWBase::RotationFlag_none);
}
};
template <class R>
class OpGetStartingAngle : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
std::string_view axis = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
float ret = 0.f;
if (!axis.empty())
{
if (axis[0] == 'x')
{
ret = osg::RadiansToDegrees(ptr.getCellRef().getPosition().rot[0]);
}
else if (axis[0] == 'y')
{
ret = osg::RadiansToDegrees(ptr.getCellRef().getPosition().rot[1]);
}
else if (axis[0] == 'z')
{
ret = osg::RadiansToDegrees(ptr.getCellRef().getPosition().rot[2]);
}
}
runtime.push(ret);
}
};
template <class R>
class OpGetAngle : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
std::string_view axis = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
float ret = 0.f;
if (!axis.empty())
{
if (axis[0] == 'x')
{
ret = osg::RadiansToDegrees(ptr.getRefData().getPosition().rot[0]);
}
else if (axis[0] == 'y')
{
ret = osg::RadiansToDegrees(ptr.getRefData().getPosition().rot[1]);
}
else if (axis[0] == 'z')
{
ret = osg::RadiansToDegrees(ptr.getRefData().getPosition().rot[2]);
}
}
runtime.push(ret);
}
};
template <class R>
class OpGetPos : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
std::string_view axis = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
float ret = 0.f;
if (!axis.empty())
{
if (axis[0] == 'x')
{
ret = ptr.getRefData().getPosition().pos[0];
}
else if (axis[0] == 'y')
{
ret = ptr.getRefData().getPosition().pos[1];
}
else if (axis[0] == 'z')
{
ret = ptr.getRefData().getPosition().pos[2];
}
}
runtime.push(ret);
}
};
template <class R>
class OpSetPos : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
std::string_view axis = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Float pos = runtime[0].mFloat;
runtime.pop();
if (!ptr.isInCell())
return;
// Note: SetPos does not skip weather transitions in vanilla engine, so we do not call
// setTeleported(true) here.
const auto curPos = ptr.getRefData().getPosition().asVec3();
auto newPos = curPos;
if (axis == "x")
{
newPos[0] = pos;
}
else if (axis == "y")
{
newPos[1] = pos;
}
else if (axis == "z")
{
// We should not place actors under ground
if (ptr.getClass().isActor())
{
float terrainHeight = -std::numeric_limits<float>::max();
if (ptr.getCell()->isExterior())
terrainHeight = MWBase::Environment::get().getWorld()->getTerrainHeightAt(
curPos, ptr.getCell()->getCell()->getWorldSpace());
if (pos < terrainHeight)
pos = terrainHeight;
}
newPos[2] = pos;
}
else
{
return;
}
dynamic_cast<MWScript::InterpreterContext&>(runtime.getContext())
.updatePtr(ptr, MWBase::Environment::get().getWorld()->moveObjectBy(ptr, newPos - curPos, true));
}
};
template <class R>
class OpGetStartingPos : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
std::string_view axis = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
float ret = 0.f;
if (!axis.empty())
{
if (axis[0] == 'x')
{
ret = ptr.getCellRef().getPosition().pos[0];
}
else if (axis[0] == 'y')
{
ret = ptr.getCellRef().getPosition().pos[1];
}
else if (axis[0] == 'z')
{
ret = ptr.getCellRef().getPosition().pos[2];
}
}
runtime.push(ret);
}
};
template <class R>
class OpPositionCell : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Float x = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float y = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float z = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float zRot = runtime[0].mFloat;
runtime.pop();
std::string_view cellID = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
if (ptr.getContainerStore())
return;
bool isPlayer = ptr == MWMechanics::getPlayer();
auto world = MWBase::Environment::get().getWorld();
auto worldModel = MWBase::Environment::get().getWorldModel();
if (ptr.getClass().isActor())
ptr.getClass().getCreatureStats(ptr).setTeleported(true);
if (isPlayer)
world->getPlayer().setTeleported(true);
MWWorld::CellStore* store = worldModel->findCell(cellID);
if (store != nullptr && store->isExterior())
store = &worldModel->getExterior(
ESM::positionToExteriorCellLocation(x, y, store->getCell()->getWorldSpace()));
if (store == nullptr)
{
// cell not found, move to exterior instead if moving the player (vanilla PositionCell
// compatibility)
std::string error = "PositionCell: unknown interior cell (" + std::string(cellID) + ")";
if (isPlayer)
error += ", moving to exterior instead";
runtime.getContext().report(error);
if (!isPlayer)
{
Log(Debug::Error) << error;
return;
}
Log(Debug::Warning) << error;
const ESM::ExteriorCellLocation cellIndex
= ESM::positionToExteriorCellLocation(x, y, ESM::Cell::sDefaultWorldspaceId);
store = &worldModel->getExterior(cellIndex);
}
MWWorld::Ptr base = ptr;
ptr = world->moveObject(ptr, store, osg::Vec3f(x, y, z));
dynamic_cast<MWScript::InterpreterContext&>(runtime.getContext()).updatePtr(base, ptr);
auto rot = ptr.getRefData().getPosition().asRotationVec3();
// Note that you must specify ZRot in minutes (1 degree = 60 minutes; north = 0, east = 5400, south
// = 10800, west = 16200) except for when you position the player, then degrees must be used. See
// "Morrowind Scripting for Dummies (9th Edition)" pages 50 and 54 for reference.
if (!isPlayer)
zRot = zRot / 60.0f;
rot.z() = osg::DegreesToRadians(zRot);
world->rotateObject(ptr, rot);
bool cellActive = MWBase::Environment::get().getWorldScene()->isCellActive(*ptr.getCell());
ptr.getClass().adjustPosition(ptr, isPlayer || !cellActive);
MWBase::Environment::get().getLuaManager()->objectTeleported(ptr);
}
};
template <class R>
class OpPosition : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Float x = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float y = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float z = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float zRot = runtime[0].mFloat;
runtime.pop();
if (!ptr.isInCell())
return;
bool isPlayer = ptr == MWMechanics::getPlayer();
auto world = MWBase::Environment::get().getWorld();
if (ptr.getClass().isActor())
ptr.getClass().getCreatureStats(ptr).setTeleported(true);
if (isPlayer)
world->getPlayer().setTeleported(true);
const ESM::ExteriorCellLocation location
= ESM::positionToExteriorCellLocation(x, y, ESM::Cell::sDefaultWorldspaceId);
// another morrowind oddity: player will be moved to the exterior cell at this location,
// non-player actors will move within the cell they are in.
MWWorld::Ptr base = ptr;
if (isPlayer)
{
MWWorld::CellStore* cell = &MWBase::Environment::get().getWorldModel()->getExterior(location);
ptr = world->moveObject(ptr, cell, osg::Vec3(x, y, z));
}
else
{
ptr = world->moveObject(ptr, osg::Vec3f(x, y, z), true, true);
}
dynamic_cast<MWScript::InterpreterContext&>(runtime.getContext()).updatePtr(base, ptr);
auto rot = ptr.getRefData().getPosition().asRotationVec3();
// Note that you must specify ZRot in minutes (1 degree = 60 minutes; north = 0, east = 5400, south =
// 10800, west = 16200) except for when you position the player, then degrees must be used. See
// "Morrowind Scripting for Dummies (9th Edition)" pages 50 and 54 for reference.
if (!isPlayer)
zRot = zRot / 60.0f;
rot.z() = osg::DegreesToRadians(zRot);
world->rotateObject(ptr, rot);
bool cellActive = MWBase::Environment::get().getWorldScene()->isCellActive(*ptr.getCell());
ptr.getClass().adjustPosition(ptr, isPlayer || !cellActive);
MWBase::Environment::get().getLuaManager()->objectTeleported(ptr);
}
};
class OpPlaceItemCell : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
const ESM::RefId itemID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
std::string_view cellName = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Float x = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float y = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float z = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float zRotDegrees = runtime[0].mFloat;
runtime.pop();
MWWorld::CellStore* const store = MWBase::Environment::get().getWorldModel()->findCell(cellName);
if (store == nullptr)
{
const std::string message = "unknown cell (" + std::string(cellName) + ")";
runtime.getContext().report(message);
Log(Debug::Error) << message;
return;
}
ESM::Position pos;
pos.pos[0] = x;
pos.pos[1] = y;
pos.pos[2] = z;
pos.rot[0] = pos.rot[1] = 0;
pos.rot[2] = osg::DegreesToRadians(zRotDegrees);
MWWorld::ManualRef ref(*MWBase::Environment::get().getESMStore(), itemID);
ref.getPtr().mRef->mData.mPhysicsPostponed = !ref.getPtr().getClass().isActor();
ref.getPtr().getCellRef().setPosition(pos);
MWWorld::Ptr placed = MWBase::Environment::get().getWorld()->placeObject(ref.getPtr(), store, pos);
placed.getClass().adjustPosition(placed, true);
}
};
class OpPlaceItem : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
ESM::RefId itemID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
Interpreter::Type_Float x = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float y = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float z = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float zRotDegrees = runtime[0].mFloat;
runtime.pop();
MWWorld::Ptr player = MWMechanics::getPlayer();
if (!player.isInCell())
throw std::runtime_error("player not in a cell");
MWWorld::CellStore* store = nullptr;
if (player.getCell()->isExterior())
{
const ESM::ExteriorCellLocation cellIndex
= ESM::positionToExteriorCellLocation(x, y, player.getCell()->getCell()->getWorldSpace());
store = &MWBase::Environment::get().getWorldModel()->getExterior(cellIndex);
}
else
store = player.getCell();
ESM::Position pos;
pos.pos[0] = x;
pos.pos[1] = y;
pos.pos[2] = z;
pos.rot[0] = pos.rot[1] = 0;
pos.rot[2] = osg::DegreesToRadians(zRotDegrees);
MWWorld::ManualRef ref(*MWBase::Environment::get().getESMStore(), itemID);
ref.getPtr().mRef->mData.mPhysicsPostponed = !ref.getPtr().getClass().isActor();
ref.getPtr().getCellRef().setPosition(pos);
MWWorld::Ptr placed = MWBase::Environment::get().getWorld()->placeObject(ref.getPtr(), store, pos);
placed.getClass().adjustPosition(placed, true);
}
};
template <class R, bool pc>
class OpPlaceAt : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr actor = pc ? MWMechanics::getPlayer() : R()(runtime);
ESM::RefId itemID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
Interpreter::Type_Integer count = runtime[0].mInteger;
runtime.pop();
Interpreter::Type_Float distance = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Integer direction = runtime[0].mInteger;
runtime.pop();
if (direction < 0 || direction > 3)
throw std::runtime_error("invalid direction");
if (count < 0)
throw std::runtime_error("count must be non-negative");
if (!actor.isInCell())
throw std::runtime_error("actor is not in a cell");
for (int i = 0; i < count; ++i)
{
// create item
MWWorld::ManualRef ref(*MWBase::Environment::get().getESMStore(), itemID, 1);
ref.getPtr().mRef->mData.mPhysicsPostponed = !ref.getPtr().getClass().isActor();
MWWorld::Ptr ptr = MWBase::Environment::get().getWorld()->safePlaceObject(
ref.getPtr(), actor, actor.getCell(), direction, distance);
MWBase::Environment::get().getWorld()->scaleObject(ptr, actor.getCellRef().getScale());
}
}
};
template <class R>
class OpRotate : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
const MWWorld::Ptr& ptr = R()(runtime);
std::string_view axis = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Float rotation
= osg::DegreesToRadians(runtime[0].mFloat * MWBase::Environment::get().getFrameDuration());
runtime.pop();
auto rot = ptr.getRefData().getPosition().asRotationVec3();
// Regardless of the axis argument, the player may only be rotated on Z
if (axis == "z" || MWMechanics::getPlayer() == ptr)
rot.z() += rotation;
else if (axis == "x")
rot.x() += rotation;
else if (axis == "y")
rot.y() += rotation;
MWBase::Environment::get().getWorld()->rotateObject(ptr, rot);
}
};
template <class R>
class OpRotateWorld : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
std::string_view axis = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Float rotation
= osg::DegreesToRadians(runtime[0].mFloat * MWBase::Environment::get().getFrameDuration());
runtime.pop();
if (!ptr.getRefData().getBaseNode())
return;
// We can rotate actors only around Z axis
if (ptr.getClass().isActor() && (axis == "x" || axis == "y"))
return;
osg::Quat rot;
if (axis == "x")
rot = osg::Quat(rotation, -osg::X_AXIS);
else if (axis == "y")
rot = osg::Quat(rotation, -osg::Y_AXIS);
else if (axis == "z")
rot = osg::Quat(rotation, -osg::Z_AXIS);
else
return;
osg::Quat attitude = ptr.getRefData().getBaseNode()->getAttitude();
MWBase::Environment::get().getWorld()->rotateWorldObject(ptr, attitude * rot);
}
};
template <class R>
class OpSetAtStart : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
if (!ptr.isInCell())
return;
MWBase::Environment::get().getWorld()->rotateObject(
ptr, ptr.getCellRef().getPosition().asRotationVec3());
dynamic_cast<MWScript::InterpreterContext&>(runtime.getContext())
.updatePtr(ptr,
MWBase::Environment::get().getWorld()->moveObject(
ptr, ptr.getCellRef().getPosition().asVec3()));
}
};
template <class R>
class OpMove : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
const MWWorld::Ptr& ptr = R()(runtime);
if (!ptr.isInCell())
return;
std::string_view axis = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Float movement = (runtime[0].mFloat * MWBase::Environment::get().getFrameDuration());
runtime.pop();
osg::Vec3f posChange;
if (axis == "x")
{
posChange = osg::Vec3f(movement, 0, 0);
}
else if (axis == "y")
{
posChange = osg::Vec3f(0, movement, 0);
}
else if (axis == "z")
{
posChange = osg::Vec3f(0, 0, movement);
}
else
return;
// is it correct that disabled objects can't be Move-d?
if (!ptr.getRefData().getBaseNode())
return;
osg::Vec3f diff = ptr.getRefData().getBaseNode()->getAttitude() * posChange;
// We should move actors, standing on moving object, too.
// This approach can be used to create elevators.
moveStandingActors(ptr, diff);
dynamic_cast<MWScript::InterpreterContext&>(runtime.getContext())
.updatePtr(ptr, MWBase::Environment::get().getWorld()->moveObjectBy(ptr, diff, false));
}
};
template <class R>
class OpMoveWorld : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
if (!ptr.isInCell())
return;
std::string_view axis = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Float movement = (runtime[0].mFloat * MWBase::Environment::get().getFrameDuration());
runtime.pop();
osg::Vec3f diff;
if (axis == "x")
diff.x() = movement;
else if (axis == "y")
diff.y() = movement;
else if (axis == "z")
diff.z() = movement;
else
return;
// We should move actors, standing on moving object, too.
// This approach can be used to create elevators.
moveStandingActors(ptr, diff);
dynamic_cast<MWScript::InterpreterContext&>(runtime.getContext())
.updatePtr(ptr, MWBase::Environment::get().getWorld()->moveObjectBy(ptr, diff, false));
}
};
class OpResetActors : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWBase::Environment::get().getWorld()->resetActors();
}
};
class OpFixme : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWBase::Environment::get().getWorld()->fixPosition();
}
};
void installOpcodes(Interpreter::Interpreter& interpreter)
{
interpreter.installSegment5<OpGetDistance<ImplicitRef>>(Compiler::Transformation::opcodeGetDistance);
interpreter.installSegment5<OpGetDistance<ExplicitRef>>(
Compiler::Transformation::opcodeGetDistanceExplicit);
interpreter.installSegment5<OpSetScale<ImplicitRef>>(Compiler::Transformation::opcodeSetScale);
interpreter.installSegment5<OpSetScale<ExplicitRef>>(Compiler::Transformation::opcodeSetScaleExplicit);
interpreter.installSegment5<OpSetAngle<ImplicitRef>>(Compiler::Transformation::opcodeSetAngle);
interpreter.installSegment5<OpSetAngle<ExplicitRef>>(Compiler::Transformation::opcodeSetAngleExplicit);
interpreter.installSegment5<OpGetScale<ImplicitRef>>(Compiler::Transformation::opcodeGetScale);
interpreter.installSegment5<OpGetScale<ExplicitRef>>(Compiler::Transformation::opcodeGetScaleExplicit);
interpreter.installSegment5<OpGetAngle<ImplicitRef>>(Compiler::Transformation::opcodeGetAngle);
interpreter.installSegment5<OpGetAngle<ExplicitRef>>(Compiler::Transformation::opcodeGetAngleExplicit);
interpreter.installSegment5<OpGetPos<ImplicitRef>>(Compiler::Transformation::opcodeGetPos);
interpreter.installSegment5<OpGetPos<ExplicitRef>>(Compiler::Transformation::opcodeGetPosExplicit);
interpreter.installSegment5<OpSetPos<ImplicitRef>>(Compiler::Transformation::opcodeSetPos);
interpreter.installSegment5<OpSetPos<ExplicitRef>>(Compiler::Transformation::opcodeSetPosExplicit);
interpreter.installSegment5<OpGetStartingPos<ImplicitRef>>(Compiler::Transformation::opcodeGetStartingPos);
interpreter.installSegment5<OpGetStartingPos<ExplicitRef>>(
Compiler::Transformation::opcodeGetStartingPosExplicit);
interpreter.installSegment5<OpPosition<ImplicitRef>>(Compiler::Transformation::opcodePosition);
interpreter.installSegment5<OpPosition<ExplicitRef>>(Compiler::Transformation::opcodePositionExplicit);
interpreter.installSegment5<OpPositionCell<ImplicitRef>>(Compiler::Transformation::opcodePositionCell);
interpreter.installSegment5<OpPositionCell<ExplicitRef>>(
Compiler::Transformation::opcodePositionCellExplicit);
interpreter.installSegment5<OpPlaceItemCell>(Compiler::Transformation::opcodePlaceItemCell);
interpreter.installSegment5<OpPlaceItem>(Compiler::Transformation::opcodePlaceItem);
interpreter.installSegment5<OpPlaceAt<ImplicitRef, true>>(Compiler::Transformation::opcodePlaceAtPc);
interpreter.installSegment5<OpPlaceAt<ImplicitRef, false>>(Compiler::Transformation::opcodePlaceAtMe);
interpreter.installSegment5<OpPlaceAt<ExplicitRef, false>>(
Compiler::Transformation::opcodePlaceAtMeExplicit);
interpreter.installSegment5<OpModScale<ImplicitRef>>(Compiler::Transformation::opcodeModScale);
interpreter.installSegment5<OpModScale<ExplicitRef>>(Compiler::Transformation::opcodeModScaleExplicit);
interpreter.installSegment5<OpRotate<ImplicitRef>>(Compiler::Transformation::opcodeRotate);
interpreter.installSegment5<OpRotate<ExplicitRef>>(Compiler::Transformation::opcodeRotateExplicit);
interpreter.installSegment5<OpRotateWorld<ImplicitRef>>(Compiler::Transformation::opcodeRotateWorld);
interpreter.installSegment5<OpRotateWorld<ExplicitRef>>(
Compiler::Transformation::opcodeRotateWorldExplicit);
interpreter.installSegment5<OpSetAtStart<ImplicitRef>>(Compiler::Transformation::opcodeSetAtStart);
interpreter.installSegment5<OpSetAtStart<ExplicitRef>>(Compiler::Transformation::opcodeSetAtStartExplicit);
interpreter.installSegment5<OpMove<ImplicitRef>>(Compiler::Transformation::opcodeMove);
interpreter.installSegment5<OpMove<ExplicitRef>>(Compiler::Transformation::opcodeMoveExplicit);
interpreter.installSegment5<OpMoveWorld<ImplicitRef>>(Compiler::Transformation::opcodeMoveWorld);
interpreter.installSegment5<OpMoveWorld<ExplicitRef>>(Compiler::Transformation::opcodeMoveWorldExplicit);
interpreter.installSegment5<OpGetStartingAngle<ImplicitRef>>(
Compiler::Transformation::opcodeGetStartingAngle);
interpreter.installSegment5<OpGetStartingAngle<ExplicitRef>>(
Compiler::Transformation::opcodeGetStartingAngleExplicit);
interpreter.installSegment5<OpResetActors>(Compiler::Transformation::opcodeResetActors);
interpreter.installSegment5<OpFixme>(Compiler::Transformation::opcodeFixme);
}
}
}
| 37,115
|
C++
|
.cpp
| 752
| 33.321809
| 120
| 0.529186
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,431
|
containerextensions.cpp
|
OpenMW_openmw/apps/openmw/mwscript/containerextensions.cpp
|
#include "containerextensions.hpp"
#include <stdexcept>
#include <MyGUI_LanguageManager.h>
#include <components/debug/debuglog.hpp>
#include <components/compiler/opcodes.hpp>
#include <components/interpreter/interpreter.hpp>
#include <components/interpreter/opcodes.hpp>
#include <components/misc/strings/format.hpp>
#include <components/esm3/loadcrea.hpp>
#include <components/esm3/loadlevlist.hpp>
#include <components/esm3/loadskil.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/action.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/manualref.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/levelledlist.hpp"
#include "interpretercontext.hpp"
#include "ref.hpp"
namespace
{
void addToStore(const MWWorld::Ptr& itemPtr, int count, MWWorld::ContainerStore& store, bool resolve = true)
{
if (itemPtr.getClass().getScript(itemPtr).empty())
{
store.add(itemPtr, count, true, resolve);
}
else
{
// Adding just one item per time to make sure there isn't a stack of scripted items
for (int i = 0; i < count; i++)
store.add(itemPtr, 1, true, resolve);
}
}
void addRandomToStore(const MWWorld::Ptr& itemPtr, int count, MWWorld::ContainerStore& store, bool topLevel = true)
{
if (itemPtr.getType() == ESM::ItemLevList::sRecordId)
{
const ESM::ItemLevList* levItemList = itemPtr.get<ESM::ItemLevList>()->mBase;
if (topLevel && count > 1 && levItemList->mFlags & ESM::ItemLevList::Each)
{
for (int i = 0; i < count; i++)
addRandomToStore(itemPtr, 1, store, true);
}
else
{
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
const ESM::RefId& itemId
= MWMechanics::getLevelledItem(itemPtr.get<ESM::ItemLevList>()->mBase, false, prng);
if (itemId.empty())
return;
MWWorld::ManualRef manualRef(*MWBase::Environment::get().getESMStore(), itemId, 1);
addRandomToStore(manualRef.getPtr(), count, store, false);
}
}
else
addToStore(itemPtr, count, store);
}
}
namespace MWScript
{
namespace Container
{
template <class R>
class OpAddItem : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId item = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
Interpreter::Type_Integer count = runtime[0].mInteger;
runtime.pop();
if (!MWBase::Environment::get().getESMStore()->find(item))
{
runtime.getContext().report("Failed to add item '" + item.getRefIdString() + "': unknown ID");
return;
}
if (count < 0)
count = static_cast<uint16_t>(count);
// no-op
if (count == 0)
return;
if (item == "gold_005" || item == "gold_010" || item == "gold_025" || item == "gold_100")
item = MWWorld::ContainerStore::sGoldId;
// Check if "item" can be placed in a container
MWWorld::ManualRef manualRef(*MWBase::Environment::get().getESMStore(), item, 1);
MWWorld::Ptr itemPtr = manualRef.getPtr();
bool isLevelledList = itemPtr.getClass().getType() == ESM::ItemLevList::sRecordId;
if (!isLevelledList)
MWWorld::ContainerStore::getType(itemPtr);
// Explicit calls to non-unique actors affect the base record
if (!R::implicit && ptr.getClass().isActor()
&& MWBase::Environment::get().getESMStore()->getRefCount(ptr.getCellRef().getRefId()) > 1)
{
ptr.getClass().modifyBaseInventory(ptr.getCellRef().getRefId(), item, count);
return;
}
// Calls to unresolved containers affect the base record
if (ptr.getClass().getType() == ESM::Container::sRecordId
&& (!ptr.getRefData().getCustomData() || !ptr.getClass().getContainerStore(ptr).isResolved()))
{
ptr.getClass().modifyBaseInventory(ptr.getCellRef().getRefId(), item, count);
const ESM::Container* baseRecord
= MWBase::Environment::get().getESMStore()->get<ESM::Container>().find(
ptr.getCellRef().getRefId());
const auto& ptrs = MWBase::Environment::get().getWorld()->getAll(ptr.getCellRef().getRefId());
for (const auto& container : ptrs)
{
// use the new base record
container.get<ESM::Container>()->mBase = baseRecord;
if (container.getRefData().getCustomData())
{
auto& store = container.getClass().getContainerStore(container);
if (isLevelledList)
{
if (store.isResolved())
{
addRandomToStore(itemPtr, count, store);
}
}
else
addToStore(itemPtr, count, store, store.isResolved());
}
}
return;
}
MWWorld::ContainerStore& store = ptr.getClass().getContainerStore(ptr);
if (isLevelledList)
addRandomToStore(itemPtr, count, store);
else
addToStore(itemPtr, count, store);
// Spawn a messagebox (only for items added to player's inventory and if player is talking to someone)
if (ptr == MWBase::Environment::get().getWorld()->getPlayerPtr())
{
// The two GMST entries below expand to strings informing the player of what, and how many of it has
// been added to their inventory
std::string msgBox;
std::string_view itemName = itemPtr.getClass().getName(itemPtr);
if (count == 1)
{
msgBox = MyGUI::LanguageManager::getInstance().replaceTags("#{sNotifyMessage60}");
msgBox = ::Misc::StringUtils::format(msgBox, itemName);
}
else
{
msgBox = MyGUI::LanguageManager::getInstance().replaceTags("#{sNotifyMessage61}");
msgBox = ::Misc::StringUtils::format(msgBox, count, itemName);
}
MWBase::Environment::get().getWindowManager()->messageBox(msgBox, MWGui::ShowInDialogueMode_Only);
}
}
};
template <class R>
class OpGetItemCount : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime, false);
ESM::RefId item = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
if (ptr.isEmpty() || (ptr.getType() != ESM::Container::sRecordId && !ptr.getClass().isActor()))
{
runtime.push(0);
return;
}
if (item == "gold_005" || item == "gold_010" || item == "gold_025" || item == "gold_100")
item = MWWorld::ContainerStore::sGoldId;
MWWorld::ContainerStore& store = ptr.getClass().getContainerStore(ptr);
runtime.push(store.count(item));
}
};
template <class R>
class OpRemoveItem : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId item = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
Interpreter::Type_Integer count = runtime[0].mInteger;
runtime.pop();
if (!MWBase::Environment::get().getESMStore()->find(item))
{
runtime.getContext().report("Failed to remove item '" + item.getRefIdString() + "': unknown ID");
return;
}
if (count < 0)
count = static_cast<uint16_t>(count);
// no-op
if (count == 0)
return;
if (item == "gold_005" || item == "gold_010" || item == "gold_025" || item == "gold_100")
item = MWWorld::ContainerStore::sGoldId;
// Explicit calls to non-unique actors affect the base record
if (!R::implicit && ptr.getClass().isActor()
&& MWBase::Environment::get().getESMStore()->getRefCount(ptr.getCellRef().getRefId()) > 1)
{
ptr.getClass().modifyBaseInventory(ptr.getCellRef().getRefId(), item, -count);
return;
}
// Calls to unresolved containers affect the base record instead
else if (ptr.getClass().getType() == ESM::Container::sRecordId
&& (!ptr.getRefData().getCustomData() || !ptr.getClass().getContainerStore(ptr).isResolved()))
{
ptr.getClass().modifyBaseInventory(ptr.getCellRef().getRefId(), item, -count);
const ESM::Container* baseRecord
= MWBase::Environment::get().getESMStore()->get<ESM::Container>().find(
ptr.getCellRef().getRefId());
const auto& ptrs = MWBase::Environment::get().getWorld()->getAll(ptr.getCellRef().getRefId());
for (const auto& container : ptrs)
{
container.get<ESM::Container>()->mBase = baseRecord;
if (container.getRefData().getCustomData())
{
auto& store = container.getClass().getContainerStore(container);
// Note that unlike AddItem, RemoveItem only removes from unresolved containers
if (!store.isResolved())
store.remove(item, count, false, false);
}
}
return;
}
MWWorld::ContainerStore& store = ptr.getClass().getContainerStore(ptr);
std::string_view itemName;
for (MWWorld::ConstContainerStoreIterator iter(store.cbegin()); iter != store.cend(); ++iter)
{
if (iter->getCellRef().getRefId() == item)
{
itemName = iter->getClass().getName(*iter);
break;
}
}
int numRemoved = store.remove(item, count);
// Spawn a messagebox (only for items removed from player's inventory)
if ((numRemoved > 0) && (ptr == MWMechanics::getPlayer()))
{
// The two GMST entries below expand to strings informing the player of what, and how many of it has
// been removed from their inventory
std::string msgBox;
if (numRemoved > 1)
{
msgBox = MyGUI::LanguageManager::getInstance().replaceTags("#{sNotifyMessage63}");
msgBox = ::Misc::StringUtils::format(msgBox, numRemoved, itemName);
}
else
{
msgBox = MyGUI::LanguageManager::getInstance().replaceTags("#{sNotifyMessage62}");
msgBox = ::Misc::StringUtils::format(msgBox, itemName);
}
MWBase::Environment::get().getWindowManager()->messageBox(msgBox, MWGui::ShowInDialogueMode_Only);
}
}
};
template <class R>
class OpEquip : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId item = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
MWWorld::InventoryStore& invStore = ptr.getClass().getInventoryStore(ptr);
auto found = invStore.end();
const auto& store = *MWBase::Environment::get().getESMStore();
// With soul gems we prefer filled ones.
for (auto it = invStore.begin(); it != invStore.end(); ++it)
{
if (it->getCellRef().getRefId() == item)
{
found = it;
const ESM::RefId& soul = it->getCellRef().getSoul();
if (!it->getClass().isSoulGem(*it)
|| (!soul.empty() && store.get<ESM::Creature>().search(soul)))
break;
}
}
if (found == invStore.end())
{
MWWorld::ManualRef ref(store, item, 1);
found = ptr.getClass().getContainerStore(ptr).add(ref.getPtr(), 1, false);
Log(Debug::Warning) << "Implicitly adding one " << item << " to the inventory store of "
<< ptr.getCellRef().getRefId()
<< " to fulfill the requirements of Equip instruction";
}
if (ptr == MWMechanics::getPlayer())
MWBase::Environment::get().getWindowManager()->useItem(*found, true);
else
{
std::unique_ptr<MWWorld::Action> action = found->getClass().use(*found, true);
action->execute(ptr, true);
}
}
};
template <class R>
class OpGetArmorType : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer location = runtime[0].mInteger;
runtime.pop();
int slot;
switch (location)
{
case 0:
slot = MWWorld::InventoryStore::Slot_Helmet;
break;
case 1:
slot = MWWorld::InventoryStore::Slot_Cuirass;
break;
case 2:
slot = MWWorld::InventoryStore::Slot_LeftPauldron;
break;
case 3:
slot = MWWorld::InventoryStore::Slot_RightPauldron;
break;
case 4:
slot = MWWorld::InventoryStore::Slot_Greaves;
break;
case 5:
slot = MWWorld::InventoryStore::Slot_Boots;
break;
case 6:
slot = MWWorld::InventoryStore::Slot_LeftGauntlet;
break;
case 7:
slot = MWWorld::InventoryStore::Slot_RightGauntlet;
break;
case 8:
slot = MWWorld::InventoryStore::Slot_CarriedLeft; // shield
break;
case 9:
slot = MWWorld::InventoryStore::Slot_LeftGauntlet;
break;
case 10:
slot = MWWorld::InventoryStore::Slot_RightGauntlet;
break;
default:
throw std::runtime_error("armor index out of range");
}
const MWWorld::InventoryStore& invStore = ptr.getClass().getInventoryStore(ptr);
MWWorld::ConstContainerStoreIterator it = invStore.getSlot(slot);
if (it == invStore.end() || it->getType() != ESM::Armor::sRecordId)
{
runtime.push(-1);
return;
}
ESM::RefId skill = it->getClass().getEquipmentSkill(*it);
if (skill == ESM::Skill::HeavyArmor)
runtime.push(2);
else if (skill == ESM::Skill::MediumArmor)
runtime.push(1);
else if (skill == ESM::Skill::LightArmor)
runtime.push(0);
else
runtime.push(-1);
}
};
template <class R>
class OpHasItemEquipped : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId item = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
const MWWorld::InventoryStore& invStore = ptr.getClass().getInventoryStore(ptr);
for (int slot = 0; slot < MWWorld::InventoryStore::Slots; ++slot)
{
MWWorld::ConstContainerStoreIterator it = invStore.getSlot(slot);
if (it != invStore.end() && it->getCellRef().getRefId() == item)
{
runtime.push(1);
return;
}
}
runtime.push(0);
}
};
template <class R>
class OpHasSoulGem : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId name = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
int count = 0;
const MWWorld::InventoryStore& invStore = ptr.getClass().getInventoryStore(ptr);
for (MWWorld::ConstContainerStoreIterator it
= invStore.cbegin(MWWorld::ContainerStore::Type_Miscellaneous);
it != invStore.cend(); ++it)
{
if (it->getCellRef().getSoul() == name)
count += it->getCellRef().getCount();
}
runtime.push(count);
}
};
template <class R>
class OpGetWeaponType : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
const MWWorld::InventoryStore& invStore = ptr.getClass().getInventoryStore(ptr);
MWWorld::ConstContainerStoreIterator it = invStore.getSlot(MWWorld::InventoryStore::Slot_CarriedRight);
if (it == invStore.end())
{
runtime.push(-1);
return;
}
else if (it->getType() != ESM::Weapon::sRecordId)
{
if (it->getType() == ESM::Lockpick::sRecordId)
{
runtime.push(-2);
}
else if (it->getType() == ESM::Probe::sRecordId)
{
runtime.push(-3);
}
else
{
runtime.push(-1);
}
return;
}
runtime.push(it->get<ESM::Weapon>()->mBase->mData.mType);
}
};
void installOpcodes(Interpreter::Interpreter& interpreter)
{
interpreter.installSegment5<OpAddItem<ImplicitRef>>(Compiler::Container::opcodeAddItem);
interpreter.installSegment5<OpAddItem<ExplicitRef>>(Compiler::Container::opcodeAddItemExplicit);
interpreter.installSegment5<OpGetItemCount<ImplicitRef>>(Compiler::Container::opcodeGetItemCount);
interpreter.installSegment5<OpGetItemCount<ExplicitRef>>(Compiler::Container::opcodeGetItemCountExplicit);
interpreter.installSegment5<OpRemoveItem<ImplicitRef>>(Compiler::Container::opcodeRemoveItem);
interpreter.installSegment5<OpRemoveItem<ExplicitRef>>(Compiler::Container::opcodeRemoveItemExplicit);
interpreter.installSegment5<OpEquip<ImplicitRef>>(Compiler::Container::opcodeEquip);
interpreter.installSegment5<OpEquip<ExplicitRef>>(Compiler::Container::opcodeEquipExplicit);
interpreter.installSegment5<OpGetArmorType<ImplicitRef>>(Compiler::Container::opcodeGetArmorType);
interpreter.installSegment5<OpGetArmorType<ExplicitRef>>(Compiler::Container::opcodeGetArmorTypeExplicit);
interpreter.installSegment5<OpHasItemEquipped<ImplicitRef>>(Compiler::Container::opcodeHasItemEquipped);
interpreter.installSegment5<OpHasItemEquipped<ExplicitRef>>(
Compiler::Container::opcodeHasItemEquippedExplicit);
interpreter.installSegment5<OpHasSoulGem<ImplicitRef>>(Compiler::Container::opcodeHasSoulGem);
interpreter.installSegment5<OpHasSoulGem<ExplicitRef>>(Compiler::Container::opcodeHasSoulGemExplicit);
interpreter.installSegment5<OpGetWeaponType<ImplicitRef>>(Compiler::Container::opcodeGetWeaponType);
interpreter.installSegment5<OpGetWeaponType<ExplicitRef>>(Compiler::Container::opcodeGetWeaponTypeExplicit);
}
}
}
| 22,913
|
C++
|
.cpp
| 467
| 32.040685
| 120
| 0.510835
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,432
|
globalscripts.cpp
|
OpenMW_openmw/apps/openmw/mwscript/globalscripts.cpp
|
#include "globalscripts.hpp"
#include <components/debug/debuglog.hpp>
#include <components/esm3/esmwriter.hpp>
#include <components/esm3/globalscript.hpp>
#include <components/esm3/loadscpt.hpp>
#include <components/esm3/loadsscr.hpp>
#include <components/misc/strings/lower.hpp>
#include "../mwworld/esmstore.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/scriptmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/worldmodel.hpp"
#include "interpretercontext.hpp"
namespace
{
struct ScriptCreatingVisitor
{
ESM::GlobalScript operator()(const MWWorld::Ptr& ptr) const
{
ESM::GlobalScript script;
script.mRunning = false;
if (!ptr.isEmpty())
{
if (ptr.getCellRef().hasContentFile())
{
script.mTargetId = ptr.getCellRef().getRefId();
script.mTargetRef = ptr.getCellRef().getRefNum();
}
else if (MWBase::Environment::get().getWorld()->getPlayerPtr() == ptr)
script.mTargetId = ptr.getCellRef().getRefId();
}
return script;
}
ESM::GlobalScript operator()(const std::pair<ESM::RefNum, ESM::RefId>& pair) const
{
ESM::GlobalScript script;
script.mTargetId = pair.second;
script.mTargetRef = pair.first;
script.mRunning = false;
return script;
}
};
struct PtrGettingVisitor
{
const MWWorld::Ptr* operator()(const MWWorld::Ptr& ptr) const { return &ptr; }
const MWWorld::Ptr* operator()(const std::pair<ESM::RefNum, ESM::RefId>& pair) const { return nullptr; }
};
struct PtrResolvingVisitor
{
MWWorld::Ptr operator()(const MWWorld::Ptr& ptr) const { return ptr; }
MWWorld::Ptr operator()(const std::pair<ESM::RefNum, ESM::RefId>& pair) const
{
if (pair.second.empty())
return MWWorld::Ptr();
else if (pair.first.hasContentFile())
return MWBase::Environment::get().getWorldModel()->getPtr(pair.first);
return MWBase::Environment::get().getWorld()->searchPtr(pair.second, false);
}
};
class MatchPtrVisitor
{
const MWWorld::Ptr& mPtr;
public:
MatchPtrVisitor(const MWWorld::Ptr& ptr)
: mPtr(ptr)
{
}
bool operator()(const MWWorld::Ptr& ptr) const { return ptr == mPtr; }
bool operator()(const std::pair<ESM::RefNum, ESM::RefId>& pair) const { return false; }
};
struct IdGettingVisitor
{
ESM::RefId operator()(const MWWorld::Ptr& ptr) const
{
if (ptr.isEmpty())
return ESM::RefId();
return ptr.mRef->mRef.getRefId();
}
ESM::RefId operator()(const std::pair<ESM::RefNum, ESM::RefId>& pair) const { return pair.second; }
};
}
namespace MWScript
{
GlobalScriptDesc::GlobalScriptDesc()
: mRunning(false)
{
}
const MWWorld::Ptr* GlobalScriptDesc::getPtrIfPresent() const
{
return std::visit(PtrGettingVisitor(), mTarget);
}
MWWorld::Ptr GlobalScriptDesc::getPtr()
{
MWWorld::Ptr ptr = std::visit(PtrResolvingVisitor{}, mTarget);
mTarget = ptr;
return ptr;
}
ESM::RefId GlobalScriptDesc::getId() const
{
return std::visit(IdGettingVisitor{}, mTarget);
}
GlobalScripts::GlobalScripts(const MWWorld::ESMStore& store)
: mStore(store)
{
}
void GlobalScripts::addScript(const ESM::RefId& name, const MWWorld::Ptr& target)
{
const auto iter = mScripts.find(name);
if (iter == mScripts.end())
{
if (const ESM::Script* script = mStore.get<ESM::Script>().search(name))
{
auto desc = std::make_shared<GlobalScriptDesc>();
MWWorld::Ptr ptr = target;
desc->mTarget = ptr;
desc->mRunning = true;
desc->mLocals.configure(*script);
mScripts.insert(std::make_pair(name, desc));
}
else
{
Log(Debug::Error) << "Failed to add global script " << name << ": script record not found";
}
}
else if (!iter->second->mRunning)
{
iter->second->mRunning = true;
MWWorld::Ptr ptr = target;
iter->second->mTarget = ptr;
}
}
void GlobalScripts::removeScript(const ESM::RefId& name)
{
const auto iter = mScripts.find(name);
if (iter != mScripts.end())
iter->second->mRunning = false;
}
bool GlobalScripts::isRunning(const ESM::RefId& name) const
{
const auto iter = mScripts.find(name);
if (iter == mScripts.end())
return false;
return iter->second->mRunning;
}
void GlobalScripts::run()
{
for (const auto& script : mScripts)
{
if (script.second->mRunning)
{
MWScript::InterpreterContext context(script.second);
if (!MWBase::Environment::get().getScriptManager()->run(script.first, context))
script.second->mRunning = false;
}
}
}
void GlobalScripts::clear()
{
mScripts.clear();
}
void GlobalScripts::addStartup()
{
// make list of global scripts to be added
std::vector<ESM::RefId> scripts;
scripts.emplace_back(ESM::RefId::stringRefId("main"));
for (MWWorld::Store<ESM::StartScript>::iterator iter = mStore.get<ESM::StartScript>().begin();
iter != mStore.get<ESM::StartScript>().end(); ++iter)
{
scripts.push_back(iter->mId);
}
// add scripts
for (auto iter(scripts.begin()); iter != scripts.end(); ++iter)
{
try
{
addScript(*iter);
}
catch (const std::exception& exception)
{
Log(Debug::Error) << "Failed to add start script " << *iter << " because an exception has "
<< "been thrown: " << exception.what();
}
}
}
int GlobalScripts::countSavedGameRecords() const
{
return mScripts.size();
}
void GlobalScripts::write(ESM::ESMWriter& writer, Loading::Listener& progress) const
{
for (const auto& [id, desc] : mScripts)
{
ESM::GlobalScript script = std::visit(ScriptCreatingVisitor{}, desc->mTarget);
script.mId = id;
desc->mLocals.write(script.mLocals, id);
script.mRunning = desc->mRunning;
writer.startRecord(ESM::REC_GSCR);
script.save(writer);
writer.endRecord(ESM::REC_GSCR);
}
}
bool GlobalScripts::readRecord(ESM::ESMReader& reader, uint32_t type)
{
if (type == ESM::REC_GSCR)
{
ESM::GlobalScript script;
script.load(reader);
auto iter = mScripts.find(script.mId);
if (iter == mScripts.end())
{
if (const ESM::Script* scriptRecord = mStore.get<ESM::Script>().search(script.mId))
{
try
{
auto desc = std::make_shared<GlobalScriptDesc>();
if (!script.mTargetId.empty())
{
desc->mTarget = std::make_pair(script.mTargetRef, script.mTargetId);
}
desc->mLocals.configure(*scriptRecord);
iter = mScripts.insert(std::make_pair(script.mId, desc)).first;
}
catch (const std::exception& exception)
{
Log(Debug::Error) << "Failed to add start script " << script.mId
<< " because an exception has been thrown: " << exception.what();
return true;
}
}
else // script does not exist anymore
return true;
}
iter->second->mRunning = script.mRunning;
iter->second->mLocals.read(script.mLocals, script.mId);
return true;
}
return false;
}
Locals& GlobalScripts::getLocals(const ESM::RefId& name)
{
auto iter = mScripts.find(name);
if (iter == mScripts.end())
{
const ESM::Script* script = mStore.get<ESM::Script>().find(name);
auto desc = std::make_shared<GlobalScriptDesc>();
desc->mLocals.configure(*script);
iter = mScripts.emplace(name, desc).first;
}
return iter->second->mLocals;
}
const GlobalScriptDesc* GlobalScripts::getScriptIfPresent(const ESM::RefId& name) const
{
auto iter = mScripts.find(name);
if (iter == mScripts.end())
return nullptr;
return iter->second.get();
}
void GlobalScripts::updatePtrs(const MWWorld::Ptr& base, const MWWorld::Ptr& updated)
{
MatchPtrVisitor visitor(base);
for (const auto& script : mScripts)
{
if (std::visit(visitor, script.second->mTarget))
script.second->mTarget = updated;
}
}
}
| 9,539
|
C++
|
.cpp
| 267
| 25.213483
| 112
| 0.548769
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,433
|
miscextensions.cpp
|
OpenMW_openmw/apps/openmw/mwscript/miscextensions.cpp
|
#include "miscextensions.hpp"
#include <chrono>
#include <cstdlib>
#include <iomanip>
#include <sstream>
#include <components/compiler/extensions.hpp>
#include <components/compiler/locals.hpp>
#include <components/compiler/opcodes.hpp>
#include <components/debug/debuglog.hpp>
#include <components/interpreter/interpreter.hpp>
#include <components/interpreter/opcodes.hpp>
#include <components/interpreter/runtime.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/misc/rng.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/resource/scenemanager.hpp>
#include <components/sceneutil/positionattitudetransform.hpp>
#include <components/esm3/loadacti.hpp>
#include <components/esm3/loadalch.hpp>
#include <components/esm3/loadappa.hpp>
#include <components/esm3/loadarmo.hpp>
#include <components/esm3/loadbody.hpp>
#include <components/esm3/loadbook.hpp>
#include <components/esm3/loadclot.hpp>
#include <components/esm3/loadcont.hpp>
#include <components/esm3/loadcrea.hpp>
#include <components/esm3/loaddoor.hpp>
#include <components/esm3/loadingr.hpp>
#include <components/esm3/loadlevlist.hpp>
#include <components/esm3/loadligh.hpp>
#include <components/esm3/loadlock.hpp>
#include <components/esm3/loadmgef.hpp>
#include <components/esm3/loadmisc.hpp>
#include <components/esm3/loadprob.hpp>
#include <components/esm3/loadrepa.hpp>
#include <components/esm3/loadscpt.hpp>
#include <components/esm3/loadstat.hpp>
#include <components/esm3/loadweap.hpp>
#include <components/files/conversion.hpp>
#include <components/misc/strings/conversion.hpp>
#include <components/sceneutil/util.hpp>
#include <components/vfs/manager.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/luamanager.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/scriptmanager.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/manualref.hpp"
#include "../mwworld/player.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/aicast.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "../mwmechanics/spellcasting.hpp"
#include "../mwrender/animation.hpp"
#include "interpretercontext.hpp"
#include "ref.hpp"
namespace
{
struct TextureFetchVisitor : osg::NodeVisitor
{
std::vector<std::pair<std::string, std::string>> mTextures;
TextureFetchVisitor(osg::NodeVisitor::TraversalMode mode = TRAVERSE_ALL_CHILDREN)
: osg::NodeVisitor(mode)
{
}
void apply(osg::Node& node) override
{
const osg::StateSet* stateset = node.getStateSet();
if (stateset)
{
const osg::StateSet::TextureAttributeList& texAttributes = stateset->getTextureAttributeList();
for (size_t i = 0; i < texAttributes.size(); i++)
{
const osg::StateAttribute* attr = stateset->getTextureAttribute(i, osg::StateAttribute::TEXTURE);
if (!attr)
continue;
const osg::Texture* texture = attr->asTexture();
if (!texture)
continue;
const osg::Image* image = texture->getImage(0);
std::string fileName;
if (image)
fileName = image->getFileName();
mTextures.emplace_back(SceneUtil::getTextureType(*stateset, *texture, i), fileName);
}
}
traverse(node);
}
};
void addToLevList(ESM::LevelledListBase* list, const ESM::RefId& itemId, int level)
{
for (auto& levelItem : list->mList)
{
if (levelItem.mLevel == level && itemId == levelItem.mId)
return;
}
ESM::LevelledListBase::LevelItem item;
item.mId = itemId;
item.mLevel = level;
list->mList.push_back(item);
}
void removeFromLevList(ESM::LevelledListBase* list, const ESM::RefId& itemId, int level)
{
// level of -1 removes all items with that itemId
for (std::vector<ESM::LevelledListBase::LevelItem>::iterator it = list->mList.begin(); it != list->mList.end();)
{
if (level != -1 && it->mLevel != level)
{
++it;
continue;
}
if (itemId == it->mId)
it = list->mList.erase(it);
else
++it;
}
}
}
namespace MWScript
{
namespace Misc
{
class OpMenuMode : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
runtime.push(MWBase::Environment::get().getWindowManager()->isGuiMode());
}
};
class OpRandom : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
Interpreter::Type_Integer limit = runtime[0].mInteger;
runtime.pop();
if (limit < 0)
throw std::runtime_error("random: argument out of range (Don't be so negative!)");
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
runtime.push(static_cast<Interpreter::Type_Float>(::Misc::Rng::rollDice(limit, prng))); // [o, limit)
}
};
template <class R>
class OpStartScript : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr target = R()(runtime, false);
ESM::RefId name = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
if (!MWBase::Environment::get().getESMStore()->get<ESM::Script>().search(name))
{
runtime.getContext().report(
"Failed to start global script '" + name.getRefIdString() + "': script record not found");
return;
}
MWBase::Environment::get().getScriptManager()->getGlobalScripts().addScript(name, target);
}
};
class OpScriptRunning : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
const ESM::RefId& name = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
runtime.push(MWBase::Environment::get().getScriptManager()->getGlobalScripts().isRunning(name));
}
};
class OpStopScript : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
const ESM::RefId& name = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
if (!MWBase::Environment::get().getESMStore()->get<ESM::Script>().search(name))
{
runtime.getContext().report(
"Failed to stop global script '" + name.getRefIdString() + "': script record not found");
return;
}
MWBase::Environment::get().getScriptManager()->getGlobalScripts().removeScript(name);
}
};
class OpGetSecondsPassed : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
runtime.push(MWBase::Environment::get().getFrameDuration());
}
};
template <class R>
class OpEnable : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
MWBase::Environment::get().getWorld()->enable(ptr);
}
};
template <class R>
class OpDisable : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
MWBase::Environment::get().getWorld()->disable(ptr);
}
};
template <class R>
class OpGetDisabled : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
runtime.push(!ptr.getRefData().isEnabled());
}
};
class OpPlayBink : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
std::string_view name = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
bool allowSkipping = runtime[0].mInteger != 0;
runtime.pop();
MWBase::Environment::get().getWindowManager()->playVideo(name, allowSkipping);
}
};
class OpGetPcSleep : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
runtime.push(MWBase::Environment::get().getWindowManager()->getPlayerSleeping());
}
};
class OpGetPcJumping : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWBase::World* world = MWBase::Environment::get().getWorld();
runtime.push(world->getPlayer().getJumping());
}
};
class OpWakeUpPc : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWBase::Environment::get().getWindowManager()->wakeUpPlayer();
}
};
class OpXBox : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override { runtime.push(0); }
};
template <class R>
class OpOnActivate : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
runtime.push(ptr.getRefData().onActivate());
}
};
template <class R>
class OpActivate : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
InterpreterContext& context = static_cast<InterpreterContext&>(runtime.getContext());
MWWorld::Ptr ptr = R()(runtime);
if (ptr.getRefData().activateByScript() || ptr.getContainerStore())
context.executeActivation(ptr, MWMechanics::getPlayer());
}
};
template <class R>
class OpLock : public Interpreter::Opcode1
{
public:
void execute(Interpreter::Runtime& runtime, unsigned int arg0) override
{
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer lockLevel = ptr.getCellRef().getLockLevel();
if (lockLevel == 0)
{ // no lock level was ever set, set to 100 as default
lockLevel = 100;
}
if (arg0 == 1)
{
lockLevel = runtime[0].mInteger;
runtime.pop();
}
ptr.getCellRef().lock(lockLevel);
// Instantly reset door to closed state
// This is done when using Lock in scripts, but not when using Lock spells.
if (ptr.getType() == ESM::Door::sRecordId && !ptr.getCellRef().getTeleport())
{
MWBase::Environment::get().getWorld()->activateDoor(ptr, MWWorld::DoorState::Idle);
}
}
};
template <class R>
class OpUnlock : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
if (ptr.getCellRef().isLocked())
ptr.getCellRef().unlock();
}
};
class OpToggleCollisionDebug : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
bool enabled = MWBase::Environment::get().getWorld()->toggleRenderMode(MWRender::Render_CollisionDebug);
runtime.getContext().report(
enabled ? "Collision Mesh Rendering -> On" : "Collision Mesh Rendering -> Off");
}
};
class OpToggleCollisionBoxes : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
bool enabled = MWBase::Environment::get().getWorld()->toggleRenderMode(MWRender::Render_CollisionDebug);
runtime.getContext().report(
enabled ? "Collision Mesh Rendering -> On" : "Collision Mesh Rendering -> Off");
}
};
class OpToggleWireframe : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
bool enabled = MWBase::Environment::get().getWorld()->toggleRenderMode(MWRender::Render_Wireframe);
runtime.getContext().report(enabled ? "Wireframe Rendering -> On" : "Wireframe Rendering -> Off");
}
};
class OpToggleBorders : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
bool enabled = MWBase::Environment::get().getWorld()->toggleBorders();
runtime.getContext().report(enabled ? "Border Rendering -> On" : "Border Rendering -> Off");
}
};
class OpTogglePathgrid : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
bool enabled = MWBase::Environment::get().getWorld()->toggleRenderMode(MWRender::Render_Pathgrid);
runtime.getContext().report(enabled ? "Path Grid rendering -> On" : "Path Grid Rendering -> Off");
}
};
class OpFadeIn : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
Interpreter::Type_Float time = runtime[0].mFloat;
runtime.pop();
MWBase::Environment::get().getWindowManager()->fadeScreenIn(time, false);
}
};
class OpFadeOut : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
Interpreter::Type_Float time = runtime[0].mFloat;
runtime.pop();
MWBase::Environment::get().getWindowManager()->fadeScreenOut(time, false);
}
};
class OpFadeTo : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
Interpreter::Type_Float alpha = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float time = runtime[0].mFloat;
runtime.pop();
MWBase::Environment::get().getWindowManager()->fadeScreenTo(static_cast<int>(alpha), time, false);
}
};
class OpToggleWater : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
runtime.getContext().report(
MWBase::Environment::get().getWorld()->toggleWater() ? "Water -> On" : "Water -> Off");
}
};
class OpToggleWorld : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
runtime.getContext().report(
MWBase::Environment::get().getWorld()->toggleWorld() ? "World -> On" : "World -> Off");
}
};
class OpDontSaveObject : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
// We are ignoring the DontSaveObject statement for now. Probably not worth
// bothering with. The incompatibility we are creating should be marginal at most.
}
};
class OpPcForce1stPerson : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
if (!MWBase::Environment::get().getWorld()->isFirstPerson())
MWBase::Environment::get().getWorld()->togglePOV(true);
}
};
class OpPcForce3rdPerson : public Interpreter::Opcode0
{
void execute(Interpreter::Runtime& runtime) override
{
if (MWBase::Environment::get().getWorld()->isFirstPerson())
MWBase::Environment::get().getWorld()->togglePOV(true);
}
};
class OpPcGet3rdPerson : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
runtime.push(!MWBase::Environment::get().getWorld()->isFirstPerson());
}
};
class OpToggleVanityMode : public Interpreter::Opcode0
{
static bool sActivate;
public:
void execute(Interpreter::Runtime& runtime) override
{
MWBase::World* world = MWBase::Environment::get().getWorld();
if (world->toggleVanityMode(sActivate))
{
runtime.getContext().report(sActivate ? "Vanity Mode -> On" : "Vanity Mode -> Off");
sActivate = !sActivate;
}
else
{
runtime.getContext().report("Vanity Mode -> No");
}
}
};
bool OpToggleVanityMode::sActivate = true;
template <class R>
class OpGetLocked : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
runtime.push(ptr.getCellRef().isLocked());
}
};
template <class R>
class OpGetEffect : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
std::string_view effect = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
if (!ptr.getClass().isActor())
{
runtime.push(0);
return;
}
long key;
if (const auto k = ::Misc::StringUtils::toNumeric<long>(effect.data());
k.has_value() && *k >= 0 && *k <= 32767)
key = *k;
else
key = ESM::MagicEffect::effectGmstIdToIndex(effect);
const MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr);
for (const auto& spell : stats.getActiveSpells())
{
for (const auto& effect : spell.getEffects())
{
if (effect.mFlags & ESM::ActiveEffect::Flag_Applied && effect.mEffectId == key)
{
runtime.push(1);
return;
}
}
}
runtime.push(0);
}
};
template <class R>
class OpAddSoulGem : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId creature = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
ESM::RefId gem = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
if (!ptr.getClass().isActor())
return;
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
store.get<ESM::Creature>().find(
creature); // This line throws an exception if it can't find the creature
MWWorld::Ptr item = *ptr.getClass().getContainerStore(ptr).add(gem, 1);
// Set the soul on just one of the gems, not the whole stack
item.getContainerStore()->unstack(item);
item.getCellRef().setSoul(creature);
// Restack the gem with other gems with the same soul
item.getContainerStore()->restack(item);
}
};
template <class R>
class OpRemoveSoulGem : public Interpreter::Opcode1
{
public:
void execute(Interpreter::Runtime& runtime, unsigned int arg0) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId soul = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
// throw away additional arguments
for (unsigned int i = 0; i < arg0; ++i)
runtime.pop();
if (!ptr.getClass().isActor())
return;
MWWorld::ContainerStore& store = ptr.getClass().getContainerStore(ptr);
for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it)
{
if (it->getCellRef().getSoul() == soul)
{
store.remove(*it, 1);
return;
}
}
}
};
template <class R>
class OpDrop : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId item = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
Interpreter::Type_Integer amount = runtime[0].mInteger;
runtime.pop();
if (amount < 0)
throw std::runtime_error("amount must be non-negative");
// no-op
if (amount == 0)
return;
if (!ptr.getClass().isActor())
return;
MWWorld::InventoryStore* invStorePtr = nullptr;
if (ptr.getClass().hasInventoryStore(ptr))
{
invStorePtr = &ptr.getClass().getInventoryStore(ptr);
// Prefer dropping unequipped items first; re-stack if possible by unequipping items before dropping
// them.
int numNotEquipped = invStorePtr->count(item);
for (int slot = 0; slot < MWWorld::InventoryStore::Slots; ++slot)
{
MWWorld::ConstContainerStoreIterator it = invStorePtr->getSlot(slot);
if (it != invStorePtr->end() && it->getCellRef().getRefId() == item)
{
numNotEquipped -= it->getCellRef().getCount();
}
}
for (int slot = 0; slot < MWWorld::InventoryStore::Slots && amount > numNotEquipped; ++slot)
{
MWWorld::ContainerStoreIterator it = invStorePtr->getSlot(slot);
if (it != invStorePtr->end() && it->getCellRef().getRefId() == item)
{
int numToRemove = std::min(amount - numNotEquipped, it->getCellRef().getCount());
invStorePtr->unequipItemQuantity(*it, numToRemove);
numNotEquipped += numToRemove;
}
}
}
MWWorld::ContainerStore& store = ptr.getClass().getContainerStore(ptr);
for (MWWorld::ContainerStoreIterator iter(store.begin()); iter != store.end(); ++iter)
{
if (iter->getCellRef().getRefId() == item && (!invStorePtr || !invStorePtr->isEquipped(*iter)))
{
int removed = store.remove(*iter, amount);
MWWorld::Ptr dropped
= MWBase::Environment::get().getWorld()->dropObjectOnGround(ptr, *iter, removed);
dropped.getCellRef().setOwner(ESM::RefId());
amount -= removed;
if (amount <= 0)
break;
}
}
MWWorld::ManualRef ref(*MWBase::Environment::get().getESMStore(), item, 1);
MWWorld::Ptr itemPtr(ref.getPtr());
if (amount > 0)
{
if (itemPtr.getClass().getScript(itemPtr).empty())
{
MWBase::Environment::get().getWorld()->dropObjectOnGround(ptr, itemPtr, amount);
}
else
{
// Dropping one item per time to prevent making stacks of scripted items
for (int i = 0; i < amount; i++)
MWBase::Environment::get().getWorld()->dropObjectOnGround(ptr, itemPtr, 1);
}
}
MWBase::Environment::get().getSoundManager()->playSound3D(
ptr, itemPtr.getClass().getDownSoundId(itemPtr), 1.f, 1.f);
}
};
template <class R>
class OpDropSoulGem : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId soul = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
if (!ptr.getClass().isActor())
return;
MWWorld::ContainerStore& store = ptr.getClass().getContainerStore(ptr);
for (MWWorld::ContainerStoreIterator iter(store.begin()); iter != store.end(); ++iter)
{
if (iter->getCellRef().getSoul() == soul)
{
MWBase::Environment::get().getWorld()->dropObjectOnGround(ptr, *iter, 1);
store.remove(*iter, 1);
break;
}
}
}
};
template <class R>
class OpGetAttacked : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
runtime.push(ptr.getClass().getCreatureStats(ptr).getAttacked());
}
};
template <class R>
class OpGetWeaponDrawn : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
auto& cls = ptr.getClass();
if (!cls.hasInventoryStore(ptr) && !cls.isBipedal(ptr))
{
runtime.push(0);
return;
}
if (cls.getCreatureStats(ptr).getDrawState() != MWMechanics::DrawState::Weapon)
{
runtime.push(0);
return;
}
MWRender::Animation* anim = MWBase::Environment::get().getWorld()->getAnimation(ptr);
runtime.push(anim && anim->getWeaponsShown());
}
};
template <class R>
class OpGetSpellReadied : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
runtime.push(ptr.getClass().getCreatureStats(ptr).getDrawState() == MWMechanics::DrawState::Spell);
}
};
template <class R>
class OpGetSpellEffects : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId id = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
if (!ptr.getClass().isActor())
{
runtime.push(0);
return;
}
const MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr);
runtime.push(stats.getActiveSpells().isSpellActive(id));
}
};
class OpGetCurrentTime : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
runtime.push(MWBase::Environment::get().getWorld()->getTimeStamp().getHour());
}
};
template <class R>
class OpSetDelete : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
int parameter = runtime[0].mInteger;
runtime.pop();
if (parameter == 1)
MWBase::Environment::get().getWorld()->deleteObject(ptr);
else if (parameter == 0)
MWBase::Environment::get().getWorld()->undeleteObject(ptr);
else
throw std::runtime_error("SetDelete: unexpected parameter");
}
};
class OpGetSquareRoot : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
float param = runtime[0].mFloat;
runtime.pop();
if (param < 0)
throw std::runtime_error("square root of negative number (we aren't that imaginary)");
runtime.push(std::sqrt(param));
}
};
template <class R>
class OpFall : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override {}
};
template <class R>
class OpGetStandingPc : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
runtime.push(MWBase::Environment::get().getWorld()->getPlayerStandingOn(ptr));
}
};
template <class R>
class OpGetStandingActor : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
runtime.push(MWBase::Environment::get().getWorld()->getActorStandingOn(ptr));
}
};
template <class R>
class OpGetCollidingPc : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
runtime.push(MWBase::Environment::get().getWorld()->getPlayerCollidingWith(ptr));
}
};
template <class R>
class OpGetCollidingActor : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
runtime.push(MWBase::Environment::get().getWorld()->getActorCollidingWith(ptr));
}
};
template <class R>
class OpHurtStandingActor : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
float healthDiffPerSecond = runtime[0].mFloat;
runtime.pop();
MWBase::Environment::get().getWorld()->hurtStandingActors(ptr, healthDiffPerSecond);
}
};
template <class R>
class OpHurtCollidingActor : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
float healthDiffPerSecond = runtime[0].mFloat;
runtime.pop();
MWBase::Environment::get().getWorld()->hurtCollidingActors(ptr, healthDiffPerSecond);
}
};
class OpGetWindSpeed : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
runtime.push(MWBase::Environment::get().getWorld()->getWindSpeed());
}
};
template <class R>
class OpHitOnMe : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId objectID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr);
bool hit = objectID == stats.getLastHitObject();
runtime.push(hit);
if (hit)
stats.clearLastHitObject();
}
};
template <class R>
class OpHitAttemptOnMe : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId objectID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr);
bool hit = objectID == stats.getLastHitAttemptObject();
runtime.push(hit);
if (hit)
stats.clearLastHitAttemptObject();
}
};
template <bool Enable>
class OpEnableTeleporting : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWBase::World* world = MWBase::Environment::get().getWorld();
world->enableTeleporting(Enable);
}
};
template <bool Enable>
class OpEnableLevitation : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWBase::World* world = MWBase::Environment::get().getWorld();
world->enableLevitation(Enable);
}
};
template <class R>
class OpShow : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime, false);
std::string_view var = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
std::stringstream output;
if (!ptr.isEmpty())
{
ESM::RefId script = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
if (!script.empty())
{
const Compiler::Locals& locals
= MWBase::Environment::get().getScriptManager()->getLocals(script);
char type = locals.getType(var);
std::string refId = ptr.getCellRef().getRefId().getRefIdString();
if (refId.find(' ') != std::string::npos)
refId = '"' + refId + '"';
switch (type)
{
case 'l':
case 's':
output << refId << "." << var << " = "
<< ptr.getRefData().getLocals().getIntVar(script, var);
break;
case 'f':
output << refId << "." << var << " = "
<< ptr.getRefData().getLocals().getFloatVar(script, var);
break;
}
}
}
if (output.rdbuf()->in_avail() == 0)
{
MWBase::World* world = MWBase::Environment::get().getWorld();
char type = world->getGlobalVariableType(var);
switch (type)
{
case 's':
output << var << " = " << runtime.getContext().getGlobalShort(var);
break;
case 'l':
output << var << " = " << runtime.getContext().getGlobalLong(var);
break;
case 'f':
output << var << " = " << runtime.getContext().getGlobalFloat(var);
break;
default:
output << "unknown variable";
}
}
runtime.getContext().report(output.str());
}
};
template <class R>
class OpShowVars : public Interpreter::Opcode0
{
void printLocalVars(Interpreter::Runtime& runtime, const MWWorld::Ptr& ptr)
{
std::stringstream str;
const ESM::RefId& script = ptr.getClass().getScript(ptr);
if (script.empty())
str << ptr.getCellRef().getRefId() << " does not have a script.";
else
{
str << "Local variables for " << ptr.getCellRef().getRefId();
const Locals& locals = ptr.getRefData().getLocals();
const Compiler::Locals& complocals
= MWBase::Environment::get().getScriptManager()->getLocals(script);
const std::vector<std::string>* names = &complocals.get('s');
for (size_t i = 0; i < names->size(); ++i)
{
if (i >= locals.mShorts.size())
break;
str << std::endl << " " << (*names)[i] << " = " << locals.mShorts[i] << " (short)";
}
names = &complocals.get('l');
for (size_t i = 0; i < names->size(); ++i)
{
if (i >= locals.mLongs.size())
break;
str << std::endl << " " << (*names)[i] << " = " << locals.mLongs[i] << " (long)";
}
names = &complocals.get('f');
for (size_t i = 0; i < names->size(); ++i)
{
if (i >= locals.mFloats.size())
break;
str << std::endl << " " << (*names)[i] << " = " << locals.mFloats[i] << " (float)";
}
}
runtime.getContext().report(str.str());
}
void printGlobalVars(Interpreter::Runtime& runtime)
{
std::stringstream str;
str << "Global variables:";
MWBase::World* world = MWBase::Environment::get().getWorld();
std::vector<std::string> names = runtime.getContext().getGlobals();
for (size_t i = 0; i < names.size(); ++i)
{
char type = world->getGlobalVariableType(names[i]);
str << std::endl << " " << names[i] << " = ";
switch (type)
{
case 's':
str << runtime.getContext().getGlobalShort(names[i]) << " (short)";
break;
case 'l':
str << runtime.getContext().getGlobalLong(names[i]) << " (long)";
break;
case 'f':
str << runtime.getContext().getGlobalFloat(names[i]) << " (float)";
break;
default:
str << "<unknown type>";
}
}
runtime.getContext().report(str.str());
}
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime, false);
if (!ptr.isEmpty())
printLocalVars(runtime, ptr);
else
{
// No reference, no problem.
printGlobalVars(runtime);
}
}
};
class OpToggleScripts : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
bool enabled = MWBase::Environment::get().getWorld()->toggleScripts();
runtime.getContext().report(enabled ? "Scripts -> On" : "Scripts -> Off");
}
};
class OpToggleGodMode : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
bool enabled = MWBase::Environment::get().getWorld()->toggleGodMode();
runtime.getContext().report(enabled ? "God Mode -> On" : "God Mode -> Off");
}
};
template <class R>
class OpCast : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId spellId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
ESM::RefId targetId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().search(spellId);
if (!spell)
{
runtime.getContext().report(
"spellcasting failed: cannot find spell \"" + spellId.getRefIdString() + "\"");
return;
}
if (ptr == MWMechanics::getPlayer())
{
MWBase::Environment::get().getWorld()->getPlayer().setSelectedSpell(spell->mId);
return;
}
if (ptr.getClass().isActor())
{
if (!MWBase::Environment::get().getMechanicsManager()->isCastingSpell(ptr))
{
MWMechanics::AiCast castPackage(targetId, spell->mId, true);
ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(castPackage, ptr);
}
return;
}
MWWorld::Ptr target = MWBase::Environment::get().getWorld()->searchPtr(targetId, false, false);
if (target.isEmpty())
return;
MWMechanics::CastSpell cast(ptr, target, false, true);
cast.playSpellCastingEffects(spell);
cast.mHitPosition = target.getRefData().getPosition().asVec3();
cast.mAlwaysSucceed = true;
cast.cast(spell);
}
};
template <class R>
class OpExplodeSpell : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr ptr = R()(runtime);
ESM::RefId spellId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().search(spellId);
if (!spell)
{
runtime.getContext().report(
"spellcasting failed: cannot find spell \"" + spellId.getRefIdString() + "\"");
return;
}
if (ptr == MWMechanics::getPlayer())
{
MWBase::Environment::get().getWorld()->getPlayer().setSelectedSpell(spell->mId);
return;
}
if (ptr.getClass().isActor())
{
if (!MWBase::Environment::get().getMechanicsManager()->isCastingSpell(ptr))
{
MWMechanics::AiCast castPackage(ptr.getCellRef().getRefId(), spell->mId, true);
ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(castPackage, ptr);
}
return;
}
MWMechanics::CastSpell cast(ptr, ptr, false, true);
cast.mHitPosition = ptr.getRefData().getPosition().asVec3();
cast.mAlwaysSucceed = true;
cast.cast(spell);
}
};
class OpGoToJail : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWBase::World* world = MWBase::Environment::get().getWorld();
world->goToJail();
}
};
class OpPayFine : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr player = MWMechanics::getPlayer();
player.getClass().getNpcStats(player).setBounty(0);
MWBase::World* world = MWBase::Environment::get().getWorld();
world->confiscateStolenItems(player);
world->getPlayer().recordCrimeId();
world->getPlayer().setDrawState(MWMechanics::DrawState::Nothing);
}
};
class OpPayFineThief : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWWorld::Ptr player = MWMechanics::getPlayer();
player.getClass().getNpcStats(player).setBounty(0);
MWBase::Environment::get().getWorld()->getPlayer().recordCrimeId();
}
};
class OpGetPcInJail : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
runtime.push(MWBase::Environment::get().getWorld()->isPlayerInJail());
}
};
class OpGetPcTraveling : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
runtime.push(MWBase::Environment::get().getWorld()->isPlayerTraveling());
}
};
template <class R>
class OpBetaComment : public Interpreter::Opcode1
{
public:
void execute(Interpreter::Runtime& runtime, unsigned int arg0) override
{
MWWorld::Ptr ptr = R()(runtime);
std::stringstream msg;
msg << "Report time: ";
std::time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
tm timeinfo{};
#ifdef _WIN32
gmtime_s(&timeinfo, ¤tTime);
#else
gmtime_r(¤tTime, &timeinfo);
#endif
msg << std::put_time(&timeinfo, "%Y.%m.%d %T UTC") << std::endl;
msg << "Content file: " << ptr.getCellRef().getRefNum().mContentFile;
if (!ptr.getCellRef().hasContentFile())
msg << " [None]" << std::endl;
else
{
std::vector<std::string> contentFiles = MWBase::Environment::get().getWorld()->getContentFiles();
msg << " [" << contentFiles.at(ptr.getCellRef().getRefNum().mContentFile) << "]" << std::endl;
}
msg << "RefNum: " << ptr.getCellRef().getRefNum().mIndex << std::endl;
if (ptr.getRefData().isDeletedByContentFile())
msg << "[Deleted by content file]" << std::endl;
if (!ptr.getCellRef().getCount())
msg << "[Deleted]" << std::endl;
msg << "RefID: " << ptr.getCellRef().getRefId() << std::endl;
msg << "Memory address: " << ptr.getBase() << std::endl;
if (ptr.isInCell())
{
MWWorld::CellStore* cell = ptr.getCell();
msg << "Cell: " << MWBase::Environment::get().getWorld()->getCellName(cell) << std::endl;
if (cell->getCell()->isExterior())
msg << "Grid: " << cell->getCell()->getGridX() << " " << cell->getCell()->getGridY()
<< std::endl;
osg::Vec3f pos(ptr.getRefData().getPosition().asVec3());
msg << "Coordinates: " << pos.x() << " " << pos.y() << " " << pos.z() << std::endl;
auto vfs = MWBase::Environment::get().getResourceSystem()->getVFS();
const VFS::Path::Normalized model = ::Misc::ResourceHelpers::correctActorModelPath(
VFS::Path::toNormalized(ptr.getClass().getCorrectedModel(ptr)), vfs);
msg << "Model: " << model.value() << std::endl;
if (!model.empty())
{
const std::string archive = vfs->getArchive(model);
if (!archive.empty())
msg << "(" << archive << ")" << std::endl;
TextureFetchVisitor visitor;
SceneUtil::PositionAttitudeTransform* baseNode = ptr.getRefData().getBaseNode();
if (baseNode)
baseNode->accept(visitor);
// The instance might not have a physical model due to paging or scripting.
// If this is the case, fall back to the template
if (visitor.mTextures.empty())
{
Resource::SceneManager* sceneManager
= MWBase::Environment::get().getResourceSystem()->getSceneManager();
const_cast<osg::Node*>(sceneManager->getTemplate(model).get())->accept(visitor);
msg << "Bound textures: [None]" << std::endl;
if (!visitor.mTextures.empty())
msg << "Model textures: ";
}
else
{
msg << "Bound textures: ";
}
if (!visitor.mTextures.empty())
{
msg << std::endl;
std::string lastTextureSrc;
for (auto& [textureName, fileName] : visitor.mTextures)
{
std::string textureSrc;
if (!fileName.empty())
textureSrc = vfs->getArchive(fileName);
if (lastTextureSrc.empty() || textureSrc != lastTextureSrc)
{
lastTextureSrc = std::move(textureSrc);
if (lastTextureSrc.empty())
lastTextureSrc = "[No Source]";
msg << " " << lastTextureSrc << std::endl;
}
msg << " ";
msg << (textureName.empty() ? "[Anonymous]: " : textureName) << ": ";
msg << (fileName.empty() ? "[No File]" : fileName) << std::endl;
}
}
else
{
msg << "[None]" << std::endl;
}
}
if (!ptr.getClass().getScript(ptr).empty())
msg << "Script: " << ptr.getClass().getScript(ptr) << std::endl;
}
while (arg0 > 0)
{
std::string_view notes = runtime.getStringLiteral(runtime[0].mInteger);
runtime.pop();
if (!notes.empty())
msg << "Notes: " << notes << std::endl;
--arg0;
}
Log(Debug::Warning) << "\n" << msg.str();
runtime.getContext().report(msg.str());
}
};
class OpAddToLevCreature : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
const ESM::RefId& levId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
const ESM::RefId& creatureId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
int level = runtime[0].mInteger;
runtime.pop();
ESM::CreatureLevList listCopy
= *MWBase::Environment::get().getESMStore()->get<ESM::CreatureLevList>().find(levId);
addToLevList(&listCopy, creatureId, level);
MWBase::Environment::get().getESMStore()->overrideRecord(listCopy);
}
};
class OpRemoveFromLevCreature : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
const ESM::RefId& levId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
const ESM::RefId& creatureId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
int level = runtime[0].mInteger;
runtime.pop();
ESM::CreatureLevList listCopy
= *MWBase::Environment::get().getESMStore()->get<ESM::CreatureLevList>().find(levId);
removeFromLevList(&listCopy, creatureId, level);
MWBase::Environment::get().getESMStore()->overrideRecord(listCopy);
}
};
class OpAddToLevItem : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
const ESM::RefId& levId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
const ESM::RefId& itemId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
int level = runtime[0].mInteger;
runtime.pop();
ESM::ItemLevList listCopy
= *MWBase::Environment::get().getESMStore()->get<ESM::ItemLevList>().find(levId);
addToLevList(&listCopy, itemId, level);
MWBase::Environment::get().getESMStore()->overrideRecord(listCopy);
}
};
class OpRemoveFromLevItem : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
const ESM::RefId& levId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
const ESM::RefId& itemId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger));
runtime.pop();
int level = runtime[0].mInteger;
runtime.pop();
ESM::ItemLevList listCopy
= *MWBase::Environment::get().getESMStore()->get<ESM::ItemLevList>().find(levId);
removeFromLevList(&listCopy, itemId, level);
MWBase::Environment::get().getESMStore()->overrideRecord(listCopy);
}
};
template <class R>
class OpShowSceneGraph : public Interpreter::Opcode1
{
public:
void execute(Interpreter::Runtime& runtime, unsigned int arg0) override
{
MWWorld::Ptr ptr = R()(runtime, false);
int confirmed = 0;
if (arg0 == 1)
{
confirmed = runtime[0].mInteger;
runtime.pop();
}
if (ptr.isEmpty() && !confirmed)
runtime.getContext().report(
"Exporting the entire scene graph will result in a large file. Confirm this action using "
"'showscenegraph 1' or select an object instead.");
else
{
const auto filename = MWBase::Environment::get().getWorld()->exportSceneGraph(ptr);
runtime.getContext().report("Wrote '" + Files::pathToUnicodeString(filename) + "'");
}
}
};
class OpToggleNavMesh : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
bool enabled = MWBase::Environment::get().getWorld()->toggleRenderMode(MWRender::Render_NavMesh);
runtime.getContext().report(
enabled ? "Navigation Mesh Rendering -> On" : "Navigation Mesh Rendering -> Off");
}
};
class OpToggleActorsPaths : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
bool enabled = MWBase::Environment::get().getWorld()->toggleRenderMode(MWRender::Render_ActorsPaths);
runtime.getContext().report(enabled ? "Agents Paths Rendering -> On" : "Agents Paths Rendering -> Off");
}
};
class OpSetNavMeshNumberToRender : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
const auto navMeshNumber = runtime[0].mInteger;
runtime.pop();
if (navMeshNumber < 0)
{
runtime.getContext().report("Invalid navmesh number: use not less than zero values");
return;
}
MWBase::Environment::get().getWorld()->setNavMeshNumberToRender(
static_cast<std::size_t>(navMeshNumber));
}
};
template <class R>
class OpRepairedOnMe : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
// Broken in vanilla and deliberately no-op.
runtime.push(0);
}
};
class OpToggleRecastMesh : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
bool enabled = MWBase::Environment::get().getWorld()->toggleRenderMode(MWRender::Render_RecastMesh);
runtime.getContext().report(enabled ? "Recast Mesh Rendering -> On" : "Recast Mesh Rendering -> Off");
}
};
class OpHelp : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
std::stringstream message;
message << MWBase::Environment::get().getWindowManager()->getVersionDescription() << "\n\n";
std::vector<std::string> commands;
MWBase::Environment::get().getScriptManager()->getExtensions().listKeywords(commands);
for (const auto& command : commands)
message << command << "\n";
runtime.getContext().report(message.str());
}
};
class OpReloadLua : public Interpreter::Opcode0
{
public:
void execute(Interpreter::Runtime& runtime) override
{
MWBase::Environment::get().getLuaManager()->reloadAllScripts();
runtime.getContext().report("All Lua scripts are reloaded");
}
};
class OpTestModels : public Interpreter::Opcode0
{
template <class T>
void test(int& count) const
{
Resource::SceneManager* sceneManager
= MWBase::Environment::get().getResourceSystem()->getSceneManager();
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
for (const T& record : store.get<T>())
{
MWWorld::ManualRef ref(store, record.mId);
VFS::Path::Normalized model(ref.getPtr().getClass().getCorrectedModel(ref.getPtr()));
if (!model.empty())
{
sceneManager->getTemplate(model);
++count;
}
}
}
public:
void execute(Interpreter::Runtime& runtime) override
{
Resource::SceneManager* sceneManager
= MWBase::Environment::get().getResourceSystem()->getSceneManager();
double delay = sceneManager->getExpiryDelay();
sceneManager->setExpiryDelay(0.0);
int count = 0;
test<ESM::Activator>(count);
test<ESM::Apparatus>(count);
test<ESM::Armor>(count);
test<ESM::Potion>(count);
test<ESM::BodyPart>(count);
test<ESM::Book>(count);
test<ESM::Clothing>(count);
test<ESM::Container>(count);
test<ESM::Creature>(count);
test<ESM::Door>(count);
test<ESM::Ingredient>(count);
test<ESM::Light>(count);
test<ESM::Lockpick>(count);
test<ESM::Miscellaneous>(count);
test<ESM::Probe>(count);
test<ESM::Repair>(count);
test<ESM::Static>(count);
test<ESM::Weapon>(count);
sceneManager->setExpiryDelay(delay);
std::stringstream message;
message << "Attempted to load models for " << count << " objects. Check the log for details.";
runtime.getContext().report(message.str());
}
};
void installOpcodes(Interpreter::Interpreter& interpreter)
{
interpreter.installSegment5<OpMenuMode>(Compiler::Misc::opcodeMenuMode);
interpreter.installSegment5<OpRandom>(Compiler::Misc::opcodeRandom);
interpreter.installSegment5<OpScriptRunning>(Compiler::Misc::opcodeScriptRunning);
interpreter.installSegment5<OpStartScript<ImplicitRef>>(Compiler::Misc::opcodeStartScript);
interpreter.installSegment5<OpStartScript<ExplicitRef>>(Compiler::Misc::opcodeStartScriptExplicit);
interpreter.installSegment5<OpStopScript>(Compiler::Misc::opcodeStopScript);
interpreter.installSegment5<OpGetSecondsPassed>(Compiler::Misc::opcodeGetSecondsPassed);
interpreter.installSegment5<OpEnable<ImplicitRef>>(Compiler::Misc::opcodeEnable);
interpreter.installSegment5<OpEnable<ExplicitRef>>(Compiler::Misc::opcodeEnableExplicit);
interpreter.installSegment5<OpDisable<ImplicitRef>>(Compiler::Misc::opcodeDisable);
interpreter.installSegment5<OpDisable<ExplicitRef>>(Compiler::Misc::opcodeDisableExplicit);
interpreter.installSegment5<OpGetDisabled<ImplicitRef>>(Compiler::Misc::opcodeGetDisabled);
interpreter.installSegment5<OpGetDisabled<ExplicitRef>>(Compiler::Misc::opcodeGetDisabledExplicit);
interpreter.installSegment5<OpXBox>(Compiler::Misc::opcodeXBox);
interpreter.installSegment5<OpOnActivate<ImplicitRef>>(Compiler::Misc::opcodeOnActivate);
interpreter.installSegment5<OpOnActivate<ExplicitRef>>(Compiler::Misc::opcodeOnActivateExplicit);
interpreter.installSegment5<OpActivate<ImplicitRef>>(Compiler::Misc::opcodeActivate);
interpreter.installSegment5<OpActivate<ExplicitRef>>(Compiler::Misc::opcodeActivateExplicit);
interpreter.installSegment3<OpLock<ImplicitRef>>(Compiler::Misc::opcodeLock);
interpreter.installSegment3<OpLock<ExplicitRef>>(Compiler::Misc::opcodeLockExplicit);
interpreter.installSegment5<OpUnlock<ImplicitRef>>(Compiler::Misc::opcodeUnlock);
interpreter.installSegment5<OpUnlock<ExplicitRef>>(Compiler::Misc::opcodeUnlockExplicit);
interpreter.installSegment5<OpToggleCollisionDebug>(Compiler::Misc::opcodeToggleCollisionDebug);
interpreter.installSegment5<OpToggleCollisionBoxes>(Compiler::Misc::opcodeToggleCollisionBoxes);
interpreter.installSegment5<OpToggleWireframe>(Compiler::Misc::opcodeToggleWireframe);
interpreter.installSegment5<OpFadeIn>(Compiler::Misc::opcodeFadeIn);
interpreter.installSegment5<OpFadeOut>(Compiler::Misc::opcodeFadeOut);
interpreter.installSegment5<OpFadeTo>(Compiler::Misc::opcodeFadeTo);
interpreter.installSegment5<OpTogglePathgrid>(Compiler::Misc::opcodeTogglePathgrid);
interpreter.installSegment5<OpToggleWater>(Compiler::Misc::opcodeToggleWater);
interpreter.installSegment5<OpToggleWorld>(Compiler::Misc::opcodeToggleWorld);
interpreter.installSegment5<OpDontSaveObject>(Compiler::Misc::opcodeDontSaveObject);
interpreter.installSegment5<OpPcForce1stPerson>(Compiler::Misc::opcodePcForce1stPerson);
interpreter.installSegment5<OpPcForce3rdPerson>(Compiler::Misc::opcodePcForce3rdPerson);
interpreter.installSegment5<OpPcGet3rdPerson>(Compiler::Misc::opcodePcGet3rdPerson);
interpreter.installSegment5<OpToggleVanityMode>(Compiler::Misc::opcodeToggleVanityMode);
interpreter.installSegment5<OpGetPcSleep>(Compiler::Misc::opcodeGetPcSleep);
interpreter.installSegment5<OpGetPcJumping>(Compiler::Misc::opcodeGetPcJumping);
interpreter.installSegment5<OpWakeUpPc>(Compiler::Misc::opcodeWakeUpPc);
interpreter.installSegment5<OpPlayBink>(Compiler::Misc::opcodePlayBink);
interpreter.installSegment5<OpPayFine>(Compiler::Misc::opcodePayFine);
interpreter.installSegment5<OpPayFineThief>(Compiler::Misc::opcodePayFineThief);
interpreter.installSegment5<OpGoToJail>(Compiler::Misc::opcodeGoToJail);
interpreter.installSegment5<OpGetLocked<ImplicitRef>>(Compiler::Misc::opcodeGetLocked);
interpreter.installSegment5<OpGetLocked<ExplicitRef>>(Compiler::Misc::opcodeGetLockedExplicit);
interpreter.installSegment5<OpGetEffect<ImplicitRef>>(Compiler::Misc::opcodeGetEffect);
interpreter.installSegment5<OpGetEffect<ExplicitRef>>(Compiler::Misc::opcodeGetEffectExplicit);
interpreter.installSegment5<OpAddSoulGem<ImplicitRef>>(Compiler::Misc::opcodeAddSoulGem);
interpreter.installSegment5<OpAddSoulGem<ExplicitRef>>(Compiler::Misc::opcodeAddSoulGemExplicit);
interpreter.installSegment3<OpRemoveSoulGem<ImplicitRef>>(Compiler::Misc::opcodeRemoveSoulGem);
interpreter.installSegment3<OpRemoveSoulGem<ExplicitRef>>(Compiler::Misc::opcodeRemoveSoulGemExplicit);
interpreter.installSegment5<OpDrop<ImplicitRef>>(Compiler::Misc::opcodeDrop);
interpreter.installSegment5<OpDrop<ExplicitRef>>(Compiler::Misc::opcodeDropExplicit);
interpreter.installSegment5<OpDropSoulGem<ImplicitRef>>(Compiler::Misc::opcodeDropSoulGem);
interpreter.installSegment5<OpDropSoulGem<ExplicitRef>>(Compiler::Misc::opcodeDropSoulGemExplicit);
interpreter.installSegment5<OpGetAttacked<ImplicitRef>>(Compiler::Misc::opcodeGetAttacked);
interpreter.installSegment5<OpGetAttacked<ExplicitRef>>(Compiler::Misc::opcodeGetAttackedExplicit);
interpreter.installSegment5<OpGetWeaponDrawn<ImplicitRef>>(Compiler::Misc::opcodeGetWeaponDrawn);
interpreter.installSegment5<OpGetWeaponDrawn<ExplicitRef>>(Compiler::Misc::opcodeGetWeaponDrawnExplicit);
interpreter.installSegment5<OpGetSpellReadied<ImplicitRef>>(Compiler::Misc::opcodeGetSpellReadied);
interpreter.installSegment5<OpGetSpellReadied<ExplicitRef>>(Compiler::Misc::opcodeGetSpellReadiedExplicit);
interpreter.installSegment5<OpGetSpellEffects<ImplicitRef>>(Compiler::Misc::opcodeGetSpellEffects);
interpreter.installSegment5<OpGetSpellEffects<ExplicitRef>>(Compiler::Misc::opcodeGetSpellEffectsExplicit);
interpreter.installSegment5<OpGetCurrentTime>(Compiler::Misc::opcodeGetCurrentTime);
interpreter.installSegment5<OpSetDelete<ImplicitRef>>(Compiler::Misc::opcodeSetDelete);
interpreter.installSegment5<OpSetDelete<ExplicitRef>>(Compiler::Misc::opcodeSetDeleteExplicit);
interpreter.installSegment5<OpGetSquareRoot>(Compiler::Misc::opcodeGetSquareRoot);
interpreter.installSegment5<OpFall<ImplicitRef>>(Compiler::Misc::opcodeFall);
interpreter.installSegment5<OpFall<ExplicitRef>>(Compiler::Misc::opcodeFallExplicit);
interpreter.installSegment5<OpGetStandingPc<ImplicitRef>>(Compiler::Misc::opcodeGetStandingPc);
interpreter.installSegment5<OpGetStandingPc<ExplicitRef>>(Compiler::Misc::opcodeGetStandingPcExplicit);
interpreter.installSegment5<OpGetStandingActor<ImplicitRef>>(Compiler::Misc::opcodeGetStandingActor);
interpreter.installSegment5<OpGetStandingActor<ExplicitRef>>(
Compiler::Misc::opcodeGetStandingActorExplicit);
interpreter.installSegment5<OpGetCollidingPc<ImplicitRef>>(Compiler::Misc::opcodeGetCollidingPc);
interpreter.installSegment5<OpGetCollidingPc<ExplicitRef>>(Compiler::Misc::opcodeGetCollidingPcExplicit);
interpreter.installSegment5<OpGetCollidingActor<ImplicitRef>>(Compiler::Misc::opcodeGetCollidingActor);
interpreter.installSegment5<OpGetCollidingActor<ExplicitRef>>(
Compiler::Misc::opcodeGetCollidingActorExplicit);
interpreter.installSegment5<OpHurtStandingActor<ImplicitRef>>(Compiler::Misc::opcodeHurtStandingActor);
interpreter.installSegment5<OpHurtStandingActor<ExplicitRef>>(
Compiler::Misc::opcodeHurtStandingActorExplicit);
interpreter.installSegment5<OpHurtCollidingActor<ImplicitRef>>(Compiler::Misc::opcodeHurtCollidingActor);
interpreter.installSegment5<OpHurtCollidingActor<ExplicitRef>>(
Compiler::Misc::opcodeHurtCollidingActorExplicit);
interpreter.installSegment5<OpGetWindSpeed>(Compiler::Misc::opcodeGetWindSpeed);
interpreter.installSegment5<OpHitOnMe<ImplicitRef>>(Compiler::Misc::opcodeHitOnMe);
interpreter.installSegment5<OpHitOnMe<ExplicitRef>>(Compiler::Misc::opcodeHitOnMeExplicit);
interpreter.installSegment5<OpHitAttemptOnMe<ImplicitRef>>(Compiler::Misc::opcodeHitAttemptOnMe);
interpreter.installSegment5<OpHitAttemptOnMe<ExplicitRef>>(Compiler::Misc::opcodeHitAttemptOnMeExplicit);
interpreter.installSegment5<OpEnableTeleporting<false>>(Compiler::Misc::opcodeDisableTeleporting);
interpreter.installSegment5<OpEnableTeleporting<true>>(Compiler::Misc::opcodeEnableTeleporting);
interpreter.installSegment5<OpShowVars<ImplicitRef>>(Compiler::Misc::opcodeShowVars);
interpreter.installSegment5<OpShowVars<ExplicitRef>>(Compiler::Misc::opcodeShowVarsExplicit);
interpreter.installSegment5<OpShow<ImplicitRef>>(Compiler::Misc::opcodeShow);
interpreter.installSegment5<OpShow<ExplicitRef>>(Compiler::Misc::opcodeShowExplicit);
interpreter.installSegment5<OpToggleGodMode>(Compiler::Misc::opcodeToggleGodMode);
interpreter.installSegment5<OpToggleScripts>(Compiler::Misc::opcodeToggleScripts);
interpreter.installSegment5<OpEnableLevitation<false>>(Compiler::Misc::opcodeDisableLevitation);
interpreter.installSegment5<OpEnableLevitation<true>>(Compiler::Misc::opcodeEnableLevitation);
interpreter.installSegment5<OpCast<ImplicitRef>>(Compiler::Misc::opcodeCast);
interpreter.installSegment5<OpCast<ExplicitRef>>(Compiler::Misc::opcodeCastExplicit);
interpreter.installSegment5<OpExplodeSpell<ImplicitRef>>(Compiler::Misc::opcodeExplodeSpell);
interpreter.installSegment5<OpExplodeSpell<ExplicitRef>>(Compiler::Misc::opcodeExplodeSpellExplicit);
interpreter.installSegment5<OpGetPcInJail>(Compiler::Misc::opcodeGetPcInJail);
interpreter.installSegment5<OpGetPcTraveling>(Compiler::Misc::opcodeGetPcTraveling);
interpreter.installSegment3<OpBetaComment<ImplicitRef>>(Compiler::Misc::opcodeBetaComment);
interpreter.installSegment3<OpBetaComment<ExplicitRef>>(Compiler::Misc::opcodeBetaCommentExplicit);
interpreter.installSegment5<OpAddToLevCreature>(Compiler::Misc::opcodeAddToLevCreature);
interpreter.installSegment5<OpRemoveFromLevCreature>(Compiler::Misc::opcodeRemoveFromLevCreature);
interpreter.installSegment5<OpAddToLevItem>(Compiler::Misc::opcodeAddToLevItem);
interpreter.installSegment5<OpRemoveFromLevItem>(Compiler::Misc::opcodeRemoveFromLevItem);
interpreter.installSegment3<OpShowSceneGraph<ImplicitRef>>(Compiler::Misc::opcodeShowSceneGraph);
interpreter.installSegment3<OpShowSceneGraph<ExplicitRef>>(Compiler::Misc::opcodeShowSceneGraphExplicit);
interpreter.installSegment5<OpToggleBorders>(Compiler::Misc::opcodeToggleBorders);
interpreter.installSegment5<OpToggleNavMesh>(Compiler::Misc::opcodeToggleNavMesh);
interpreter.installSegment5<OpToggleActorsPaths>(Compiler::Misc::opcodeToggleActorsPaths);
interpreter.installSegment5<OpSetNavMeshNumberToRender>(Compiler::Misc::opcodeSetNavMeshNumberToRender);
interpreter.installSegment5<OpRepairedOnMe<ImplicitRef>>(Compiler::Misc::opcodeRepairedOnMe);
interpreter.installSegment5<OpRepairedOnMe<ExplicitRef>>(Compiler::Misc::opcodeRepairedOnMeExplicit);
interpreter.installSegment5<OpToggleRecastMesh>(Compiler::Misc::opcodeToggleRecastMesh);
interpreter.installSegment5<OpHelp>(Compiler::Misc::opcodeHelp);
interpreter.installSegment5<OpReloadLua>(Compiler::Misc::opcodeReloadLua);
interpreter.installSegment5<OpTestModels>(Compiler::Misc::opcodeTestModels);
}
}
}
| 77,963
|
C++
|
.cpp
| 1,644
| 32.525547
| 120
| 0.547835
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,434
|
consoleextensions.cpp
|
OpenMW_openmw/apps/openmw/mwscript/consoleextensions.cpp
|
#include "consoleextensions.hpp"
#include <components/interpreter/interpreter.hpp>
namespace MWScript
{
namespace Console
{
void installOpcodes(Interpreter::Interpreter& interpreter) {}
}
}
| 212
|
C++
|
.cpp
| 9
| 20.111111
| 69
| 0.761194
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,435
|
probe.cpp
|
OpenMW_openmw/apps/openmw/mwclass/probe.cpp
|
#include "probe.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadnpc.hpp>
#include <components/esm3/loadprob.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/actionequip.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
Probe::Probe()
: MWWorld::RegisteredClass<Probe>(ESM::Probe::sRecordId)
{
}
void Probe::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
std::string_view Probe::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Probe>(ptr);
}
std::string_view Probe::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Probe>(ptr);
}
std::unique_ptr<MWWorld::Action> Probe::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
return defaultItemActivate(ptr, actor);
}
ESM::RefId Probe::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Probe>* ref = ptr.get<ESM::Probe>();
return ref->mBase->mScript;
}
std::pair<std::vector<int>, bool> Probe::getEquipmentSlots(const MWWorld::ConstPtr& ptr) const
{
std::vector<int> slots_;
slots_.push_back(int(MWWorld::InventoryStore::Slot_CarriedRight));
return std::make_pair(slots_, false);
}
int Probe::getValue(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Probe>* ref = ptr.get<ESM::Probe>();
return ref->mBase->mData.mValue;
}
const ESM::RefId& Probe::getUpSoundId(const MWWorld::ConstPtr& ptr) const
{
static const ESM::RefId sound = ESM::RefId::stringRefId("Item Probe Up");
return sound;
}
const ESM::RefId& Probe::getDownSoundId(const MWWorld::ConstPtr& ptr) const
{
static const ESM::RefId sound = ESM::RefId::stringRefId("Item Probe Down");
return sound;
}
const std::string& Probe::getInventoryIcon(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Probe>* ref = ptr.get<ESM::Probe>();
return ref->mBase->mIcon;
}
MWGui::ToolTipInfo Probe::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Probe>* ref = ptr.get<ESM::Probe>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count);
info.icon = ref->mBase->mIcon;
std::string text;
int remainingUses = getItemHealth(ptr);
text += "\n#{sUses}: " + MWGui::ToolTips::toString(remainingUses);
text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->mBase->mData.mQuality);
text += MWGui::ToolTips::getWeightString(ref->mBase->mData.mWeight, "#{sWeight}");
text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}");
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
info.text = std::move(text);
return info;
}
std::unique_ptr<MWWorld::Action> Probe::use(const MWWorld::Ptr& ptr, bool force) const
{
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::ActionEquip>(ptr, force);
action->setSound(getUpSoundId(ptr));
return action;
}
MWWorld::Ptr Probe::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Probe>* ref = ptr.get<ESM::Probe>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
std::pair<int, std::string_view> Probe::canBeEquipped(const MWWorld::ConstPtr& ptr, const MWWorld::Ptr& npc) const
{
// Do not allow equip tools from inventory during attack
if (MWBase::Environment::get().getMechanicsManager()->isAttackingOrSpell(npc)
&& MWBase::Environment::get().getWindowManager()->isGuiMode())
return { 0, "#{sCantEquipWeapWarning}" };
return { 1, {} };
}
bool Probe::canSell(const MWWorld::ConstPtr& item, int npcServices) const
{
return (npcServices & ESM::NPC::Probes) != 0;
}
int Probe::getItemMaxHealth(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Probe>* ref = ptr.get<ESM::Probe>();
return ref->mBase->mData.mUses;
}
float Probe::getWeight(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Probe>* ref = ptr.get<ESM::Probe>();
return ref->mBase->mData.mWeight;
}
}
| 5,371
|
C++
|
.cpp
| 129
| 35.077519
| 120
| 0.658143
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,436
|
apparatus.cpp
|
OpenMW_openmw/apps/openmw/mwclass/apparatus.cpp
|
#include "apparatus.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include <components/esm3/loadappa.hpp>
#include <components/esm3/loadnpc.hpp>
#include "../mwworld/actionalchemy.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwgui/tooltips.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
Apparatus::Apparatus()
: MWWorld::RegisteredClass<Apparatus>(ESM::Apparatus::sRecordId)
{
}
void Apparatus::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
std::string_view Apparatus::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Apparatus>(ptr);
}
std::string_view Apparatus::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Apparatus>(ptr);
}
std::unique_ptr<MWWorld::Action> Apparatus::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
return defaultItemActivate(ptr, actor);
}
ESM::RefId Apparatus::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Apparatus>* ref = ptr.get<ESM::Apparatus>();
return ref->mBase->mScript;
}
int Apparatus::getValue(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Apparatus>* ref = ptr.get<ESM::Apparatus>();
return ref->mBase->mData.mValue;
}
const ESM::RefId& Apparatus::getUpSoundId(const MWWorld::ConstPtr& ptr) const
{
static const auto sound = ESM::RefId::stringRefId("Item Apparatus Up");
return sound;
}
const ESM::RefId& Apparatus::getDownSoundId(const MWWorld::ConstPtr& ptr) const
{
static const auto sound = ESM::RefId::stringRefId("Item Apparatus Down");
return sound;
}
const std::string& Apparatus::getInventoryIcon(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Apparatus>* ref = ptr.get<ESM::Apparatus>();
return ref->mBase->mIcon;
}
MWGui::ToolTipInfo Apparatus::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Apparatus>* ref = ptr.get<ESM::Apparatus>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count);
info.icon = ref->mBase->mIcon;
std::string text;
text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->mBase->mData.mQuality);
text += MWGui::ToolTips::getWeightString(ref->mBase->mData.mWeight, "#{sWeight}");
text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}");
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
info.text = std::move(text);
return info;
}
std::unique_ptr<MWWorld::Action> Apparatus::use(const MWWorld::Ptr& ptr, bool force) const
{
return std::make_unique<MWWorld::ActionAlchemy>(force);
}
MWWorld::Ptr Apparatus::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Apparatus>* ref = ptr.get<ESM::Apparatus>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
bool Apparatus::canSell(const MWWorld::ConstPtr& item, int npcServices) const
{
return (npcServices & ESM::NPC::Apparatus) != 0;
}
float Apparatus::getWeight(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Apparatus>* ref = ptr.get<ESM::Apparatus>();
return ref->mBase->mData.mWeight;
}
}
| 4,281
|
C++
|
.cpp
| 104
| 34.884615
| 120
| 0.671649
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,437
|
book.cpp
|
OpenMW_openmw/apps/openmw/mwclass/book.cpp
|
#include "book.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadbook.hpp>
#include <components/esm3/loadsoun.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/actionread.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/failedaction.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
Book::Book()
: MWWorld::RegisteredClass<Book>(ESM::Book::sRecordId)
{
}
void Book::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
std::string_view Book::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Book>(ptr);
}
std::string_view Book::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Book>(ptr);
}
std::unique_ptr<MWWorld::Action> Book::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
if (actor.getClass().isNpc() && actor.getClass().getNpcStats(actor).isWerewolf())
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
const ESM::Sound* sound = store.get<ESM::Sound>().searchRandom("WolfItem", prng);
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::FailedAction>("#{sWerewolfRefusal}");
if (sound)
action->setSound(sound->mId);
return action;
}
return std::make_unique<MWWorld::ActionRead>(ptr);
}
ESM::RefId Book::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Book>* ref = ptr.get<ESM::Book>();
return ref->mBase->mScript;
}
int Book::getValue(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Book>* ref = ptr.get<ESM::Book>();
return ref->mBase->mData.mValue;
}
const ESM::RefId& Book::getUpSoundId(const MWWorld::ConstPtr& ptr) const
{
static auto var = ESM::RefId::stringRefId("Item Book Up");
return var;
}
const ESM::RefId& Book::getDownSoundId(const MWWorld::ConstPtr& ptr) const
{
static auto var = ESM::RefId::stringRefId("Item Book Down");
return var;
}
const std::string& Book::getInventoryIcon(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Book>* ref = ptr.get<ESM::Book>();
return ref->mBase->mIcon;
}
MWGui::ToolTipInfo Book::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Book>* ref = ptr.get<ESM::Book>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count);
info.icon = ref->mBase->mIcon;
std::string text;
text += MWGui::ToolTips::getWeightString(ref->mBase->mData.mWeight, "#{sWeight}");
text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}");
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
info.enchant = ref->mBase->mEnchant;
info.text = std::move(text);
return info;
}
ESM::RefId Book::getEnchantment(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Book>* ref = ptr.get<ESM::Book>();
return ref->mBase->mEnchant;
}
const ESM::RefId& Book::applyEnchantment(
const MWWorld::ConstPtr& ptr, const ESM::RefId& enchId, int enchCharge, const std::string& newName) const
{
const MWWorld::LiveCellRef<ESM::Book>* ref = ptr.get<ESM::Book>();
ESM::Book newItem = *ref->mBase;
newItem.mId = ESM::RefId();
newItem.mName = newName;
newItem.mData.mIsScroll = 1;
newItem.mData.mEnchant = enchCharge;
newItem.mEnchant = enchId;
const ESM::Book* record = MWBase::Environment::get().getESMStore()->insert(newItem);
return record->mId;
}
std::unique_ptr<MWWorld::Action> Book::use(const MWWorld::Ptr& ptr, bool force) const
{
return std::make_unique<MWWorld::ActionRead>(ptr);
}
MWWorld::Ptr Book::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Book>* ref = ptr.get<ESM::Book>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
int Book::getEnchantmentPoints(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Book>* ref = ptr.get<ESM::Book>();
return ref->mBase->mData.mEnchant;
}
bool Book::canSell(const MWWorld::ConstPtr& item, int npcServices) const
{
return (npcServices & ESM::NPC::Books)
|| ((npcServices & ESM::NPC::MagicItems) && !getEnchantment(item).empty());
}
float Book::getWeight(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Book>* ref = ptr.get<ESM::Book>();
return ref->mBase->mData.mWeight;
}
}
| 5,853
|
C++
|
.cpp
| 142
| 34.338028
| 120
| 0.647142
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,438
|
light4.cpp
|
OpenMW_openmw/apps/openmw/mwclass/light4.cpp
|
#include "light4.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwworld/ptr.hpp"
#include <components/esm4/loadligh.hpp>
namespace MWClass
{
ESM4Light::ESM4Light()
: MWWorld::RegisteredClass<ESM4Light, ESM4Base<ESM4::Light>>(ESM4::Light::sRecordId)
{
}
void ESM4Light ::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
MWWorld::LiveCellRef<ESM4::Light>* ref = ptr.get<ESM4::Light>();
// Insert even if model is empty, so that the light is added
renderingInterface.getObjects().insertModel(ptr, model, !(ref->mBase->mData.flags & ESM4::Light::OffDefault));
}
}
| 764
|
C++
|
.cpp
| 19
| 35.578947
| 118
| 0.706757
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,439
|
weapon.cpp
|
OpenMW_openmw/apps/openmw/mwclass/weapon.cpp
|
#include "weapon.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadnpc.hpp>
#include <components/esm3/loadweap.hpp>
#include <components/misc/constants.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/actionequip.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwmechanics/weapontype.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
Weapon::Weapon()
: MWWorld::RegisteredClass<Weapon>(ESM::Weapon::sRecordId)
{
}
void Weapon::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
std::string_view Weapon::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Weapon>(ptr);
}
std::string_view Weapon::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Weapon>(ptr);
}
std::unique_ptr<MWWorld::Action> Weapon::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
return defaultItemActivate(ptr, actor);
}
bool Weapon::hasItemHealth(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
int type = ref->mBase->mData.mType;
return MWMechanics::getWeaponType(type)->mFlags & ESM::WeaponType::HasHealth;
}
int Weapon::getItemMaxHealth(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
return ref->mBase->mData.mHealth;
}
ESM::RefId Weapon::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
return ref->mBase->mScript;
}
std::pair<std::vector<int>, bool> Weapon::getEquipmentSlots(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
ESM::WeaponType::Class weapClass = MWMechanics::getWeaponType(ref->mBase->mData.mType)->mWeaponClass;
std::vector<int> slots_;
bool stack = false;
if (weapClass == ESM::WeaponType::Ammo)
{
slots_.push_back(int(MWWorld::InventoryStore::Slot_Ammunition));
stack = true;
}
else if (weapClass == ESM::WeaponType::Thrown)
{
slots_.push_back(int(MWWorld::InventoryStore::Slot_CarriedRight));
stack = true;
}
else
slots_.push_back(int(MWWorld::InventoryStore::Slot_CarriedRight));
return std::make_pair(slots_, stack);
}
ESM::RefId Weapon::getEquipmentSkill(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
int type = ref->mBase->mData.mType;
return MWMechanics::getWeaponType(type)->mSkill;
}
int Weapon::getValue(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
return ref->mBase->mData.mValue;
}
const ESM::RefId& Weapon::getUpSoundId(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
int type = ref->mBase->mData.mType;
return MWMechanics::getWeaponType(type)->mSoundIdUp;
}
const ESM::RefId& Weapon::getDownSoundId(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
int type = ref->mBase->mData.mType;
return MWMechanics::getWeaponType(type)->mSoundIdDown;
}
const std::string& Weapon::getInventoryIcon(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
return ref->mBase->mIcon;
}
MWGui::ToolTipInfo Weapon::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
const ESM::WeaponType* weaponType = MWMechanics::getWeaponType(ref->mBase->mData.mType);
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count);
info.icon = ref->mBase->mIcon;
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
std::string text;
// weapon type & damage
if (weaponType->mWeaponClass != ESM::WeaponType::Ammo || Settings::game().mShowProjectileDamage)
{
text += "\n#{sType} ";
const ESM::Skill* skill
= store.get<ESM::Skill>().find(MWMechanics::getWeaponType(ref->mBase->mData.mType)->mSkill);
std::string_view oneOrTwoHanded;
if (weaponType->mWeaponClass == ESM::WeaponType::Melee)
{
if (weaponType->mFlags & ESM::WeaponType::TwoHanded)
oneOrTwoHanded = "sTwoHanded";
else
oneOrTwoHanded = "sOneHanded";
}
text += skill->mName;
if (!oneOrTwoHanded.empty())
text += ", " + store.get<ESM::GameSetting>().find(oneOrTwoHanded)->mValue.getString();
// weapon damage
if (weaponType->mWeaponClass == ESM::WeaponType::Thrown)
{
// Thrown weapons have 2x real damage applied
// as they're both the weapon and the ammo
text += "\n#{sAttack}: " + MWGui::ToolTips::toString(static_cast<int>(ref->mBase->mData.mChop[0] * 2))
+ " - " + MWGui::ToolTips::toString(static_cast<int>(ref->mBase->mData.mChop[1] * 2));
}
else if (weaponType->mWeaponClass == ESM::WeaponType::Melee)
{
// Chop
text += "\n#{sChop}: " + MWGui::ToolTips::toString(static_cast<int>(ref->mBase->mData.mChop[0])) + " - "
+ MWGui::ToolTips::toString(static_cast<int>(ref->mBase->mData.mChop[1]));
// Slash
text += "\n#{sSlash}: " + MWGui::ToolTips::toString(static_cast<int>(ref->mBase->mData.mSlash[0]))
+ " - " + MWGui::ToolTips::toString(static_cast<int>(ref->mBase->mData.mSlash[1]));
// Thrust
text += "\n#{sThrust}: " + MWGui::ToolTips::toString(static_cast<int>(ref->mBase->mData.mThrust[0]))
+ " - " + MWGui::ToolTips::toString(static_cast<int>(ref->mBase->mData.mThrust[1]));
}
else
{
// marksman
text += "\n#{sAttack}: " + MWGui::ToolTips::toString(static_cast<int>(ref->mBase->mData.mChop[0]))
+ " - " + MWGui::ToolTips::toString(static_cast<int>(ref->mBase->mData.mChop[1]));
}
}
if (hasItemHealth(ptr))
{
int remainingHealth = getItemHealth(ptr);
text += "\n#{sCondition}: " + MWGui::ToolTips::toString(remainingHealth) + "/"
+ MWGui::ToolTips::toString(ref->mBase->mData.mHealth);
}
const bool verbose = Settings::game().mShowMeleeInfo;
// add reach for melee weapon
if (weaponType->mWeaponClass == ESM::WeaponType::Melee && verbose)
{
// display value in feet
const float combatDistance
= store.get<ESM::GameSetting>().find("fCombatDistance")->mValue.getFloat() * ref->mBase->mData.mReach;
text += MWGui::ToolTips::getWeightString(combatDistance / Constants::UnitsPerFoot, "#{sRange}");
text += " #{sFeet}";
}
// add attack speed for any weapon excepts arrows and bolts
if (weaponType->mWeaponClass != ESM::WeaponType::Ammo && verbose)
{
text += MWGui::ToolTips::getPercentString(ref->mBase->mData.mSpeed, "#{sAttributeSpeed}");
}
text += MWGui::ToolTips::getWeightString(ref->mBase->mData.mWeight, "#{sWeight}");
text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}");
info.enchant = ref->mBase->mEnchant;
if (!info.enchant.empty())
info.remainingEnchantCharge = static_cast<int>(ptr.getCellRef().getEnchantmentCharge());
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
info.text = std::move(text);
return info;
}
ESM::RefId Weapon::getEnchantment(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
return ref->mBase->mEnchant;
}
const ESM::RefId& Weapon::applyEnchantment(
const MWWorld::ConstPtr& ptr, const ESM::RefId& enchId, int enchCharge, const std::string& newName) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
ESM::Weapon newItem = *ref->mBase;
newItem.mId = ESM::RefId();
newItem.mName = newName;
newItem.mData.mEnchant = enchCharge;
newItem.mEnchant = enchId;
newItem.mData.mFlags |= ESM::Weapon::Magical;
const ESM::Weapon* record = MWBase::Environment::get().getESMStore()->insert(newItem);
return record->mId;
}
std::pair<int, std::string_view> Weapon::canBeEquipped(const MWWorld::ConstPtr& ptr, const MWWorld::Ptr& npc) const
{
if (hasItemHealth(ptr) && getItemHealth(ptr) == 0)
return { 0, "#{sInventoryMessage1}" };
// Do not allow equip weapons from inventory during attack
if (npc.isInCell() && MWBase::Environment::get().getWindowManager()->isGuiMode()
&& MWBase::Environment::get().getMechanicsManager()->isAttackingOrSpell(npc))
return { 0, "#{sCantEquipWeapWarning}" };
std::pair<std::vector<int>, bool> slots_ = getEquipmentSlots(ptr);
if (slots_.first.empty())
return { 0, {} };
int type = ptr.get<ESM::Weapon>()->mBase->mData.mType;
if (MWMechanics::getWeaponType(type)->mFlags & ESM::WeaponType::TwoHanded)
{
return { 2, {} };
}
return { 1, {} };
}
std::unique_ptr<MWWorld::Action> Weapon::use(const MWWorld::Ptr& ptr, bool force) const
{
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::ActionEquip>(ptr, force);
action->setSound(getUpSoundId(ptr));
return action;
}
MWWorld::Ptr Weapon::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
int Weapon::getEnchantmentPoints(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
return ref->mBase->mData.mEnchant;
}
bool Weapon::canSell(const MWWorld::ConstPtr& item, int npcServices) const
{
return (npcServices & ESM::NPC::Weapon)
|| ((npcServices & ESM::NPC::MagicItems) && !getEnchantment(item).empty());
}
float Weapon::getWeight(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Weapon>* ref = ptr.get<ESM::Weapon>();
return ref->mBase->mData.mWeight;
}
}
| 12,135
|
C++
|
.cpp
| 262
| 37.396947
| 120
| 0.61816
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,440
|
lockpick.cpp
|
OpenMW_openmw/apps/openmw/mwclass/lockpick.cpp
|
#include "lockpick.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadlock.hpp>
#include <components/esm3/loadnpc.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/actionequip.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
Lockpick::Lockpick()
: MWWorld::RegisteredClass<Lockpick>(ESM::Lockpick::sRecordId)
{
}
void Lockpick::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
std::string_view Lockpick::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Lockpick>(ptr);
}
std::string_view Lockpick::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Lockpick>(ptr);
}
std::unique_ptr<MWWorld::Action> Lockpick::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
return defaultItemActivate(ptr, actor);
}
ESM::RefId Lockpick::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Lockpick>* ref = ptr.get<ESM::Lockpick>();
return ref->mBase->mScript;
}
std::pair<std::vector<int>, bool> Lockpick::getEquipmentSlots(const MWWorld::ConstPtr& ptr) const
{
std::vector<int> slots_;
slots_.push_back(int(MWWorld::InventoryStore::Slot_CarriedRight));
return std::make_pair(slots_, false);
}
int Lockpick::getValue(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Lockpick>* ref = ptr.get<ESM::Lockpick>();
return ref->mBase->mData.mValue;
}
const ESM::RefId& Lockpick::getUpSoundId(const MWWorld::ConstPtr& ptr) const
{
static ESM::RefId sound = ESM::RefId::stringRefId("Item Lockpick Up");
return sound;
}
const ESM::RefId& Lockpick::getDownSoundId(const MWWorld::ConstPtr& ptr) const
{
static ESM::RefId sound = ESM::RefId::stringRefId("Item Lockpick Down");
return sound;
}
const std::string& Lockpick::getInventoryIcon(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Lockpick>* ref = ptr.get<ESM::Lockpick>();
return ref->mBase->mIcon;
}
MWGui::ToolTipInfo Lockpick::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Lockpick>* ref = ptr.get<ESM::Lockpick>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count);
info.icon = ref->mBase->mIcon;
std::string text;
int remainingUses = getItemHealth(ptr);
text += "\n#{sUses}: " + MWGui::ToolTips::toString(remainingUses);
text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->mBase->mData.mQuality);
text += MWGui::ToolTips::getWeightString(ref->mBase->mData.mWeight, "#{sWeight}");
text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}");
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
info.text = std::move(text);
return info;
}
std::unique_ptr<MWWorld::Action> Lockpick::use(const MWWorld::Ptr& ptr, bool force) const
{
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::ActionEquip>(ptr, force);
action->setSound(getUpSoundId(ptr));
return action;
}
MWWorld::Ptr Lockpick::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Lockpick>* ref = ptr.get<ESM::Lockpick>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
std::pair<int, std::string_view> Lockpick::canBeEquipped(
const MWWorld::ConstPtr& ptr, const MWWorld::Ptr& npc) const
{
// Do not allow equip tools from inventory during attack
if (MWBase::Environment::get().getMechanicsManager()->isAttackingOrSpell(npc)
&& MWBase::Environment::get().getWindowManager()->isGuiMode())
return { 0, "#{sCantEquipWeapWarning}" };
return { 1, {} };
}
bool Lockpick::canSell(const MWWorld::ConstPtr& item, int npcServices) const
{
return (npcServices & ESM::NPC::Picks) != 0;
}
int Lockpick::getItemMaxHealth(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Lockpick>* ref = ptr.get<ESM::Lockpick>();
return ref->mBase->mData.mUses;
}
float Lockpick::getWeight(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Lockpick>* ref = ptr.get<ESM::Lockpick>();
return ref->mBase->mData.mWeight;
}
}
| 5,488
|
C++
|
.cpp
| 130
| 35.630769
| 120
| 0.664409
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,441
|
npc.cpp
|
OpenMW_openmw/apps/openmw/mwclass/npc.cpp
|
#include "npc.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <cassert>
#include <memory>
#include <components/misc/constants.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/misc/rng.hpp>
#include <components/debug/debuglog.hpp>
#include <components/esm3/loadbody.hpp>
#include <components/esm3/loadclas.hpp>
#include <components/esm3/loadmgef.hpp>
#include <components/esm3/loadnpc.hpp>
#include <components/esm3/loadrace.hpp>
#include <components/esm3/loadsoun.hpp>
#include <components/esm3/npcstate.hpp>
#include <components/settings/values.hpp>
#include <components/vfs/pathutil.hpp>
#include "../mwbase/dialoguemanager.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/luamanager.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/aisetting.hpp"
#include "../mwmechanics/autocalcspell.hpp"
#include "../mwmechanics/combat.hpp"
#include "../mwmechanics/creaturecustomdataresetter.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/difficultyscaling.hpp"
#include "../mwmechanics/disease.hpp"
#include "../mwmechanics/inventory.hpp"
#include "../mwmechanics/movement.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "../mwmechanics/setbaseaisetting.hpp"
#include "../mwmechanics/spellcasting.hpp"
#include "../mwmechanics/weapontype.hpp"
#include "../mwworld/actionopen.hpp"
#include "../mwworld/actiontalk.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/customdata.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/failedaction.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/localscripts.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwworld/worldmodel.hpp"
#include "../mwrender/npcanimation.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwgui/tooltips.hpp"
#include "nameorid.hpp"
namespace
{
struct NpcParts
{
const ESM::RefId mSwimLeft = ESM::RefId::stringRefId("Swim Left");
const ESM::RefId mSwimRight = ESM::RefId::stringRefId("Swim Right");
const ESM::RefId mFootWaterLeft = ESM::RefId::stringRefId("FootWaterLeft");
const ESM::RefId mFootWaterRight = ESM::RefId::stringRefId("FootWaterRight");
const ESM::RefId mFootBareLeft = ESM::RefId::stringRefId("FootBareLeft");
const ESM::RefId mFootBareRight = ESM::RefId::stringRefId("FootBareRight");
const ESM::RefId mFootLightLeft = ESM::RefId::stringRefId("footLightLeft");
const ESM::RefId mFootLightRight = ESM::RefId::stringRefId("footLightRight");
const ESM::RefId mFootMediumRight = ESM::RefId::stringRefId("FootMedRight");
const ESM::RefId mFootMediumLeft = ESM::RefId::stringRefId("FootMedLeft");
const ESM::RefId mFootHeavyLeft = ESM::RefId::stringRefId("footHeavyLeft");
const ESM::RefId mFootHeavyRight = ESM::RefId::stringRefId("footHeavyRight");
};
const NpcParts npcParts;
int is_even(double d)
{
double int_part;
modf(d / 2.0, &int_part);
return 2.0 * int_part == d;
}
int round_ieee_754(double d)
{
double i = floor(d);
d -= i;
if (d < 0.5)
return static_cast<int>(i);
if (d > 0.5)
return static_cast<int>(i) + 1;
if (is_even(i))
return static_cast<int>(i);
return static_cast<int>(i) + 1;
}
void autoCalculateAttributes(const ESM::NPC* npc, MWMechanics::CreatureStats& creatureStats)
{
// race bonus
const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(npc->mRace);
bool male = (npc->mFlags & ESM::NPC::Female) == 0;
const auto& attributes = MWBase::Environment::get().getESMStore()->get<ESM::Attribute>();
int level = creatureStats.getLevel();
for (const ESM::Attribute& attribute : attributes)
creatureStats.setAttribute(attribute.mId, race->mData.getAttribute(attribute.mId, male));
// class bonus
const ESM::Class* class_ = MWBase::Environment::get().getESMStore()->get<ESM::Class>().find(npc->mClass);
for (int attribute : class_->mData.mAttribute)
{
if (attribute >= 0 && attribute < ESM::Attribute::Length)
{
auto id = ESM::Attribute::indexToRefId(attribute);
creatureStats.setAttribute(id, creatureStats.getAttribute(id).getBase() + 10);
}
}
// skill bonus
for (const ESM::Attribute& attribute : attributes)
{
float modifierSum = 0;
int attributeIndex = ESM::Attribute::refIdToIndex(attribute.mId);
for (const ESM::Skill& skill : MWBase::Environment::get().getESMStore()->get<ESM::Skill>())
{
if (skill.mData.mAttribute != attributeIndex)
continue;
// is this a minor or major skill?
float add = 0.2f;
int index = ESM::Skill::refIdToIndex(skill.mId);
for (const auto& skills : class_->mData.mSkills)
{
if (skills[0] == index)
add = 0.5;
if (skills[1] == index)
add = 1.0;
}
modifierSum += add;
}
creatureStats.setAttribute(attribute.mId,
std::min(
round_ieee_754(creatureStats.getAttribute(attribute.mId).getBase() + (level - 1) * modifierSum),
100));
}
// initial health
float strength = creatureStats.getAttribute(ESM::Attribute::Strength).getBase();
float endurance = creatureStats.getAttribute(ESM::Attribute::Endurance).getBase();
int multiplier = 3;
if (class_->mData.mSpecialization == ESM::Class::Combat)
multiplier += 2;
else if (class_->mData.mSpecialization == ESM::Class::Stealth)
multiplier += 1;
if (std::find(class_->mData.mAttribute.begin(), class_->mData.mAttribute.end(),
ESM::Attribute::refIdToIndex(ESM::Attribute::Endurance))
!= class_->mData.mAttribute.end())
multiplier += 1;
creatureStats.setHealth(floor(0.5f * (strength + endurance)) + multiplier * (creatureStats.getLevel() - 1));
}
/**
* @brief autoCalculateSkills
*
* Skills are calculated with following formulae ( http://www.uesp.net/wiki/Morrowind:NPCs#Skills ):
*
* Skills: (Level - 1) × (Majority Multiplier + Specialization Multiplier)
*
* The Majority Multiplier is 1.0 for a Major or Minor Skill, or 0.1 for a Miscellaneous Skill.
*
* The Specialization Multiplier is 0.5 for a Skill in the same Specialization as the class,
* zero for other Skills.
*
* and by adding class, race, specialization bonus.
*/
void autoCalculateSkills(
const ESM::NPC* npc, MWMechanics::NpcStats& npcStats, const MWWorld::Ptr& ptr, bool spellsInitialised)
{
const ESM::Class* class_ = MWBase::Environment::get().getESMStore()->get<ESM::Class>().find(npc->mClass);
unsigned int level = npcStats.getLevel();
const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(npc->mRace);
for (int i = 0; i < 2; ++i)
{
int bonus = (i == 0) ? 10 : 25;
for (const auto& skills : class_->mData.mSkills)
{
ESM::RefId id = ESM::Skill::indexToRefId(skills[i]);
if (!id.empty())
{
npcStats.getSkill(id).setBase(npcStats.getSkill(id).getBase() + bonus);
}
}
}
for (const ESM::Skill& skill : MWBase::Environment::get().getESMStore()->get<ESM::Skill>())
{
float majorMultiplier = 0.1f;
float specMultiplier = 0.0f;
int raceBonus = 0;
int specBonus = 0;
int index = ESM::Skill::refIdToIndex(skill.mId);
auto bonusIt = std::find_if(race->mData.mBonus.begin(), race->mData.mBonus.end(),
[&](const auto& bonus) { return bonus.mSkill == index; });
if (bonusIt != race->mData.mBonus.end())
raceBonus = bonusIt->mBonus;
for (const auto& skills : class_->mData.mSkills)
{
// is this a minor or major skill?
if (std::find(skills.begin(), skills.end(), index) != skills.end())
{
majorMultiplier = 1.0f;
break;
}
}
// is this skill in the same Specialization as the class?
if (skill.mData.mSpecialization == class_->mData.mSpecialization)
{
specMultiplier = 0.5f;
specBonus = 5;
}
npcStats.getSkill(skill.mId).setBase(
std::min(round_ieee_754(npcStats.getSkill(skill.mId).getBase() + 5 + raceBonus + specBonus
+ (int(level) - 1) * (majorMultiplier + specMultiplier)),
100)); // Must gracefully handle level 0
}
if (!spellsInitialised)
{
std::vector<ESM::RefId> spells
= MWMechanics::autoCalcNpcSpells(npcStats.getSkills(), npcStats.getAttributes(), race);
npcStats.getSpells().addAllToInstance(spells);
}
}
}
namespace MWClass
{
Npc::Npc()
: MWWorld::RegisteredClass<Npc, Actor>(ESM::NPC::sRecordId)
{
}
class NpcCustomData : public MWWorld::TypedCustomData<NpcCustomData>
{
public:
MWMechanics::NpcStats mNpcStats;
MWMechanics::Movement mMovement;
MWWorld::InventoryStore mInventoryStore;
NpcCustomData& asNpcCustomData() override { return *this; }
const NpcCustomData& asNpcCustomData() const override { return *this; }
};
const Npc::GMST& Npc::getGmst()
{
static const GMST staticGmst = [] {
GMST gmst;
const MWWorld::Store<ESM::GameSetting>& store
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
gmst.fMinWalkSpeed = store.find("fMinWalkSpeed");
gmst.fMaxWalkSpeed = store.find("fMaxWalkSpeed");
gmst.fEncumberedMoveEffect = store.find("fEncumberedMoveEffect");
gmst.fSneakSpeedMultiplier = store.find("fSneakSpeedMultiplier");
gmst.fAthleticsRunBonus = store.find("fAthleticsRunBonus");
gmst.fBaseRunMultiplier = store.find("fBaseRunMultiplier");
gmst.fMinFlySpeed = store.find("fMinFlySpeed");
gmst.fMaxFlySpeed = store.find("fMaxFlySpeed");
gmst.fSwimRunBase = store.find("fSwimRunBase");
gmst.fSwimRunAthleticsMult = store.find("fSwimRunAthleticsMult");
gmst.fJumpEncumbranceBase = store.find("fJumpEncumbranceBase");
gmst.fJumpEncumbranceMultiplier = store.find("fJumpEncumbranceMultiplier");
gmst.fJumpAcrobaticsBase = store.find("fJumpAcrobaticsBase");
gmst.fJumpAcroMultiplier = store.find("fJumpAcroMultiplier");
gmst.fJumpRunMultiplier = store.find("fJumpRunMultiplier");
gmst.fWereWolfRunMult = store.find("fWereWolfRunMult");
gmst.fKnockDownMult = store.find("fKnockDownMult");
gmst.iKnockDownOddsMult = store.find("iKnockDownOddsMult");
gmst.iKnockDownOddsBase = store.find("iKnockDownOddsBase");
gmst.fCombatArmorMinMult = store.find("fCombatArmorMinMult");
return gmst;
}();
return staticGmst;
}
void Npc::ensureCustomData(const MWWorld::Ptr& ptr) const
{
if (!ptr.getRefData().getCustomData())
{
MWBase::Environment::get().getWorldModel()->registerPtr(ptr);
bool recalculate = false;
auto tempData = std::make_unique<NpcCustomData>();
NpcCustomData* data = tempData.get();
MWMechanics::CreatureCustomDataResetter resetter{ ptr };
ptr.getRefData().setCustomData(std::move(tempData));
MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
bool spellsInitialised = data->mNpcStats.getSpells().setSpells(ref->mBase->mId);
// creature stats
int gold = 0;
if (ref->mBase->mNpdtType != ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS)
{
gold = ref->mBase->mNpdt.mGold;
for (size_t i = 0; i < ref->mBase->mNpdt.mSkills.size(); ++i)
data->mNpcStats.getSkill(ESM::Skill::indexToRefId(i)).setBase(ref->mBase->mNpdt.mSkills[i]);
for (size_t i = 0; i < ref->mBase->mNpdt.mAttributes.size(); ++i)
data->mNpcStats.setAttribute(ESM::Attribute::indexToRefId(i), ref->mBase->mNpdt.mAttributes[i]);
data->mNpcStats.setHealth(ref->mBase->mNpdt.mHealth);
data->mNpcStats.setMagicka(ref->mBase->mNpdt.mMana);
data->mNpcStats.setFatigue(ref->mBase->mNpdt.mFatigue);
data->mNpcStats.setLevel(ref->mBase->mNpdt.mLevel);
data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt.mDisposition);
data->mNpcStats.setReputation(ref->mBase->mNpdt.mReputation);
}
else
{
gold = ref->mBase->mNpdt.mGold;
for (int i = 0; i < 3; ++i)
data->mNpcStats.setDynamic(i, 10);
data->mNpcStats.setLevel(ref->mBase->mNpdt.mLevel);
data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt.mDisposition);
data->mNpcStats.setReputation(ref->mBase->mNpdt.mReputation);
autoCalculateAttributes(ref->mBase, data->mNpcStats);
autoCalculateSkills(ref->mBase, data->mNpcStats, ptr, spellsInitialised);
recalculate = true;
}
// Persistent actors with 0 health do not play death animation
if (data->mNpcStats.isDead())
data->mNpcStats.setDeathAnimationFinished(isPersistent(ptr));
// race powers
const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(ref->mBase->mRace);
data->mNpcStats.getSpells().addAllToInstance(race->mPowers.mList);
if (!ref->mBase->mFaction.empty())
{
static const int iAutoRepFacMod = MWBase::Environment::get()
.getESMStore()
->get<ESM::GameSetting>()
.find("iAutoRepFacMod")
->mValue.getInteger();
static const int iAutoRepLevMod = MWBase::Environment::get()
.getESMStore()
->get<ESM::GameSetting>()
.find("iAutoRepLevMod")
->mValue.getInteger();
int rank = ref->mBase->getFactionRank();
data->mNpcStats.setReputation(
iAutoRepFacMod * (rank + 1) + iAutoRepLevMod * (data->mNpcStats.getLevel() - 1));
}
data->mNpcStats.getAiSequence().fill(ref->mBase->mAiPackage);
data->mNpcStats.setAiSetting(MWMechanics::AiSetting::Hello, ref->mBase->mAiData.mHello);
data->mNpcStats.setAiSetting(MWMechanics::AiSetting::Fight, ref->mBase->mAiData.mFight);
data->mNpcStats.setAiSetting(MWMechanics::AiSetting::Flee, ref->mBase->mAiData.mFlee);
data->mNpcStats.setAiSetting(MWMechanics::AiSetting::Alarm, ref->mBase->mAiData.mAlarm);
// spells
if (!spellsInitialised)
data->mNpcStats.getSpells().addAllToInstance(ref->mBase->mSpells.mList);
data->mNpcStats.setGoldPool(gold);
// store
resetter.mPtr = {};
if (recalculate)
data->mNpcStats.recalculateMagicka();
// inventory
// setting ownership is used to make the NPC auto-equip his initial equipment only, and not bartered items
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
MWWorld::InventoryStore& inventory = getInventoryStore(ptr);
inventory.setPtr(ptr);
inventory.fill(ref->mBase->mInventory, ptr.getCellRef().getRefId(), prng);
inventory.autoEquip();
}
}
void Npc::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
renderingInterface.getObjects().insertNPC(ptr);
}
bool Npc::isPersistent(const MWWorld::ConstPtr& actor) const
{
const MWWorld::LiveCellRef<ESM::NPC>* ref = actor.get<ESM::NPC>();
return (ref->mBase->mRecordFlags & ESM::FLAG_Persistent) != 0;
}
std::string_view Npc::getModel(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
std::string_view model = Settings::models().mBaseanim.get();
const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(ref->mBase->mRace);
if (race->mData.mFlags & ESM::Race::Beast)
model = Settings::models().mBaseanimkna.get();
// Base animations should be in the meshes dir
constexpr std::string_view prefix = "meshes/";
assert(VFS::Path::pathEqual(prefix, model.substr(0, prefix.size())));
return model.substr(prefix.size());
}
std::string Npc::getCorrectedModel(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(ref->mBase->mRace);
if (race->mData.mFlags & ESM::Race::Beast)
return Settings::models().mBaseanimkna.get().value();
return Settings::models().mBaseanim.get().value();
}
void Npc::getModelsToPreload(const MWWorld::ConstPtr& ptr, std::vector<std::string_view>& models) const
{
const MWWorld::LiveCellRef<ESM::NPC>* npc = ptr.get<ESM::NPC>();
const auto& esmStore = MWBase::Environment::get().getESMStore();
models.push_back(getModel(ptr));
if (!npc->mBase->mModel.empty())
models.push_back(npc->mBase->mModel);
if (!npc->mBase->mHead.empty())
{
const ESM::BodyPart* head = esmStore->get<ESM::BodyPart>().search(npc->mBase->mHead);
if (head)
models.push_back(head->mModel);
}
if (!npc->mBase->mHair.empty())
{
const ESM::BodyPart* hair = esmStore->get<ESM::BodyPart>().search(npc->mBase->mHair);
if (hair)
models.push_back(hair->mModel);
}
bool female = (npc->mBase->mFlags & ESM::NPC::Female);
const MWWorld::CustomData* customData = ptr.getRefData().getCustomData();
if (customData)
{
const MWWorld::InventoryStore& invStore = customData->asNpcCustomData().mInventoryStore;
for (int slot = 0; slot < MWWorld::InventoryStore::Slots; ++slot)
{
MWWorld::ConstContainerStoreIterator equipped = invStore.getSlot(slot);
if (equipped != invStore.end())
{
const auto addParts = [&](const std::vector<ESM::PartReference>& parts) {
for (const ESM::PartReference& partRef : parts)
{
const ESM::RefId& partname
= (female && !partRef.mFemale.empty()) || (!female && partRef.mMale.empty())
? partRef.mFemale
: partRef.mMale;
const ESM::BodyPart* part = esmStore->get<ESM::BodyPart>().search(partname);
if (part && !part->mModel.empty())
models.push_back(part->mModel);
}
};
if (equipped->getType() == ESM::Clothing::sRecordId)
{
const ESM::Clothing* clothes = equipped->get<ESM::Clothing>()->mBase;
addParts(clothes->mParts.mParts);
}
else if (equipped->getType() == ESM::Armor::sRecordId)
{
const ESM::Armor* armor = equipped->get<ESM::Armor>()->mBase;
addParts(armor->mParts.mParts);
}
else
{
std::string_view model = equipped->getClass().getModel(*equipped);
if (!model.empty())
models.push_back(model);
}
}
}
}
// preload body parts
if (const ESM::Race* race = esmStore->get<ESM::Race>().search(npc->mBase->mRace))
{
const std::vector<const ESM::BodyPart*>& parts
= MWRender::NpcAnimation::getBodyParts(race->mId, female, false, false);
for (const ESM::BodyPart* part : parts)
{
if (part && !part->mModel.empty())
models.push_back(part->mModel);
}
}
}
std::string_view Npc::getName(const MWWorld::ConstPtr& ptr) const
{
if (ptr.getRefData().getCustomData()
&& ptr.getRefData().getCustomData()->asNpcCustomData().mNpcStats.isWerewolf())
{
const MWWorld::Store<ESM::GameSetting>& store
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
return store.find("sWerewolfPopup")->mValue.getString();
}
return getNameOrId<ESM::NPC>(ptr);
}
MWMechanics::CreatureStats& Npc::getCreatureStats(const MWWorld::Ptr& ptr) const
{
ensureCustomData(ptr);
return ptr.getRefData().getCustomData()->asNpcCustomData().mNpcStats;
}
MWMechanics::NpcStats& Npc::getNpcStats(const MWWorld::Ptr& ptr) const
{
ensureCustomData(ptr);
return ptr.getRefData().getCustomData()->asNpcCustomData().mNpcStats;
}
bool Npc::evaluateHit(const MWWorld::Ptr& ptr, MWWorld::Ptr& victim, osg::Vec3f& hitPosition) const
{
victim = MWWorld::Ptr();
hitPosition = osg::Vec3f();
// Get the weapon used (if hand-to-hand, weapon = inv.end())
MWWorld::InventoryStore& inv = getInventoryStore(ptr);
MWWorld::ContainerStoreIterator weaponslot = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight);
MWWorld::Ptr weapon;
if (weaponslot != inv.end() && weaponslot->getType() == ESM::Weapon::sRecordId)
weapon = *weaponslot;
MWBase::World* world = MWBase::Environment::get().getWorld();
const MWWorld::Store<ESM::GameSetting>& store = world->getStore().get<ESM::GameSetting>();
const float fCombatDistance = store.find("fCombatDistance")->mValue.getFloat();
float dist = fCombatDistance
* (!weapon.isEmpty() ? weapon.get<ESM::Weapon>()->mBase->mData.mReach
: store.find("fHandToHandReach")->mValue.getFloat());
const std::pair<MWWorld::Ptr, osg::Vec3f> result = MWMechanics::getHitContact(ptr, dist);
if (result.first.isEmpty()) // Didn't hit anything
return true;
// Note that earlier we returned true in spite of an apparent failure to hit anything alive.
// This is because hitting nothing is not a "miss" and should be handled as such character controller-side.
victim = result.first;
hitPosition = result.second;
ESM::RefId weapskill = ESM::Skill::HandToHand;
if (!weapon.isEmpty())
weapskill = weapon.getClass().getEquipmentSkill(weapon);
float hitchance = MWMechanics::getHitChance(ptr, victim, getSkill(ptr, weapskill));
return Misc::Rng::roll0to99(world->getPrng()) < hitchance;
}
void Npc::hit(const MWWorld::Ptr& ptr, float attackStrength, int type, const MWWorld::Ptr& victim,
const osg::Vec3f& hitPosition, bool success) const
{
MWWorld::InventoryStore& inv = getInventoryStore(ptr);
MWWorld::ContainerStoreIterator weaponslot = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight);
MWWorld::Ptr weapon;
if (weaponslot != inv.end() && weaponslot->getType() == ESM::Weapon::sRecordId)
weapon = *weaponslot;
MWMechanics::applyFatigueLoss(ptr, weapon, attackStrength);
if (victim.isEmpty()) // Didn't hit anything
return;
const MWWorld::Class& othercls = victim.getClass();
MWMechanics::CreatureStats& otherstats = othercls.getCreatureStats(victim);
if (otherstats.isDead()) // Can't hit dead actors
return;
if (ptr == MWMechanics::getPlayer())
MWBase::Environment::get().getWindowManager()->setEnemy(victim);
float damage = 0.0f;
if (!success)
{
othercls.onHit(
victim, damage, false, weapon, ptr, osg::Vec3f(), false, MWMechanics::DamageSourceType::Melee);
MWMechanics::reduceWeaponCondition(damage, false, weapon, ptr);
MWMechanics::resistNormalWeapon(victim, ptr, weapon, damage);
return;
}
bool healthdmg;
if (!weapon.isEmpty())
{
const unsigned char* attack = nullptr;
if (type == ESM::Weapon::AT_Chop)
attack = weapon.get<ESM::Weapon>()->mBase->mData.mChop.data();
else if (type == ESM::Weapon::AT_Slash)
attack = weapon.get<ESM::Weapon>()->mBase->mData.mSlash.data();
else if (type == ESM::Weapon::AT_Thrust)
attack = weapon.get<ESM::Weapon>()->mBase->mData.mThrust.data();
if (attack)
{
damage = attack[0] + ((attack[1] - attack[0]) * attackStrength);
}
MWMechanics::adjustWeaponDamage(damage, weapon, ptr);
MWMechanics::reduceWeaponCondition(damage, true, weapon, ptr);
MWMechanics::resistNormalWeapon(victim, ptr, weapon, damage);
MWMechanics::applyWerewolfDamageMult(victim, weapon, damage);
healthdmg = true;
}
else
{
MWMechanics::getHandToHandDamage(ptr, victim, damage, healthdmg, attackStrength);
}
MWBase::World* world = MWBase::Environment::get().getWorld();
const MWWorld::Store<ESM::GameSetting>& store = world->getStore().get<ESM::GameSetting>();
if (ptr == MWMechanics::getPlayer())
{
ESM::RefId weapskill = ESM::Skill::HandToHand;
if (!weapon.isEmpty())
weapskill = weapon.getClass().getEquipmentSkill(weapon);
skillUsageSucceeded(ptr, weapskill, ESM::Skill::Weapon_SuccessfulHit);
const MWMechanics::AiSequence& seq = victim.getClass().getCreatureStats(victim).getAiSequence();
bool unaware
= !seq.isInCombat() && !MWBase::Environment::get().getMechanicsManager()->awarenessCheck(ptr, victim);
if (unaware)
{
damage *= store.find("fCombatCriticalStrikeMult")->mValue.getFloat();
MWBase::Environment::get().getWindowManager()->messageBox("#{sTargetCriticalStrike}");
if (healthdmg)
{
MWBase::Environment::get().getSoundManager()->playSound3D(
victim, ESM::RefId::stringRefId("critical damage"), 1.0f, 1.0f);
}
}
}
if (othercls.getCreatureStats(victim).getKnockedDown())
damage *= store.find("fCombatKODamageMult")->mValue.getFloat();
// Apply "On hit" enchanted weapons
MWMechanics::applyOnStrikeEnchantment(ptr, victim, weapon, hitPosition);
MWMechanics::applyElementalShields(ptr, victim);
if (MWMechanics::blockMeleeAttack(ptr, victim, weapon, damage, attackStrength))
damage = 0;
if (victim == MWMechanics::getPlayer() && MWBase::Environment::get().getWorld()->getGodModeState())
damage = 0;
MWMechanics::diseaseContact(victim, ptr);
othercls.onHit(victim, damage, healthdmg, weapon, ptr, hitPosition, true, MWMechanics::DamageSourceType::Melee);
}
void Npc::onHit(const MWWorld::Ptr& ptr, float damage, bool ishealth, const MWWorld::Ptr& object,
const MWWorld::Ptr& attacker, const osg::Vec3f& hitPosition, bool successful,
const MWMechanics::DamageSourceType sourceType) const
{
MWBase::SoundManager* sndMgr = MWBase::Environment::get().getSoundManager();
MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
bool wasDead = stats.isDead();
bool setOnPcHitMe = true;
// NOTE: 'object' and/or 'attacker' may be empty.
if (!attacker.isEmpty() && attacker.getClass().isActor() && !stats.getAiSequence().isInCombat(attacker))
{
stats.setAttacked(true);
bool complain = sourceType == MWMechanics::DamageSourceType::Melee;
bool supportFriendlyFire = sourceType != MWMechanics::DamageSourceType::Ranged;
if (supportFriendlyFire && MWMechanics::friendlyHit(attacker, ptr, complain))
setOnPcHitMe = false;
else
setOnPcHitMe = MWBase::Environment::get().getMechanicsManager()->actorAttacked(ptr, attacker);
}
// Attacker and target store each other as hitattemptactor if they have no one stored yet
if (!attacker.isEmpty() && attacker.getClass().isActor())
{
MWMechanics::CreatureStats& statsAttacker = attacker.getClass().getCreatureStats(attacker);
// First handle the attacked actor
if ((stats.getHitAttemptActorId() == -1)
&& (statsAttacker.getAiSequence().isInCombat(ptr) || attacker == MWMechanics::getPlayer()))
stats.setHitAttemptActorId(statsAttacker.getActorId());
// Next handle the attacking actor
if ((statsAttacker.getHitAttemptActorId() == -1)
&& (statsAttacker.getAiSequence().isInCombat(ptr) || attacker == MWMechanics::getPlayer()))
statsAttacker.setHitAttemptActorId(stats.getActorId());
}
if (!object.isEmpty())
stats.setLastHitAttemptObject(object.getCellRef().getRefId());
if (setOnPcHitMe && !attacker.isEmpty() && attacker == MWMechanics::getPlayer())
{
const ESM::RefId& script = getScript(ptr);
/* Set the OnPCHitMe script variable. The script is responsible for clearing it. */
if (!script.empty())
ptr.getRefData().getLocals().setVarByInt(script, "onpchitme", 1);
}
if (!successful)
{
// Missed
if (!attacker.isEmpty() && attacker == MWMechanics::getPlayer())
sndMgr->playSound3D(ptr, ESM::RefId::stringRefId("miss"), 1.0f, 1.0f);
return;
}
if (!object.isEmpty())
stats.setLastHitObject(object.getCellRef().getRefId());
if (damage < 0.001f)
damage = 0;
bool godmode = ptr == MWMechanics::getPlayer() && MWBase::Environment::get().getWorld()->getGodModeState();
if (godmode)
damage = 0;
if (damage > 0.0f && !attacker.isEmpty())
{
// 'ptr' is losing health. Play a 'hit' voiced dialog entry if not already saying
// something, alert the character controller, scripts, etc.
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
const GMST& gmst = getGmst();
int chance = store.get<ESM::GameSetting>().find("iVoiceHitOdds")->mValue.getInteger();
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
if (Misc::Rng::roll0to99(prng) < chance)
MWBase::Environment::get().getDialogueManager()->say(ptr, ESM::RefId::stringRefId("hit"));
// Check for knockdown
float agilityTerm
= stats.getAttribute(ESM::Attribute::Agility).getModified() * gmst.fKnockDownMult->mValue.getFloat();
float knockdownTerm = stats.getAttribute(ESM::Attribute::Agility).getModified()
* gmst.iKnockDownOddsMult->mValue.getInteger() * 0.01f
+ gmst.iKnockDownOddsBase->mValue.getInteger();
if (ishealth && agilityTerm <= damage && knockdownTerm <= Misc::Rng::roll0to99(prng))
stats.setKnockedDown(true);
else
stats.setHitRecovery(true); // Is this supposed to always occur?
if (damage > 0 && ishealth)
{
// Hit percentages:
// cuirass = 30%
// shield, helmet, greaves, boots, pauldrons = 10% each
// guantlets = 5% each
static const int hitslots[20]
= { MWWorld::InventoryStore::Slot_Cuirass, MWWorld::InventoryStore::Slot_Cuirass,
MWWorld::InventoryStore::Slot_Cuirass, MWWorld::InventoryStore::Slot_Cuirass,
MWWorld::InventoryStore::Slot_Cuirass, MWWorld::InventoryStore::Slot_Cuirass,
MWWorld::InventoryStore::Slot_CarriedLeft, MWWorld::InventoryStore::Slot_CarriedLeft,
MWWorld::InventoryStore::Slot_Helmet, MWWorld::InventoryStore::Slot_Helmet,
MWWorld::InventoryStore::Slot_Greaves, MWWorld::InventoryStore::Slot_Greaves,
MWWorld::InventoryStore::Slot_Boots, MWWorld::InventoryStore::Slot_Boots,
MWWorld::InventoryStore::Slot_LeftPauldron, MWWorld::InventoryStore::Slot_LeftPauldron,
MWWorld::InventoryStore::Slot_RightPauldron, MWWorld::InventoryStore::Slot_RightPauldron,
MWWorld::InventoryStore::Slot_LeftGauntlet, MWWorld::InventoryStore::Slot_RightGauntlet };
int hitslot = hitslots[Misc::Rng::rollDice(20, prng)];
float unmitigatedDamage = damage;
float x = damage / (damage + getArmorRating(ptr));
damage *= std::max(gmst.fCombatArmorMinMult->mValue.getFloat(), x);
int damageDiff = static_cast<int>(unmitigatedDamage - damage);
damage = std::max(1.f, damage);
damageDiff = std::max(1, damageDiff);
MWWorld::InventoryStore& inv = getInventoryStore(ptr);
MWWorld::ContainerStoreIterator armorslot = inv.getSlot(hitslot);
MWWorld::Ptr armor = ((armorslot != inv.end()) ? *armorslot : MWWorld::Ptr());
bool hasArmor = !armor.isEmpty() && armor.getType() == ESM::Armor::sRecordId;
// If there's no item in the carried left slot or if it is not a shield redistribute the hit.
if (!hasArmor && hitslot == MWWorld::InventoryStore::Slot_CarriedLeft)
{
if (Misc::Rng::rollDice(2, prng) == 0)
hitslot = MWWorld::InventoryStore::Slot_Cuirass;
else
hitslot = MWWorld::InventoryStore::Slot_LeftPauldron;
armorslot = inv.getSlot(hitslot);
if (armorslot != inv.end())
{
armor = *armorslot;
hasArmor = !armor.isEmpty() && armor.getType() == ESM::Armor::sRecordId;
}
}
if (hasArmor)
{
// Unarmed creature attacks don't affect armor condition unless it was
// explicitly requested.
if (!object.isEmpty() || attacker.isEmpty() || attacker.getClass().isNpc()
|| Settings::game().mUnarmedCreatureAttacksDamageArmor)
{
int armorhealth = armor.getClass().getItemHealth(armor);
armorhealth -= std::min(damageDiff, armorhealth);
armor.getCellRef().setCharge(armorhealth);
// Armor broken? unequip it
if (armorhealth == 0)
armor = *inv.unequipItem(armor);
}
ESM::RefId skill = armor.getClass().getEquipmentSkill(armor);
if (ptr == MWMechanics::getPlayer())
skillUsageSucceeded(ptr, skill, ESM::Skill::Armor_HitByOpponent);
if (skill == ESM::Skill::LightArmor)
sndMgr->playSound3D(ptr, ESM::RefId::stringRefId("Light Armor Hit"), 1.0f, 1.0f);
else if (skill == ESM::Skill::MediumArmor)
sndMgr->playSound3D(ptr, ESM::RefId::stringRefId("Medium Armor Hit"), 1.0f, 1.0f);
else if (skill == ESM::Skill::HeavyArmor)
sndMgr->playSound3D(ptr, ESM::RefId::stringRefId("Heavy Armor Hit"), 1.0f, 1.0f);
}
else if (ptr == MWMechanics::getPlayer())
skillUsageSucceeded(ptr, ESM::Skill::Unarmored, ESM::Skill::Armor_HitByOpponent);
}
}
if (ishealth)
{
if (!attacker.isEmpty() && !godmode)
damage = scaleDamage(damage, attacker, ptr);
if (damage > 0.0f)
{
sndMgr->playSound3D(ptr, ESM::RefId::stringRefId("Health Damage"), 1.0f, 1.0f);
if (ptr == MWMechanics::getPlayer())
MWBase::Environment::get().getWindowManager()->activateHitOverlay();
if (!attacker.isEmpty())
MWBase::Environment::get().getWorld()->spawnBloodEffect(ptr, hitPosition);
}
MWMechanics::DynamicStat<float> health(getCreatureStats(ptr).getHealth());
health.setCurrent(health.getCurrent() - damage);
stats.setHealth(health);
}
else
{
MWMechanics::DynamicStat<float> fatigue(getCreatureStats(ptr).getFatigue());
fatigue.setCurrent(fatigue.getCurrent() - damage, true);
stats.setFatigue(fatigue);
}
if (!wasDead && getCreatureStats(ptr).isDead())
{
// NPC was killed
if (!attacker.isEmpty() && attacker.getClass().isNpc()
&& attacker.getClass().getNpcStats(attacker).isWerewolf())
{
attacker.getClass().getNpcStats(attacker).addWerewolfKill();
}
MWBase::Environment::get().getMechanicsManager()->actorKilled(ptr, attacker);
}
}
std::unique_ptr<MWWorld::Action> Npc::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
// player got activated by another NPC
if (ptr == MWMechanics::getPlayer())
return std::make_unique<MWWorld::ActionTalk>(actor);
// Werewolfs can't activate NPCs
if (actor.getClass().isNpc() && actor.getClass().getNpcStats(actor).isWerewolf())
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
const ESM::Sound* sound = store.get<ESM::Sound>().searchRandom("WolfNPC", prng);
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::FailedAction>("#{sWerewolfRefusal}");
if (sound)
action->setSound(sound->mId);
return action;
}
const MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
const MWMechanics::AiSequence& aiSequence = stats.getAiSequence();
const bool isPursuing = aiSequence.isInPursuit() && actor == MWMechanics::getPlayer();
const bool inCombatWithActor = aiSequence.isInCombat(actor) || isPursuing;
if (stats.isDead())
{
// by default user can loot non-fighting actors during death animation
if (Settings::game().mCanLootDuringDeathAnimation)
return std::make_unique<MWWorld::ActionOpen>(ptr);
// otherwise wait until death animation
if (stats.isDeathAnimationFinished())
return std::make_unique<MWWorld::ActionOpen>(ptr);
}
else
{
const bool allowStealingFromKO
= Settings::game().mAlwaysAllowStealingFromKnockedOutActors || !inCombatWithActor;
if (stats.getKnockedDown() && allowStealingFromKO)
return std::make_unique<MWWorld::ActionOpen>(ptr);
const bool allowStealingWhileSneaking = !inCombatWithActor;
if (MWBase::Environment::get().getMechanicsManager()->isSneaking(actor) && allowStealingWhileSneaking)
return std::make_unique<MWWorld::ActionOpen>(ptr);
const bool allowTalking = !inCombatWithActor && !getNpcStats(ptr).isWerewolf();
if (allowTalking)
return std::make_unique<MWWorld::ActionTalk>(ptr);
}
if (inCombatWithActor)
return std::make_unique<MWWorld::FailedAction>("#{sActorInCombat}");
return std::make_unique<MWWorld::FailedAction>();
}
MWWorld::ContainerStore& Npc::getContainerStore(const MWWorld::Ptr& ptr) const
{
return getInventoryStore(ptr);
}
MWWorld::InventoryStore& Npc::getInventoryStore(const MWWorld::Ptr& ptr) const
{
ensureCustomData(ptr);
return ptr.getRefData().getCustomData()->asNpcCustomData().mInventoryStore;
}
ESM::RefId Npc::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
return ref->mBase->mScript;
}
float Npc::getMaxSpeed(const MWWorld::Ptr& ptr) const
{
// TODO: This function is called several times per frame for each NPC.
// It would be better to calculate it only once per frame for each NPC and save the result in CreatureStats.
const MWMechanics::NpcStats& stats = getNpcStats(ptr);
if (stats.isParalyzed() || stats.getKnockedDown() || stats.isDead())
return 0.f;
const MWBase::World* world = MWBase::Environment::get().getWorld();
const GMST& gmst = getGmst();
const MWMechanics::MagicEffects& mageffects = stats.getMagicEffects();
const float normalizedEncumbrance = getNormalizedEncumbrance(ptr);
bool swimming = world->isSwimming(ptr);
bool sneaking = MWBase::Environment::get().getMechanicsManager()->isSneaking(ptr);
bool running = stats.getStance(MWMechanics::CreatureStats::Stance_Run);
bool inair = !world->isOnGround(ptr) && !swimming && !world->isFlying(ptr);
running = running && (inair || MWBase::Environment::get().getMechanicsManager()->isRunning(ptr));
float moveSpeed;
if (getEncumbrance(ptr) > getCapacity(ptr))
moveSpeed = 0.0f;
else if (mageffects.getOrDefault(ESM::MagicEffect::Levitate).getMagnitude() > 0 && world->isLevitationEnabled())
{
float flySpeed = 0.01f
* (stats.getAttribute(ESM::Attribute::Speed).getModified()
+ mageffects.getOrDefault(ESM::MagicEffect::Levitate).getMagnitude());
flySpeed = gmst.fMinFlySpeed->mValue.getFloat()
+ flySpeed * (gmst.fMaxFlySpeed->mValue.getFloat() - gmst.fMinFlySpeed->mValue.getFloat());
flySpeed *= 1.0f - gmst.fEncumberedMoveEffect->mValue.getFloat() * normalizedEncumbrance;
flySpeed = std::max(0.0f, flySpeed);
moveSpeed = flySpeed;
}
else if (swimming)
moveSpeed = getSwimSpeed(ptr);
else if (running && !sneaking)
moveSpeed = getRunSpeed(ptr);
else
moveSpeed = getWalkSpeed(ptr);
if (stats.isWerewolf() && running && stats.getDrawState() == MWMechanics::DrawState::Nothing)
moveSpeed *= gmst.fWereWolfRunMult->mValue.getFloat();
return moveSpeed;
}
float Npc::getJump(const MWWorld::Ptr& ptr) const
{
if (getEncumbrance(ptr) > getCapacity(ptr))
return 0.f;
const MWMechanics::NpcStats& stats = getNpcStats(ptr);
if (stats.isParalyzed() || stats.getKnockedDown() || stats.isDead())
return 0.f;
const GMST& gmst = getGmst();
const MWMechanics::MagicEffects& mageffects = stats.getMagicEffects();
const float encumbranceTerm = gmst.fJumpEncumbranceBase->mValue.getFloat()
+ gmst.fJumpEncumbranceMultiplier->mValue.getFloat() * (1.0f - Npc::getNormalizedEncumbrance(ptr));
float a = getSkill(ptr, ESM::Skill::Acrobatics);
float b = 0.0f;
if (a > 50.0f)
{
b = a - 50.0f;
a = 50.0f;
}
float x = gmst.fJumpAcrobaticsBase->mValue.getFloat()
+ std::pow(a / 15.0f, gmst.fJumpAcroMultiplier->mValue.getFloat());
x += 3.0f * b * gmst.fJumpAcroMultiplier->mValue.getFloat();
x += mageffects.getOrDefault(ESM::MagicEffect::Jump).getMagnitude() * 64;
x *= encumbranceTerm;
if (stats.getStance(MWMechanics::CreatureStats::Stance_Run))
x *= gmst.fJumpRunMultiplier->mValue.getFloat();
x *= stats.getFatigueTerm();
x -= -Constants::GravityConst * Constants::UnitsPerMeter;
x /= 3.0f;
return x;
}
MWMechanics::Movement& Npc::getMovementSettings(const MWWorld::Ptr& ptr) const
{
ensureCustomData(ptr);
return ptr.getRefData().getCustomData()->asNpcCustomData().mMovement;
}
bool Npc::isEssential(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
return (ref->mBase->mFlags & ESM::NPC::Essential) != 0;
}
bool Npc::hasToolTip(const MWWorld::ConstPtr& ptr) const
{
if (!ptr.getRefData().getCustomData() || MWBase::Environment::get().getWindowManager()->isGuiMode())
return true;
const NpcCustomData& customData = ptr.getRefData().getCustomData()->asNpcCustomData();
if (customData.mNpcStats.isDead() && customData.mNpcStats.isDeathAnimationFinished())
return true;
const MWMechanics::AiSequence& aiSeq = customData.mNpcStats.getAiSequence();
if (!aiSeq.isInCombat() || aiSeq.isFleeing())
return true;
if (Settings::game().mAlwaysAllowStealingFromKnockedOutActors && customData.mNpcStats.getKnockedDown())
return true;
return false;
}
MWGui::ToolTipInfo Npc::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
bool fullHelp = MWBase::Environment::get().getWindowManager()->getFullHelp();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name));
if (fullHelp && !ref->mBase->mName.empty() && ptr.getRefData().getCustomData()
&& ptr.getRefData().getCustomData()->asNpcCustomData().mNpcStats.isWerewolf())
{
info.caption += " (";
info.caption += MyGUI::TextIterator::toTagsString(ref->mBase->mName);
info.caption += ")";
}
if (fullHelp)
info.extra = MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
return info;
}
float Npc::getCapacity(const MWWorld::Ptr& ptr) const
{
const MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
static const float fEncumbranceStrMult = MWBase::Environment::get()
.getESMStore()
->get<ESM::GameSetting>()
.find("fEncumbranceStrMult")
->mValue.getFloat();
return stats.getAttribute(ESM::Attribute::Strength).getModified() * fEncumbranceStrMult;
}
float Npc::getEncumbrance(const MWWorld::Ptr& ptr) const
{
// According to UESP, inventory weight is ignored in werewolf form. Does that include
// feather and burden effects?
return getNpcStats(ptr).isWerewolf() ? 0.0f : Actor::getEncumbrance(ptr);
}
void Npc::skillUsageSucceeded(const MWWorld::Ptr& ptr, ESM::RefId skill, int usageType, float extraFactor) const
{
MWBase::Environment::get().getLuaManager()->skillUse(ptr, skill, usageType, extraFactor);
}
float Npc::getArmorRating(const MWWorld::Ptr& ptr) const
{
const MWWorld::Store<ESM::GameSetting>& store
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
MWMechanics::NpcStats& stats = getNpcStats(ptr);
const MWWorld::InventoryStore& invStore = getInventoryStore(ptr);
float fUnarmoredBase1 = store.find("fUnarmoredBase1")->mValue.getFloat();
float fUnarmoredBase2 = store.find("fUnarmoredBase2")->mValue.getFloat();
float unarmoredSkill = getSkill(ptr, ESM::Skill::Unarmored);
float ratings[MWWorld::InventoryStore::Slots];
for (int i = 0; i < MWWorld::InventoryStore::Slots; i++)
{
MWWorld::ConstContainerStoreIterator it = invStore.getSlot(i);
if (it == invStore.end() || it->getType() != ESM::Armor::sRecordId)
{
// unarmored
ratings[i] = (fUnarmoredBase1 * unarmoredSkill) * (fUnarmoredBase2 * unarmoredSkill);
}
else
{
ratings[i] = it->getClass().getEffectiveArmorRating(*it, ptr);
// Take in account armor condition
const bool hasHealth = it->getClass().hasItemHealth(*it);
if (hasHealth)
{
ratings[i] *= it->getClass().getItemNormalizedHealth(*it);
}
}
}
float shield = stats.getMagicEffects().getOrDefault(ESM::MagicEffect::Shield).getMagnitude();
return ratings[MWWorld::InventoryStore::Slot_Cuirass] * 0.3f
+ (ratings[MWWorld::InventoryStore::Slot_CarriedLeft] + ratings[MWWorld::InventoryStore::Slot_Helmet]
+ ratings[MWWorld::InventoryStore::Slot_Greaves] + ratings[MWWorld::InventoryStore::Slot_Boots]
+ ratings[MWWorld::InventoryStore::Slot_LeftPauldron]
+ ratings[MWWorld::InventoryStore::Slot_RightPauldron])
* 0.1f
+ (ratings[MWWorld::InventoryStore::Slot_LeftGauntlet]
+ ratings[MWWorld::InventoryStore::Slot_RightGauntlet])
* 0.05f
+ shield;
}
void Npc::adjustScale(const MWWorld::ConstPtr& ptr, osg::Vec3f& scale, bool rendering) const
{
if (!rendering)
return; // collision meshes are not scaled based on race height
// having the same collision extents for all races makes the environments easier to test
const MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(ref->mBase->mRace);
// Race weight should not affect 1st-person meshes, otherwise it will change hand proportions and can break
// aiming.
if (ptr == MWMechanics::getPlayer() && ptr.isInCell() && MWBase::Environment::get().getWorld()->isFirstPerson())
{
if (ref->mBase->isMale())
scale *= race->mData.mMaleHeight;
else
scale *= race->mData.mFemaleHeight;
return;
}
if (ref->mBase->isMale())
{
scale.x() *= race->mData.mMaleWeight;
scale.y() *= race->mData.mMaleWeight;
scale.z() *= race->mData.mMaleHeight;
}
else
{
scale.x() *= race->mData.mFemaleWeight;
scale.y() *= race->mData.mFemaleWeight;
scale.z() *= race->mData.mFemaleHeight;
}
}
int Npc::getServices(const MWWorld::ConstPtr& actor) const
{
const ESM::NPC* npc = actor.get<ESM::NPC>()->mBase;
if (npc->mFlags & ESM::NPC::Autocalc)
{
const ESM::Class* class_ = MWBase::Environment::get().getESMStore()->get<ESM::Class>().find(npc->mClass);
return class_->mData.mServices;
}
return npc->mAiData.mServices;
}
ESM::RefId Npc::getSoundIdFromSndGen(const MWWorld::Ptr& ptr, std::string_view name) const
{
if (name == "left" || name == "right")
{
MWBase::World* world = MWBase::Environment::get().getWorld();
if (world->isFlying(ptr))
return ESM::RefId();
osg::Vec3f pos(ptr.getRefData().getPosition().asVec3());
if (world->isSwimming(ptr))
return (name == "left") ? npcParts.mSwimLeft : npcParts.mSwimRight;
if (world->isUnderwater(ptr.getCell(), pos) || world->isWalkingOnWater(ptr))
return (name == "left") ? npcParts.mFootWaterLeft : npcParts.mFootWaterRight;
if (world->isOnGround(ptr))
{
if (getNpcStats(ptr).isWerewolf()
&& getCreatureStats(ptr).getStance(MWMechanics::CreatureStats::Stance_Run))
{
int weaponType = ESM::Weapon::None;
MWMechanics::getActiveWeapon(ptr, &weaponType);
if (weaponType == ESM::Weapon::None)
return ESM::RefId();
}
const MWWorld::InventoryStore& inv = Npc::getInventoryStore(ptr);
MWWorld::ConstContainerStoreIterator boots = inv.getSlot(MWWorld::InventoryStore::Slot_Boots);
if (boots == inv.end() || boots->getType() != ESM::Armor::sRecordId)
return (name == "left") ? npcParts.mFootBareLeft : npcParts.mFootBareRight;
ESM::RefId skill = boots->getClass().getEquipmentSkill(*boots);
if (skill == ESM::Skill::LightArmor)
return (name == "left") ? npcParts.mFootLightLeft : npcParts.mFootLightRight;
else if (skill == ESM::Skill::MediumArmor)
return (name == "left") ? npcParts.mFootMediumLeft : npcParts.mFootMediumRight;
else if (skill == ESM::Skill::HeavyArmor)
return (name == "left") ? npcParts.mFootHeavyLeft : npcParts.mFootHeavyRight;
}
return ESM::RefId();
}
// Morrowind ignores land soundgen for NPCs
if (name == "land")
return ESM::RefId();
if (name == "swimleft")
return npcParts.mSwimLeft;
if (name == "swimright")
return npcParts.mSwimRight;
// TODO: I have no idea what these are supposed to do for NPCs since they use
// voiced dialog for various conditions like health loss and combat taunts. Maybe
// only for biped creatures?
if (name == "moan")
return ESM::RefId();
if (name == "roar")
return ESM::RefId();
if (name == "scream")
return ESM::RefId();
throw std::runtime_error("Unexpected soundgen type: " + std::string(name));
}
MWWorld::Ptr Npc::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
MWWorld::Ptr newPtr(cell.insert(ref), &cell);
if (newPtr.getRefData().getCustomData())
{
MWBase::Environment::get().getWorldModel()->registerPtr(newPtr);
newPtr.getClass().getContainerStore(newPtr).setPtr(newPtr);
}
return newPtr;
}
float Npc::getSkill(const MWWorld::Ptr& ptr, ESM::RefId id) const
{
return getNpcStats(ptr).getSkill(id).getModified();
}
int Npc::getBloodTexture(const MWWorld::ConstPtr& ptr) const
{
return ptr.get<ESM::NPC>()->mBase->mBloodType;
}
void Npc::readAdditionalState(const MWWorld::Ptr& ptr, const ESM::ObjectState& state) const
{
if (!state.mHasCustomState)
return;
const ESM::NpcState& npcState = state.asNpcState();
if (!ptr.getRefData().getCustomData())
{
if (npcState.mCreatureStats.mMissingACDT)
ensureCustomData(ptr);
else
{
// Create a CustomData, but don't fill it from ESM records (not needed)
auto data = std::make_unique<NpcCustomData>();
MWBase::Environment::get().getWorldModel()->registerPtr(ptr);
data->mInventoryStore.setPtr(ptr);
ptr.getRefData().setCustomData(std::move(data));
}
}
NpcCustomData& customData = ptr.getRefData().getCustomData()->asNpcCustomData();
customData.mInventoryStore.readState(npcState.mInventory);
customData.mNpcStats.readState(npcState.mNpcStats);
bool spellsInitialised = customData.mNpcStats.getSpells().setSpells(ptr.get<ESM::NPC>()->mBase->mId);
if (spellsInitialised)
customData.mNpcStats.getSpells().clear();
customData.mNpcStats.readState(npcState.mCreatureStats);
}
void Npc::writeAdditionalState(const MWWorld::ConstPtr& ptr, ESM::ObjectState& state) const
{
if (!ptr.getRefData().getCustomData())
{
state.mHasCustomState = false;
return;
}
const NpcCustomData& customData = ptr.getRefData().getCustomData()->asNpcCustomData();
if (ptr.getCellRef().getCount() <= 0
&& (!(ptr.get<ESM::NPC>()->mBase->mFlags & ESM::NPC::Respawn) || !customData.mNpcStats.isDead()))
{
state.mHasCustomState = false;
return;
}
ESM::NpcState& npcState = state.asNpcState();
customData.mInventoryStore.writeState(npcState.mInventory);
customData.mNpcStats.writeState(npcState.mNpcStats);
customData.mNpcStats.writeState(npcState.mCreatureStats);
}
int Npc::getBaseGold(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
return ref->mBase->mNpdt.mGold;
}
bool Npc::isClass(const MWWorld::ConstPtr& ptr, std::string_view className) const
{
return ptr.get<ESM::NPC>()->mBase->mClass == className;
}
bool Npc::canSwim(const MWWorld::ConstPtr& ptr) const
{
return true;
}
bool Npc::canWalk(const MWWorld::ConstPtr& ptr) const
{
return true;
}
void Npc::respawn(const MWWorld::Ptr& ptr) const
{
const MWMechanics::CreatureStats& creatureStats = getCreatureStats(ptr);
if (ptr.getCellRef().getCount() > 0 && !creatureStats.isDead())
return;
if (!creatureStats.isDeathAnimationFinished())
return;
const MWWorld::Store<ESM::GameSetting>& gmst
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
static const float fCorpseRespawnDelay = gmst.find("fCorpseRespawnDelay")->mValue.getFloat();
static const float fCorpseClearDelay = gmst.find("fCorpseClearDelay")->mValue.getFloat();
float delay
= ptr.getCellRef().getCount() == 0 ? fCorpseClearDelay : std::min(fCorpseRespawnDelay, fCorpseClearDelay);
if (ptr.get<ESM::NPC>()->mBase->mFlags & ESM::NPC::Respawn
&& creatureStats.getTimeOfDeath() + delay <= MWBase::Environment::get().getWorld()->getTimeStamp())
{
if (ptr.getCellRef().hasContentFile())
{
if (ptr.getCellRef().getCount() == 0)
{
ptr.getCellRef().setCount(1);
const ESM::RefId& script = getScript(ptr);
if (!script.empty())
MWBase::Environment::get().getWorld()->getLocalScripts().add(script, ptr);
}
MWBase::Environment::get().getWorld()->removeContainerScripts(ptr);
MWBase::Environment::get().getWindowManager()->onDeleteCustomData(ptr);
ptr.getRefData().setCustomData(nullptr);
// Reset to original position
MWBase::Environment::get().getWorld()->moveObject(ptr, ptr.getCellRef().getPosition().asVec3());
MWBase::Environment::get().getWorld()->rotateObject(
ptr, ptr.getCellRef().getPosition().asRotationVec3(), MWBase::RotationFlag_none);
}
}
}
int Npc::getBaseFightRating(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
return ref->mBase->mAiData.mFight;
}
bool Npc::isBipedal(const MWWorld::ConstPtr& ptr) const
{
return true;
}
ESM::RefId Npc::getPrimaryFaction(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
return ref->mBase->mFaction;
}
int Npc::getPrimaryFactionRank(const MWWorld::ConstPtr& ptr) const
{
const ESM::RefId& factionID = ptr.getClass().getPrimaryFaction(ptr);
if (factionID.empty())
return -1;
// Search in the NPC data first
if (const MWWorld::CustomData* data = ptr.getRefData().getCustomData())
{
int rank = data->asNpcCustomData().mNpcStats.getFactionRank(factionID);
if (rank >= 0)
return rank;
}
// Use base NPC record as a fallback
const MWWorld::LiveCellRef<ESM::NPC>* ref = ptr.get<ESM::NPC>();
return ref->mBase->getFactionRank();
}
void Npc::setBaseAISetting(const ESM::RefId& id, MWMechanics::AiSetting setting, int value) const
{
MWMechanics::setBaseAISetting<ESM::NPC>(id, setting, value);
}
void Npc::modifyBaseInventory(const ESM::RefId& actorId, const ESM::RefId& itemId, int amount) const
{
MWMechanics::modifyBaseInventory<ESM::NPC>(actorId, itemId, amount);
}
float Npc::getWalkSpeed(const MWWorld::Ptr& ptr) const
{
const GMST& gmst = getGmst();
const MWMechanics::NpcStats& stats = getNpcStats(ptr);
const float normalizedEncumbrance = getNormalizedEncumbrance(ptr);
const bool sneaking = MWBase::Environment::get().getMechanicsManager()->isSneaking(ptr);
float walkSpeed = gmst.fMinWalkSpeed->mValue.getFloat()
+ 0.01f * stats.getAttribute(ESM::Attribute::Speed).getModified()
* (gmst.fMaxWalkSpeed->mValue.getFloat() - gmst.fMinWalkSpeed->mValue.getFloat());
walkSpeed *= 1.0f - gmst.fEncumberedMoveEffect->mValue.getFloat() * normalizedEncumbrance;
walkSpeed = std::max(0.0f, walkSpeed);
if (sneaking)
walkSpeed *= gmst.fSneakSpeedMultiplier->mValue.getFloat();
return walkSpeed;
}
float Npc::getRunSpeed(const MWWorld::Ptr& ptr) const
{
const GMST& gmst = getGmst();
return getWalkSpeed(ptr)
* (0.01f * getSkill(ptr, ESM::Skill::Athletics) * gmst.fAthleticsRunBonus->mValue.getFloat()
+ gmst.fBaseRunMultiplier->mValue.getFloat());
}
float Npc::getSwimSpeed(const MWWorld::Ptr& ptr) const
{
const MWBase::World* world = MWBase::Environment::get().getWorld();
const MWMechanics::NpcStats& stats = getNpcStats(ptr);
const MWMechanics::MagicEffects& mageffects = stats.getMagicEffects();
const bool swimming = world->isSwimming(ptr);
const bool inair = !world->isOnGround(ptr) && !swimming && !world->isFlying(ptr);
const bool running = stats.getStance(MWMechanics::CreatureStats::Stance_Run)
&& (inair || MWBase::Environment::get().getMechanicsManager()->isRunning(ptr));
return getSwimSpeedImpl(ptr, getGmst(), mageffects, running ? getRunSpeed(ptr) : getWalkSpeed(ptr));
}
}
| 65,307
|
C++
|
.cpp
| 1,278
| 39.104851
| 120
| 0.597529
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,442
|
creature.cpp
|
OpenMW_openmw/apps/openmw/mwclass/creature.cpp
|
#include "creature.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/creaturestate.hpp>
#include <components/esm3/loadclas.hpp>
#include <components/esm3/loadcrea.hpp>
#include <components/esm3/loadsndg.hpp>
#include <components/esm3/loadsoun.hpp>
#include <components/misc/rng.hpp>
#include <components/settings/values.hpp>
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/aisetting.hpp"
#include "../mwmechanics/combat.hpp"
#include "../mwmechanics/creaturecustomdataresetter.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/difficultyscaling.hpp"
#include "../mwmechanics/disease.hpp"
#include "../mwmechanics/inventory.hpp"
#include "../mwmechanics/magiceffects.hpp"
#include "../mwmechanics/movement.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "../mwmechanics/setbaseaisetting.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/actionopen.hpp"
#include "../mwworld/actiontalk.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/customdata.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/failedaction.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/localscripts.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwworld/worldmodel.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwgui/tooltips.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace
{
bool isFlagBitSet(const MWWorld::ConstPtr& ptr, ESM::Creature::Flags bitMask)
{
return (ptr.get<ESM::Creature>()->mBase->mFlags & bitMask) != 0;
}
}
namespace MWClass
{
class CreatureCustomData : public MWWorld::TypedCustomData<CreatureCustomData>
{
public:
MWMechanics::CreatureStats mCreatureStats;
std::unique_ptr<MWWorld::ContainerStore> mContainerStore; // may be InventoryStore for some creatures
MWMechanics::Movement mMovement;
CreatureCustomData() = default;
CreatureCustomData(const CreatureCustomData& other);
CreatureCustomData(CreatureCustomData&& other) = default;
CreatureCustomData& asCreatureCustomData() override { return *this; }
const CreatureCustomData& asCreatureCustomData() const override { return *this; }
};
CreatureCustomData::CreatureCustomData(const CreatureCustomData& other)
: mCreatureStats(other.mCreatureStats)
, mContainerStore(other.mContainerStore->clone())
, mMovement(other.mMovement)
{
}
Creature::Creature()
: MWWorld::RegisteredClass<Creature, Actor>(ESM::Creature::sRecordId)
{
}
const Creature::GMST& Creature::getGmst()
{
static const GMST staticGmst = [] {
GMST gmst;
const MWWorld::Store<ESM::GameSetting>& store
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
gmst.fMinWalkSpeedCreature = store.find("fMinWalkSpeedCreature");
gmst.fMaxWalkSpeedCreature = store.find("fMaxWalkSpeedCreature");
gmst.fEncumberedMoveEffect = store.find("fEncumberedMoveEffect");
gmst.fSneakSpeedMultiplier = store.find("fSneakSpeedMultiplier");
gmst.fAthleticsRunBonus = store.find("fAthleticsRunBonus");
gmst.fBaseRunMultiplier = store.find("fBaseRunMultiplier");
gmst.fMinFlySpeed = store.find("fMinFlySpeed");
gmst.fMaxFlySpeed = store.find("fMaxFlySpeed");
gmst.fSwimRunBase = store.find("fSwimRunBase");
gmst.fSwimRunAthleticsMult = store.find("fSwimRunAthleticsMult");
gmst.fKnockDownMult = store.find("fKnockDownMult");
gmst.iKnockDownOddsMult = store.find("iKnockDownOddsMult");
gmst.iKnockDownOddsBase = store.find("iKnockDownOddsBase");
return gmst;
}();
return staticGmst;
}
void Creature::ensureCustomData(const MWWorld::Ptr& ptr) const
{
if (!ptr.getRefData().getCustomData())
{
MWBase::Environment::get().getWorldModel()->registerPtr(ptr);
auto tempData = std::make_unique<CreatureCustomData>();
CreatureCustomData* data = tempData.get();
MWMechanics::CreatureCustomDataResetter resetter{ ptr };
ptr.getRefData().setCustomData(std::move(tempData));
MWWorld::LiveCellRef<ESM::Creature>* ref = ptr.get<ESM::Creature>();
// creature stats
for (size_t i = 0; i < ref->mBase->mData.mAttributes.size(); ++i)
data->mCreatureStats.setAttribute(ESM::Attribute::indexToRefId(i), ref->mBase->mData.mAttributes[i]);
data->mCreatureStats.setHealth(static_cast<float>(ref->mBase->mData.mHealth));
data->mCreatureStats.setMagicka(static_cast<float>(ref->mBase->mData.mMana));
data->mCreatureStats.setFatigue(static_cast<float>(ref->mBase->mData.mFatigue));
data->mCreatureStats.setLevel(ref->mBase->mData.mLevel);
data->mCreatureStats.getAiSequence().fill(ref->mBase->mAiPackage);
data->mCreatureStats.setAiSetting(MWMechanics::AiSetting::Hello, ref->mBase->mAiData.mHello);
data->mCreatureStats.setAiSetting(MWMechanics::AiSetting::Fight, ref->mBase->mAiData.mFight);
data->mCreatureStats.setAiSetting(MWMechanics::AiSetting::Flee, ref->mBase->mAiData.mFlee);
data->mCreatureStats.setAiSetting(MWMechanics::AiSetting::Alarm, ref->mBase->mAiData.mAlarm);
// Persistent actors with 0 health do not play death animation
if (data->mCreatureStats.isDead())
data->mCreatureStats.setDeathAnimationFinished(isPersistent(ptr));
// spells
bool spellsInitialised = data->mCreatureStats.getSpells().setSpells(ref->mBase->mId);
if (!spellsInitialised)
data->mCreatureStats.getSpells().addAllToInstance(ref->mBase->mSpells.mList);
// inventory
bool hasInventory = hasInventoryStore(ptr);
if (hasInventory)
data->mContainerStore = std::make_unique<MWWorld::InventoryStore>();
else
data->mContainerStore = std::make_unique<MWWorld::ContainerStore>();
data->mContainerStore->setPtr(ptr);
data->mCreatureStats.setGoldPool(ref->mBase->mData.mGold);
resetter.mPtr = {};
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
getContainerStore(ptr).fill(ref->mBase->mInventory, ptr.getCellRef().getRefId(), prng);
if (hasInventory)
getInventoryStore(ptr).autoEquip();
}
}
void Creature::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
MWRender::Objects& objects = renderingInterface.getObjects();
objects.insertCreature(ptr, model, hasInventoryStore(ptr));
}
std::string_view Creature::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Creature>(ptr);
}
void Creature::getModelsToPreload(const MWWorld::ConstPtr& ptr, std::vector<std::string_view>& models) const
{
std::string_view model = getModel(ptr);
if (!model.empty())
models.push_back(model);
const MWWorld::CustomData* customData = ptr.getRefData().getCustomData();
if (customData && hasInventoryStore(ptr))
{
const auto& invStore
= static_cast<const MWWorld::InventoryStore&>(*customData->asCreatureCustomData().mContainerStore);
for (int slot = 0; slot < MWWorld::InventoryStore::Slots; ++slot)
{
MWWorld::ConstContainerStoreIterator equipped = invStore.getSlot(slot);
if (equipped != invStore.end())
{
model = equipped->getClass().getModel(*equipped);
if (!model.empty())
models.push_back(model);
}
}
}
}
std::string_view Creature::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Creature>(ptr);
}
MWMechanics::CreatureStats& Creature::getCreatureStats(const MWWorld::Ptr& ptr) const
{
ensureCustomData(ptr);
return ptr.getRefData().getCustomData()->asCreatureCustomData().mCreatureStats;
}
bool Creature::evaluateHit(const MWWorld::Ptr& ptr, MWWorld::Ptr& victim, osg::Vec3f& hitPosition) const
{
victim = MWWorld::Ptr();
hitPosition = osg::Vec3f();
// Get the weapon used (if hand-to-hand, weapon = inv.end())
MWWorld::Ptr weapon;
if (hasInventoryStore(ptr))
{
MWWorld::InventoryStore& inv = getInventoryStore(ptr);
MWWorld::ContainerStoreIterator weaponslot = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight);
if (weaponslot != inv.end() && weaponslot->getType() == ESM::Weapon::sRecordId)
weapon = *weaponslot;
}
MWBase::World* world = MWBase::Environment::get().getWorld();
const MWWorld::Store<ESM::GameSetting>& store = world->getStore().get<ESM::GameSetting>();
float dist = store.find("fCombatDistance")->mValue.getFloat();
if (!weapon.isEmpty())
dist *= weapon.get<ESM::Weapon>()->mBase->mData.mReach;
const std::pair<MWWorld::Ptr, osg::Vec3f> result = MWMechanics::getHitContact(ptr, dist);
if (result.first.isEmpty()) // Didn't hit anything
return true;
// Note that earlier we returned true in spite of an apparent failure to hit anything alive.
// This is because hitting nothing is not a "miss" and should be handled as such character controller-side.
victim = result.first;
hitPosition = result.second;
float hitchance = MWMechanics::getHitChance(ptr, victim, ptr.get<ESM::Creature>()->mBase->mData.mCombat);
return Misc::Rng::roll0to99(world->getPrng()) < hitchance;
}
void Creature::hit(const MWWorld::Ptr& ptr, float attackStrength, int type, const MWWorld::Ptr& victim,
const osg::Vec3f& hitPosition, bool success) const
{
MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
if (stats.getDrawState() != MWMechanics::DrawState::Weapon)
return;
MWWorld::Ptr weapon;
if (hasInventoryStore(ptr))
{
MWWorld::InventoryStore& inv = getInventoryStore(ptr);
MWWorld::ContainerStoreIterator weaponslot = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight);
if (weaponslot != inv.end() && weaponslot->getType() == ESM::Weapon::sRecordId)
weapon = *weaponslot;
}
MWMechanics::applyFatigueLoss(ptr, weapon, attackStrength);
if (victim.isEmpty())
return; // Didn't hit anything
const MWWorld::Class& othercls = victim.getClass();
MWMechanics::CreatureStats& otherstats = othercls.getCreatureStats(victim);
if (otherstats.isDead()) // Can't hit dead actors
return;
if (!success)
{
victim.getClass().onHit(
victim, 0.0f, false, MWWorld::Ptr(), ptr, osg::Vec3f(), false, MWMechanics::DamageSourceType::Melee);
MWMechanics::reduceWeaponCondition(0.f, false, weapon, ptr);
return;
}
MWWorld::LiveCellRef<ESM::Creature>* ref = ptr.get<ESM::Creature>();
int min, max;
switch (type)
{
case 0:
min = ref->mBase->mData.mAttack[0];
max = ref->mBase->mData.mAttack[1];
break;
case 1:
min = ref->mBase->mData.mAttack[2];
max = ref->mBase->mData.mAttack[3];
break;
case 2:
default:
min = ref->mBase->mData.mAttack[4];
max = ref->mBase->mData.mAttack[5];
break;
}
float damage = min + (max - min) * attackStrength;
bool healthdmg = true;
if (!weapon.isEmpty())
{
const unsigned char* attack = nullptr;
if (type == ESM::Weapon::AT_Chop)
attack = weapon.get<ESM::Weapon>()->mBase->mData.mChop.data();
else if (type == ESM::Weapon::AT_Slash)
attack = weapon.get<ESM::Weapon>()->mBase->mData.mSlash.data();
else if (type == ESM::Weapon::AT_Thrust)
attack = weapon.get<ESM::Weapon>()->mBase->mData.mThrust.data();
if (attack)
{
damage = attack[0] + ((attack[1] - attack[0]) * attackStrength);
MWMechanics::adjustWeaponDamage(damage, weapon, ptr);
MWMechanics::reduceWeaponCondition(damage, true, weapon, ptr);
MWMechanics::resistNormalWeapon(victim, ptr, weapon, damage);
}
// Apply "On hit" enchanted weapons
MWMechanics::applyOnStrikeEnchantment(ptr, victim, weapon, hitPosition);
}
else if (isBipedal(ptr))
{
MWMechanics::getHandToHandDamage(ptr, victim, damage, healthdmg, attackStrength);
}
MWMechanics::applyElementalShields(ptr, victim);
if (MWMechanics::blockMeleeAttack(ptr, victim, weapon, damage, attackStrength))
damage = 0;
MWMechanics::diseaseContact(victim, ptr);
victim.getClass().onHit(
victim, damage, healthdmg, weapon, ptr, hitPosition, true, MWMechanics::DamageSourceType::Melee);
}
void Creature::onHit(const MWWorld::Ptr& ptr, float damage, bool ishealth, const MWWorld::Ptr& object,
const MWWorld::Ptr& attacker, const osg::Vec3f& hitPosition, bool successful,
const MWMechanics::DamageSourceType sourceType) const
{
MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
// Self defense
bool setOnPcHitMe = true;
// NOTE: 'object' and/or 'attacker' may be empty.
if (!attacker.isEmpty() && attacker.getClass().isActor() && !stats.getAiSequence().isInCombat(attacker))
{
stats.setAttacked(true);
// No retaliation for totally static creatures (they have no movement or attacks anyway)
if (isMobile(ptr))
{
bool complain = sourceType == MWMechanics::DamageSourceType::Melee;
bool supportFriendlyFire = sourceType != MWMechanics::DamageSourceType::Ranged;
if (supportFriendlyFire && MWMechanics::friendlyHit(attacker, ptr, complain))
setOnPcHitMe = false;
else
setOnPcHitMe = MWBase::Environment::get().getMechanicsManager()->actorAttacked(ptr, attacker);
}
}
// Attacker and target store each other as hitattemptactor if they have no one stored yet
if (!attacker.isEmpty() && attacker.getClass().isActor())
{
MWMechanics::CreatureStats& statsAttacker = attacker.getClass().getCreatureStats(attacker);
// First handle the attacked actor
if ((stats.getHitAttemptActorId() == -1)
&& (statsAttacker.getAiSequence().isInCombat(ptr) || attacker == MWMechanics::getPlayer()))
stats.setHitAttemptActorId(statsAttacker.getActorId());
// Next handle the attacking actor
if ((statsAttacker.getHitAttemptActorId() == -1)
&& (statsAttacker.getAiSequence().isInCombat(ptr) || attacker == MWMechanics::getPlayer()))
statsAttacker.setHitAttemptActorId(stats.getActorId());
}
if (!object.isEmpty())
stats.setLastHitAttemptObject(object.getCellRef().getRefId());
if (setOnPcHitMe && !attacker.isEmpty() && attacker == MWMechanics::getPlayer())
{
const ESM::RefId& script = ptr.get<ESM::Creature>()->mBase->mScript;
/* Set the OnPCHitMe script variable. The script is responsible for clearing it. */
if (!script.empty())
ptr.getRefData().getLocals().setVarByInt(script, "onpchitme", 1);
}
if (!successful)
{
// Missed
if (!attacker.isEmpty() && attacker == MWMechanics::getPlayer())
MWBase::Environment::get().getSoundManager()->playSound3D(
ptr, ESM::RefId::stringRefId("miss"), 1.0f, 1.0f);
return;
}
if (!object.isEmpty())
stats.setLastHitObject(object.getCellRef().getRefId());
if (damage < 0.001f)
damage = 0;
if (damage > 0.f)
{
if (!attacker.isEmpty())
{
// Check for knockdown
float agilityTerm = stats.getAttribute(ESM::Attribute::Agility).getModified()
* getGmst().fKnockDownMult->mValue.getFloat();
float knockdownTerm = stats.getAttribute(ESM::Attribute::Agility).getModified()
* getGmst().iKnockDownOddsMult->mValue.getInteger() * 0.01f
+ getGmst().iKnockDownOddsBase->mValue.getInteger();
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
if (ishealth && agilityTerm <= damage && knockdownTerm <= Misc::Rng::roll0to99(prng))
stats.setKnockedDown(true);
else
stats.setHitRecovery(true); // Is this supposed to always occur?
}
if (ishealth)
{
damage *= damage / (damage + getArmorRating(ptr));
damage = std::max(1.f, damage);
if (!attacker.isEmpty())
{
damage = scaleDamage(damage, attacker, ptr);
MWBase::Environment::get().getWorld()->spawnBloodEffect(ptr, hitPosition);
}
MWBase::Environment::get().getSoundManager()->playSound3D(
ptr, ESM::RefId::stringRefId("Health Damage"), 1.0f, 1.0f);
MWMechanics::DynamicStat<float> health(stats.getHealth());
health.setCurrent(health.getCurrent() - damage);
stats.setHealth(health);
}
else
{
MWMechanics::DynamicStat<float> fatigue(stats.getFatigue());
fatigue.setCurrent(fatigue.getCurrent() - damage, true);
stats.setFatigue(fatigue);
}
}
}
std::unique_ptr<MWWorld::Action> Creature::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
if (actor.getClass().isNpc() && actor.getClass().getNpcStats(actor).isWerewolf())
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
const ESM::Sound* sound = store.get<ESM::Sound>().searchRandom("WolfCreature", prng);
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::FailedAction>("#{sWerewolfRefusal}");
if (sound)
action->setSound(sound->mId);
return action;
}
const MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
if (stats.isDead())
{
// by default user can loot non-fighting actors during death animation
if (Settings::game().mCanLootDuringDeathAnimation)
return std::make_unique<MWWorld::ActionOpen>(ptr);
// otherwise wait until death animation
if (stats.isDeathAnimationFinished())
return std::make_unique<MWWorld::ActionOpen>(ptr);
}
else if (!stats.getKnockedDown())
return std::make_unique<MWWorld::ActionTalk>(ptr);
// Tribunal and some mod companions oddly enough must use open action as fallback
if (!getScript(ptr).empty() && ptr.getRefData().getLocals().getIntVar(getScript(ptr), "companion"))
return std::make_unique<MWWorld::ActionOpen>(ptr);
return std::make_unique<MWWorld::FailedAction>();
}
MWWorld::ContainerStore& Creature::getContainerStore(const MWWorld::Ptr& ptr) const
{
ensureCustomData(ptr);
return *ptr.getRefData().getCustomData()->asCreatureCustomData().mContainerStore;
}
MWWorld::InventoryStore& Creature::getInventoryStore(const MWWorld::Ptr& ptr) const
{
if (hasInventoryStore(ptr))
return static_cast<MWWorld::InventoryStore&>(getContainerStore(ptr));
else
throw std::runtime_error("this creature has no inventory store");
}
bool Creature::hasInventoryStore(const MWWorld::ConstPtr& ptr) const
{
return isFlagBitSet(ptr, ESM::Creature::Weapon);
}
ESM::RefId Creature::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Creature>* ref = ptr.get<ESM::Creature>();
return ref->mBase->mScript;
}
bool Creature::isEssential(const MWWorld::ConstPtr& ptr) const
{
return isFlagBitSet(ptr, ESM::Creature::Essential);
}
float Creature::getMaxSpeed(const MWWorld::Ptr& ptr) const
{
const MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
if (stats.isParalyzed() || stats.getKnockedDown() || stats.isDead())
return 0.f;
const GMST& gmst = getGmst();
const MWBase::World* world = MWBase::Environment::get().getWorld();
const MWMechanics::MagicEffects& mageffects = stats.getMagicEffects();
float moveSpeed;
if (getEncumbrance(ptr) > getCapacity(ptr))
moveSpeed = 0.0f;
else if (canFly(ptr)
|| (mageffects.getOrDefault(ESM::MagicEffect::Levitate).getMagnitude() > 0 && world->isLevitationEnabled()))
{
float flySpeed = 0.01f
* (stats.getAttribute(ESM::Attribute::Speed).getModified()
+ mageffects.getOrDefault(ESM::MagicEffect::Levitate).getMagnitude());
flySpeed = gmst.fMinFlySpeed->mValue.getFloat()
+ flySpeed * (gmst.fMaxFlySpeed->mValue.getFloat() - gmst.fMinFlySpeed->mValue.getFloat());
const float normalizedEncumbrance = getNormalizedEncumbrance(ptr);
flySpeed *= 1.0f - gmst.fEncumberedMoveEffect->mValue.getFloat() * normalizedEncumbrance;
flySpeed = std::max(0.0f, flySpeed);
moveSpeed = flySpeed;
}
else if (world->isSwimming(ptr))
moveSpeed = getSwimSpeed(ptr);
else
moveSpeed = getWalkSpeed(ptr);
return moveSpeed;
}
MWMechanics::Movement& Creature::getMovementSettings(const MWWorld::Ptr& ptr) const
{
ensureCustomData(ptr);
return ptr.getRefData().getCustomData()->asCreatureCustomData().mMovement;
}
bool Creature::hasToolTip(const MWWorld::ConstPtr& ptr) const
{
if (!ptr.getRefData().getCustomData() || MWBase::Environment::get().getWindowManager()->isGuiMode())
return true;
const CreatureCustomData& customData = ptr.getRefData().getCustomData()->asCreatureCustomData();
if (customData.mCreatureStats.isDead() && customData.mCreatureStats.isDeathAnimationFinished())
return true;
const MWMechanics::AiSequence& aiSeq = customData.mCreatureStats.getAiSequence();
return !aiSeq.isInCombat() || aiSeq.isFleeing();
}
MWGui::ToolTipInfo Creature::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Creature>* ref = ptr.get<ESM::Creature>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name));
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
return info;
}
float Creature::getArmorRating(const MWWorld::Ptr& ptr) const
{
// Equipment armor rating is deliberately ignored.
return getCreatureStats(ptr).getMagicEffects().getOrDefault(ESM::MagicEffect::Shield).getMagnitude();
}
float Creature::getCapacity(const MWWorld::Ptr& ptr) const
{
const MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
return stats.getAttribute(ESM::Attribute::Strength).getModified() * 5;
}
int Creature::getServices(const MWWorld::ConstPtr& actor) const
{
return actor.get<ESM::Creature>()->mBase->mAiData.mServices;
}
bool Creature::isPersistent(const MWWorld::ConstPtr& actor) const
{
const MWWorld::LiveCellRef<ESM::Creature>* ref = actor.get<ESM::Creature>();
return (ref->mBase->mRecordFlags & ESM::FLAG_Persistent) != 0;
}
ESM::RefId Creature::getSoundIdFromSndGen(const MWWorld::Ptr& ptr, std::string_view name) const
{
int type = getSndGenTypeFromName(ptr, name);
if (type < 0)
return ESM::RefId();
std::vector<const ESM::SoundGenerator*> sounds;
std::vector<const ESM::SoundGenerator*> fallbacksounds;
MWWorld::LiveCellRef<ESM::Creature>* ref = ptr.get<ESM::Creature>();
const ESM::RefId& ourId = (ref->mBase->mOriginal.empty()) ? ptr.getCellRef().getRefId() : ref->mBase->mOriginal;
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
auto sound = store.get<ESM::SoundGenerator>().begin();
while (sound != store.get<ESM::SoundGenerator>().end())
{
if (type == sound->mType && !sound->mCreature.empty() && ourId == sound->mCreature)
sounds.push_back(&*sound);
if (type == sound->mType && sound->mCreature.empty())
fallbacksounds.push_back(&*sound);
++sound;
}
if (sounds.empty())
{
const std::string_view model = getModel(ptr);
if (!model.empty())
{
for (const ESM::Creature& creature : store.get<ESM::Creature>())
{
if (creature.mId != ourId && creature.mOriginal != ourId && !creature.mModel.empty()
&& Misc::StringUtils::ciEqual(model, creature.mModel))
{
const ESM::RefId& fallbackId = !creature.mOriginal.empty() ? creature.mOriginal : creature.mId;
sound = store.get<ESM::SoundGenerator>().begin();
while (sound != store.get<ESM::SoundGenerator>().end())
{
if (type == sound->mType && !sound->mCreature.empty() && fallbackId == sound->mCreature)
sounds.push_back(&*sound);
++sound;
}
break;
}
}
}
}
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
if (!sounds.empty())
return sounds[Misc::Rng::rollDice(sounds.size(), prng)]->mSound;
if (!fallbacksounds.empty())
return fallbacksounds[Misc::Rng::rollDice(fallbacksounds.size(), prng)]->mSound;
return ESM::RefId();
}
MWWorld::Ptr Creature::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Creature>* ref = ptr.get<ESM::Creature>();
MWWorld::Ptr newPtr(cell.insert(ref), &cell);
if (newPtr.getRefData().getCustomData())
{
MWBase::Environment::get().getWorldModel()->registerPtr(newPtr);
newPtr.getClass().getContainerStore(newPtr).setPtr(newPtr);
}
return newPtr;
}
bool Creature::isBipedal(const MWWorld::ConstPtr& ptr) const
{
return isFlagBitSet(ptr, ESM::Creature::Bipedal);
}
bool Creature::canFly(const MWWorld::ConstPtr& ptr) const
{
return isFlagBitSet(ptr, ESM::Creature::Flies);
}
bool Creature::canSwim(const MWWorld::ConstPtr& ptr) const
{
return isFlagBitSet(ptr, static_cast<ESM::Creature::Flags>(ESM::Creature::Swims | ESM::Creature::Bipedal));
}
bool Creature::canWalk(const MWWorld::ConstPtr& ptr) const
{
return isFlagBitSet(ptr, static_cast<ESM::Creature::Flags>(ESM::Creature::Walks | ESM::Creature::Bipedal));
}
int Creature::getSndGenTypeFromName(const MWWorld::Ptr& ptr, std::string_view name)
{
if (name == "left")
{
MWBase::World* world = MWBase::Environment::get().getWorld();
if (world->isFlying(ptr))
return -1;
osg::Vec3f pos(ptr.getRefData().getPosition().asVec3());
if (world->isUnderwater(ptr.getCell(), pos) || world->isWalkingOnWater(ptr))
return ESM::SoundGenerator::SwimLeft;
if (world->isOnGround(ptr))
return ESM::SoundGenerator::LeftFoot;
return -1;
}
if (name == "right")
{
MWBase::World* world = MWBase::Environment::get().getWorld();
if (world->isFlying(ptr))
return -1;
osg::Vec3f pos(ptr.getRefData().getPosition().asVec3());
if (world->isUnderwater(ptr.getCell(), pos) || world->isWalkingOnWater(ptr))
return ESM::SoundGenerator::SwimRight;
if (world->isOnGround(ptr))
return ESM::SoundGenerator::RightFoot;
return -1;
}
if (name == "swimleft")
return ESM::SoundGenerator::SwimLeft;
if (name == "swimright")
return ESM::SoundGenerator::SwimRight;
if (name == "moan")
return ESM::SoundGenerator::Moan;
if (name == "roar")
return ESM::SoundGenerator::Roar;
if (name == "scream")
return ESM::SoundGenerator::Scream;
if (name == "land")
return ESM::SoundGenerator::Land;
throw std::runtime_error("Unexpected soundgen type: " + std::string(name));
}
float Creature::getSkill(const MWWorld::Ptr& ptr, ESM::RefId id) const
{
MWWorld::LiveCellRef<ESM::Creature>* ref = ptr.get<ESM::Creature>();
const ESM::Skill* skillRecord = MWBase::Environment::get().getESMStore()->get<ESM::Skill>().find(id);
switch (skillRecord->mData.mSpecialization)
{
case ESM::Class::Combat:
return ref->mBase->mData.mCombat;
case ESM::Class::Magic:
return ref->mBase->mData.mMagic;
case ESM::Class::Stealth:
return ref->mBase->mData.mStealth;
default:
throw std::runtime_error("invalid specialisation");
}
}
int Creature::getBloodTexture(const MWWorld::ConstPtr& ptr) const
{
return ptr.get<ESM::Creature>()->mBase->mBloodType;
}
void Creature::readAdditionalState(const MWWorld::Ptr& ptr, const ESM::ObjectState& state) const
{
if (!state.mHasCustomState)
return;
const ESM::CreatureState& creatureState = state.asCreatureState();
if (!ptr.getRefData().getCustomData())
{
if (creatureState.mCreatureStats.mMissingACDT)
ensureCustomData(ptr);
else
{
// Create a CustomData, but don't fill it from ESM records (not needed)
auto data = std::make_unique<CreatureCustomData>();
if (hasInventoryStore(ptr))
data->mContainerStore = std::make_unique<MWWorld::InventoryStore>();
else
data->mContainerStore = std::make_unique<MWWorld::ContainerStore>();
MWBase::Environment::get().getWorldModel()->registerPtr(ptr);
data->mContainerStore->setPtr(ptr);
ptr.getRefData().setCustomData(std::move(data));
}
}
CreatureCustomData& customData = ptr.getRefData().getCustomData()->asCreatureCustomData();
customData.mContainerStore->readState(creatureState.mInventory);
bool spellsInitialised = customData.mCreatureStats.getSpells().setSpells(ptr.get<ESM::Creature>()->mBase->mId);
if (spellsInitialised)
customData.mCreatureStats.getSpells().clear();
customData.mCreatureStats.readState(creatureState.mCreatureStats);
}
void Creature::writeAdditionalState(const MWWorld::ConstPtr& ptr, ESM::ObjectState& state) const
{
if (!ptr.getRefData().getCustomData())
{
state.mHasCustomState = false;
return;
}
const CreatureCustomData& customData = ptr.getRefData().getCustomData()->asCreatureCustomData();
if (ptr.getCellRef().getCount() <= 0
&& (!isFlagBitSet(ptr, ESM::Creature::Respawn) || !customData.mCreatureStats.isDead()))
{
state.mHasCustomState = false;
return;
}
ESM::CreatureState& creatureState = state.asCreatureState();
customData.mContainerStore->writeState(creatureState.mInventory);
customData.mCreatureStats.writeState(creatureState.mCreatureStats);
}
int Creature::getBaseGold(const MWWorld::ConstPtr& ptr) const
{
return ptr.get<ESM::Creature>()->mBase->mData.mGold;
}
void Creature::respawn(const MWWorld::Ptr& ptr) const
{
const MWMechanics::CreatureStats& creatureStats = getCreatureStats(ptr);
if (ptr.getCellRef().getCount() > 0 && !creatureStats.isDead())
return;
if (!creatureStats.isDeathAnimationFinished())
return;
const MWWorld::Store<ESM::GameSetting>& gmst
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
static const float fCorpseRespawnDelay = gmst.find("fCorpseRespawnDelay")->mValue.getFloat();
static const float fCorpseClearDelay = gmst.find("fCorpseClearDelay")->mValue.getFloat();
float delay
= ptr.getCellRef().getCount() == 0 ? fCorpseClearDelay : std::min(fCorpseRespawnDelay, fCorpseClearDelay);
if (isFlagBitSet(ptr, ESM::Creature::Respawn)
&& creatureStats.getTimeOfDeath() + delay <= MWBase::Environment::get().getWorld()->getTimeStamp())
{
if (ptr.getCellRef().hasContentFile())
{
if (ptr.getCellRef().getCount() == 0)
{
ptr.getCellRef().setCount(1);
const ESM::RefId& script = getScript(ptr);
if (!script.empty())
MWBase::Environment::get().getWorld()->getLocalScripts().add(script, ptr);
}
MWBase::Environment::get().getWorld()->removeContainerScripts(ptr);
MWBase::Environment::get().getWindowManager()->onDeleteCustomData(ptr);
ptr.getRefData().setCustomData(nullptr);
// Reset to original position
MWBase::Environment::get().getWorld()->moveObject(ptr, ptr.getCellRef().getPosition().asVec3());
MWBase::Environment::get().getWorld()->rotateObject(
ptr, ptr.getCellRef().getPosition().asRotationVec3(), MWBase::RotationFlag_none);
}
}
}
int Creature::getBaseFightRating(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Creature>* ref = ptr.get<ESM::Creature>();
return ref->mBase->mAiData.mFight;
}
void Creature::adjustScale(const MWWorld::ConstPtr& ptr, osg::Vec3f& scale, bool /* rendering */) const
{
const MWWorld::LiveCellRef<ESM::Creature>* ref = ptr.get<ESM::Creature>();
scale *= ref->mBase->mScale;
}
void Creature::setBaseAISetting(const ESM::RefId& id, MWMechanics::AiSetting setting, int value) const
{
MWMechanics::setBaseAISetting<ESM::Creature>(id, setting, value);
}
void Creature::modifyBaseInventory(const ESM::RefId& actorId, const ESM::RefId& itemId, int amount) const
{
MWMechanics::modifyBaseInventory<ESM::Creature>(actorId, itemId, amount);
}
float Creature::getWalkSpeed(const MWWorld::Ptr& ptr) const
{
const MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
const GMST& gmst = getGmst();
return gmst.fMinWalkSpeedCreature->mValue.getFloat()
+ 0.01f * stats.getAttribute(ESM::Attribute::Speed).getModified()
* (gmst.fMaxWalkSpeedCreature->mValue.getFloat() - gmst.fMinWalkSpeedCreature->mValue.getFloat());
}
float Creature::getRunSpeed(const MWWorld::Ptr& ptr) const
{
return getWalkSpeed(ptr);
}
float Creature::getSwimSpeed(const MWWorld::Ptr& ptr) const
{
const MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
const MWMechanics::MagicEffects& mageffects = stats.getMagicEffects();
return getSwimSpeedImpl(ptr, getGmst(), mageffects, getWalkSpeed(ptr));
}
}
| 37,568
|
C++
|
.cpp
| 770
| 38.211688
| 120
| 0.621865
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,443
|
actor.cpp
|
OpenMW_openmw/apps/openmw/mwclass/actor.cpp
|
#include "actor.hpp"
#include <components/esm3/loadmgef.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/luamanager.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/magiceffects.hpp"
#include "../mwmechanics/movement.hpp"
#include "../mwphysics/physicssystem.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/worldmodel.hpp"
namespace MWClass
{
void Actor::adjustPosition(const MWWorld::Ptr& ptr, bool force) const
{
MWBase::Environment::get().getWorld()->adjustPosition(ptr, force);
}
void Actor::insertObject(const MWWorld::Ptr& ptr, const std::string& model, const osg::Quat& rotation,
MWPhysics::PhysicsSystem& physics) const
{
physics.addActor(ptr, VFS::Path::toNormalized(model));
if (getCreatureStats(ptr).isDead() && getCreatureStats(ptr).isDeathAnimationFinished())
MWBase::Environment::get().getWorld()->enableActorCollision(ptr, false);
}
bool Actor::useAnim() const
{
return true;
}
osg::Vec3f Actor::getRotationVector(const MWWorld::Ptr& ptr) const
{
MWMechanics::Movement& movement = getMovementSettings(ptr);
osg::Vec3f vec(movement.mRotation[0], movement.mRotation[1], movement.mRotation[2]);
movement.mRotation[0] = 0.0f;
movement.mRotation[1] = 0.0f;
movement.mRotation[2] = 0.0f;
return vec;
}
float Actor::getEncumbrance(const MWWorld::Ptr& ptr) const
{
float weight = getContainerStore(ptr).getWeight();
const MWMechanics::MagicEffects& effects = getCreatureStats(ptr).getMagicEffects();
weight -= effects.getOrDefault(MWMechanics::EffectKey(ESM::MagicEffect::Feather)).getMagnitude();
if (ptr != MWMechanics::getPlayer() || !MWBase::Environment::get().getWorld()->getGodModeState())
weight += effects.getOrDefault(MWMechanics::EffectKey(ESM::MagicEffect::Burden)).getMagnitude();
return (weight < 0) ? 0.0f : weight;
}
bool Actor::allowTelekinesis(const MWWorld::ConstPtr& ptr) const
{
return false;
}
bool Actor::isActor() const
{
return true;
}
float Actor::getCurrentSpeed(const MWWorld::Ptr& ptr) const
{
const MWMechanics::Movement& movementSettings = ptr.getClass().getMovementSettings(ptr);
float moveSpeed = this->getMaxSpeed(ptr) * movementSettings.mSpeedFactor;
if (movementSettings.mIsStrafing)
moveSpeed *= 0.75f;
return moveSpeed;
}
bool Actor::consume(const MWWorld::Ptr& consumable, const MWWorld::Ptr& actor) const
{
MWMechanics::CastSpell cast(actor, actor);
const ESM::RefId& recordId = consumable.getCellRef().getRefId();
MWBase::Environment::get().getWorldModel()->registerPtr(consumable);
MWBase::Environment::get().getLuaManager()->itemConsumed(consumable, actor);
actor.getClass().getContainerStore(actor).remove(consumable, 1);
if (cast.cast(recordId))
{
MWBase::Environment::get().getWorld()->breakInvisibility(actor);
return true;
}
return false;
}
}
| 3,293
|
C++
|
.cpp
| 79
| 35.240506
| 108
| 0.679375
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,444
|
creaturelevlist.cpp
|
OpenMW_openmw/apps/openmw/mwclass/creaturelevlist.cpp
|
#include "creaturelevlist.hpp"
#include <components/esm3/creaturelevliststate.hpp>
#include <components/esm3/loadlevlist.hpp>
#include "../mwmechanics/levelledlist.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/customdata.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/manualref.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp"
namespace MWClass
{
class CreatureLevListCustomData : public MWWorld::TypedCustomData<CreatureLevListCustomData>
{
public:
// actorId of the creature we spawned
int mSpawnActorId;
bool mSpawn; // Should a new creature be spawned?
CreatureLevListCustomData& asCreatureLevListCustomData() override { return *this; }
const CreatureLevListCustomData& asCreatureLevListCustomData() const override { return *this; }
};
CreatureLevList::CreatureLevList()
: MWWorld::RegisteredClass<CreatureLevList>(ESM::CreatureLevList::sRecordId)
{
}
MWWorld::Ptr CreatureLevList::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::CreatureLevList>* ref = ptr.get<ESM::CreatureLevList>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
void CreatureLevList::adjustPosition(const MWWorld::Ptr& ptr, bool force) const
{
if (ptr.getRefData().getCustomData() == nullptr)
return;
CreatureLevListCustomData& customData = ptr.getRefData().getCustomData()->asCreatureLevListCustomData();
MWWorld::Ptr creature = (customData.mSpawnActorId == -1)
? MWWorld::Ptr()
: MWBase::Environment::get().getWorld()->searchPtrViaActorId(customData.mSpawnActorId);
if (!creature.isEmpty())
MWBase::Environment::get().getWorld()->adjustPosition(creature, force);
}
std::string_view CreatureLevList::getName(const MWWorld::ConstPtr& ptr) const
{
return {};
}
bool CreatureLevList::hasToolTip(const MWWorld::ConstPtr& ptr) const
{
return false;
}
void CreatureLevList::respawn(const MWWorld::Ptr& ptr) const
{
ensureCustomData(ptr);
CreatureLevListCustomData& customData = ptr.getRefData().getCustomData()->asCreatureLevListCustomData();
if (customData.mSpawn)
return;
MWWorld::Ptr creature;
if (customData.mSpawnActorId != -1)
{
creature = MWBase::Environment::get().getWorld()->searchPtrViaActorId(customData.mSpawnActorId);
if (creature.isEmpty())
creature = ptr.getCell()->getMovedActor(customData.mSpawnActorId);
}
if (!creature.isEmpty())
{
const MWMechanics::CreatureStats& creatureStats = creature.getClass().getCreatureStats(creature);
if (creature.getCellRef().getCount() == 0)
customData.mSpawn = true;
else if (creatureStats.isDead())
{
const MWWorld::Store<ESM::GameSetting>& gmst
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
static const float fCorpseRespawnDelay = gmst.find("fCorpseRespawnDelay")->mValue.getFloat();
static const float fCorpseClearDelay = gmst.find("fCorpseClearDelay")->mValue.getFloat();
float delay = std::min(fCorpseRespawnDelay, fCorpseClearDelay);
if (creatureStats.getTimeOfDeath() + delay <= MWBase::Environment::get().getWorld()->getTimeStamp())
customData.mSpawn = true;
}
}
else
customData.mSpawn = true;
}
void CreatureLevList::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
ensureCustomData(ptr);
CreatureLevListCustomData& customData = ptr.getRefData().getCustomData()->asCreatureLevListCustomData();
if (!customData.mSpawn)
return;
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
const ESM::RefId& id = MWMechanics::getLevelledItem(
store.get<ESM::CreatureLevList>().find(ptr.getCellRef().getRefId()), true, prng);
if (!id.empty())
{
// Delete the previous creature
if (customData.mSpawnActorId != -1)
{
MWWorld::Ptr creature
= MWBase::Environment::get().getWorld()->searchPtrViaActorId(customData.mSpawnActorId);
if (!creature.isEmpty())
MWBase::Environment::get().getWorld()->deleteObject(creature);
customData.mSpawnActorId = -1;
}
MWWorld::ManualRef manualRef(store, id);
manualRef.getPtr().getCellRef().setPosition(ptr.getCellRef().getPosition());
manualRef.getPtr().getCellRef().setScale(ptr.getCellRef().getScale());
MWWorld::Ptr placed = MWBase::Environment::get().getWorld()->placeObject(
manualRef.getPtr(), ptr.getCell(), ptr.getRefData().getPosition());
customData.mSpawnActorId = placed.getClass().getCreatureStats(placed).getActorId();
customData.mSpawn = false;
}
else
customData.mSpawn = false;
}
void CreatureLevList::ensureCustomData(const MWWorld::Ptr& ptr) const
{
if (!ptr.getRefData().getCustomData())
{
std::unique_ptr<CreatureLevListCustomData> data = std::make_unique<CreatureLevListCustomData>();
data->mSpawnActorId = -1;
data->mSpawn = true;
ptr.getRefData().setCustomData(std::move(data));
}
}
void CreatureLevList::readAdditionalState(const MWWorld::Ptr& ptr, const ESM::ObjectState& state) const
{
if (!state.mHasCustomState)
return;
ensureCustomData(ptr);
CreatureLevListCustomData& customData = ptr.getRefData().getCustomData()->asCreatureLevListCustomData();
const ESM::CreatureLevListState& levListState = state.asCreatureLevListState();
customData.mSpawnActorId = levListState.mSpawnActorId;
customData.mSpawn = levListState.mSpawn;
}
void CreatureLevList::writeAdditionalState(const MWWorld::ConstPtr& ptr, ESM::ObjectState& state) const
{
if (!ptr.getRefData().getCustomData())
{
state.mHasCustomState = false;
return;
}
const CreatureLevListCustomData& customData = ptr.getRefData().getCustomData()->asCreatureLevListCustomData();
ESM::CreatureLevListState& levListState = state.asCreatureLevListState();
levListState.mSpawnActorId = customData.mSpawnActorId;
levListState.mSpawn = customData.mSpawn;
}
}
| 6,963
|
C++
|
.cpp
| 148
| 37.716216
| 118
| 0.656793
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,445
|
repair.cpp
|
OpenMW_openmw/apps/openmw/mwclass/repair.cpp
|
#include "repair.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadnpc.hpp>
#include <components/esm3/loadrepa.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/actionrepair.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
Repair::Repair()
: MWWorld::RegisteredClass<Repair>(ESM::Repair::sRecordId)
{
}
void Repair::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
std::string_view Repair::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Repair>(ptr);
}
std::string_view Repair::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Repair>(ptr);
}
std::unique_ptr<MWWorld::Action> Repair::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
return defaultItemActivate(ptr, actor);
}
ESM::RefId Repair::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Repair>* ref = ptr.get<ESM::Repair>();
return ref->mBase->mScript;
}
int Repair::getValue(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Repair>* ref = ptr.get<ESM::Repair>();
return ref->mBase->mData.mValue;
}
const ESM::RefId& Repair::getUpSoundId(const MWWorld::ConstPtr& ptr) const
{
static auto val = ESM::RefId::stringRefId("Item Repair Up");
return val;
}
const ESM::RefId& Repair::getDownSoundId(const MWWorld::ConstPtr& ptr) const
{
static auto val = ESM::RefId::stringRefId("Item Repair Down");
return val;
}
const std::string& Repair::getInventoryIcon(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Repair>* ref = ptr.get<ESM::Repair>();
return ref->mBase->mIcon;
}
bool Repair::hasItemHealth(const MWWorld::ConstPtr& ptr) const
{
return true;
}
int Repair::getItemMaxHealth(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Repair>* ref = ptr.get<ESM::Repair>();
return ref->mBase->mData.mUses;
}
MWGui::ToolTipInfo Repair::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Repair>* ref = ptr.get<ESM::Repair>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count);
info.icon = ref->mBase->mIcon;
std::string text;
int remainingUses = getItemHealth(ptr);
text += "\n#{sUses}: " + MWGui::ToolTips::toString(remainingUses);
text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->mBase->mData.mQuality);
text += MWGui::ToolTips::getWeightString(ref->mBase->mData.mWeight, "#{sWeight}");
text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}");
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
info.text = std::move(text);
return info;
}
MWWorld::Ptr Repair::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Repair>* ref = ptr.get<ESM::Repair>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
std::unique_ptr<MWWorld::Action> Repair::use(const MWWorld::Ptr& ptr, bool force) const
{
return std::make_unique<MWWorld::ActionRepair>(ptr, force);
}
bool Repair::canSell(const MWWorld::ConstPtr& item, int npcServices) const
{
return (npcServices & ESM::NPC::RepairItem) != 0;
}
float Repair::getWeight(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Repair>* ref = ptr.get<ESM::Repair>();
return ref->mBase->mData.mWeight;
}
}
| 4,590
|
C++
|
.cpp
| 115
| 33.521739
| 120
| 0.659833
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,446
|
activator.cpp
|
OpenMW_openmw/apps/openmw/mwclass/activator.cpp
|
#include "activator.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadacti.hpp>
#include <components/esm3/loadcrea.hpp>
#include <components/esm3/loadsndg.hpp>
#include <components/esm3/loadsoun.hpp>
#include <components/misc/rng.hpp>
#include <components/sceneutil/positionattitudetransform.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/action.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/failedaction.hpp"
#include "../mwworld/nullaction.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwphysics/physicssystem.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwrender/vismask.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "classmodel.hpp"
namespace MWClass
{
Activator::Activator()
: MWWorld::RegisteredClass<Activator>(ESM::Activator::sRecordId)
{
}
void Activator::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
ptr.getRefData().getBaseNode()->setNodeMask(MWRender::Mask_Static);
}
}
void Activator::insertObject(const MWWorld::Ptr& ptr, const std::string& model, const osg::Quat& rotation,
MWPhysics::PhysicsSystem& physics) const
{
insertObjectPhysics(ptr, model, rotation, physics);
}
void Activator::insertObjectPhysics(const MWWorld::Ptr& ptr, const std::string& model, const osg::Quat& rotation,
MWPhysics::PhysicsSystem& physics) const
{
physics.addObject(ptr, VFS::Path::toNormalized(model), rotation, MWPhysics::CollisionType_World);
}
std::string_view Activator::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Activator>(ptr);
}
bool Activator::isActivator() const
{
return true;
}
bool Activator::useAnim() const
{
return true;
}
std::string_view Activator::getName(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Activator>* ref = ptr.get<ESM::Activator>();
return ref->mBase->mName;
}
ESM::RefId Activator::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Activator>* ref = ptr.get<ESM::Activator>();
return ref->mBase->mScript;
}
bool Activator::hasToolTip(const MWWorld::ConstPtr& ptr) const
{
return !getName(ptr).empty();
}
MWGui::ToolTipInfo Activator::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Activator>* ref = ptr.get<ESM::Activator>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count);
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
return info;
}
std::unique_ptr<MWWorld::Action> Activator::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
if (actor.getClass().isNpc() && actor.getClass().getNpcStats(actor).isWerewolf())
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
const ESM::Sound* sound = store.get<ESM::Sound>().searchRandom("WolfActivator", prng);
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::FailedAction>("#{sWerewolfRefusal}");
if (sound)
action->setSound(sound->mId);
return action;
}
return std::make_unique<MWWorld::NullAction>();
}
MWWorld::Ptr Activator::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Activator>* ref = ptr.get<ESM::Activator>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
ESM::RefId Activator::getSoundIdFromSndGen(const MWWorld::Ptr& ptr, std::string_view name) const
{
// Assume it's not empty, since we wouldn't have gotten the soundgen otherwise
const std::string_view model = getModel(ptr);
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
const ESM::RefId* creatureId = nullptr;
for (const ESM::Creature& iter : store.get<ESM::Creature>())
{
if (!iter.mModel.empty() && Misc::StringUtils::ciEqual(model, iter.mModel))
{
creatureId = !iter.mOriginal.empty() ? &iter.mOriginal : &iter.mId;
break;
}
}
int type = getSndGenTypeFromName(name);
std::vector<const ESM::SoundGenerator*> fallbacksounds;
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
if (creatureId && !creatureId->empty())
{
std::vector<const ESM::SoundGenerator*> sounds;
for (auto sound = store.get<ESM::SoundGenerator>().begin(); sound != store.get<ESM::SoundGenerator>().end();
++sound)
{
if (type == sound->mType && !sound->mCreature.empty() && (*creatureId == sound->mCreature))
sounds.push_back(&*sound);
if (type == sound->mType && sound->mCreature.empty())
fallbacksounds.push_back(&*sound);
}
if (!sounds.empty())
return sounds[Misc::Rng::rollDice(sounds.size(), prng)]->mSound;
if (!fallbacksounds.empty())
return fallbacksounds[Misc::Rng::rollDice(fallbacksounds.size(), prng)]->mSound;
}
else
{
// The activator doesn't have a corresponding creature ID, but we can try to use the defaults
for (auto sound = store.get<ESM::SoundGenerator>().begin(); sound != store.get<ESM::SoundGenerator>().end();
++sound)
if (type == sound->mType && sound->mCreature.empty())
fallbacksounds.push_back(&*sound);
if (!fallbacksounds.empty())
return fallbacksounds[Misc::Rng::rollDice(fallbacksounds.size(), prng)]->mSound;
}
return ESM::RefId();
}
int Activator::getSndGenTypeFromName(std::string_view name)
{
if (name == "left")
return ESM::SoundGenerator::LeftFoot;
if (name == "right")
return ESM::SoundGenerator::RightFoot;
if (name == "swimleft")
return ESM::SoundGenerator::SwimLeft;
if (name == "swimright")
return ESM::SoundGenerator::SwimRight;
if (name == "moan")
return ESM::SoundGenerator::Moan;
if (name == "roar")
return ESM::SoundGenerator::Roar;
if (name == "scream")
return ESM::SoundGenerator::Scream;
if (name == "land")
return ESM::SoundGenerator::Land;
throw std::runtime_error("Unexpected soundgen type: " + std::string(name));
}
}
| 7,578
|
C++
|
.cpp
| 174
| 35.235632
| 120
| 0.6315
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,448
|
potion.cpp
|
OpenMW_openmw/apps/openmw/mwclass/potion.cpp
|
#include "potion.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include <components/esm3/loadalch.hpp>
#include <components/esm3/loadnpc.hpp>
#include "../mwworld/actionapply.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwmechanics/alchemy.hpp"
#include "../mwmechanics/spellutil.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
Potion::Potion()
: MWWorld::RegisteredClass<Potion>(ESM::Potion::sRecordId)
{
}
void Potion::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
std::string_view Potion::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Potion>(ptr);
}
std::string_view Potion::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Potion>(ptr);
}
std::unique_ptr<MWWorld::Action> Potion::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
return defaultItemActivate(ptr, actor);
}
ESM::RefId Potion::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Potion>* ref = ptr.get<ESM::Potion>();
return ref->mBase->mScript;
}
int Potion::getValue(const MWWorld::ConstPtr& ptr) const
{
return MWMechanics::getPotionValue(*ptr.get<ESM::Potion>()->mBase);
}
const ESM::RefId& Potion::getUpSoundId(const MWWorld::ConstPtr& ptr) const
{
static const auto sound = ESM::RefId::stringRefId("Item Potion Up");
return sound;
}
const ESM::RefId& Potion::getDownSoundId(const MWWorld::ConstPtr& ptr) const
{
static const auto sound = ESM::RefId::stringRefId("Item Potion Down");
return sound;
}
const std::string& Potion::getInventoryIcon(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Potion>* ref = ptr.get<ESM::Potion>();
return ref->mBase->mIcon;
}
MWGui::ToolTipInfo Potion::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Potion>* ref = ptr.get<ESM::Potion>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count);
info.icon = ref->mBase->mIcon;
std::string text;
text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight);
text += MWGui::ToolTips::getValueString(getValue(ptr), "#{sValue}");
info.effects = MWGui::Widgets::MWEffectList::effectListFromESM(&ref->mBase->mEffects);
// hide effects the player doesn't know about
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
for (size_t i = 0; i < info.effects.size(); ++i)
info.effects[i].mKnown = MWMechanics::Alchemy::knownEffect(i, player);
info.isPotion = true;
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
info.text = std::move(text);
return info;
}
std::unique_ptr<MWWorld::Action> Potion::use(const MWWorld::Ptr& ptr, bool force) const
{
MWWorld::LiveCellRef<ESM::Potion>* ref = ptr.get<ESM::Potion>();
auto action = std::make_unique<MWWorld::ActionApply>(ptr, ref->mBase->mId);
action->setSound(ESM::RefId::stringRefId("Drink"));
return action;
}
MWWorld::Ptr Potion::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Potion>* ref = ptr.get<ESM::Potion>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
bool Potion::canSell(const MWWorld::ConstPtr& item, int npcServices) const
{
return (npcServices & ESM::NPC::Potions) != 0;
}
float Potion::getWeight(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Potion>* ref = ptr.get<ESM::Potion>();
return ref->mBase->mData.mWeight;
}
}
| 4,721
|
C++
|
.cpp
| 114
| 35
| 120
| 0.661926
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,449
|
classes.cpp
|
OpenMW_openmw/apps/openmw/mwclass/classes.cpp
|
#include "classes.hpp"
#include <components/esm4/loadacti.hpp>
#include <components/esm4/loadalch.hpp>
#include <components/esm4/loadammo.hpp>
#include <components/esm4/loadarmo.hpp>
#include <components/esm4/loadbook.hpp>
#include <components/esm4/loadclot.hpp>
#include <components/esm4/loadcont.hpp>
#include <components/esm4/loadcrea.hpp>
#include <components/esm4/loaddoor.hpp>
#include <components/esm4/loadflor.hpp>
#include <components/esm4/loadfurn.hpp>
#include <components/esm4/loadimod.hpp>
#include <components/esm4/loadingr.hpp>
#include <components/esm4/loadligh.hpp>
#include <components/esm4/loadmisc.hpp>
#include <components/esm4/loadmstt.hpp>
#include <components/esm4/loadnpc.hpp>
#include <components/esm4/loadscol.hpp>
#include <components/esm4/loadstat.hpp>
#include <components/esm4/loadterm.hpp>
#include <components/esm4/loadtree.hpp>
#include <components/esm4/loadweap.hpp>
#include "activator.hpp"
#include "apparatus.hpp"
#include "armor.hpp"
#include "bodypart.hpp"
#include "book.hpp"
#include "clothing.hpp"
#include "container.hpp"
#include "creature.hpp"
#include "creaturelevlist.hpp"
#include "door.hpp"
#include "ingredient.hpp"
#include "itemlevlist.hpp"
#include "light.hpp"
#include "lockpick.hpp"
#include "misc.hpp"
#include "npc.hpp"
#include "potion.hpp"
#include "probe.hpp"
#include "repair.hpp"
#include "static.hpp"
#include "weapon.hpp"
#include "esm4base.hpp"
#include "esm4npc.hpp"
#include "light4.hpp"
namespace MWClass
{
void registerClasses()
{
Activator::registerSelf();
Creature::registerSelf();
Npc::registerSelf();
Weapon::registerSelf();
Armor::registerSelf();
Potion::registerSelf();
Apparatus::registerSelf();
Book::registerSelf();
Clothing::registerSelf();
Container::registerSelf();
Door::registerSelf();
Ingredient::registerSelf();
CreatureLevList::registerSelf();
ItemLevList::registerSelf();
Light::registerSelf();
Lockpick::registerSelf();
Miscellaneous::registerSelf();
Probe::registerSelf();
Repair::registerSelf();
Static::registerSelf();
BodyPart::registerSelf();
ESM4Named<ESM4::Activator>::registerSelf();
ESM4Named<ESM4::Ammunition>::registerSelf();
ESM4Named<ESM4::Armor>::registerSelf();
ESM4Named<ESM4::Book>::registerSelf();
ESM4Named<ESM4::Clothing>::registerSelf();
ESM4Named<ESM4::Creature>::registerSelf();
ESM4Named<ESM4::Container>::registerSelf();
ESM4Named<ESM4::Door>::registerSelf();
ESM4Named<ESM4::Flora>::registerSelf();
ESM4Named<ESM4::Furniture>::registerSelf();
ESM4Named<ESM4::Ingredient>::registerSelf();
ESM4Named<ESM4::ItemMod>::registerSelf();
ESM4Light::registerSelf();
ESM4Named<ESM4::MiscItem>::registerSelf();
ESM4Named<ESM4::MovableStatic>::registerSelf();
ESM4Npc::registerSelf();
ESM4Named<ESM4::Potion>::registerSelf();
ESM4Static::registerSelf();
ESM4Named<ESM4::StaticCollection>::registerSelf();
ESM4Named<ESM4::Terminal>::registerSelf();
ESM4Tree::registerSelf();
ESM4Named<ESM4::Weapon>::registerSelf();
}
}
| 3,283
|
C++
|
.cpp
| 96
| 29.4375
| 58
| 0.707731
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,450
|
bodypart.cpp
|
OpenMW_openmw/apps/openmw/mwclass/bodypart.cpp
|
#include "bodypart.hpp"
#include <components/esm3/loadbody.hpp>
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwworld/cellstore.hpp"
#include "classmodel.hpp"
namespace MWClass
{
BodyPart::BodyPart()
: MWWorld::RegisteredClass<BodyPart>(ESM::BodyPart::sRecordId)
{
}
MWWorld::Ptr BodyPart::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::BodyPart>* ref = ptr.get<ESM::BodyPart>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
void BodyPart::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
std::string_view BodyPart::getName(const MWWorld::ConstPtr& ptr) const
{
return {};
}
bool BodyPart::hasToolTip(const MWWorld::ConstPtr& ptr) const
{
return false;
}
std::string_view BodyPart::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::BodyPart>(ptr);
}
}
| 1,232
|
C++
|
.cpp
| 38
| 26.789474
| 114
| 0.674281
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,451
|
ingredient.cpp
|
OpenMW_openmw/apps/openmw/mwclass/ingredient.cpp
|
#include "ingredient.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadingr.hpp>
#include <components/esm3/loadnpc.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/actioneat.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/nullaction.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
Ingredient::Ingredient()
: MWWorld::RegisteredClass<Ingredient>(ESM::Ingredient::sRecordId)
{
}
void Ingredient::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
std::string_view Ingredient::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Ingredient>(ptr);
}
std::string_view Ingredient::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Ingredient>(ptr);
}
std::unique_ptr<MWWorld::Action> Ingredient::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
return defaultItemActivate(ptr, actor);
}
ESM::RefId Ingredient::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Ingredient>* ref = ptr.get<ESM::Ingredient>();
return ref->mBase->mScript;
}
int Ingredient::getValue(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Ingredient>* ref = ptr.get<ESM::Ingredient>();
return ref->mBase->mData.mValue;
}
std::unique_ptr<MWWorld::Action> Ingredient::use(const MWWorld::Ptr& ptr, bool force) const
{
if (ptr.get<ESM::Ingredient>()->mBase->mData.mEffectID[0] < 0)
return std::make_unique<MWWorld::NullAction>();
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::ActionEat>(ptr);
action->setSound(ESM::RefId::stringRefId("Swallow"));
return action;
}
const ESM::RefId& Ingredient::getUpSoundId(const MWWorld::ConstPtr& ptr) const
{
static auto sound = ESM::RefId::stringRefId("Item Ingredient Up");
return sound;
}
const ESM::RefId& Ingredient::getDownSoundId(const MWWorld::ConstPtr& ptr) const
{
static auto sound = ESM::RefId::stringRefId("Item Ingredient Down");
return sound;
}
const std::string& Ingredient::getInventoryIcon(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Ingredient>* ref = ptr.get<ESM::Ingredient>();
return ref->mBase->mIcon;
}
MWGui::ToolTipInfo Ingredient::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Ingredient>* ref = ptr.get<ESM::Ingredient>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count);
info.icon = ref->mBase->mIcon;
std::string text;
text += MWGui::ToolTips::getWeightString(ref->mBase->mData.mWeight, "#{sWeight}");
text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}");
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
float alchemySkill = player.getClass().getSkill(player, ESM::Skill::Alchemy);
static const float fWortChanceValue = MWBase::Environment::get()
.getESMStore()
->get<ESM::GameSetting>()
.find("fWortChanceValue")
->mValue.getFloat();
MWGui::Widgets::SpellEffectList list;
for (int i = 0; i < 4; ++i)
{
if (ref->mBase->mData.mEffectID[i] < 0)
continue;
MWGui::Widgets::SpellEffectParams params;
params.mEffectID = ref->mBase->mData.mEffectID[i];
params.mAttribute = ESM::Attribute::indexToRefId(ref->mBase->mData.mAttributes[i]);
params.mSkill = ESM::Skill::indexToRefId(ref->mBase->mData.mSkills[i]);
params.mKnown = alchemySkill >= fWortChanceValue * (i + 1);
list.push_back(params);
}
info.effects = std::move(list);
info.text = std::move(text);
info.isIngredient = true;
return info;
}
MWWorld::Ptr Ingredient::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Ingredient>* ref = ptr.get<ESM::Ingredient>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
bool Ingredient::canSell(const MWWorld::ConstPtr& item, int npcServices) const
{
return (npcServices & ESM::NPC::Ingredients) != 0;
}
float Ingredient::getWeight(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Ingredient>* ref = ptr.get<ESM::Ingredient>();
return ref->mBase->mData.mWeight;
}
}
| 5,759
|
C++
|
.cpp
| 131
| 35.648855
| 120
| 0.639535
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,452
|
itemlevlist.cpp
|
OpenMW_openmw/apps/openmw/mwclass/itemlevlist.cpp
|
#include "itemlevlist.hpp"
#include <components/esm3/loadlevlist.hpp>
namespace MWClass
{
ItemLevList::ItemLevList()
: MWWorld::RegisteredClass<ItemLevList>(ESM::ItemLevList::sRecordId)
{
}
std::string_view ItemLevList::getName(const MWWorld::ConstPtr& ptr) const
{
return {};
}
bool ItemLevList::hasToolTip(const MWWorld::ConstPtr& ptr) const
{
return false;
}
}
| 428
|
C++
|
.cpp
| 17
| 20.411765
| 77
| 0.685504
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,453
|
clothing.cpp
|
OpenMW_openmw/apps/openmw/mwclass/clothing.cpp
|
#include "clothing.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadclot.hpp>
#include <components/esm3/loadnpc.hpp>
#include <components/esm3/loadrace.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/actionequip.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
Clothing::Clothing()
: MWWorld::RegisteredClass<Clothing>(ESM::Clothing::sRecordId)
{
}
void Clothing::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
std::string_view Clothing::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Clothing>(ptr);
}
std::string_view Clothing::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Clothing>(ptr);
}
std::unique_ptr<MWWorld::Action> Clothing::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
return defaultItemActivate(ptr, actor);
}
ESM::RefId Clothing::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
return ref->mBase->mScript;
}
std::pair<std::vector<int>, bool> Clothing::getEquipmentSlots(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
std::vector<int> slots_;
if (ref->mBase->mData.mType == ESM::Clothing::Ring)
{
slots_.push_back(int(MWWorld::InventoryStore::Slot_LeftRing));
slots_.push_back(int(MWWorld::InventoryStore::Slot_RightRing));
}
else
{
const int size = 9;
static const int sMapping[size][2] = { { ESM::Clothing::Shirt, MWWorld::InventoryStore::Slot_Shirt },
{ ESM::Clothing::Belt, MWWorld::InventoryStore::Slot_Belt },
{ ESM::Clothing::Robe, MWWorld::InventoryStore::Slot_Robe },
{ ESM::Clothing::Pants, MWWorld::InventoryStore::Slot_Pants },
{ ESM::Clothing::Shoes, MWWorld::InventoryStore::Slot_Boots },
{ ESM::Clothing::LGlove, MWWorld::InventoryStore::Slot_LeftGauntlet },
{ ESM::Clothing::RGlove, MWWorld::InventoryStore::Slot_RightGauntlet },
{ ESM::Clothing::Skirt, MWWorld::InventoryStore::Slot_Skirt },
{ ESM::Clothing::Amulet, MWWorld::InventoryStore::Slot_Amulet } };
for (int i = 0; i < size; ++i)
if (sMapping[i][0] == ref->mBase->mData.mType)
{
slots_.push_back(int(sMapping[i][1]));
break;
}
}
return std::make_pair(slots_, false);
}
ESM::RefId Clothing::getEquipmentSkill(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
if (ref->mBase->mData.mType == ESM::Clothing::Shoes)
return ESM::Skill::Unarmored;
return {};
}
int Clothing::getValue(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
return ref->mBase->mData.mValue;
}
const ESM::RefId& Clothing::getUpSoundId(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
static const ESM::RefId ringUp = ESM::RefId::stringRefId("Item Ring Up");
static const ESM::RefId clothsUp = ESM::RefId::stringRefId("Item Clothes Up");
if (ref->mBase->mData.mType == ESM::Clothing::Ring)
{
return ringUp;
}
return clothsUp;
}
const ESM::RefId& Clothing::getDownSoundId(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
static const ESM::RefId ringDown = ESM::RefId::stringRefId("Item Ring Down");
static const ESM::RefId clothsDown = ESM::RefId::stringRefId("Item Clothes Down");
if (ref->mBase->mData.mType == ESM::Clothing::Ring)
{
return ringDown;
}
return clothsDown;
}
const std::string& Clothing::getInventoryIcon(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
return ref->mBase->mIcon;
}
MWGui::ToolTipInfo Clothing::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count);
info.icon = ref->mBase->mIcon;
std::string text;
text += MWGui::ToolTips::getWeightString(ref->mBase->mData.mWeight, "#{sWeight}");
text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}");
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
info.enchant = ref->mBase->mEnchant;
if (!info.enchant.empty())
info.remainingEnchantCharge = static_cast<int>(ptr.getCellRef().getEnchantmentCharge());
info.text = std::move(text);
return info;
}
ESM::RefId Clothing::getEnchantment(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
return ref->mBase->mEnchant;
}
const ESM::RefId& Clothing::applyEnchantment(
const MWWorld::ConstPtr& ptr, const ESM::RefId& enchId, int enchCharge, const std::string& newName) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
ESM::Clothing newItem = *ref->mBase;
newItem.mId = ESM::RefId();
newItem.mName = newName;
newItem.mData.mEnchant = enchCharge;
newItem.mEnchant = enchId;
const ESM::Clothing* record = MWBase::Environment::get().getESMStore()->insert(newItem);
return record->mId;
}
std::pair<int, std::string_view> Clothing::canBeEquipped(
const MWWorld::ConstPtr& ptr, const MWWorld::Ptr& npc) const
{
// slots that this item can be equipped in
std::pair<std::vector<int>, bool> slots_ = getEquipmentSlots(ptr);
if (slots_.first.empty())
return { 0, {} };
if (npc.getClass().isNpc())
{
const ESM::RefId& npcRace = npc.get<ESM::NPC>()->mBase->mRace;
// Beast races cannot equip shoes / boots, or full helms (head part vs hair part)
const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(npcRace);
if (race->mData.mFlags & ESM::Race::Beast)
{
std::vector<ESM::PartReference> parts = ptr.get<ESM::Clothing>()->mBase->mParts.mParts;
for (std::vector<ESM::PartReference>::iterator itr = parts.begin(); itr != parts.end(); ++itr)
{
if ((*itr).mPart == ESM::PRT_Head)
return { 0, "#{sNotifyMessage13}" };
if ((*itr).mPart == ESM::PRT_LFoot || (*itr).mPart == ESM::PRT_RFoot)
return { 0, "#{sNotifyMessage15}" };
}
}
}
return { 1, {} };
}
std::unique_ptr<MWWorld::Action> Clothing::use(const MWWorld::Ptr& ptr, bool force) const
{
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::ActionEquip>(ptr, force);
action->setSound(getUpSoundId(ptr));
return action;
}
MWWorld::Ptr Clothing::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
int Clothing::getEnchantmentPoints(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
return ref->mBase->mData.mEnchant;
}
bool Clothing::canSell(const MWWorld::ConstPtr& item, int npcServices) const
{
return (npcServices & ESM::NPC::Clothing)
|| ((npcServices & ESM::NPC::MagicItems) && !getEnchantment(item).empty());
}
float Clothing::getWeight(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Clothing>* ref = ptr.get<ESM::Clothing>();
return ref->mBase->mData.mWeight;
}
}
| 9,393
|
C++
|
.cpp
| 209
| 36.344498
| 120
| 0.622261
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,454
|
container.cpp
|
OpenMW_openmw/apps/openmw/mwclass/container.cpp
|
#include "container.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/containerstate.hpp>
#include <components/esm3/loadcont.hpp>
#include <components/esm3/loadsoun.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwphysics/physicssystem.hpp"
#include "../mwworld/actionharvest.hpp"
#include "../mwworld/actionopen.hpp"
#include "../mwworld/actiontrap.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/failedaction.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/nullaction.hpp"
#include "../mwworld/worldmodel.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwrender/animation.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwmechanics/inventory.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
ContainerCustomData::ContainerCustomData(const ESM::Container& container, MWWorld::CellStore* cell)
{
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
unsigned int seed = Misc::Rng::rollDice(std::numeric_limits<int>::max(), prng);
// setting ownership not needed, since taking items from a container inherits the
// container's owner automatically
mStore.fillNonRandom(container.mInventory, ESM::RefId(), seed);
}
ContainerCustomData::ContainerCustomData(const ESM::InventoryState& inventory)
{
mStore.readState(inventory);
}
ContainerCustomData& ContainerCustomData::asContainerCustomData()
{
return *this;
}
const ContainerCustomData& ContainerCustomData::asContainerCustomData() const
{
return *this;
}
Container::Container()
: MWWorld::RegisteredClass<Container>(ESM::Container::sRecordId)
{
}
void Container::ensureCustomData(const MWWorld::Ptr& ptr) const
{
if (!ptr.getRefData().getCustomData())
{
MWBase::Environment::get().getWorldModel()->registerPtr(ptr);
MWWorld::LiveCellRef<ESM::Container>* ref = ptr.get<ESM::Container>();
// store
ptr.getRefData().setCustomData(std::make_unique<ContainerCustomData>(*ref->mBase, ptr.getCell()));
getContainerStore(ptr).setPtr(ptr);
MWBase::Environment::get().getWorld()->addContainerScripts(ptr, ptr.getCell());
}
}
bool Container::canBeHarvested(const MWWorld::ConstPtr& ptr) const
{
if (!Settings::game().mGraphicHerbalism)
return false;
const MWRender::Animation* animation = MWBase::Environment::get().getWorld()->getAnimation(ptr);
if (animation == nullptr)
return false;
return animation->canBeHarvested();
}
void Container::respawn(const MWWorld::Ptr& ptr) const
{
MWWorld::LiveCellRef<ESM::Container>* ref = ptr.get<ESM::Container>();
if (ref->mBase->mFlags & ESM::Container::Respawn)
{
// Container was not touched, there is no need to modify its content.
if (ptr.getRefData().getCustomData() == nullptr)
return;
MWBase::Environment::get().getWorld()->removeContainerScripts(ptr);
ptr.getRefData().setCustomData(nullptr);
}
}
void Container::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
void Container::insertObject(const MWWorld::Ptr& ptr, const std::string& model, const osg::Quat& rotation,
MWPhysics::PhysicsSystem& physics) const
{
insertObjectPhysics(ptr, model, rotation, physics);
}
void Container::insertObjectPhysics(const MWWorld::Ptr& ptr, const std::string& model, const osg::Quat& rotation,
MWPhysics::PhysicsSystem& physics) const
{
physics.addObject(ptr, VFS::Path::toNormalized(model), rotation, MWPhysics::CollisionType_World);
}
std::string_view Container::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Container>(ptr);
}
bool Container::useAnim() const
{
return true;
}
std::unique_ptr<MWWorld::Action> Container::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
if (!MWBase::Environment::get().getWindowManager()->isAllowed(MWGui::GW_Inventory))
return std::make_unique<MWWorld::NullAction>();
if (actor.getClass().isNpc() && actor.getClass().getNpcStats(actor).isWerewolf())
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
const ESM::Sound* sound = store.get<ESM::Sound>().searchRandom("WolfContainer", prng);
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::FailedAction>("#{sWerewolfRefusal}");
if (sound)
action->setSound(sound->mId);
return action;
}
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
MWWorld::InventoryStore& invStore = player.getClass().getInventoryStore(player);
bool isLocked = ptr.getCellRef().isLocked();
bool isTrapped = !ptr.getCellRef().getTrap().empty();
bool hasKey = false;
std::string_view keyName;
const ESM::RefId& keyId = ptr.getCellRef().getKey();
if (!keyId.empty())
{
MWWorld::Ptr keyPtr = invStore.search(keyId);
if (!keyPtr.isEmpty())
{
hasKey = true;
keyName = keyPtr.getClass().getName(keyPtr);
}
}
if (isLocked && hasKey)
{
MWBase::Environment::get().getWindowManager()->messageBox(std::string{ keyName } + " #{sKeyUsed}");
ptr.getCellRef().unlock();
// using a key disarms the trap
if (isTrapped)
{
ptr.getCellRef().setTrap(ESM::RefId());
MWBase::Environment::get().getSoundManager()->playSound3D(
ptr, ESM::RefId::stringRefId("Disarm Trap"), 1.0f, 1.0f);
isTrapped = false;
}
}
if (!isLocked || hasKey)
{
if (!isTrapped)
{
if (canBeHarvested(ptr))
{
return std::make_unique<MWWorld::ActionHarvest>(ptr);
}
return std::make_unique<MWWorld::ActionOpen>(ptr);
}
else
{
// Activate trap
std::unique_ptr<MWWorld::Action> action
= std::make_unique<MWWorld::ActionTrap>(ptr.getCellRef().getTrap(), ptr);
action->setSound(ESM::RefId::stringRefId("Disarm Trap Fail"));
return action;
}
}
else
{
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::FailedAction>(std::string_view{}, ptr);
action->setSound(ESM::RefId::stringRefId("LockedChest"));
return action;
}
}
std::string_view Container::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Container>(ptr);
}
MWWorld::ContainerStore& Container::getContainerStore(const MWWorld::Ptr& ptr) const
{
ensureCustomData(ptr);
return ptr.getRefData().getCustomData()->asContainerCustomData().mStore;
}
ESM::RefId Container::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Container>* ref = ptr.get<ESM::Container>();
return ref->mBase->mScript;
}
bool Container::hasToolTip(const MWWorld::ConstPtr& ptr) const
{
if (const MWWorld::CustomData* data = ptr.getRefData().getCustomData())
return !canBeHarvested(ptr) || data->asContainerCustomData().mStore.hasVisibleItems();
return true;
}
MWGui::ToolTipInfo Container::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Container>* ref = ptr.get<ESM::Container>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name));
std::string text;
int lockLevel = ptr.getCellRef().getLockLevel();
if (lockLevel)
{
if (ptr.getCellRef().isLocked())
text += "\n#{sLockLevel}: " + MWGui::ToolTips::toString(lockLevel);
else
text += "\n#{sUnlocked}";
}
if (ptr.getCellRef().getTrap() != ESM::RefId())
text += "\n#{sTrapped}";
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
if (ptr.getCellRef().getRefId() == "stolen_goods")
info.extra += "\nYou cannot use evidence chests";
}
info.text = std::move(text);
return info;
}
float Container::getCapacity(const MWWorld::Ptr& ptr) const
{
MWWorld::LiveCellRef<ESM::Container>* ref = ptr.get<ESM::Container>();
return ref->mBase->mWeight;
}
float Container::getEncumbrance(const MWWorld::Ptr& ptr) const
{
return getContainerStore(ptr).getWeight();
}
bool Container::canLock(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Container>* ref = ptr.get<ESM::Container>();
return !(ref->mBase->mFlags & ESM::Container::Organic);
}
void Container::modifyBaseInventory(const ESM::RefId& containerId, const ESM::RefId& itemId, int amount) const
{
MWMechanics::modifyBaseInventory<ESM::Container>(containerId, itemId, amount);
}
MWWorld::Ptr Container::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Container>* ref = ptr.get<ESM::Container>();
MWWorld::Ptr newPtr(cell.insert(ref), &cell);
if (newPtr.getRefData().getCustomData())
{
MWBase::Environment::get().getWorldModel()->registerPtr(newPtr);
getContainerStore(newPtr).setPtr(newPtr);
}
return newPtr;
}
void Container::readAdditionalState(const MWWorld::Ptr& ptr, const ESM::ObjectState& state) const
{
if (!state.mHasCustomState)
return;
const ESM::ContainerState& containerState = state.asContainerState();
ptr.getRefData().setCustomData(std::make_unique<ContainerCustomData>(containerState.mInventory));
MWBase::Environment::get().getWorldModel()->registerPtr(ptr);
getContainerStore(ptr).setPtr(ptr);
}
void Container::writeAdditionalState(const MWWorld::ConstPtr& ptr, ESM::ObjectState& state) const
{
if (!ptr.getRefData().getCustomData())
{
state.mHasCustomState = false;
return;
}
const ContainerCustomData& customData = ptr.getRefData().getCustomData()->asContainerCustomData();
if (!customData.mStore.isResolved())
{
state.mHasCustomState = false;
return;
}
ESM::ContainerState& containerState = state.asContainerState();
customData.mStore.writeState(containerState.mInventory);
}
}
| 11,947
|
C++
|
.cpp
| 285
| 33.336842
| 119
| 0.631969
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,455
|
static.cpp
|
OpenMW_openmw/apps/openmw/mwclass/static.cpp
|
#include "static.hpp"
#include <components/esm3/loadstat.hpp>
#include <components/esm4/loadstat.hpp>
#include <components/sceneutil/positionattitudetransform.hpp>
#include "../mwphysics/physicssystem.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwrender/vismask.hpp"
#include "classmodel.hpp"
namespace MWClass
{
Static::Static()
: MWWorld::RegisteredClass<Static>(ESM::Static::sRecordId)
{
}
void Static::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
ptr.getRefData().getBaseNode()->setNodeMask(MWRender::Mask_Static);
}
}
void Static::insertObject(const MWWorld::Ptr& ptr, const std::string& model, const osg::Quat& rotation,
MWPhysics::PhysicsSystem& physics) const
{
insertObjectPhysics(ptr, model, rotation, physics);
}
void Static::insertObjectPhysics(const MWWorld::Ptr& ptr, const std::string& model, const osg::Quat& rotation,
MWPhysics::PhysicsSystem& physics) const
{
physics.addObject(ptr, VFS::Path::toNormalized(model), rotation, MWPhysics::CollisionType_World);
}
std::string_view Static::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Static>(ptr);
}
std::string_view Static::getName(const MWWorld::ConstPtr& ptr) const
{
return {};
}
bool Static::hasToolTip(const MWWorld::ConstPtr& ptr) const
{
return false;
}
MWWorld::Ptr Static::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Static>* ref = ptr.get<ESM::Static>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
}
| 2,007
|
C++
|
.cpp
| 54
| 31.62963
| 114
| 0.690722
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,456
|
esm4npc.cpp
|
OpenMW_openmw/apps/openmw/mwclass/esm4npc.cpp
|
#include "esm4npc.hpp"
#include <components/esm4/loadarmo.hpp>
#include <components/esm4/loadclot.hpp>
#include <components/esm4/loadlvli.hpp>
#include <components/esm4/loadlvln.hpp>
#include <components/esm4/loadnpc.hpp>
#include <components/esm4/loadotft.hpp>
#include <components/esm4/loadrace.hpp>
#include <components/misc/resourcehelpers.hpp>
#include "../mwworld/customdata.hpp"
#include "../mwworld/esmstore.hpp"
#include "esm4base.hpp"
namespace MWClass
{
template <class LevelledRecord, class TargetRecord>
static std::vector<const TargetRecord*> withBaseTemplates(
const TargetRecord* rec, int level = MWClass::ESM4Impl::sDefaultLevel)
{
std::vector<const TargetRecord*> res{ rec };
while (true)
{
const TargetRecord* newRec
= MWClass::ESM4Impl::resolveLevelled<ESM4::LevelledNpc, ESM4::Npc>(rec->mBaseTemplate, level);
if (!newRec || newRec == rec)
return res;
res.push_back(rec = newRec);
}
}
static const ESM4::Npc* chooseTemplate(const std::vector<const ESM4::Npc*>& recs, uint16_t flag)
{
for (const auto* rec : recs)
{
if (rec->mIsTES4)
return rec;
else if (rec->mIsFONV)
{
// TODO: FO3 should use this branch as well. But it is not clear how to distinguish FO3 from
// TES5. Currently FO3 uses wrong template flags that can lead to "ESM4 NPC traits not found"
// exception the NPC will not be added to the scene. But in any way it shouldn't cause a crash.
if (!(rec->mBaseConfig.fo3.templateFlags & flag))
return rec;
}
else if (rec->mIsFO4)
{
if (!(rec->mBaseConfig.fo4.templateFlags & flag))
return rec;
}
else if (!(rec->mBaseConfig.tes5.templateFlags & flag))
return rec;
}
return nullptr;
}
class ESM4NpcCustomData : public MWWorld::TypedCustomData<ESM4NpcCustomData>
{
public:
const ESM4::Npc* mTraits;
const ESM4::Npc* mBaseData;
const ESM4::Race* mRace;
bool mIsFemale;
// TODO: Use InventoryStore instead (currently doesn't support ESM4 objects)
std::vector<const ESM4::Armor*> mEquippedArmor;
std::vector<const ESM4::Clothing*> mEquippedClothing;
ESM4NpcCustomData& asESM4NpcCustomData() override { return *this; }
const ESM4NpcCustomData& asESM4NpcCustomData() const override { return *this; }
};
ESM4NpcCustomData& ESM4Npc::getCustomData(const MWWorld::ConstPtr& ptr)
{
// Note: the argument is ConstPtr because this function is used in `getModel` and `getName`
// which are virtual and work with ConstPtr. `getModel` and `getName` use custom data
// because they require a lot of work including levelled records resolving and it would be
// stupid to not to cache the results. Maybe we should stop using ConstPtr at all
// to avoid such workarounds.
MWWorld::RefData& refData = const_cast<MWWorld::RefData&>(ptr.getRefData());
if (auto* data = refData.getCustomData())
return data->asESM4NpcCustomData();
auto data = std::make_unique<ESM4NpcCustomData>();
const MWWorld::ESMStore* store = MWBase::Environment::get().getESMStore();
const ESM4::Npc* const base = ptr.get<ESM4::Npc>()->mBase;
auto npcRecs = withBaseTemplates<ESM4::LevelledNpc, ESM4::Npc>(base);
data->mTraits = chooseTemplate(npcRecs, ESM4::Npc::Template_UseTraits);
if (data->mTraits == nullptr)
Log(Debug::Warning) << "Traits are not found for ESM4 NPC base record: \"" << base->mEditorId << "\" ("
<< ESM::RefId(base->mId) << ")";
data->mBaseData = chooseTemplate(npcRecs, ESM4::Npc::Template_UseBaseData);
if (data->mBaseData == nullptr)
Log(Debug::Warning) << "Base data is not found for ESM4 NPC base record: \"" << base->mEditorId << "\" ("
<< ESM::RefId(base->mId) << ")";
if (data->mTraits != nullptr)
{
data->mRace = store->get<ESM4::Race>().find(data->mTraits->mRace);
if (data->mTraits->mIsTES4)
data->mIsFemale = data->mTraits->mBaseConfig.tes4.flags & ESM4::Npc::TES4_Female;
else if (data->mTraits->mIsFONV)
data->mIsFemale = data->mTraits->mBaseConfig.fo3.flags & ESM4::Npc::FO3_Female;
else if (data->mTraits->mIsFO4)
data->mIsFemale
= data->mTraits->mBaseConfig.fo4.flags & ESM4::Npc::TES5_Female; // FO4 flags are the same as TES5
else
data->mIsFemale = data->mTraits->mBaseConfig.tes5.flags & ESM4::Npc::TES5_Female;
}
if (auto inv = chooseTemplate(npcRecs, ESM4::Npc::Template_UseInventory))
{
for (const ESM4::InventoryItem& item : inv->mInventory)
{
if (auto* armor
= ESM4Impl::resolveLevelled<ESM4::LevelledItem, ESM4::Armor>(ESM::FormId::fromUint32(item.item)))
data->mEquippedArmor.push_back(armor);
else if (data->mTraits != nullptr && data->mTraits->mIsTES4)
{
const auto* clothing = ESM4Impl::resolveLevelled<ESM4::LevelledItem, ESM4::Clothing>(
ESM::FormId::fromUint32(item.item));
if (clothing)
data->mEquippedClothing.push_back(clothing);
}
}
if (!inv->mDefaultOutfit.isZeroOrUnset())
{
if (const ESM4::Outfit* outfit = store->get<ESM4::Outfit>().search(inv->mDefaultOutfit))
{
for (ESM::FormId itemId : outfit->mInventory)
if (auto* armor = ESM4Impl::resolveLevelled<ESM4::LevelledItem, ESM4::Armor>(itemId))
data->mEquippedArmor.push_back(armor);
}
else
Log(Debug::Error) << "Outfit not found: " << ESM::RefId(inv->mDefaultOutfit);
}
}
ESM4NpcCustomData& res = *data;
refData.setCustomData(std::move(data));
return res;
}
const std::vector<const ESM4::Armor*>& ESM4Npc::getEquippedArmor(const MWWorld::Ptr& ptr)
{
return getCustomData(ptr).mEquippedArmor;
}
const std::vector<const ESM4::Clothing*>& ESM4Npc::getEquippedClothing(const MWWorld::Ptr& ptr)
{
return getCustomData(ptr).mEquippedClothing;
}
const ESM4::Npc* ESM4Npc::getTraitsRecord(const MWWorld::Ptr& ptr)
{
return getCustomData(ptr).mTraits;
}
const ESM4::Race* ESM4Npc::getRace(const MWWorld::Ptr& ptr)
{
return getCustomData(ptr).mRace;
}
bool ESM4Npc::isFemale(const MWWorld::Ptr& ptr)
{
return getCustomData(ptr).mIsFemale;
}
std::string_view ESM4Npc::getModel(const MWWorld::ConstPtr& ptr) const
{
const ESM4NpcCustomData& data = getCustomData(ptr);
if (data.mTraits == nullptr)
return {};
if (data.mTraits->mIsTES4)
return data.mTraits->mModel;
return data.mIsFemale ? data.mRace->mModelFemale : data.mRace->mModelMale;
}
std::string_view ESM4Npc::getName(const MWWorld::ConstPtr& ptr) const
{
const ESM4::Npc* const baseData = getCustomData(ptr).mBaseData;
if (baseData == nullptr)
return {};
return baseData->mFullName;
}
}
| 7,742
|
C++
|
.cpp
| 168
| 35.470238
| 118
| 0.602756
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,457
|
door.cpp
|
OpenMW_openmw/apps/openmw/mwclass/door.cpp
|
#include "door.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/doorstate.hpp>
#include <components/esm3/loaddoor.hpp>
#include <components/esm3/loadmgef.hpp>
#include <components/sceneutil/positionattitudetransform.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwphysics/physicssystem.hpp"
#include "../mwworld/actiondoor.hpp"
#include "../mwworld/actionteleport.hpp"
#include "../mwworld/actiontrap.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/customdata.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/failedaction.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwworld/worldmodel.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwrender/animation.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwrender/vismask.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
class DoorCustomData : public MWWorld::TypedCustomData<DoorCustomData>
{
public:
MWWorld::DoorState mDoorState = MWWorld::DoorState::Idle;
DoorCustomData& asDoorCustomData() override { return *this; }
const DoorCustomData& asDoorCustomData() const override { return *this; }
};
Door::Door()
: MWWorld::RegisteredClass<Door>(ESM::Door::sRecordId)
{
}
void Door::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
ptr.getRefData().getBaseNode()->setNodeMask(MWRender::Mask_Static);
}
}
void Door::insertObject(const MWWorld::Ptr& ptr, const std::string& model, const osg::Quat& rotation,
MWPhysics::PhysicsSystem& physics) const
{
insertObjectPhysics(ptr, model, rotation, physics);
// Resume the door's opening/closing animation if it wasn't finished
if (ptr.getRefData().getCustomData())
{
const DoorCustomData& customData = ptr.getRefData().getCustomData()->asDoorCustomData();
if (customData.mDoorState != MWWorld::DoorState::Idle)
{
MWBase::Environment::get().getWorld()->activateDoor(ptr, customData.mDoorState);
}
}
}
void Door::insertObjectPhysics(const MWWorld::Ptr& ptr, const std::string& model, const osg::Quat& rotation,
MWPhysics::PhysicsSystem& physics) const
{
physics.addObject(ptr, VFS::Path::toNormalized(model), rotation, MWPhysics::CollisionType_Door);
}
bool Door::isDoor() const
{
return true;
}
bool Door::useAnim() const
{
return true;
}
std::string_view Door::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Door>(ptr);
}
std::string_view Door::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Door>(ptr);
}
std::unique_ptr<MWWorld::Action> Door::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
MWWorld::LiveCellRef<ESM::Door>* ref = ptr.get<ESM::Door>();
const ESM::RefId& openSound = ref->mBase->mOpenSound;
const ESM::RefId& closeSound = ref->mBase->mCloseSound;
const ESM::RefId lockedSound = ESM::RefId::stringRefId("LockedDoor");
// FIXME: If NPC activate teleporting door, it can lead to crash due to iterator invalidation in the Actors
// update. Make such activation a no-op for now, like how it is in the vanilla game.
if (actor != MWMechanics::getPlayer() && ptr.getCellRef().getTeleport())
{
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::FailedAction>(std::string_view{}, ptr);
action->setSound(lockedSound);
return action;
}
// make door glow if player activates it with telekinesis
if (actor == MWMechanics::getPlayer()
&& MWBase::Environment::get().getWorld()->getDistanceToFacedObject()
> MWBase::Environment::get().getWorld()->getMaxActivationDistance())
{
MWRender::Animation* animation = MWBase::Environment::get().getWorld()->getAnimation(ptr);
if (animation)
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
const ESM::MagicEffect* effect = store.get<ESM::MagicEffect>().find(ESM::MagicEffect::Telekinesis);
animation->addSpellCastGlow(
effect->getColor(), 1); // 1 second glow to match the time taken for a door opening or closing
}
}
MWWorld::ContainerStore& invStore = actor.getClass().getContainerStore(actor);
bool isLocked = ptr.getCellRef().isLocked();
bool isTrapped = !ptr.getCellRef().getTrap().empty();
bool hasKey = false;
std::string_view keyName;
const ESM::RefId& keyId = ptr.getCellRef().getKey();
if (!keyId.empty())
{
MWWorld::Ptr keyPtr = invStore.search(keyId);
if (!keyPtr.isEmpty())
{
hasKey = true;
keyName = keyPtr.getClass().getName(keyPtr);
}
}
if (isLocked && hasKey)
{
if (actor == MWMechanics::getPlayer())
MWBase::Environment::get().getWindowManager()->messageBox(std::string{ keyName } + " #{sKeyUsed}");
ptr.getCellRef().unlock(); // Call the function here. because that makes sense.
// using a key disarms the trap
if (isTrapped)
{
ptr.getCellRef().setTrap(ESM::RefId());
MWBase::Environment::get().getSoundManager()->playSound3D(
ptr, ESM::RefId::stringRefId("Disarm Trap"), 1.0f, 1.0f);
isTrapped = false;
}
}
if (!isLocked || hasKey)
{
if (isTrapped)
{
// Trap activation
std::unique_ptr<MWWorld::Action> action
= std::make_unique<MWWorld::ActionTrap>(ptr.getCellRef().getTrap(), ptr);
action->setSound(ESM::RefId::stringRefId("Disarm Trap Fail"));
return action;
}
if (ptr.getCellRef().getTeleport())
{
if (actor == MWMechanics::getPlayer()
&& MWBase::Environment::get().getWorld()->getDistanceToFacedObject()
> MWBase::Environment::get().getWorld()->getMaxActivationDistance())
{
// player activated teleport door with telekinesis
return std::make_unique<MWWorld::FailedAction>();
}
else
{
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::ActionTeleport>(
ptr.getCellRef().getDestCell(), ptr.getCellRef().getDoorDest(), true);
action->setSound(openSound);
return action;
}
}
else
{
// animated door
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::ActionDoor>(ptr);
const auto doorState = getDoorState(ptr);
bool opening = true;
float doorRot = ptr.getRefData().getPosition().rot[2] - ptr.getCellRef().getPosition().rot[2];
if (doorState == MWWorld::DoorState::Opening)
opening = false;
if (doorState == MWWorld::DoorState::Idle && doorRot != 0)
opening = false;
if (opening)
{
MWBase::Environment::get().getSoundManager()->fadeOutSound3D(ptr, closeSound, 0.5f);
// Doors rotate at 90 degrees per second, so start the sound at
// where it would be at the current rotation.
float offset = doorRot / (osg::PI * 0.5f);
action->setSoundOffset(offset);
action->setSound(openSound);
}
else
{
MWBase::Environment::get().getSoundManager()->fadeOutSound3D(ptr, openSound, 0.5f);
float offset = 1.0f - doorRot / (osg::PI * 0.5f);
action->setSoundOffset(std::max(offset, 0.0f));
action->setSound(closeSound);
}
return action;
}
}
else
{
// locked, and we can't open.
std::unique_ptr<MWWorld::Action> action = std::make_unique<MWWorld::FailedAction>(std::string_view{}, ptr);
action->setSound(lockedSound);
return action;
}
}
bool Door::canLock(const MWWorld::ConstPtr& ptr) const
{
return true;
}
bool Door::allowTelekinesis(const MWWorld::ConstPtr& ptr) const
{
if (ptr.getCellRef().getTeleport() && !ptr.getCellRef().isLocked() && ptr.getCellRef().getTrap().empty())
return false;
else
return true;
}
ESM::RefId Door::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Door>* ref = ptr.get<ESM::Door>();
return ref->mBase->mScript;
}
MWGui::ToolTipInfo Door::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Door>* ref = ptr.get<ESM::Door>();
MWGui::ToolTipInfo info;
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name));
std::string text;
if (ptr.getCellRef().getTeleport())
{
text += "\n#{sTo}";
text += "\n" + getDestination(*ref);
}
int lockLevel = ptr.getCellRef().getLockLevel();
if (lockLevel)
{
if (ptr.getCellRef().isLocked())
text += "\n#{sLockLevel}: " + MWGui::ToolTips::toString(lockLevel);
else
text += "\n#{sUnlocked}";
}
if (!ptr.getCellRef().getTrap().empty())
text += "\n#{sTrapped}";
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
info.text = std::move(text);
return info;
}
std::string Door::getDestination(const MWWorld::LiveCellRef<ESM::Door>& door)
{
std::string_view dest = MWBase::Environment::get().getWorld()->getCellName(
&MWBase::Environment::get().getWorldModel()->getCell(door.mRef.getDestCell()));
return "#{sCell=" + std::string{ dest } + "}";
}
MWWorld::Ptr Door::copyToCellImpl(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell) const
{
const MWWorld::LiveCellRef<ESM::Door>* ref = ptr.get<ESM::Door>();
return MWWorld::Ptr(cell.insert(ref), &cell);
}
void Door::ensureCustomData(const MWWorld::Ptr& ptr) const
{
if (!ptr.getRefData().getCustomData())
{
ptr.getRefData().setCustomData(std::make_unique<DoorCustomData>());
}
}
MWWorld::DoorState Door::getDoorState(const MWWorld::ConstPtr& ptr) const
{
if (!ptr.getRefData().getCustomData())
return MWWorld::DoorState::Idle;
const DoorCustomData& customData = ptr.getRefData().getCustomData()->asDoorCustomData();
return customData.mDoorState;
}
void Door::setDoorState(const MWWorld::Ptr& ptr, MWWorld::DoorState state) const
{
if (ptr.getCellRef().getTeleport())
throw std::runtime_error("load doors can't be moved");
ensureCustomData(ptr);
DoorCustomData& customData = ptr.getRefData().getCustomData()->asDoorCustomData();
customData.mDoorState = state;
}
void Door::readAdditionalState(const MWWorld::Ptr& ptr, const ESM::ObjectState& state) const
{
if (!state.mHasCustomState)
return;
ensureCustomData(ptr);
DoorCustomData& customData = ptr.getRefData().getCustomData()->asDoorCustomData();
const ESM::DoorState& doorState = state.asDoorState();
customData.mDoorState = MWWorld::DoorState(doorState.mDoorState);
}
void Door::writeAdditionalState(const MWWorld::ConstPtr& ptr, ESM::ObjectState& state) const
{
if (!ptr.getRefData().getCustomData())
{
state.mHasCustomState = false;
return;
}
const DoorCustomData& customData = ptr.getRefData().getCustomData()->asDoorCustomData();
ESM::DoorState& doorState = state.asDoorState();
doorState.mDoorState = int(customData.mDoorState);
}
}
| 13,298
|
C++
|
.cpp
| 309
| 32.977346
| 119
| 0.598887
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,458
|
misc.cpp
|
OpenMW_openmw/apps/openmw/mwclass/misc.cpp
|
#include "misc.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadcrea.hpp>
#include <components/esm3/loadmisc.hpp>
#include <components/esm3/loadnpc.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/actionsoulgem.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/manualref.hpp"
#include "../mwworld/nullaction.hpp"
#include "../mwworld/worldmodel.hpp"
#include "../mwgui/tooltips.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "classmodel.hpp"
#include "nameorid.hpp"
namespace MWClass
{
Miscellaneous::Miscellaneous()
: MWWorld::RegisteredClass<Miscellaneous>(ESM::Miscellaneous::sRecordId)
{
}
bool Miscellaneous::isGold(const MWWorld::ConstPtr& ptr) const
{
return ptr.getCellRef().getRefId() == "gold_001" || ptr.getCellRef().getRefId() == "gold_005"
|| ptr.getCellRef().getRefId() == "gold_010" || ptr.getCellRef().getRefId() == "gold_025"
|| ptr.getCellRef().getRefId() == "gold_100";
}
void Miscellaneous::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
}
}
std::string_view Miscellaneous::getModel(const MWWorld::ConstPtr& ptr) const
{
return getClassModel<ESM::Miscellaneous>(ptr);
}
std::string_view Miscellaneous::getName(const MWWorld::ConstPtr& ptr) const
{
return getNameOrId<ESM::Miscellaneous>(ptr);
}
std::unique_ptr<MWWorld::Action> Miscellaneous::activate(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const
{
return defaultItemActivate(ptr, actor);
}
ESM::RefId Miscellaneous::getScript(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Miscellaneous>* ref = ptr.get<ESM::Miscellaneous>();
return ref->mBase->mScript;
}
int Miscellaneous::getValue(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Miscellaneous>* ref = ptr.get<ESM::Miscellaneous>();
int value = ref->mBase->mData.mValue;
if (isGold(ptr) && ptr.getCellRef().getCount() != 1)
value = 1;
if (!ptr.getCellRef().getSoul().empty())
{
const ESM::Creature* creature
= MWBase::Environment::get().getESMStore()->get<ESM::Creature>().search(ref->mRef.getSoul());
if (creature)
{
int soul = creature->mData.mSoul;
if (Settings::game().mRebalanceSoulGemValues)
{
// use the 'soul gem value rebalance' formula from the Morrowind Code Patch
float soulValue = 0.0001 * pow(soul, 3) + 2 * soul;
// for Azura's star add the unfilled value
if (ptr.getCellRef().getRefId() == "Misc_SoulGem_Azura")
value += soulValue;
else
value = soulValue;
}
else
value *= soul;
}
}
return value;
}
const ESM::RefId& Miscellaneous::getUpSoundId(const MWWorld::ConstPtr& ptr) const
{
static const ESM::RefId soundGold = ESM::RefId::stringRefId("Item Gold Up");
static const ESM::RefId soundMisc = ESM::RefId::stringRefId("Item Misc Up");
if (isGold(ptr))
return soundGold;
return soundMisc;
}
const ESM::RefId& Miscellaneous::getDownSoundId(const MWWorld::ConstPtr& ptr) const
{
static const ESM::RefId soundGold = ESM::RefId::stringRefId("Item Gold Down");
static const ESM::RefId soundMisc = ESM::RefId::stringRefId("Item Misc Down");
if (isGold(ptr))
return soundGold;
return soundMisc;
}
const std::string& Miscellaneous::getInventoryIcon(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Miscellaneous>* ref = ptr.get<ESM::Miscellaneous>();
return ref->mBase->mIcon;
}
MWGui::ToolTipInfo Miscellaneous::getToolTipInfo(const MWWorld::ConstPtr& ptr, int count) const
{
const MWWorld::LiveCellRef<ESM::Miscellaneous>* ref = ptr.get<ESM::Miscellaneous>();
MWGui::ToolTipInfo info;
bool gold = isGold(ptr);
if (gold)
count *= getValue(ptr);
std::string countString;
if (!gold)
countString = MWGui::ToolTips::getCountString(count);
else // gold displays its count also if it's 1.
countString = " (" + std::to_string(count) + ")";
std::string_view name = getName(ptr);
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count)
+ MWGui::ToolTips::getSoulString(ptr.getCellRef());
info.icon = ref->mBase->mIcon;
std::string text;
text += MWGui::ToolTips::getWeightString(ref->mBase->mData.mWeight, "#{sWeight}");
if (!gold && !(ref->mBase->mData.mFlags & ESM::Miscellaneous::Key))
text += MWGui::ToolTips::getValueString(getValue(ptr), "#{sValue}");
if (MWBase::Environment::get().getWindowManager()->getFullHelp())
{
info.extra += MWGui::ToolTips::getCellRefString(ptr.getCellRef());
info.extra += MWGui::ToolTips::getMiscString(ref->mBase->mScript.getRefIdString(), "Script");
}
info.text = std::move(text);
return info;
}
static MWWorld::Ptr createGold(MWWorld::CellStore& cell, int goldAmount)
{
std::string_view base = "gold_001";
if (goldAmount >= 100)
base = "gold_100";
else if (goldAmount >= 25)
base = "gold_025";
else if (goldAmount >= 10)
base = "gold_010";
else if (goldAmount >= 5)
base = "gold_005";
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
MWWorld::ManualRef newRef(store, ESM::RefId::stringRefId(base));
const MWWorld::LiveCellRef<ESM::Miscellaneous>* ref = newRef.getPtr().get<ESM::Miscellaneous>();
MWWorld::Ptr ptr(cell.insert(ref), &cell);
ptr.getCellRef().setCount(goldAmount);
return ptr;
}
MWWorld::Ptr Miscellaneous::copyToCell(const MWWorld::ConstPtr& ptr, MWWorld::CellStore& cell, int count) const
{
MWWorld::Ptr newPtr;
if (isGold(ptr))
newPtr = createGold(cell, getValue(ptr) * count);
else
{
const MWWorld::LiveCellRef<ESM::Miscellaneous>* ref = ptr.get<ESM::Miscellaneous>();
newPtr = MWWorld::Ptr(cell.insert(ref), &cell);
newPtr.getCellRef().setCount(count);
}
newPtr.getCellRef().unsetRefNum();
newPtr.getRefData().setLuaScripts(nullptr);
MWBase::Environment::get().getWorldModel()->registerPtr(newPtr);
return newPtr;
}
MWWorld::Ptr Miscellaneous::moveToCell(const MWWorld::Ptr& ptr, MWWorld::CellStore& cell) const
{
MWWorld::Ptr newPtr;
if (isGold(ptr))
{
newPtr = createGold(cell, getValue(ptr) * ptr.getCellRef().getCount());
newPtr.getRefData() = ptr.getRefData();
newPtr.getCellRef().setRefNum(ptr.getCellRef().getRefNum());
}
else
{
const MWWorld::LiveCellRef<ESM::Miscellaneous>* ref = ptr.get<ESM::Miscellaneous>();
newPtr = MWWorld::Ptr(cell.insert(ref), &cell);
}
ptr.getRefData().setLuaScripts(nullptr);
MWBase::Environment::get().getWorldModel()->registerPtr(newPtr);
return newPtr;
}
std::unique_ptr<MWWorld::Action> Miscellaneous::use(const MWWorld::Ptr& ptr, bool force) const
{
if (isSoulGem(ptr))
return std::make_unique<MWWorld::ActionSoulgem>(ptr);
return std::make_unique<MWWorld::NullAction>();
}
bool Miscellaneous::canSell(const MWWorld::ConstPtr& item, int npcServices) const
{
const MWWorld::LiveCellRef<ESM::Miscellaneous>* ref = item.get<ESM::Miscellaneous>();
return !(ref->mBase->mData.mFlags & ESM::Miscellaneous::Key) && (npcServices & ESM::NPC::Misc) && !isGold(item);
}
float Miscellaneous::getWeight(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Miscellaneous>* ref = ptr.get<ESM::Miscellaneous>();
return ref->mBase->mData.mWeight;
}
bool Miscellaneous::isKey(const MWWorld::ConstPtr& ptr) const
{
const MWWorld::LiveCellRef<ESM::Miscellaneous>* ref = ptr.get<ESM::Miscellaneous>();
return ref->mBase->mData.mFlags & ESM::Miscellaneous::Key;
}
bool Miscellaneous::isSoulGem(const MWWorld::ConstPtr& ptr) const
{
return ptr.getCellRef().getRefId().startsWith("misc_soulgem");
}
}
| 9,179
|
C++
|
.cpp
| 213
| 34.558685
| 120
| 0.626444
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,460
|
esm4base.cpp
|
OpenMW_openmw/apps/openmw/mwclass/esm4base.cpp
|
#include "esm4base.hpp"
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/sceneutil/positionattitudetransform.hpp>
#include "../mwgui/tooltips.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
#include "../mwrender/vismask.hpp"
#include "../mwphysics/physicssystem.hpp"
#include "../mwworld/ptr.hpp"
namespace MWClass
{
void ESM4Impl::insertObjectRendering(
const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface)
{
if (!model.empty())
{
renderingInterface.getObjects().insertModel(ptr, model);
ptr.getRefData().getBaseNode()->setNodeMask(MWRender::Mask_Static);
}
}
void ESM4Impl::insertObjectPhysics(
const MWWorld::Ptr& ptr, const std::string& model, const osg::Quat& rotation, MWPhysics::PhysicsSystem& physics)
{
physics.addObject(ptr, VFS::Path::toNormalized(model), rotation, MWPhysics::CollisionType_World);
}
MWGui::ToolTipInfo ESM4Impl::getToolTipInfo(std::string_view name, int count)
{
MWGui::ToolTipInfo info;
info.caption = MyGUI::TextIterator::toTagsString(MyGUI::UString(name)) + MWGui::ToolTips::getCountString(count);
return info;
}
}
| 1,304
|
C++
|
.cpp
| 33
| 34.272727
| 120
| 0.709422
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,461
|
postprocessorhud.cpp
|
OpenMW_openmw/apps/openmw/mwgui/postprocessorhud.cpp
|
#include "postprocessorhud.hpp"
#include <MyGUI_Align.h>
#include <MyGUI_Button.h>
#include <MyGUI_Delegate.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_EventPair.h>
#include <MyGUI_FactoryManager.h>
#include <MyGUI_Gui.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_Macros.h>
#include <MyGUI_ScrollView.h>
#include <MyGUI_TabItem.h>
#include <MyGUI_UString.h>
#include <MyGUI_Widget.h>
#include <MyGUI_WidgetDefines.h>
#include <MyGUI_WidgetInput.h>
#include <MyGUI_Window.h>
#include <components/fx/technique.hpp>
#include <components/fx/widgets.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/utf8stream.hpp>
#include <components/widgets/box.hpp>
#include "../mwrender/postprocessor.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
namespace MWGui
{
void PostProcessorHud::ListWrapper::onKeyButtonPressed(MyGUI::KeyCode key, MyGUI::Char ch)
{
if (MyGUI::InputManager::getInstance().isShiftPressed()
&& (key == MyGUI::KeyCode::ArrowUp || key == MyGUI::KeyCode::ArrowDown))
return;
MyGUI::ListBox::onKeyButtonPressed(key, ch);
}
PostProcessorHud::PostProcessorHud()
: WindowBase("openmw_postprocessor_hud.layout")
{
getWidget(mActiveList, "ActiveList");
getWidget(mInactiveList, "InactiveList");
getWidget(mConfigLayout, "ConfigLayout");
getWidget(mFilter, "Filter");
getWidget(mButtonActivate, "ButtonActivate");
getWidget(mButtonDeactivate, "ButtonDeactivate");
getWidget(mButtonUp, "ButtonUp");
getWidget(mButtonDown, "ButtonDown");
mButtonActivate->eventMouseButtonClick += MyGUI::newDelegate(this, &PostProcessorHud::notifyActivatePressed);
mButtonDeactivate->eventMouseButtonClick
+= MyGUI::newDelegate(this, &PostProcessorHud::notifyDeactivatePressed);
mButtonUp->eventMouseButtonClick += MyGUI::newDelegate(this, &PostProcessorHud::notifyShaderUpPressed);
mButtonDown->eventMouseButtonClick += MyGUI::newDelegate(this, &PostProcessorHud::notifyShaderDownPressed);
mActiveList->eventKeyButtonPressed += MyGUI::newDelegate(this, &PostProcessorHud::notifyKeyButtonPressed);
mInactiveList->eventKeyButtonPressed += MyGUI::newDelegate(this, &PostProcessorHud::notifyKeyButtonPressed);
mActiveList->eventListChangePosition += MyGUI::newDelegate(this, &PostProcessorHud::notifyListChangePosition);
mInactiveList->eventListChangePosition += MyGUI::newDelegate(this, &PostProcessorHud::notifyListChangePosition);
mFilter->eventEditTextChange += MyGUI::newDelegate(this, &PostProcessorHud::notifyFilterChanged);
mMainWidget->castType<MyGUI::Window>()->eventWindowChangeCoord
+= MyGUI::newDelegate(this, &PostProcessorHud::notifyWindowResize);
mShaderInfo = mConfigLayout->createWidget<Gui::AutoSizedEditBox>("HeaderText", {}, MyGUI::Align::Default);
mShaderInfo->setUserString("VStretch", "true");
mShaderInfo->setUserString("HStretch", "true");
mShaderInfo->setTextAlign(MyGUI::Align::Left | MyGUI::Align::Top);
mShaderInfo->setEditReadOnly(true);
mShaderInfo->setEditWordWrap(true);
mShaderInfo->setEditMultiLine(true);
mShaderInfo->setNeedMouseFocus(false);
mConfigLayout->setVisibleVScroll(true);
mConfigArea = mConfigLayout->createWidget<MyGUI::Widget>({}, {}, MyGUI::Align::Default);
mConfigLayout->eventMouseWheel += MyGUI::newDelegate(this, &PostProcessorHud::notifyMouseWheel);
mConfigArea->eventMouseWheel += MyGUI::newDelegate(this, &PostProcessorHud::notifyMouseWheel);
}
void PostProcessorHud::notifyFilterChanged(MyGUI::EditBox* sender)
{
updateTechniques();
}
void PostProcessorHud::notifyWindowResize(MyGUI::Window* sender)
{
layout();
}
void PostProcessorHud::notifyResetButtonClicked(MyGUI::Widget* sender)
{
for (size_t i = 1; i < mConfigArea->getChildCount(); ++i)
{
if (auto* child = dynamic_cast<fx::Widgets::UniformBase*>(mConfigArea->getChildAt(i)))
child->toDefault();
}
}
void PostProcessorHud::notifyListChangePosition(MyGUI::ListBox* sender, size_t index)
{
if (sender == mActiveList)
mInactiveList->clearIndexSelected();
else if (sender == mInactiveList)
mActiveList->clearIndexSelected();
if (index >= sender->getItemCount())
return;
updateConfigView(sender->getItemNameAt(index));
}
void PostProcessorHud::toggleTechnique(bool enabled)
{
auto* list = enabled ? mInactiveList : mActiveList;
size_t selected = list->getIndexSelected();
if (selected != MyGUI::ITEM_NONE)
{
auto* processor = MWBase::Environment::get().getWorld()->getPostProcessor();
mOverrideHint = list->getItemNameAt(selected);
auto technique = *list->getItemDataAt<std::shared_ptr<fx::Technique>>(selected);
if (technique->getDynamic())
return;
if (enabled)
processor->enableTechnique(std::move(technique));
else
processor->disableTechnique(std::move(technique));
processor->saveChain();
}
}
void PostProcessorHud::notifyActivatePressed(MyGUI::Widget* sender)
{
toggleTechnique(true);
}
void PostProcessorHud::notifyDeactivatePressed(MyGUI::Widget* sender)
{
toggleTechnique(false);
}
void PostProcessorHud::moveShader(Direction direction)
{
auto* processor = MWBase::Environment::get().getWorld()->getPostProcessor();
size_t selected = mActiveList->getIndexSelected();
if (selected == MyGUI::ITEM_NONE)
return;
int index = direction == Direction::Up ? static_cast<int>(selected) - 1 : selected + 1;
index = std::clamp<int>(index, 0, mActiveList->getItemCount() - 1);
if (static_cast<size_t>(index) != selected)
{
auto technique = *mActiveList->getItemDataAt<std::shared_ptr<fx::Technique>>(selected);
if (technique->getDynamic() || technique->getInternal())
return;
if (processor->enableTechnique(std::move(technique), index - mOffset)
!= MWRender::PostProcessor::Status_Error)
processor->saveChain();
}
}
void PostProcessorHud::notifyShaderUpPressed(MyGUI::Widget* sender)
{
moveShader(Direction::Up);
}
void PostProcessorHud::notifyShaderDownPressed(MyGUI::Widget* sender)
{
moveShader(Direction::Down);
}
void PostProcessorHud::notifyKeyButtonPressed(MyGUI::Widget* sender, MyGUI::KeyCode key, MyGUI::Char ch)
{
MyGUI::ListBox* list = static_cast<MyGUI::ListBox*>(sender);
if (list->getIndexSelected() == MyGUI::ITEM_NONE)
return;
if (key == MyGUI::KeyCode::ArrowLeft && list == mActiveList)
{
if (MyGUI::InputManager::getInstance().isShiftPressed())
{
toggleTechnique(false);
}
else
{
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mInactiveList);
mActiveList->clearIndexSelected();
select(mInactiveList, 0);
}
}
else if (key == MyGUI::KeyCode::ArrowRight && list == mInactiveList)
{
if (MyGUI::InputManager::getInstance().isShiftPressed())
{
toggleTechnique(true);
}
else
{
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mActiveList);
mInactiveList->clearIndexSelected();
select(mActiveList, 0);
}
}
else if (list == mActiveList && MyGUI::InputManager::getInstance().isShiftPressed()
&& (key == MyGUI::KeyCode::ArrowUp || key == MyGUI::KeyCode::ArrowDown))
{
moveShader(key == MyGUI::KeyCode::ArrowUp ? Direction::Up : Direction::Down);
}
}
void PostProcessorHud::onOpen()
{
toggleMode(Settings::ShaderManager::Mode::Debug);
updateTechniques();
}
void PostProcessorHud::onClose()
{
toggleMode(Settings::ShaderManager::Mode::Normal);
}
void PostProcessorHud::layout()
{
constexpr int padding = 12;
constexpr int padding2 = padding * 2;
mShaderInfo->setCoord(
padding, padding, mConfigLayout->getSize().width - padding2 - padding, mShaderInfo->getTextSize().height);
int totalHeight = mShaderInfo->getTop() + mShaderInfo->getTextSize().height + padding;
mConfigArea->setCoord({ padding, totalHeight, mShaderInfo->getSize().width, mConfigLayout->getHeight() });
int childHeights = 0;
MyGUI::EnumeratorWidgetPtr enumerator = mConfigArea->getEnumerator();
while (enumerator.next())
{
enumerator.current()->setCoord(padding, childHeights + padding, mShaderInfo->getSize().width - padding2,
enumerator.current()->getHeight());
childHeights += enumerator.current()->getHeight() + padding;
}
totalHeight += childHeights;
mConfigArea->setSize(mConfigArea->getWidth(), childHeights);
mConfigLayout->setCanvasSize(mConfigLayout->getWidth() - padding2, totalHeight);
mConfigLayout->setSize(mConfigLayout->getWidth(), mConfigLayout->getParentSize().height - padding2);
}
void PostProcessorHud::notifyMouseWheel(MyGUI::Widget* sender, int rel)
{
int offset = mConfigLayout->getViewOffset().top + rel * 0.3;
if (offset > 0)
mConfigLayout->setViewOffset(MyGUI::IntPoint(0, 0));
else
mConfigLayout->setViewOffset(MyGUI::IntPoint(0, static_cast<int>(offset)));
}
void PostProcessorHud::select(ListWrapper* list, size_t index)
{
list->setIndexSelected(index);
notifyListChangePosition(list, index);
}
void PostProcessorHud::toggleMode(Settings::ShaderManager::Mode mode)
{
Settings::ShaderManager::get().setMode(mode);
MWBase::Environment::get().getWorld()->getPostProcessor()->toggleMode();
if (!isVisible())
return;
if (mInactiveList->getIndexSelected() != MyGUI::ITEM_NONE)
updateConfigView(mInactiveList->getItemNameAt(mInactiveList->getIndexSelected()));
else if (mActiveList->getIndexSelected() != MyGUI::ITEM_NONE)
updateConfigView(mActiveList->getItemNameAt(mActiveList->getIndexSelected()));
}
void PostProcessorHud::updateConfigView(const std::string& name)
{
auto* processor = MWBase::Environment::get().getWorld()->getPostProcessor();
auto technique = processor->loadTechnique(name);
if (!technique || technique->getStatus() == fx::Technique::Status::File_Not_exists)
return;
while (mConfigArea->getChildCount() > 0)
MyGUI::Gui::getInstance().destroyWidget(mConfigArea->getChildAt(0));
mShaderInfo->setCaption({});
std::ostringstream ss;
const std::string_view NA = "#{Interface:NotAvailableShort}";
const char endl = '\n';
std::string_view author = technique->getAuthor().empty() ? NA : technique->getAuthor();
std::string_view version = technique->getVersion().empty() ? NA : technique->getVersion();
std::string_view description = technique->getDescription().empty() ? NA : technique->getDescription();
auto serializeBool = [](bool value) { return value ? "#{Interface:Yes}" : "#{Interface:No}"; };
const auto flags = technique->getFlags();
const auto flag_interior = serializeBool(!(flags & fx::Technique::Flag_Disable_Interiors));
const auto flag_exterior = serializeBool(!(flags & fx::Technique::Flag_Disable_Exteriors));
const auto flag_underwater = serializeBool(!(flags & fx::Technique::Flag_Disable_Underwater));
const auto flag_abovewater = serializeBool(!(flags & fx::Technique::Flag_Disable_Abovewater));
switch (technique->getStatus())
{
case fx::Technique::Status::Success:
case fx::Technique::Status::Uncompiled:
{
if (technique->getDynamic())
ss << "#{fontcolourhtml=header}#{OMWShaders:ShaderLocked}: #{fontcolourhtml=normal} "
"#{OMWShaders:ShaderLockedDescription}"
<< endl
<< endl;
ss << "#{fontcolourhtml=header}#{OMWShaders:Author}: #{fontcolourhtml=normal} " << author << endl
<< endl
<< "#{fontcolourhtml=header}#{OMWShaders:Version}: #{fontcolourhtml=normal} " << version << endl
<< endl
<< "#{fontcolourhtml=header}#{OMWShaders:Description}: #{fontcolourhtml=normal} " << description
<< endl
<< endl
<< "#{fontcolourhtml=header}#{OMWShaders:InInteriors}: #{fontcolourhtml=normal} " << flag_interior
<< "#{fontcolourhtml=header} #{OMWShaders:InExteriors}: #{fontcolourhtml=normal} " << flag_exterior
<< "#{fontcolourhtml=header} #{OMWShaders:Underwater}: #{fontcolourhtml=normal} "
<< flag_underwater
<< "#{fontcolourhtml=header} #{OMWShaders:Abovewater}: #{fontcolourhtml=normal} "
<< flag_abovewater;
break;
}
case fx::Technique::Status::Parse_Error:
ss << "#{fontcolourhtml=negative}Shader Compile Error: #{fontcolourhtml=normal} <"
<< std::string(technique->getName()) << "> failed to compile." << endl
<< endl
<< technique->getLastError();
break;
case fx::Technique::Status::File_Not_exists:
break;
}
mShaderInfo->setCaptionWithReplacing(ss.str());
if (Settings::ShaderManager::get().getMode() == Settings::ShaderManager::Mode::Debug)
{
if (technique->getUniformMap().size() > 0)
{
MyGUI::Button* resetButton
= mConfigArea->createWidget<MyGUI::Button>("MW_Button", { 0, 0, 0, 24 }, MyGUI::Align::Default);
resetButton->setCaptionWithReplacing("#{OMWShaders:ResetShader}");
resetButton->setTextAlign(MyGUI::Align::Center);
resetButton->eventMouseWheel += MyGUI::newDelegate(this, &PostProcessorHud::notifyMouseWheel);
resetButton->eventMouseButtonClick
+= MyGUI::newDelegate(this, &PostProcessorHud::notifyResetButtonClicked);
}
for (const auto& uniform : technique->getUniformMap())
{
if (!uniform->mStatic || uniform->mSamplerType)
continue;
if (!uniform->mHeader.empty())
{
Gui::AutoSizedTextBox* divider = mConfigArea->createWidget<Gui::AutoSizedTextBox>(
"MW_UniformGroup", { 0, 0, 0, 34 }, MyGUI::Align::Default);
divider->setNeedMouseFocus(false);
divider->setCaptionWithReplacing(uniform->mHeader);
}
fx::Widgets::UniformBase* uwidget = mConfigArea->createWidget<fx::Widgets::UniformBase>(
"MW_UniformEdit", { 0, 0, 0, 22 }, MyGUI::Align::Default);
uwidget->init(uniform);
uwidget->getLabel()->eventMouseWheel += MyGUI::newDelegate(this, &PostProcessorHud::notifyMouseWheel);
}
}
layout();
}
void PostProcessorHud::updateTechniques()
{
if (!isVisible())
return;
std::string hint;
ListWrapper* hintWidget = nullptr;
if (mInactiveList->getIndexSelected() != MyGUI::ITEM_NONE)
{
hint = mInactiveList->getItemNameAt(mInactiveList->getIndexSelected());
hintWidget = mInactiveList;
}
else if (mActiveList->getIndexSelected() != MyGUI::ITEM_NONE)
{
hint = mActiveList->getItemNameAt(mActiveList->getIndexSelected());
hintWidget = mActiveList;
}
mInactiveList->removeAllItems();
mActiveList->removeAllItems();
auto* processor = MWBase::Environment::get().getWorld()->getPostProcessor();
std::vector<std::string> techniques;
for (const auto& [name, _] : processor->getTechniqueMap())
techniques.push_back(name);
std::sort(techniques.begin(), techniques.end(), Misc::StringUtils::ciLess);
for (const std::string& name : techniques)
{
auto technique = processor->loadTechnique(name);
if (!technique)
continue;
if (!technique->getHidden() && !processor->isTechniqueEnabled(technique))
{
std::string lowerName = Utf8Stream::lowerCaseUtf8(name);
std::string lowerCaption = mFilter->getCaption();
lowerCaption = Utf8Stream::lowerCaseUtf8(lowerCaption);
if (lowerName.find(lowerCaption) != std::string::npos)
mInactiveList->addItem(name, technique);
}
}
mOffset = 0;
for (auto technique : processor->getTechniques())
{
if (!technique->getHidden())
{
mActiveList->addItem(technique->getName(), technique);
if (technique->getInternal())
mOffset++;
}
}
auto tryFocus = [this](ListWrapper* widget, const std::string& hint) {
MyGUI::Widget* oldFocus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
if (oldFocus == mFilter)
return;
size_t index = widget->findItemIndexWith(hint);
if (index != MyGUI::ITEM_NONE)
{
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(widget);
select(widget, index);
}
};
if (!mOverrideHint.empty())
{
tryFocus(mActiveList, mOverrideHint);
tryFocus(mInactiveList, mOverrideHint);
mOverrideHint.clear();
}
else if (hintWidget && !hint.empty())
tryFocus(hintWidget, hint);
}
void PostProcessorHud::registerMyGUIComponents()
{
MyGUI::FactoryManager& factory = MyGUI::FactoryManager::getInstance();
factory.registerFactory<fx::Widgets::UniformBase>("Widget");
factory.registerFactory<fx::Widgets::EditNumberFloat4>("Widget");
factory.registerFactory<fx::Widgets::EditNumberFloat3>("Widget");
factory.registerFactory<fx::Widgets::EditNumberFloat2>("Widget");
factory.registerFactory<fx::Widgets::EditNumberFloat>("Widget");
factory.registerFactory<fx::Widgets::EditNumberInt>("Widget");
factory.registerFactory<fx::Widgets::EditBool>("Widget");
factory.registerFactory<fx::Widgets::EditChoice>("Widget");
factory.registerFactory<ListWrapper>("Widget");
}
}
| 19,550
|
C++
|
.cpp
| 408
| 37.411765
| 120
| 0.625098
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,462
|
merchantrepair.cpp
|
OpenMW_openmw/apps/openmw/mwgui/merchantrepair.cpp
|
#include "merchantrepair.hpp"
#include <components/esm3/loadgmst.hpp>
#include <components/settings/values.hpp>
#include <MyGUI_Button.h>
#include <MyGUI_Gui.h>
#include <MyGUI_ScrollView.h>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/esmstore.hpp"
namespace MWGui
{
MerchantRepair::MerchantRepair()
: WindowBase("openmw_merchantrepair.layout")
{
getWidget(mList, "RepairView");
getWidget(mOkButton, "OkButton");
getWidget(mGoldLabel, "PlayerGold");
mOkButton->eventMouseButtonClick += MyGUI::newDelegate(this, &MerchantRepair::onOkButtonClick);
}
void MerchantRepair::setPtr(const MWWorld::Ptr& actor)
{
if (actor.isEmpty() || !actor.getClass().isActor())
throw std::runtime_error("Invalid argument in MerchantRepair::setPtr");
mActor = actor;
while (mList->getChildCount())
MyGUI::Gui::getInstance().destroyWidget(mList->getChildAt(0));
const int lineHeight = Settings::gui().mFontSize + 2;
int currentY = 0;
MWWorld::Ptr player = MWMechanics::getPlayer();
int playerGold = player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId);
MWWorld::ContainerStore& store = player.getClass().getContainerStore(player);
int categories = MWWorld::ContainerStore::Type_Weapon | MWWorld::ContainerStore::Type_Armor;
std::vector<std::tuple<std::string, int, MWWorld::Ptr>> items;
for (MWWorld::ContainerStoreIterator iter(store.begin(categories)); iter != store.end(); ++iter)
{
if (iter->getClass().hasItemHealth(*iter))
{
int maxDurability = iter->getClass().getItemMaxHealth(*iter);
int durability = iter->getClass().getItemHealth(*iter);
if (maxDurability <= durability || maxDurability == 0)
continue;
int basePrice = iter->getClass().getValue(*iter);
float fRepairMult = MWBase::Environment::get()
.getESMStore()
->get<ESM::GameSetting>()
.find("fRepairMult")
->mValue.getFloat();
float p = static_cast<float>(std::max(1, basePrice));
float r = static_cast<float>(std::max(1, static_cast<int>(maxDurability / p)));
int x = static_cast<int>((maxDurability - durability) / r);
x = static_cast<int>(fRepairMult * x);
x = std::max(1, x);
int price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mActor, x, true);
std::string name{ iter->getClass().getName(*iter) };
name += " - " + MyGUI::utility::toString(price)
+ MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>().find("sgp")->mValue.getString();
items.emplace_back(name, price, *iter);
}
}
std::stable_sort(items.begin(), items.end(),
[](const auto& a, const auto& b) { return Misc::StringUtils::ciLess(std::get<0>(a), std::get<0>(b)); });
for (const auto& [name, price, ptr] : items)
{
MyGUI::Button* button = mList->createWidget<MyGUI::Button>(price <= playerGold
? "SandTextButton"
: "SandTextButtonDisabled", // can't use setEnabled since that removes tooltip
0, currentY, 0, lineHeight, MyGUI::Align::Default);
currentY += lineHeight;
button->setUserString("Price", MyGUI::utility::toString(price));
button->setUserData(MWWorld::Ptr(ptr));
button->setCaptionWithReplacing(name);
button->setSize(mList->getWidth(), lineHeight);
button->eventMouseWheel += MyGUI::newDelegate(this, &MerchantRepair::onMouseWheel);
button->setUserString("ToolTipType", "ItemPtr");
button->eventMouseButtonClick += MyGUI::newDelegate(this, &MerchantRepair::onRepairButtonClick);
}
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
// scrollbar is hidden
mList->setVisibleVScroll(false);
mList->setCanvasSize(MyGUI::IntSize(mList->getWidth(), std::max(mList->getHeight(), currentY)));
mList->setVisibleVScroll(true);
mGoldLabel->setCaptionWithReplacing("#{sGold}: " + MyGUI::utility::toString(playerGold));
}
void MerchantRepair::onMouseWheel(MyGUI::Widget* _sender, int _rel)
{
if (mList->getViewOffset().top + _rel * 0.3f > 0)
mList->setViewOffset(MyGUI::IntPoint(0, 0));
else
mList->setViewOffset(MyGUI::IntPoint(0, static_cast<int>(mList->getViewOffset().top + _rel * 0.3f)));
}
void MerchantRepair::onOpen()
{
center();
// Reset scrollbars
mList->setViewOffset(MyGUI::IntPoint(0, 0));
}
void MerchantRepair::onRepairButtonClick(MyGUI::Widget* sender)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
int price = MyGUI::utility::parseInt(sender->getUserString("Price"));
if (price > player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId))
return;
// repair
MWWorld::Ptr item = *sender->getUserData<MWWorld::Ptr>();
item.getCellRef().setCharge(item.getClass().getItemMaxHealth(item));
player.getClass().getContainerStore(player).restack(item);
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Repair"));
player.getClass().getContainerStore(player).remove(MWWorld::ContainerStore::sGoldId, price);
// add gold to NPC trading gold pool
MWMechanics::CreatureStats& actorStats = mActor.getClass().getCreatureStats(mActor);
actorStats.setGoldPool(actorStats.getGoldPool() + price);
setPtr(mActor);
}
void MerchantRepair::onOkButtonClick(MyGUI::Widget* sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_MerchantRepair);
}
}
| 6,489
|
C++
|
.cpp
| 123
| 42.154472
| 120
| 0.625849
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,463
|
referenceinterface.cpp
|
OpenMW_openmw/apps/openmw/mwgui/referenceinterface.cpp
|
#include "referenceinterface.hpp"
namespace MWGui
{
ReferenceInterface::ReferenceInterface() = default;
ReferenceInterface::~ReferenceInterface() = default;
void ReferenceInterface::checkReferenceAvailable()
{
// check if count of the reference has become 0
if (!mPtr.isEmpty() && mPtr.getCellRef().getCount() == 0)
{
mPtr = MWWorld::Ptr();
onReferenceUnavailable();
}
}
}
| 452
|
C++
|
.cpp
| 15
| 23.866667
| 65
| 0.647465
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,464
|
confirmationdialog.cpp
|
OpenMW_openmw/apps/openmw/mwgui/confirmationdialog.cpp
|
#include "confirmationdialog.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_EditBox.h>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
namespace MWGui
{
ConfirmationDialog::ConfirmationDialog()
: WindowModal("openmw_confirmation_dialog.layout")
{
getWidget(mMessage, "Message");
getWidget(mOkButton, "OkButton");
getWidget(mCancelButton, "CancelButton");
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &ConfirmationDialog::onCancelButtonClicked);
mOkButton->eventMouseButtonClick += MyGUI::newDelegate(this, &ConfirmationDialog::onOkButtonClicked);
}
void ConfirmationDialog::askForConfirmation(const std::string& message)
{
setVisible(true);
mMessage->setCaptionWithReplacing(message);
int height = mMessage->getTextSize().height + 60;
int width = mMessage->getTextSize().width + 24;
mMainWidget->setSize(width, height);
mMessage->setSize(mMessage->getWidth(), mMessage->getTextSize().height + 24);
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mOkButton);
center();
}
bool ConfirmationDialog::exit()
{
setVisible(false);
eventCancelClicked();
return true;
}
void ConfirmationDialog::onCancelButtonClicked(MyGUI::Widget* _sender)
{
exit();
}
void ConfirmationDialog::onOkButtonClicked(MyGUI::Widget* _sender)
{
setVisible(false);
eventOkClicked();
}
}
| 1,554
|
C++
|
.cpp
| 43
| 29.651163
| 117
| 0.690301
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,465
|
tradewindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/tradewindow.cpp
|
#include "tradewindow.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_ControllerManager.h>
#include <MyGUI_ControllerRepeatClick.h>
#include <MyGUI_InputManager.h>
#include <components/misc/rng.hpp>
#include <components/misc/strings/format.hpp>
#include <components/widgets/numericeditbox.hpp>
#include "../mwbase/dialoguemanager.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "containeritemmodel.hpp"
#include "countdialog.hpp"
#include "inventorywindow.hpp"
#include "itemview.hpp"
#include "sortfilteritemmodel.hpp"
#include "tooltips.hpp"
#include "tradeitemmodel.hpp"
namespace
{
int getEffectiveValue(MWWorld::Ptr item, int count)
{
float price = static_cast<float>(item.getClass().getValue(item));
if (item.getClass().hasItemHealth(item))
{
price *= item.getClass().getItemNormalizedHealth(item);
}
return static_cast<int>(price * count);
}
bool haggle(const MWWorld::Ptr& player, const MWWorld::Ptr& merchant, int playerOffer, int merchantOffer)
{
// accept if merchant offer is better than player offer
if (playerOffer <= merchantOffer)
{
return true;
}
// reject if npc is a creature
if (merchant.getType() != ESM::NPC::sRecordId)
{
return false;
}
const MWWorld::Store<ESM::GameSetting>& gmst
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
// Is the player buying?
bool buying = (merchantOffer < 0);
int a = std::abs(merchantOffer);
int b = std::abs(playerOffer);
int d = (buying) ? int(100 * (a - b) / a) : int(100 * (b - a) / b);
int clampedDisposition = MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(merchant);
const MWMechanics::CreatureStats& merchantStats = merchant.getClass().getCreatureStats(merchant);
const MWMechanics::CreatureStats& playerStats = player.getClass().getCreatureStats(player);
float a1 = static_cast<float>(player.getClass().getSkill(player, ESM::Skill::Mercantile));
float b1 = 0.1f * playerStats.getAttribute(ESM::Attribute::Luck).getModified();
float c1 = 0.2f * playerStats.getAttribute(ESM::Attribute::Personality).getModified();
float d1 = static_cast<float>(merchant.getClass().getSkill(merchant, ESM::Skill::Mercantile));
float e1 = 0.1f * merchantStats.getAttribute(ESM::Attribute::Luck).getModified();
float f1 = 0.2f * merchantStats.getAttribute(ESM::Attribute::Personality).getModified();
float dispositionTerm = gmst.find("fDispositionMod")->mValue.getFloat() * (clampedDisposition - 50);
float pcTerm = (dispositionTerm + a1 + b1 + c1) * playerStats.getFatigueTerm();
float npcTerm = (d1 + e1 + f1) * merchantStats.getFatigueTerm();
float x = gmst.find("fBargainOfferMulti")->mValue.getFloat() * d
+ gmst.find("fBargainOfferBase")->mValue.getFloat() + int(pcTerm - npcTerm);
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
int roll = Misc::Rng::rollDice(100, prng) + 1;
// reject if roll fails
// (or if player tries to buy things and get money)
if (roll > x || (merchantOffer < 0 && 0 < playerOffer))
{
return false;
}
// apply skill gain on successful barter
float skillGain = 0.f;
int finalPrice = std::abs(playerOffer);
int initialMerchantOffer = std::abs(merchantOffer);
if (!buying && (finalPrice > initialMerchantOffer))
{
skillGain = std::floor(100.f * (finalPrice - initialMerchantOffer) / finalPrice);
}
else if (buying && (finalPrice < initialMerchantOffer))
{
skillGain = std::floor(100.f * (initialMerchantOffer - finalPrice) / initialMerchantOffer);
}
player.getClass().skillUsageSucceeded(
player, ESM::Skill::Mercantile, ESM::Skill::Mercantile_Success, skillGain);
return true;
}
}
namespace MWGui
{
TradeWindow::TradeWindow()
: WindowBase("openmw_trade_window.layout")
, mSortModel(nullptr)
, mTradeModel(nullptr)
, mItemToSell(-1)
, mCurrentBalance(0)
, mCurrentMerchantOffer(0)
{
getWidget(mFilterAll, "AllButton");
getWidget(mFilterWeapon, "WeaponButton");
getWidget(mFilterApparel, "ApparelButton");
getWidget(mFilterMagic, "MagicButton");
getWidget(mFilterMisc, "MiscButton");
getWidget(mMaxSaleButton, "MaxSaleButton");
getWidget(mCancelButton, "CancelButton");
getWidget(mOfferButton, "OfferButton");
getWidget(mPlayerGold, "PlayerGold");
getWidget(mMerchantGold, "MerchantGold");
getWidget(mIncreaseButton, "IncreaseButton");
getWidget(mDecreaseButton, "DecreaseButton");
getWidget(mTotalBalance, "TotalBalance");
getWidget(mTotalBalanceLabel, "TotalBalanceLabel");
getWidget(mBottomPane, "BottomPane");
getWidget(mFilterEdit, "FilterEdit");
getWidget(mItemView, "ItemView");
mItemView->eventItemClicked += MyGUI::newDelegate(this, &TradeWindow::onItemSelected);
mFilterAll->setStateSelected(true);
mFilterAll->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onFilterChanged);
mFilterWeapon->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onFilterChanged);
mFilterApparel->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onFilterChanged);
mFilterMagic->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onFilterChanged);
mFilterMisc->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onFilterChanged);
mFilterEdit->eventEditTextChange += MyGUI::newDelegate(this, &TradeWindow::onNameFilterChanged);
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onCancelButtonClicked);
mOfferButton->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onOfferButtonClicked);
mMaxSaleButton->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onMaxSaleButtonClicked);
mIncreaseButton->eventMouseButtonPressed += MyGUI::newDelegate(this, &TradeWindow::onIncreaseButtonPressed);
mIncreaseButton->eventMouseButtonReleased += MyGUI::newDelegate(this, &TradeWindow::onBalanceButtonReleased);
mDecreaseButton->eventMouseButtonPressed += MyGUI::newDelegate(this, &TradeWindow::onDecreaseButtonPressed);
mDecreaseButton->eventMouseButtonReleased += MyGUI::newDelegate(this, &TradeWindow::onBalanceButtonReleased);
mTotalBalance->eventValueChanged += MyGUI::newDelegate(this, &TradeWindow::onBalanceValueChanged);
mTotalBalance->eventEditSelectAccept += MyGUI::newDelegate(this, &TradeWindow::onAccept);
mTotalBalance->setMinValue(
std::numeric_limits<int>::min() + 1); // disallow INT_MIN since abs(INT_MIN) is undefined
setCoord(400, 0, 400, 300);
}
void TradeWindow::setPtr(const MWWorld::Ptr& actor)
{
if (actor.isEmpty() || !actor.getClass().isActor())
throw std::runtime_error("Invalid argument in TradeWindow::setPtr");
mPtr = actor;
mCurrentBalance = 0;
mCurrentMerchantOffer = 0;
std::vector<MWWorld::Ptr> itemSources;
// Important: actor goes first, so purchased items come out of the actor's pocket first
itemSources.push_back(actor);
MWBase::Environment::get().getWorld()->getContainersOwnedBy(actor, itemSources);
std::vector<MWWorld::Ptr> worldItems;
MWBase::Environment::get().getWorld()->getItemsOwnedBy(actor, worldItems);
auto tradeModel
= std::make_unique<TradeItemModel>(std::make_unique<ContainerItemModel>(itemSources, worldItems), mPtr);
mTradeModel = tradeModel.get();
auto sortModel = std::make_unique<SortFilterItemModel>(std::move(tradeModel));
mSortModel = sortModel.get();
mItemView->setModel(std::move(sortModel));
mItemView->resetScrollBars();
updateLabels();
setTitle(actor.getClass().getName(actor));
onFilterChanged(mFilterAll);
mFilterEdit->setCaption({});
}
void TradeWindow::onFrame(float dt)
{
checkReferenceAvailable();
}
void TradeWindow::onNameFilterChanged(MyGUI::EditBox* _sender)
{
mSortModel->setNameFilter(_sender->getCaption());
mItemView->update();
}
void TradeWindow::onFilterChanged(MyGUI::Widget* _sender)
{
if (_sender == mFilterAll)
mSortModel->setCategory(SortFilterItemModel::Category_All);
else if (_sender == mFilterWeapon)
mSortModel->setCategory(SortFilterItemModel::Category_Weapon);
else if (_sender == mFilterApparel)
mSortModel->setCategory(SortFilterItemModel::Category_Apparel);
else if (_sender == mFilterMagic)
mSortModel->setCategory(SortFilterItemModel::Category_Magic);
else if (_sender == mFilterMisc)
mSortModel->setCategory(SortFilterItemModel::Category_Misc);
mFilterAll->setStateSelected(false);
mFilterWeapon->setStateSelected(false);
mFilterApparel->setStateSelected(false);
mFilterMagic->setStateSelected(false);
mFilterMisc->setStateSelected(false);
_sender->castType<MyGUI::Button>()->setStateSelected(true);
mItemView->update();
}
int TradeWindow::getMerchantServices()
{
return mPtr.getClass().getServices(mPtr);
}
bool TradeWindow::exit()
{
mTradeModel->abort();
MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getTradeModel()->abort();
return true;
}
void TradeWindow::onItemSelected(int index)
{
const ItemStack& item = mSortModel->getItem(index);
MWWorld::Ptr object = item.mBase;
int count = item.mCount;
bool shift = MyGUI::InputManager::getInstance().isShiftPressed();
if (MyGUI::InputManager::getInstance().isControlPressed())
count = 1;
if (count > 1 && !shift)
{
CountDialog* dialog = MWBase::Environment::get().getWindowManager()->getCountDialog();
std::string message = "#{sQuanityMenuMessage02}";
std::string name{ object.getClass().getName(object) };
name += MWGui::ToolTips::getSoulString(object.getCellRef());
dialog->openCountDialog(name, message, count);
dialog->eventOkClicked.clear();
dialog->eventOkClicked += MyGUI::newDelegate(this, &TradeWindow::sellItem);
mItemToSell = mSortModel->mapToSource(index);
}
else
{
mItemToSell = mSortModel->mapToSource(index);
sellItem(nullptr, count);
}
}
void TradeWindow::sellItem(MyGUI::Widget* sender, int count)
{
const ItemStack& item = mTradeModel->getItem(mItemToSell);
const ESM::RefId& sound = item.mBase.getClass().getUpSoundId(item.mBase);
MWBase::Environment::get().getWindowManager()->playSound(sound);
TradeItemModel* playerTradeModel
= MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getTradeModel();
if (item.mType == ItemStack::Type_Barter)
{
// this was an item borrowed to us by the player
mTradeModel->returnItemBorrowedToUs(mItemToSell, count);
playerTradeModel->returnItemBorrowedFromUs(mItemToSell, mTradeModel, count);
buyFromNpc(item.mBase, count, true);
}
else
{
// borrow item to player
playerTradeModel->borrowItemToUs(mItemToSell, mTradeModel, count);
mTradeModel->borrowItemFromUs(mItemToSell, count);
buyFromNpc(item.mBase, count, false);
}
MWBase::Environment::get().getWindowManager()->getInventoryWindow()->updateItemView();
mItemView->update();
}
void TradeWindow::borrowItem(int index, size_t count)
{
TradeItemModel* playerTradeModel
= MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getTradeModel();
mTradeModel->borrowItemToUs(index, playerTradeModel, count);
mItemView->update();
sellToNpc(playerTradeModel->getItem(index).mBase, count, false);
}
void TradeWindow::returnItem(int index, size_t count)
{
TradeItemModel* playerTradeModel
= MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getTradeModel();
const ItemStack& item = playerTradeModel->getItem(index);
mTradeModel->returnItemBorrowedFromUs(index, playerTradeModel, count);
mItemView->update();
sellToNpc(item.mBase, count, true);
}
void TradeWindow::addOrRemoveGold(int amount, const MWWorld::Ptr& actor)
{
MWWorld::ContainerStore& store = actor.getClass().getContainerStore(actor);
if (amount > 0)
{
store.add(MWWorld::ContainerStore::sGoldId, amount);
}
else
{
store.remove(MWWorld::ContainerStore::sGoldId, -amount);
}
}
void TradeWindow::onOfferButtonClicked(MyGUI::Widget* _sender)
{
TradeItemModel* playerItemModel
= MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getTradeModel();
const MWWorld::Store<ESM::GameSetting>& gmst
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
if (mTotalBalance->getValue() == 0)
mCurrentBalance = 0;
// were there any items traded at all?
const std::vector<ItemStack>& playerBought = playerItemModel->getItemsBorrowedToUs();
const std::vector<ItemStack>& merchantBought = mTradeModel->getItemsBorrowedToUs();
if (playerBought.empty() && merchantBought.empty())
{
// user notification
MWBase::Environment::get().getWindowManager()->messageBox("#{sBarterDialog11}");
return;
}
MWWorld::Ptr player = MWMechanics::getPlayer();
int playerGold = player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId);
// check if the player can afford this
if (mCurrentBalance < 0 && playerGold < std::abs(mCurrentBalance))
{
// user notification
MWBase::Environment::get().getWindowManager()->messageBox("#{sBarterDialog1}");
return;
}
// check if the merchant can afford this
if (mCurrentBalance > 0 && getMerchantGold() < mCurrentBalance)
{
// user notification
MWBase::Environment::get().getWindowManager()->messageBox("#{sBarterDialog2}");
return;
}
// check if the player is attempting to sell back an item stolen from this actor
for (const ItemStack& itemStack : merchantBought)
{
if (MWBase::Environment::get().getMechanicsManager()->isItemStolenFrom(
itemStack.mBase.getCellRef().getRefId(), mPtr))
{
std::string msg = gmst.find("sNotifyMessage49")->mValue.getString();
msg = Misc::StringUtils::format(msg, itemStack.mBase.getClass().getName(itemStack.mBase));
MWBase::Environment::get().getWindowManager()->messageBox(msg);
MWBase::Environment::get().getMechanicsManager()->confiscateStolenItemToOwner(
player, itemStack.mBase, mPtr, itemStack.mCount);
onCancelButtonClicked(mCancelButton);
MWBase::Environment::get().getWindowManager()->exitCurrentGuiMode();
return;
}
}
bool offerAccepted = haggle(player, mPtr, mCurrentBalance, mCurrentMerchantOffer);
// apply disposition change if merchant is NPC
if (mPtr.getClass().isNpc())
{
int dispositionDelta = offerAccepted ? gmst.find("iBarterSuccessDisposition")->mValue.getInteger()
: gmst.find("iBarterFailDisposition")->mValue.getInteger();
MWBase::Environment::get().getDialogueManager()->applyBarterDispositionChange(dispositionDelta);
}
// display message on haggle failure
if (!offerAccepted)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage9}");
return;
}
// make the item transfer
mTradeModel->transferItems();
playerItemModel->transferItems();
// transfer the gold
if (mCurrentBalance != 0)
{
addOrRemoveGold(mCurrentBalance, player);
mPtr.getClass().getCreatureStats(mPtr).setGoldPool(
mPtr.getClass().getCreatureStats(mPtr).getGoldPool() - mCurrentBalance);
}
eventTradeDone();
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Item Gold Up"));
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Barter);
}
void TradeWindow::onAccept(MyGUI::EditBox* sender)
{
onOfferButtonClicked(sender);
// To do not spam onAccept() again and again
MWBase::Environment::get().getWindowManager()->injectKeyRelease(MyGUI::KeyCode::None);
}
void TradeWindow::onCancelButtonClicked(MyGUI::Widget* _sender)
{
exit();
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Barter);
}
void TradeWindow::onMaxSaleButtonClicked(MyGUI::Widget* _sender)
{
mCurrentBalance = getMerchantGold();
updateLabels();
}
void TradeWindow::addRepeatController(MyGUI::Widget* widget)
{
MyGUI::ControllerItem* item
= MyGUI::ControllerManager::getInstance().createItem(MyGUI::ControllerRepeatClick::getClassTypeName());
MyGUI::ControllerRepeatClick* controller = static_cast<MyGUI::ControllerRepeatClick*>(item);
controller->eventRepeatClick += newDelegate(this, &TradeWindow::onRepeatClick);
MyGUI::ControllerManager::getInstance().addItem(widget, controller);
}
void TradeWindow::onIncreaseButtonPressed(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
{
addRepeatController(_sender);
onIncreaseButtonTriggered();
}
void TradeWindow::onDecreaseButtonPressed(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
{
addRepeatController(_sender);
onDecreaseButtonTriggered();
}
void TradeWindow::onRepeatClick(MyGUI::Widget* widget, MyGUI::ControllerItem* controller)
{
if (widget == mIncreaseButton)
onIncreaseButtonTriggered();
else if (widget == mDecreaseButton)
onDecreaseButtonTriggered();
}
void TradeWindow::onBalanceButtonReleased(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
{
MyGUI::ControllerManager::getInstance().removeItem(_sender);
}
void TradeWindow::onBalanceValueChanged(int value)
{
int previousBalance = mCurrentBalance;
// Entering a "-" sign inverts the buying/selling state
mCurrentBalance = (mCurrentBalance >= 0 ? 1 : -1) * value;
updateLabels();
if (mCurrentBalance == 0)
mCurrentBalance = previousBalance;
if (value != std::abs(value))
mTotalBalance->setValue(std::abs(value));
}
void TradeWindow::onIncreaseButtonTriggered()
{
// prevent overflows, and prevent entering INT_MIN since abs(INT_MIN) is undefined
if (mCurrentBalance == std::numeric_limits<int>::max()
|| mCurrentBalance == std::numeric_limits<int>::min() + 1)
return;
if (mTotalBalance->getValue() == 0)
mCurrentBalance = 0;
if (mCurrentBalance < 0)
mCurrentBalance -= 1;
else
mCurrentBalance += 1;
updateLabels();
}
void TradeWindow::onDecreaseButtonTriggered()
{
if (mTotalBalance->getValue() == 0)
mCurrentBalance = 0;
if (mCurrentBalance < 0)
mCurrentBalance += 1;
else
mCurrentBalance -= 1;
updateLabels();
}
void TradeWindow::updateLabels()
{
MWWorld::Ptr player = MWMechanics::getPlayer();
int playerGold = player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId);
mPlayerGold->setCaptionWithReplacing("#{sYourGold} " + MyGUI::utility::toString(playerGold));
TradeItemModel* playerTradeModel
= MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getTradeModel();
const std::vector<ItemStack>& playerBorrowed = playerTradeModel->getItemsBorrowedToUs();
const std::vector<ItemStack>& merchantBorrowed = mTradeModel->getItemsBorrowedToUs();
if (playerBorrowed.empty() && merchantBorrowed.empty())
{
mCurrentBalance = 0;
}
if (mCurrentBalance < 0)
{
mTotalBalanceLabel->setCaptionWithReplacing("#{sTotalCost}");
}
else
{
mTotalBalanceLabel->setCaptionWithReplacing("#{sTotalSold}");
}
mTotalBalance->setValue(std::abs(mCurrentBalance));
mMerchantGold->setCaptionWithReplacing("#{sSellerGold} " + MyGUI::utility::toString(getMerchantGold()));
}
void TradeWindow::updateOffer()
{
TradeItemModel* playerTradeModel
= MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getTradeModel();
int merchantOffer = 0;
// The offered price must be capped at 75% of the base price to avoid exploits
// connected to buying and selling the same item.
// This value has been determined by researching the limitations of the vanilla formula
// and may not be sufficient if getBarterOffer behavior has been changed.
const std::vector<ItemStack>& playerBorrowed = playerTradeModel->getItemsBorrowedToUs();
for (const ItemStack& itemStack : playerBorrowed)
{
const int basePrice = getEffectiveValue(itemStack.mBase, itemStack.mCount);
const int cap
= static_cast<int>(std::max(1.f, 0.75f * basePrice)); // Minimum buying price -- 75% of the base
const int buyingPrice
= MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr, basePrice, true);
merchantOffer -= std::max(cap, buyingPrice);
}
const std::vector<ItemStack>& merchantBorrowed = mTradeModel->getItemsBorrowedToUs();
for (const ItemStack& itemStack : merchantBorrowed)
{
const int basePrice = getEffectiveValue(itemStack.mBase, itemStack.mCount);
const int cap
= static_cast<int>(std::max(1.f, 0.75f * basePrice)); // Maximum selling price -- 75% of the base
const int sellingPrice
= MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr, basePrice, false);
merchantOffer += mPtr.getClass().isNpc() ? std::min(cap, sellingPrice) : sellingPrice;
}
int diff = merchantOffer - mCurrentMerchantOffer;
mCurrentMerchantOffer = merchantOffer;
mCurrentBalance += diff;
updateLabels();
}
void TradeWindow::sellToNpc(const MWWorld::Ptr& item, int count, bool boughtItem)
{
updateOffer();
}
void TradeWindow::buyFromNpc(const MWWorld::Ptr& item, int count, bool soldItem)
{
updateOffer();
}
void TradeWindow::onReferenceUnavailable()
{
// remove both Trade and Dialogue (since you always trade with the NPC/creature that you have previously talked
// to)
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Barter);
MWBase::Environment::get().getWindowManager()->exitCurrentGuiMode();
}
int TradeWindow::getMerchantGold()
{
int merchantGold = mPtr.getClass().getCreatureStats(mPtr).getGoldPool();
return merchantGold;
}
void TradeWindow::resetReference()
{
ReferenceInterface::resetReference();
mItemView->setModel(nullptr);
mTradeModel = nullptr;
mSortModel = nullptr;
}
void TradeWindow::onClose()
{
// Make sure the window was actually closed and not temporarily hidden.
if (MWBase::Environment::get().getWindowManager()->containsMode(GM_Barter))
return;
resetReference();
}
void TradeWindow::onDeleteCustomData(const MWWorld::Ptr& ptr)
{
if (mTradeModel && mTradeModel->usesContainer(ptr))
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Barter);
}
}
| 25,405
|
C++
|
.cpp
| 539
| 38.207792
| 119
| 0.659195
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,466
|
charactercreation.cpp
|
OpenMW_openmw/apps/openmw/mwgui/charactercreation.cpp
|
#include "charactercreation.hpp"
#include <MyGUI_ITexture.h>
#include <components/debug/debuglog.hpp>
#include <components/fallback/fallback.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/misc/rng.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/player.hpp"
#include "birth.hpp"
#include "class.hpp"
#include "inventorywindow.hpp"
#include "race.hpp"
#include "review.hpp"
#include "textinput.hpp"
namespace
{
struct Response
{
const std::string mText;
const ESM::Class::Specialization mSpecialization;
};
struct Step
{
const std::string mText;
const Response mResponses[3];
const VFS::Path::Normalized mSound;
};
Step sGenerateClassSteps(int number)
{
number++;
std::string question{ Fallback::Map::getString("Question_" + MyGUI::utility::toString(number) + "_Question") };
std::string answer0{ Fallback::Map::getString("Question_" + MyGUI::utility::toString(number) + "_AnswerOne") };
std::string answer1{ Fallback::Map::getString("Question_" + MyGUI::utility::toString(number) + "_AnswerTwo") };
std::string answer2{ Fallback::Map::getString(
"Question_" + MyGUI::utility::toString(number) + "_AnswerThree") };
std::string sound = "vo\\misc\\chargen qa" + MyGUI::utility::toString(number) + ".wav";
Response r0 = { std::move(answer0), ESM::Class::Combat };
Response r1 = { std::move(answer1), ESM::Class::Magic };
Response r2 = { std::move(answer2), ESM::Class::Stealth };
// randomize order in which responses are displayed
int order = Misc::Rng::rollDice(6);
switch (order)
{
case 0:
return { std::move(question), { std::move(r0), std::move(r1), std::move(r2) }, std::move(sound) };
case 1:
return { std::move(question), { std::move(r0), std::move(r2), std::move(r1) }, std::move(sound) };
case 2:
return { std::move(question), { std::move(r1), std::move(r0), std::move(r2) }, std::move(sound) };
case 3:
return { std::move(question), { std::move(r1), std::move(r2), std::move(r0) }, std::move(sound) };
case 4:
return { std::move(question), { std::move(r2), std::move(r0), std::move(r1) }, std::move(sound) };
default:
return { std::move(question), { std::move(r2), std::move(r1), std::move(r0) }, std::move(sound) };
}
}
}
namespace MWGui
{
CharacterCreation::CharacterCreation(osg::Group* parent, Resource::ResourceSystem* resourceSystem)
: mParent(parent)
, mResourceSystem(resourceSystem)
, mGenerateClassStep(0)
{
mCreationStage = CSE_NotStarted;
mGenerateClassResponses[0] = ESM::Class::Combat;
mGenerateClassResponses[1] = ESM::Class::Magic;
mGenerateClassResponses[2] = ESM::Class::Stealth;
mGenerateClassSpecializations[0] = 0;
mGenerateClassSpecializations[1] = 0;
mGenerateClassSpecializations[2] = 0;
// Setup player stats
const auto& store = MWBase::Environment::get().getWorld()->getStore();
for (const ESM::Attribute& attribute : store.get<ESM::Attribute>())
mPlayerAttributes.emplace(attribute.mId, MWMechanics::AttributeValue());
for (const auto& skill : store.get<ESM::Skill>())
mPlayerSkillValues.emplace(skill.mId, MWMechanics::SkillValue());
}
void CharacterCreation::setAttribute(ESM::RefId id, const MWMechanics::AttributeValue& value)
{
mPlayerAttributes[id] = value;
if (mReviewDialog)
mReviewDialog->setAttribute(id, value);
}
void CharacterCreation::setValue(std::string_view id, const MWMechanics::DynamicStat<float>& value)
{
if (mReviewDialog)
{
if (id == "HBar")
{
mReviewDialog->setHealth(value);
}
else if (id == "MBar")
{
mReviewDialog->setMagicka(value);
}
else if (id == "FBar")
{
mReviewDialog->setFatigue(value);
}
}
}
void CharacterCreation::setValue(ESM::RefId id, const MWMechanics::SkillValue& value)
{
mPlayerSkillValues[id] = value;
if (mReviewDialog)
mReviewDialog->setSkillValue(id, value);
}
void CharacterCreation::configureSkills(const std::vector<ESM::RefId>& major, const std::vector<ESM::RefId>& minor)
{
if (mReviewDialog)
mReviewDialog->configureSkills(major, minor);
mPlayerMajorSkills = major;
mPlayerMinorSkills = minor;
}
void CharacterCreation::onFrame(float duration)
{
if (mReviewDialog)
mReviewDialog->onFrame(duration);
}
void CharacterCreation::spawnDialog(const char id)
{
try
{
switch (id)
{
case GM_Name:
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mNameDialog));
mNameDialog = std::make_unique<TextInputDialog>();
mNameDialog->setTextLabel(
MWBase::Environment::get().getWindowManager()->getGameSettingString("sName", "Name"));
mNameDialog->setTextInput(mPlayerName);
mNameDialog->setNextButtonShow(mCreationStage >= CSE_NameChosen);
mNameDialog->eventDone += MyGUI::newDelegate(this, &CharacterCreation::onNameDialogDone);
mNameDialog->setVisible(true);
break;
case GM_Race:
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mRaceDialog));
mRaceDialog = std::make_unique<RaceDialog>(mParent, mResourceSystem);
mRaceDialog->setNextButtonShow(mCreationStage >= CSE_RaceChosen);
mRaceDialog->setRaceId(mPlayerRaceId);
mRaceDialog->eventDone += MyGUI::newDelegate(this, &CharacterCreation::onRaceDialogDone);
mRaceDialog->eventBack += MyGUI::newDelegate(this, &CharacterCreation::onRaceDialogBack);
mRaceDialog->setVisible(true);
if (mCreationStage < CSE_NameChosen)
mCreationStage = CSE_NameChosen;
break;
case GM_Class:
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mClassChoiceDialog));
mClassChoiceDialog = std::make_unique<ClassChoiceDialog>();
mClassChoiceDialog->eventButtonSelected
+= MyGUI::newDelegate(this, &CharacterCreation::onClassChoice);
mClassChoiceDialog->setVisible(true);
if (mCreationStage < CSE_RaceChosen)
mCreationStage = CSE_RaceChosen;
break;
case GM_ClassPick:
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mPickClassDialog));
mPickClassDialog = std::make_unique<PickClassDialog>();
mPickClassDialog->setNextButtonShow(mCreationStage >= CSE_ClassChosen);
mPickClassDialog->setClassId(mPlayerClass.mId);
mPickClassDialog->eventDone += MyGUI::newDelegate(this, &CharacterCreation::onPickClassDialogDone);
mPickClassDialog->eventBack += MyGUI::newDelegate(this, &CharacterCreation::onPickClassDialogBack);
mPickClassDialog->setVisible(true);
if (mCreationStage < CSE_RaceChosen)
mCreationStage = CSE_RaceChosen;
break;
case GM_Birth:
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mBirthSignDialog));
mBirthSignDialog = std::make_unique<BirthDialog>();
mBirthSignDialog->setNextButtonShow(mCreationStage >= CSE_BirthSignChosen);
mBirthSignDialog->setBirthId(mPlayerBirthSignId);
mBirthSignDialog->eventDone += MyGUI::newDelegate(this, &CharacterCreation::onBirthSignDialogDone);
mBirthSignDialog->eventBack += MyGUI::newDelegate(this, &CharacterCreation::onBirthSignDialogBack);
mBirthSignDialog->setVisible(true);
if (mCreationStage < CSE_ClassChosen)
mCreationStage = CSE_ClassChosen;
break;
case GM_ClassCreate:
if (mCreateClassDialog == nullptr)
{
mCreateClassDialog = std::make_unique<CreateClassDialog>();
mCreateClassDialog->eventDone
+= MyGUI::newDelegate(this, &CharacterCreation::onCreateClassDialogDone);
mCreateClassDialog->eventBack
+= MyGUI::newDelegate(this, &CharacterCreation::onCreateClassDialogBack);
}
mCreateClassDialog->setNextButtonShow(mCreationStage >= CSE_ClassChosen);
mCreateClassDialog->setVisible(true);
if (mCreationStage < CSE_RaceChosen)
mCreationStage = CSE_RaceChosen;
break;
case GM_ClassGenerate:
mGenerateClassStep = 0;
mGenerateClass = ESM::RefId();
mGenerateClassSpecializations[0] = 0;
mGenerateClassSpecializations[1] = 0;
mGenerateClassSpecializations[2] = 0;
showClassQuestionDialog();
if (mCreationStage < CSE_RaceChosen)
mCreationStage = CSE_RaceChosen;
break;
case GM_Review:
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mReviewDialog));
mReviewDialog = std::make_unique<ReviewDialog>();
MWBase::World* world = MWBase::Environment::get().getWorld();
const ESM::NPC* playerNpc = world->getPlayerPtr().get<ESM::NPC>()->mBase;
const MWWorld::Player& player = world->getPlayer();
const ESM::Class* playerClass = world->getStore().get<ESM::Class>().find(playerNpc->mClass);
mReviewDialog->setPlayerName(playerNpc->mName);
mReviewDialog->setRace(playerNpc->mRace);
mReviewDialog->setClass(*playerClass);
mReviewDialog->setBirthSign(player.getBirthSign());
MWWorld::Ptr playerPtr = MWMechanics::getPlayer();
const MWMechanics::CreatureStats& stats = playerPtr.getClass().getCreatureStats(playerPtr);
mReviewDialog->setHealth(stats.getHealth());
mReviewDialog->setMagicka(stats.getMagicka());
mReviewDialog->setFatigue(stats.getFatigue());
for (auto& attributePair : mPlayerAttributes)
{
mReviewDialog->setAttribute(attributePair.first, attributePair.second);
}
for (const auto& [skill, value] : mPlayerSkillValues)
{
mReviewDialog->setSkillValue(skill, value);
}
mReviewDialog->configureSkills(mPlayerMajorSkills, mPlayerMinorSkills);
mReviewDialog->eventDone += MyGUI::newDelegate(this, &CharacterCreation::onReviewDialogDone);
mReviewDialog->eventBack += MyGUI::newDelegate(this, &CharacterCreation::onReviewDialogBack);
mReviewDialog->eventActivateDialog
+= MyGUI::newDelegate(this, &CharacterCreation::onReviewActivateDialog);
mReviewDialog->setVisible(true);
if (mCreationStage < CSE_BirthSignChosen)
mCreationStage = CSE_BirthSignChosen;
break;
}
}
catch (std::exception& e)
{
Log(Debug::Error) << "Error: Failed to create chargen window: " << e.what();
}
}
void CharacterCreation::onReviewDialogDone(WindowBase* parWindow)
{
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mReviewDialog));
MWBase::Environment::get().getWindowManager()->popGuiMode();
}
void CharacterCreation::onReviewDialogBack()
{
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mReviewDialog));
mCreationStage = CSE_ReviewBack;
MWBase::Environment::get().getWindowManager()->popGuiMode();
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Birth);
}
void CharacterCreation::onReviewActivateDialog(int parDialog)
{
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mReviewDialog));
mCreationStage = CSE_ReviewNext;
MWBase::Environment::get().getWindowManager()->popGuiMode();
switch (parDialog)
{
case ReviewDialog::NAME_DIALOG:
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Name);
break;
case ReviewDialog::RACE_DIALOG:
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Race);
break;
case ReviewDialog::CLASS_DIALOG:
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Class);
break;
case ReviewDialog::BIRTHSIGN_DIALOG:
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Birth);
};
}
void CharacterCreation::selectPickedClass()
{
if (mPickClassDialog)
{
const ESM::RefId& classId = mPickClassDialog->getClassId();
if (!classId.empty())
MWBase::Environment::get().getMechanicsManager()->setPlayerClass(classId);
const ESM::Class* pickedClass = MWBase::Environment::get().getESMStore()->get<ESM::Class>().find(classId);
if (pickedClass)
{
mPlayerClass = *pickedClass;
}
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mPickClassDialog));
}
}
void CharacterCreation::onPickClassDialogDone(WindowBase* parWindow)
{
selectPickedClass();
handleDialogDone(CSE_ClassChosen, GM_Birth);
}
void CharacterCreation::onPickClassDialogBack()
{
selectPickedClass();
MWBase::Environment::get().getWindowManager()->popGuiMode();
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Class);
}
void CharacterCreation::onClassChoice(int _index)
{
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mClassChoiceDialog));
MWBase::Environment::get().getWindowManager()->popGuiMode();
switch (_index)
{
case ClassChoiceDialog::Class_Generate:
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_ClassGenerate);
break;
case ClassChoiceDialog::Class_Pick:
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_ClassPick);
break;
case ClassChoiceDialog::Class_Create:
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_ClassCreate);
break;
case ClassChoiceDialog::Class_Back:
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Race);
break;
};
}
void CharacterCreation::onNameDialogDone(WindowBase* parWindow)
{
if (mNameDialog)
{
mPlayerName = mNameDialog->getTextInput();
MWBase::Environment::get().getMechanicsManager()->setPlayerName(mPlayerName);
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mNameDialog));
}
handleDialogDone(CSE_NameChosen, GM_Race);
}
void CharacterCreation::selectRace()
{
if (mRaceDialog)
{
const ESM::NPC& data = mRaceDialog->getResult();
mPlayerRaceId = data.mRace;
if (!mPlayerRaceId.empty())
{
MWBase::Environment::get().getMechanicsManager()->setPlayerRace(
data.mRace, data.isMale(), data.mHead, data.mHair);
}
MWBase::Environment::get().getWindowManager()->getInventoryWindow()->rebuildAvatar();
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mRaceDialog));
}
}
void CharacterCreation::onRaceDialogBack()
{
selectRace();
MWBase::Environment::get().getWindowManager()->popGuiMode();
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Name);
}
void CharacterCreation::onRaceDialogDone(WindowBase* parWindow)
{
selectRace();
handleDialogDone(CSE_RaceChosen, GM_Class);
}
void CharacterCreation::selectBirthSign()
{
if (mBirthSignDialog)
{
mPlayerBirthSignId = mBirthSignDialog->getBirthId();
if (!mPlayerBirthSignId.empty())
MWBase::Environment::get().getMechanicsManager()->setPlayerBirthsign(mPlayerBirthSignId);
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mBirthSignDialog));
}
}
void CharacterCreation::onBirthSignDialogDone(WindowBase* parWindow)
{
selectBirthSign();
handleDialogDone(CSE_BirthSignChosen, GM_Review);
}
void CharacterCreation::onBirthSignDialogBack()
{
selectBirthSign();
MWBase::Environment::get().getWindowManager()->popGuiMode();
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Class);
}
void CharacterCreation::selectCreatedClass()
{
if (mCreateClassDialog)
{
ESM::Class createdClass;
createdClass.mName = mCreateClassDialog->getName();
createdClass.mDescription = mCreateClassDialog->getDescription();
createdClass.mData.mSpecialization = mCreateClassDialog->getSpecializationId();
createdClass.mData.mIsPlayable = 0x1;
createdClass.mRecordFlags = 0;
std::vector<ESM::RefId> attributes = mCreateClassDialog->getFavoriteAttributes();
assert(attributes.size() >= createdClass.mData.mAttribute.size());
for (size_t i = 0; i < createdClass.mData.mAttribute.size(); ++i)
createdClass.mData.mAttribute[i] = ESM::Attribute::refIdToIndex(attributes[i]);
std::vector<ESM::RefId> majorSkills = mCreateClassDialog->getMajorSkills();
std::vector<ESM::RefId> minorSkills = mCreateClassDialog->getMinorSkills();
assert(majorSkills.size() >= createdClass.mData.mSkills.size());
assert(minorSkills.size() >= createdClass.mData.mSkills.size());
for (size_t i = 0; i < createdClass.mData.mSkills.size(); ++i)
{
createdClass.mData.mSkills[i][1] = ESM::Skill::refIdToIndex(majorSkills[i]);
createdClass.mData.mSkills[i][0] = ESM::Skill::refIdToIndex(minorSkills[i]);
}
MWBase::Environment::get().getMechanicsManager()->setPlayerClass(createdClass);
mPlayerClass = std::move(createdClass);
// Do not delete dialog, so that choices are remembered in case we want to go back and adjust them later
mCreateClassDialog->setVisible(false);
}
}
void CharacterCreation::onCreateClassDialogDone(WindowBase* parWindow)
{
selectCreatedClass();
handleDialogDone(CSE_ClassChosen, GM_Birth);
}
void CharacterCreation::onCreateClassDialogBack()
{
// not done in MW, but we do it for consistency with the other dialogs
selectCreatedClass();
MWBase::Environment::get().getWindowManager()->popGuiMode();
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Class);
}
void CharacterCreation::onClassQuestionChosen(int _index)
{
MWBase::Environment::get().getSoundManager()->stopSay();
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mGenerateClassQuestionDialog));
if (_index < 0 || _index >= 3)
{
MWBase::Environment::get().getWindowManager()->popGuiMode();
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Class);
return;
}
ESM::Class::Specialization specialization = mGenerateClassResponses[_index];
if (specialization == ESM::Class::Combat)
++mGenerateClassSpecializations[0];
else if (specialization == ESM::Class::Magic)
++mGenerateClassSpecializations[1];
else if (specialization == ESM::Class::Stealth)
++mGenerateClassSpecializations[2];
++mGenerateClassStep;
showClassQuestionDialog();
}
void CharacterCreation::showClassQuestionDialog()
{
if (mGenerateClassStep == 10)
{
unsigned combat = mGenerateClassSpecializations[0];
unsigned magic = mGenerateClassSpecializations[1];
unsigned stealth = mGenerateClassSpecializations[2];
std::string_view className;
if (combat > 7)
{
className = "Warrior";
}
else if (magic > 7)
{
className = "Mage";
}
else if (stealth > 7)
{
className = "Thief";
}
else
{
switch (combat)
{
case 4:
className = "Rogue";
break;
case 5:
if (stealth == 3)
className = "Scout";
else
className = "Archer";
break;
case 6:
if (stealth == 1)
className = "Barbarian";
else if (stealth == 3)
className = "Crusader";
else
className = "Knight";
break;
case 7:
className = "Warrior";
break;
default:
switch (magic)
{
case 4:
className = "Spellsword";
break;
case 5:
className = "Witchhunter";
break;
case 6:
if (combat == 2)
className = "Sorcerer";
else if (combat == 3)
className = "Healer";
else
className = "Battlemage";
break;
case 7:
className = "Mage";
break;
default:
switch (stealth)
{
case 3:
if (magic == 3)
className = "Bard"; // unreachable
else
className = "Warrior";
break;
case 5:
if (magic == 3)
className = "Monk";
else
className = "Pilgrim";
break;
case 6:
if (magic == 1)
className = "Agent";
else if (magic == 3)
className = "Assassin";
else
className = "Acrobat";
break;
case 7:
className = "Thief";
break;
default:
className = "Warrior";
}
}
}
}
mGenerateClass = ESM::RefId::stringRefId(className);
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mGenerateClassResultDialog));
mGenerateClassResultDialog = std::make_unique<GenerateClassResultDialog>();
mGenerateClassResultDialog->setClassId(mGenerateClass);
mGenerateClassResultDialog->eventBack += MyGUI::newDelegate(this, &CharacterCreation::onGenerateClassBack);
mGenerateClassResultDialog->eventDone += MyGUI::newDelegate(this, &CharacterCreation::onGenerateClassDone);
mGenerateClassResultDialog->setVisible(true);
return;
}
if (mGenerateClassStep > 10)
{
MWBase::Environment::get().getWindowManager()->popGuiMode();
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Class);
return;
}
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mGenerateClassQuestionDialog));
mGenerateClassQuestionDialog = std::make_unique<InfoBoxDialog>();
Step step = sGenerateClassSteps(mGenerateClassStep);
mGenerateClassResponses[0] = step.mResponses[0].mSpecialization;
mGenerateClassResponses[1] = step.mResponses[1].mSpecialization;
mGenerateClassResponses[2] = step.mResponses[2].mSpecialization;
InfoBoxDialog::ButtonList buttons;
mGenerateClassQuestionDialog->setText(step.mText);
buttons.push_back(step.mResponses[0].mText);
buttons.push_back(step.mResponses[1].mText);
buttons.push_back(step.mResponses[2].mText);
mGenerateClassQuestionDialog->setButtons(buttons);
mGenerateClassQuestionDialog->eventButtonSelected
+= MyGUI::newDelegate(this, &CharacterCreation::onClassQuestionChosen);
mGenerateClassQuestionDialog->setVisible(true);
MWBase::Environment::get().getSoundManager()->say(Misc::ResourceHelpers::correctSoundPath(step.mSound));
}
void CharacterCreation::selectGeneratedClass()
{
MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mGenerateClassResultDialog));
MWBase::Environment::get().getMechanicsManager()->setPlayerClass(mGenerateClass);
const ESM::Class* generatedClass
= MWBase::Environment::get().getESMStore()->get<ESM::Class>().find(mGenerateClass);
mPlayerClass = *generatedClass;
}
void CharacterCreation::onGenerateClassBack()
{
selectGeneratedClass();
MWBase::Environment::get().getWindowManager()->popGuiMode();
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Class);
}
void CharacterCreation::onGenerateClassDone(WindowBase* parWindow)
{
selectGeneratedClass();
handleDialogDone(CSE_ClassChosen, GM_Birth);
}
CharacterCreation::~CharacterCreation() = default;
void CharacterCreation::handleDialogDone(CSE currentStage, int nextMode)
{
MWBase::Environment::get().getWindowManager()->popGuiMode();
if (mCreationStage == CSE_ReviewNext)
{
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Review);
}
else if (mCreationStage >= currentStage)
{
MWBase::Environment::get().getWindowManager()->pushGuiMode((GuiMode)nextMode);
}
else
{
mCreationStage = currentStage;
}
}
}
| 29,184
|
C++
|
.cpp
| 612
| 33.346405
| 119
| 0.5689
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,467
|
mapwindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/mapwindow.cpp
|
#include "mapwindow.hpp"
#include <osg/Texture2D>
#include <MyGUI_Button.h>
#include <MyGUI_FactoryManager.h>
#include <MyGUI_Gui.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_LanguageManager.h>
#include <MyGUI_RenderManager.h>
#include <MyGUI_RotatingSkin.h>
#include <MyGUI_ScrollView.h>
#include <MyGUI_TextIterator.h>
#include <components/esm3/esmwriter.hpp>
#include <components/esm3/globalmap.hpp>
#include <components/myguiplatform/myguitexture.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/player.hpp"
#include "../mwworld/worldmodel.hpp"
#include "../mwrender/globalmap.hpp"
#include "../mwrender/localmap.hpp"
#include "confirmationdialog.hpp"
#include <numeric>
namespace
{
const int cellSize = Constants::CellSizeInUnits;
constexpr float speed = 1.08f; // the zoom speed, it should be greater than 1
enum LocalMapWidgetDepth
{
Local_MarkerAboveFogLayer = 0,
Local_CompassLayer = 1,
Local_FogLayer = 2,
Local_MarkerLayer = 3,
Local_MapLayer = 4
};
enum GlobalMapWidgetDepth
{
Global_CompassLayer = 0,
Global_MarkerLayer = 1,
Global_ExploreOverlayLayer = 2,
Global_MapLayer = 3
};
/// @brief A widget that changes its color when hovered.
class MarkerWidget final : public MyGUI::Widget
{
MYGUI_RTTI_DERIVED(MarkerWidget)
public:
void setNormalColour(const MyGUI::Colour& colour)
{
mNormalColour = colour;
setColour(colour);
}
void setHoverColour(const MyGUI::Colour& colour) { mHoverColour = colour; }
private:
MyGUI::Colour mNormalColour;
MyGUI::Colour mHoverColour;
void onMouseLostFocus(MyGUI::Widget* _new) override { setColour(mNormalColour); }
void onMouseSetFocus(MyGUI::Widget* _old) override { setColour(mHoverColour); }
};
MyGUI::IntRect createRect(const MyGUI::IntPoint& center, int radius)
{
return { center.left - radius, center.top - radius, center.left + radius, center.top + radius };
}
int getLocalViewingDistance()
{
if (!Settings::map().mAllowZooming)
return Constants::CellGridRadius;
if (!Settings::terrain().mDistantTerrain)
return Constants::CellGridRadius;
const int viewingDistanceInCells = Settings::camera().mViewingDistance / Constants::CellSizeInUnits;
return std::clamp(
viewingDistanceInCells, Constants::CellGridRadius, Settings::map().mMaxLocalViewingDistance.get());
}
ESM::RefId getCellIdInWorldSpace(const MWWorld::Cell& cell, int x, int y)
{
if (cell.isExterior())
return ESM::Cell::generateIdForCell(true, {}, x, y);
return cell.getId();
}
}
namespace MWGui
{
void CustomMarkerCollection::addMarker(const ESM::CustomMarker& marker, bool triggerEvent)
{
mMarkers.insert(std::make_pair(marker.mCell, marker));
if (triggerEvent)
eventMarkersChanged();
}
void CustomMarkerCollection::deleteMarker(const ESM::CustomMarker& marker)
{
std::pair<ContainerType::iterator, ContainerType::iterator> range = mMarkers.equal_range(marker.mCell);
for (ContainerType::iterator it = range.first; it != range.second; ++it)
{
if (it->second == marker)
{
mMarkers.erase(it);
eventMarkersChanged();
return;
}
}
throw std::runtime_error("can't find marker to delete");
}
void CustomMarkerCollection::updateMarker(const ESM::CustomMarker& marker, const std::string& newNote)
{
std::pair<ContainerType::iterator, ContainerType::iterator> range = mMarkers.equal_range(marker.mCell);
for (ContainerType::iterator it = range.first; it != range.second; ++it)
{
if (it->second == marker)
{
it->second.mNote = newNote;
eventMarkersChanged();
return;
}
}
throw std::runtime_error("can't find marker to update");
}
void CustomMarkerCollection::clear()
{
mMarkers.clear();
eventMarkersChanged();
}
CustomMarkerCollection::ContainerType::const_iterator CustomMarkerCollection::begin() const
{
return mMarkers.begin();
}
CustomMarkerCollection::ContainerType::const_iterator CustomMarkerCollection::end() const
{
return mMarkers.end();
}
CustomMarkerCollection::RangeType CustomMarkerCollection::getMarkers(const ESM::RefId& cellId) const
{
return mMarkers.equal_range(cellId);
}
size_t CustomMarkerCollection::size() const
{
return mMarkers.size();
}
// ------------------------------------------------------
LocalMapBase::LocalMapBase(
CustomMarkerCollection& markers, MWRender::LocalMap* localMapRender, bool fogOfWarEnabled)
: mLocalMapRender(localMapRender)
, mActiveCell(nullptr)
, mLocalMap(nullptr)
, mCompass(nullptr)
, mFogOfWarToggled(true)
, mFogOfWarEnabled(fogOfWarEnabled)
, mNumCells(1)
, mCellDistance(0)
, mCustomMarkers(markers)
, mMarkerUpdateTimer(0.0f)
, mLastDirectionX(0.0f)
, mLastDirectionY(0.0f)
, mNeedDoorMarkersUpdate(false)
{
mCustomMarkers.eventMarkersChanged += MyGUI::newDelegate(this, &LocalMapBase::updateCustomMarkers);
}
LocalMapBase::~LocalMapBase()
{
mCustomMarkers.eventMarkersChanged -= MyGUI::newDelegate(this, &LocalMapBase::updateCustomMarkers);
}
void LocalMapBase::init(MyGUI::ScrollView* widget, MyGUI::ImageBox* compass, int cellDistance)
{
mLocalMap = widget;
mCompass = compass;
mCellDistance = cellDistance;
mNumCells = mCellDistance * 2 + 1;
const int mapWidgetSize = Settings::map().mLocalMapWidgetSize;
mLocalMap->setCanvasSize(mapWidgetSize * mNumCells, mapWidgetSize * mNumCells);
mCompass->setDepth(Local_CompassLayer);
mCompass->setNeedMouseFocus(false);
for (int mx = 0; mx < mNumCells; ++mx)
{
for (int my = 0; my < mNumCells; ++my)
{
MyGUI::ImageBox* map = mLocalMap->createWidget<MyGUI::ImageBox>("ImageBox",
MyGUI::IntCoord(mx * mapWidgetSize, my * mapWidgetSize, mapWidgetSize, mapWidgetSize),
MyGUI::Align::Top | MyGUI::Align::Left);
map->setDepth(Local_MapLayer);
MyGUI::ImageBox* fog = mLocalMap->createWidget<MyGUI::ImageBox>("ImageBox",
MyGUI::IntCoord(mx * mapWidgetSize, my * mapWidgetSize, mapWidgetSize, mapWidgetSize),
MyGUI::Align::Top | MyGUI::Align::Left);
fog->setDepth(Local_FogLayer);
fog->setColour(MyGUI::Colour(0, 0, 0));
map->setNeedMouseFocus(false);
fog->setNeedMouseFocus(false);
mMaps.emplace_back(map, fog);
}
}
}
bool LocalMapBase::toggleFogOfWar()
{
mFogOfWarToggled = !mFogOfWarToggled;
applyFogOfWar();
return mFogOfWarToggled;
}
void LocalMapBase::applyFogOfWar()
{
if (!mFogOfWarToggled || !mFogOfWarEnabled)
{
for (auto& entry : mMaps)
{
entry.mFogWidget->setImageTexture({});
entry.mFogTexture.reset();
}
}
redraw();
}
MyGUI::IntPoint LocalMapBase::getPosition(int cellX, int cellY, float nX, float nY) const
{
// normalized cell coordinates
auto mapWidgetSize = getWidgetSize();
return MyGUI::IntPoint(std::round((nX + mCellDistance + cellX - mActiveCell->getGridX()) * mapWidgetSize),
std::round((nY + mCellDistance - cellY + mActiveCell->getGridY()) * mapWidgetSize));
}
MyGUI::IntPoint LocalMapBase::getMarkerPosition(float worldX, float worldY, MarkerUserData& markerPos) const
{
osg::Vec2i cellIndex;
// normalized cell coordinates
float nX, nY;
if (mActiveCell->isExterior())
{
ESM::ExteriorCellLocation cellPos = ESM::positionToExteriorCellLocation(worldX, worldY);
cellIndex.x() = cellPos.mX;
cellIndex.y() = cellPos.mY;
nX = (worldX - cellSize * cellIndex.x()) / cellSize;
// Image space is -Y up, cells are Y up
nY = 1 - (worldY - cellSize * cellIndex.y()) / cellSize;
}
else
mLocalMapRender->worldToInteriorMapPosition({ worldX, worldY }, nX, nY, cellIndex.x(), cellIndex.y());
markerPos.cellX = cellIndex.x();
markerPos.cellY = cellIndex.y();
markerPos.nX = nX;
markerPos.nY = nY;
return getPosition(markerPos.cellX, markerPos.cellY, markerPos.nX, markerPos.nY);
}
MyGUI::IntCoord LocalMapBase::getMarkerCoordinates(
float worldX, float worldY, MarkerUserData& markerPos, size_t markerSize) const
{
int halfMarkerSize = markerSize / 2;
auto position = getMarkerPosition(worldX, worldY, markerPos);
return MyGUI::IntCoord(position.left - halfMarkerSize, position.top - halfMarkerSize, markerSize, markerSize);
}
MyGUI::Widget* LocalMapBase::createDoorMarker(const std::string& name, float x, float y) const
{
MarkerUserData data(mLocalMapRender);
data.caption = name;
MarkerWidget* markerWidget = mLocalMap->createWidget<MarkerWidget>(
"MarkerButton", getMarkerCoordinates(x, y, data, 8), MyGUI::Align::Default);
markerWidget->setNormalColour(
MyGUI::Colour::parse(MyGUI::LanguageManager::getInstance().replaceTags("#{fontcolour=normal}")));
markerWidget->setHoverColour(
MyGUI::Colour::parse(MyGUI::LanguageManager::getInstance().replaceTags("#{fontcolour=normal_over}")));
markerWidget->setDepth(Local_MarkerLayer);
markerWidget->setNeedMouseFocus(true);
// Used by tooltips to not show the tooltip if marker is hidden by fog of war
markerWidget->setUserString("ToolTipType", "MapMarker");
markerWidget->setUserData(data);
return markerWidget;
}
void LocalMapBase::centerView()
{
MyGUI::IntPoint pos = mCompass->getPosition() + MyGUI::IntPoint{ 16, 16 };
MyGUI::IntSize viewsize = mLocalMap->getSize();
MyGUI::IntPoint viewOffset((viewsize.width / 2) - pos.left, (viewsize.height / 2) - pos.top);
mLocalMap->setViewOffset(viewOffset);
}
MyGUI::IntCoord LocalMapBase::getMarkerCoordinates(MyGUI::Widget* widget, size_t markerSize) const
{
MarkerUserData& markerPos(*widget->getUserData<MarkerUserData>());
auto position = getPosition(markerPos.cellX, markerPos.cellY, markerPos.nX, markerPos.nY);
return MyGUI::IntCoord(position.left - markerSize / 2, position.top - markerSize / 2, markerSize, markerSize);
}
std::vector<MyGUI::Widget*>& LocalMapBase::currentDoorMarkersWidgets()
{
return mActiveCell->isExterior() ? mExteriorDoorMarkerWidgets : mInteriorDoorMarkerWidgets;
}
void LocalMapBase::updateCustomMarkers()
{
for (MyGUI::Widget* widget : mCustomMarkerWidgets)
MyGUI::Gui::getInstance().destroyWidget(widget);
mCustomMarkerWidgets.clear();
if (!mActiveCell)
return;
for (int dX = -mCellDistance; dX <= mCellDistance; ++dX)
{
for (int dY = -mCellDistance; dY <= mCellDistance; ++dY)
{
ESM::RefId cellRefId
= getCellIdInWorldSpace(*mActiveCell, mActiveCell->getGridX() + dX, mActiveCell->getGridY() + dY);
CustomMarkerCollection::RangeType markers = mCustomMarkers.getMarkers(cellRefId);
for (CustomMarkerCollection::ContainerType::const_iterator it = markers.first; it != markers.second;
++it)
{
const ESM::CustomMarker& marker = it->second;
MarkerUserData markerPos(mLocalMapRender);
MarkerWidget* markerWidget = mLocalMap->createWidget<MarkerWidget>("CustomMarkerButton",
getMarkerCoordinates(marker.mWorldX, marker.mWorldY, markerPos, 16), MyGUI::Align::Default);
markerWidget->setDepth(Local_MarkerAboveFogLayer);
markerWidget->setUserString("ToolTipType", "Layout");
markerWidget->setUserString("ToolTipLayout", "TextToolTipOneLine");
markerWidget->setUserString("Caption_TextOneLine", MyGUI::TextIterator::toTagsString(marker.mNote));
markerWidget->setNormalColour(MyGUI::Colour(0.6f, 0.6f, 0.6f));
markerWidget->setHoverColour(MyGUI::Colour(1.0f, 1.0f, 1.0f));
markerWidget->setUserData(marker);
markerWidget->setNeedMouseFocus(true);
customMarkerCreated(markerWidget);
mCustomMarkerWidgets.push_back(markerWidget);
}
}
}
redraw();
}
void LocalMapBase::setActiveCell(const MWWorld::Cell& cell)
{
if (&cell == mActiveCell)
return; // don't do anything if we're still in the same cell
const int x = cell.getGridX();
const int y = cell.getGridY();
if (cell.isExterior())
{
const MyGUI::IntRect activeGrid = createRect({ x, y }, Constants::CellGridRadius);
const MyGUI::IntRect currentView = createRect({ x, y }, mCellDistance);
mExteriorDoorMarkerWidgets.clear();
for (auto& [coord, doors] : mExteriorDoorsByCell)
{
if (!mHasALastActiveCell || !currentView.inside({ coord.first, coord.second })
|| activeGrid.inside({ coord.first, coord.second }))
{
mDoorMarkersToRecycle.insert(mDoorMarkersToRecycle.end(), doors.begin(), doors.end());
doors.clear();
}
else
mExteriorDoorMarkerWidgets.insert(mExteriorDoorMarkerWidgets.end(), doors.begin(), doors.end());
}
for (auto& widget : mDoorMarkersToRecycle)
widget->setVisible(false);
if (mHasALastActiveCell)
{
for (const auto& entry : mMaps)
{
if (!currentView.inside({ entry.mCellX, entry.mCellY }))
mLocalMapRender->removeExteriorCell(entry.mCellX, entry.mCellY);
}
}
}
mActiveCell = &cell;
for (int mx = 0; mx < mNumCells; ++mx)
{
for (int my = 0; my < mNumCells; ++my)
{
MapEntry& entry = mMaps[my + mNumCells * mx];
entry.mMapWidget->setRenderItemTexture(nullptr);
entry.mFogWidget->setRenderItemTexture(nullptr);
entry.mMapTexture.reset();
entry.mFogTexture.reset();
entry.mCellX = x + (mx - mCellDistance);
entry.mCellY = y - (my - mCellDistance);
}
}
// Delay the door markers update until scripts have been given a chance to run.
// If we don't do this, door markers that should be disabled will still appear on the map.
mNeedDoorMarkersUpdate = true;
for (MyGUI::Widget* widget : currentDoorMarkersWidgets())
widget->setCoord(getMarkerCoordinates(widget, 8));
if (mActiveCell->isExterior())
mHasALastActiveCell = true;
updateMagicMarkers();
updateCustomMarkers();
}
void LocalMapBase::requestMapRender(const MWWorld::CellStore* cell)
{
mLocalMapRender->requestMap(cell);
}
void LocalMapBase::redraw()
{
// Redraw children in proper order
mLocalMap->getParent()->_updateChilds();
}
float LocalMapBase::getWidgetSize() const
{
return mLocalMapZoom * Settings::map().mLocalMapWidgetSize;
}
void LocalMapBase::setPlayerPos(int cellX, int cellY, const float nx, const float ny)
{
MyGUI::IntPoint pos = getPosition(cellX, cellY, nx, ny) - MyGUI::IntPoint{ 16, 16 };
if (pos != mCompass->getPosition())
{
notifyPlayerUpdate();
mCompass->setPosition(pos);
}
osg::Vec2f curPos((cellX + nx) * cellSize, (cellY + 1 - ny) * cellSize);
if ((curPos - mCurPos).length2() > 0.001)
{
mCurPos = curPos;
centerView();
}
}
void LocalMapBase::setPlayerDir(const float x, const float y)
{
if (x == mLastDirectionX && y == mLastDirectionY)
return;
notifyPlayerUpdate();
MyGUI::ISubWidget* main = mCompass->getSubWidgetMain();
MyGUI::RotatingSkin* rotatingSubskin = main->castType<MyGUI::RotatingSkin>();
rotatingSubskin->setCenter(MyGUI::IntPoint(16, 16));
float angle = std::atan2(x, y);
rotatingSubskin->setAngle(angle);
mLastDirectionX = x;
mLastDirectionY = y;
}
void LocalMapBase::addDetectionMarkers(int type)
{
std::vector<MWWorld::Ptr> markers;
MWBase::World* world = MWBase::Environment::get().getWorld();
world->listDetectedReferences(world->getPlayerPtr(), markers, MWBase::World::DetectionType(type));
if (markers.empty())
return;
std::string_view markerTexture;
if (type == MWBase::World::Detect_Creature)
{
markerTexture = "textures\\detect_animal_icon.dds";
}
if (type == MWBase::World::Detect_Key)
{
markerTexture = "textures\\detect_key_icon.dds";
}
if (type == MWBase::World::Detect_Enchantment)
{
markerTexture = "textures\\detect_enchantment_icon.dds";
}
for (const MWWorld::Ptr& ptr : markers)
{
const ESM::Position& worldPos = ptr.getRefData().getPosition();
MarkerUserData markerPos(mLocalMapRender);
MyGUI::ImageBox* markerWidget = mLocalMap->createWidget<MyGUI::ImageBox>("ImageBox",
getMarkerCoordinates(worldPos.pos[0], worldPos.pos[1], markerPos, 8), MyGUI::Align::Default);
markerWidget->setDepth(Local_MarkerAboveFogLayer);
markerWidget->setImageTexture(markerTexture);
markerWidget->setImageCoord(MyGUI::IntCoord(0, 0, 8, 8));
markerWidget->setNeedMouseFocus(false);
markerWidget->setUserData(markerPos);
mMagicMarkerWidgets.push_back(markerWidget);
}
}
void LocalMapBase::onFrame(float dt)
{
if (mNeedDoorMarkersUpdate)
{
updateDoorMarkers();
mNeedDoorMarkersUpdate = false;
}
mMarkerUpdateTimer += dt;
if (mMarkerUpdateTimer >= 0.25)
{
mMarkerUpdateTimer = 0;
updateMagicMarkers();
}
updateRequiredMaps();
}
bool widgetCropped(MyGUI::Widget* widget, MyGUI::Widget* cropTo)
{
MyGUI::IntRect coord = widget->getAbsoluteRect();
MyGUI::IntRect croppedCoord = cropTo->getAbsoluteRect();
if (coord.left < croppedCoord.left && coord.right < croppedCoord.left)
return true;
if (coord.left > croppedCoord.right && coord.right > croppedCoord.right)
return true;
if (coord.top < croppedCoord.top && coord.bottom < croppedCoord.top)
return true;
if (coord.top > croppedCoord.bottom && coord.bottom > croppedCoord.bottom)
return true;
return false;
}
void LocalMapBase::updateRequiredMaps()
{
bool needRedraw = false;
for (MapEntry& entry : mMaps)
{
if (widgetCropped(entry.mMapWidget, mLocalMap))
continue;
if (!entry.mMapTexture)
{
if (mActiveCell->isExterior())
requestMapRender(&MWBase::Environment::get().getWorldModel()->getExterior(
ESM::ExteriorCellLocation(entry.mCellX, entry.mCellY, ESM::Cell::sDefaultWorldspaceId)));
osg::ref_ptr<osg::Texture2D> texture = mLocalMapRender->getMapTexture(entry.mCellX, entry.mCellY);
if (texture)
{
entry.mMapTexture = std::make_unique<osgMyGUI::OSGTexture>(texture);
entry.mMapWidget->setRenderItemTexture(entry.mMapTexture.get());
entry.mMapWidget->getSubWidgetMain()->_setUVSet(MyGUI::FloatRect(0.f, 0.f, 1.f, 1.f));
needRedraw = true;
}
else
entry.mMapTexture = std::make_unique<osgMyGUI::OSGTexture>(std::string(), nullptr);
}
if (!entry.mFogTexture && mFogOfWarToggled && mFogOfWarEnabled)
{
osg::ref_ptr<osg::Texture2D> tex = mLocalMapRender->getFogOfWarTexture(entry.mCellX, entry.mCellY);
if (tex)
{
entry.mFogTexture = std::make_unique<osgMyGUI::OSGTexture>(tex);
entry.mFogWidget->setRenderItemTexture(entry.mFogTexture.get());
entry.mFogWidget->getSubWidgetMain()->_setUVSet(MyGUI::FloatRect(0.f, 1.f, 1.f, 0.f));
}
else
{
entry.mFogWidget->setImageTexture("black");
entry.mFogTexture = std::make_unique<osgMyGUI::OSGTexture>(std::string(), nullptr);
}
needRedraw = true;
}
}
if (needRedraw)
redraw();
}
void LocalMapBase::updateDoorMarkers()
{
std::vector<MWBase::World::DoorMarker> doors;
MWBase::World* world = MWBase::Environment::get().getWorld();
MWWorld::WorldModel* worldModel = MWBase::Environment::get().getWorldModel();
mDoorMarkersToRecycle.insert(
mDoorMarkersToRecycle.end(), mInteriorDoorMarkerWidgets.begin(), mInteriorDoorMarkerWidgets.end());
mInteriorDoorMarkerWidgets.clear();
if (!mActiveCell->isExterior())
{
for (MyGUI::Widget* widget : mExteriorDoorMarkerWidgets)
widget->setVisible(false);
MWWorld::CellStore& cell = worldModel->getInterior(mActiveCell->getNameId());
world->getDoorMarkers(cell, doors);
}
else
{
for (MapEntry& entry : mMaps)
{
if (!entry.mMapTexture && !widgetCropped(entry.mMapWidget, mLocalMap))
world->getDoorMarkers(worldModel->getExterior(ESM::ExteriorCellLocation(
entry.mCellX, entry.mCellY, ESM::Cell::sDefaultWorldspaceId)),
doors);
}
if (doors.empty())
return;
}
// Create a widget for each marker
for (MWBase::World::DoorMarker& marker : doors)
{
std::vector<std::string> destNotes;
CustomMarkerCollection::RangeType markers = mCustomMarkers.getMarkers(marker.dest);
for (CustomMarkerCollection::ContainerType::const_iterator iter = markers.first; iter != markers.second;
++iter)
destNotes.push_back(iter->second.mNote);
MyGUI::Widget* markerWidget = nullptr;
MarkerUserData* data;
if (mDoorMarkersToRecycle.empty())
{
markerWidget = createDoorMarker(marker.name, marker.x, marker.y);
data = markerWidget->getUserData<MarkerUserData>();
data->notes = std::move(destNotes);
doorMarkerCreated(markerWidget);
}
else
{
markerWidget = (MarkerWidget*)mDoorMarkersToRecycle.back();
mDoorMarkersToRecycle.pop_back();
data = markerWidget->getUserData<MarkerUserData>();
data->notes = std::move(destNotes);
data->caption = marker.name;
markerWidget->setCoord(getMarkerCoordinates(marker.x, marker.y, *data, 8));
markerWidget->setVisible(true);
}
currentDoorMarkersWidgets().push_back(markerWidget);
if (mActiveCell->isExterior())
mExteriorDoorsByCell[{ data->cellX, data->cellY }].push_back(markerWidget);
}
for (auto& widget : mDoorMarkersToRecycle)
widget->setVisible(false);
}
void LocalMapBase::updateMagicMarkers()
{
// clear all previous markers
for (MyGUI::Widget* widget : mMagicMarkerWidgets)
MyGUI::Gui::getInstance().destroyWidget(widget);
mMagicMarkerWidgets.clear();
addDetectionMarkers(MWBase::World::Detect_Creature);
addDetectionMarkers(MWBase::World::Detect_Key);
addDetectionMarkers(MWBase::World::Detect_Enchantment);
// Add marker for the spot marked with Mark magic effect
MWWorld::CellStore* markedCell = nullptr;
ESM::Position markedPosition;
MWBase::Environment::get().getWorld()->getPlayer().getMarkedPosition(markedCell, markedPosition);
if (markedCell && markedCell->getCell()->getWorldSpace() == mActiveCell->getWorldSpace())
{
MarkerUserData markerPos(mLocalMapRender);
MyGUI::ImageBox* markerWidget = mLocalMap->createWidget<MyGUI::ImageBox>("ImageBox",
getMarkerCoordinates(markedPosition.pos[0], markedPosition.pos[1], markerPos, 8),
MyGUI::Align::Default);
markerWidget->setDepth(Local_MarkerAboveFogLayer);
markerWidget->setImageTexture("textures\\menu_map_smark.dds");
markerWidget->setNeedMouseFocus(false);
markerWidget->setUserData(markerPos);
mMagicMarkerWidgets.push_back(markerWidget);
}
redraw();
}
void LocalMapBase::updateLocalMap()
{
auto mapWidgetSize = getWidgetSize();
mLocalMap->setCanvasSize(mapWidgetSize * mNumCells, mapWidgetSize * mNumCells);
const auto size = MyGUI::IntSize(std::ceil(mapWidgetSize), std::ceil(mapWidgetSize));
for (auto& entry : mMaps)
{
const auto position = getPosition(entry.mCellX, entry.mCellY, 0, 0);
entry.mMapWidget->setCoord({ position, size });
entry.mFogWidget->setCoord({ position, size });
}
MarkerUserData markerPos(mLocalMapRender);
for (MyGUI::Widget* widget : currentDoorMarkersWidgets())
widget->setCoord(getMarkerCoordinates(widget, 8));
for (MyGUI::Widget* widget : mCustomMarkerWidgets)
{
const auto& marker = *widget->getUserData<ESM::CustomMarker>();
widget->setCoord(getMarkerCoordinates(marker.mWorldX, marker.mWorldY, markerPos, 16));
}
for (MyGUI::Widget* widget : mMagicMarkerWidgets)
widget->setCoord(getMarkerCoordinates(widget, 8));
}
// ------------------------------------------------------------------------------------------
MapWindow::MapWindow(CustomMarkerCollection& customMarkers, DragAndDrop* drag, MWRender::LocalMap* localMapRender,
SceneUtil::WorkQueue* workQueue)
#ifdef USE_OPENXR
: WindowPinnableBase("openmw_map_window_vr.layout")
#else
: WindowPinnableBase("openmw_map_window.layout")
#endif
, LocalMapBase(customMarkers, localMapRender, true)
, NoDrop(drag, mMainWidget)
, mGlobalMap(nullptr)
, mGlobalMapImage(nullptr)
, mGlobalMapOverlay(nullptr)
, mEventBoxGlobal(nullptr)
, mEventBoxLocal(nullptr)
, mGlobalMapRender(std::make_unique<MWRender::GlobalMap>(localMapRender->getRoot(), workQueue))
, mEditNoteDialog()
{
static bool registered = false;
if (!registered)
{
MyGUI::FactoryManager::getInstance().registerFactory<MarkerWidget>("Widget");
registered = true;
}
mEditNoteDialog.setVisible(false);
mEditNoteDialog.eventOkClicked += MyGUI::newDelegate(this, &MapWindow::onNoteEditOk);
mEditNoteDialog.eventDeleteClicked += MyGUI::newDelegate(this, &MapWindow::onNoteEditDelete);
setCoord(500, 0, 320, 300);
getWidget(mLocalMap, "LocalMap");
getWidget(mGlobalMap, "GlobalMap");
getWidget(mGlobalMapImage, "GlobalMapImage");
getWidget(mGlobalMapOverlay, "GlobalMapOverlay");
getWidget(mPlayerArrowLocal, "CompassLocal");
getWidget(mPlayerArrowGlobal, "CompassGlobal");
mPlayerArrowGlobal->setDepth(Global_CompassLayer);
mPlayerArrowGlobal->setNeedMouseFocus(false);
mGlobalMapImage->setDepth(Global_MapLayer);
mGlobalMapOverlay->setDepth(Global_ExploreOverlayLayer);
mLastScrollWindowCoordinates = mLocalMap->getCoord();
mLocalMap->eventChangeCoord += MyGUI::newDelegate(this, &MapWindow::onChangeScrollWindowCoord);
mGlobalMap->setVisible(false);
getWidget(mButton, "WorldButton");
mButton->eventMouseButtonClick += MyGUI::newDelegate(this, &MapWindow::onWorldButtonClicked);
const bool global = Settings::map().mGlobal;
mButton->setCaptionWithReplacing(global ? "#{sLocal}" : "#{sWorld}");
getWidget(mEventBoxGlobal, "EventBoxGlobal");
mEventBoxGlobal->eventMouseDrag += MyGUI::newDelegate(this, &MapWindow::onMouseDrag);
mEventBoxGlobal->eventMouseButtonPressed += MyGUI::newDelegate(this, &MapWindow::onDragStart);
const bool allowZooming = Settings::map().mAllowZooming;
if (allowZooming)
mEventBoxGlobal->eventMouseWheel += MyGUI::newDelegate(this, &MapWindow::onMapZoomed);
mEventBoxGlobal->setDepth(Global_ExploreOverlayLayer);
getWidget(mEventBoxLocal, "EventBoxLocal");
mEventBoxLocal->eventMouseDrag += MyGUI::newDelegate(this, &MapWindow::onMouseDrag);
mEventBoxLocal->eventMouseButtonPressed += MyGUI::newDelegate(this, &MapWindow::onDragStart);
mEventBoxLocal->eventMouseButtonDoubleClick += MyGUI::newDelegate(this, &MapWindow::onMapDoubleClicked);
if (allowZooming)
mEventBoxLocal->eventMouseWheel += MyGUI::newDelegate(this, &MapWindow::onMapZoomed);
LocalMapBase::init(mLocalMap, mPlayerArrowLocal, getLocalViewingDistance());
mGlobalMap->setVisible(global);
mLocalMap->setVisible(!global);
}
void MapWindow::onNoteEditOk()
{
if (mEditNoteDialog.getDeleteButtonShown())
mCustomMarkers.updateMarker(mEditingMarker, mEditNoteDialog.getText());
else
{
mEditingMarker.mNote = mEditNoteDialog.getText();
mCustomMarkers.addMarker(mEditingMarker);
}
mEditNoteDialog.setVisible(false);
}
void MapWindow::onNoteEditDelete()
{
ConfirmationDialog* confirmation = MWBase::Environment::get().getWindowManager()->getConfirmationDialog();
confirmation->askForConfirmation("#{sDeleteNote}");
confirmation->eventCancelClicked.clear();
confirmation->eventOkClicked.clear();
confirmation->eventOkClicked += MyGUI::newDelegate(this, &MapWindow::onNoteEditDeleteConfirm);
}
void MapWindow::onNoteEditDeleteConfirm()
{
mCustomMarkers.deleteMarker(mEditingMarker);
mEditNoteDialog.setVisible(false);
}
void MapWindow::onCustomMarkerDoubleClicked(MyGUI::Widget* sender)
{
mEditingMarker = *sender->getUserData<ESM::CustomMarker>();
mEditNoteDialog.setText(mEditingMarker.mNote);
mEditNoteDialog.showDeleteButton(true);
mEditNoteDialog.setVisible(true);
}
void MapWindow::onMapDoubleClicked(MyGUI::Widget* sender)
{
MyGUI::IntPoint clickedPos = MyGUI::InputManager::getInstance().getMousePosition();
MyGUI::IntPoint widgetPos = clickedPos - mEventBoxLocal->getAbsolutePosition();
auto mapWidgetSize = getWidgetSize();
int x = int(widgetPos.left / float(mapWidgetSize)) - mCellDistance;
int y = (int(widgetPos.top / float(mapWidgetSize)) - mCellDistance) * -1;
float nX = widgetPos.left / float(mapWidgetSize) - int(widgetPos.left / float(mapWidgetSize));
float nY = widgetPos.top / float(mapWidgetSize) - int(widgetPos.top / float(mapWidgetSize));
x += mActiveCell->getGridX();
y += mActiveCell->getGridY();
osg::Vec2f worldPos;
if (!mActiveCell->isExterior())
{
worldPos = mLocalMapRender->interiorMapToWorldPosition(nX, nY, x, y);
}
else
{
worldPos.x() = (x + nX) * cellSize;
worldPos.y() = (y + (1.0f - nY)) * cellSize;
}
mEditingMarker.mWorldX = worldPos.x();
mEditingMarker.mWorldY = worldPos.y();
ESM::RefId clickedId = getCellIdInWorldSpace(*mActiveCell, x, y);
mEditingMarker.mCell = clickedId;
mEditNoteDialog.setVisible(true);
mEditNoteDialog.showDeleteButton(false);
mEditNoteDialog.setText({});
}
void MapWindow::onMapZoomed(MyGUI::Widget* sender, int rel)
{
const int localWidgetSize = Settings::map().mLocalMapWidgetSize;
const bool zoomOut = rel < 0;
const bool zoomIn = !zoomOut;
const double speedDiff = zoomOut ? 1.0 / speed : speed;
const float localMapSizeInUnits = localWidgetSize * mNumCells;
const float currentMinLocalMapZoom = std::max({ (float(Settings::map().mGlobalMapCellSize) * 4.f)
/ float(localWidgetSize),
float(mLocalMap->getWidth()) / localMapSizeInUnits, float(mLocalMap->getHeight()) / localMapSizeInUnits });
if (Settings::map().mGlobal)
{
const float currentGlobalZoom = mGlobalMapZoom;
const float currentMinGlobalMapZoom
= std::min(float(mGlobalMap->getWidth()) / float(mGlobalMapRender->getWidth()),
float(mGlobalMap->getHeight()) / float(mGlobalMapRender->getHeight()));
mGlobalMapZoom *= speedDiff;
if (zoomIn && mGlobalMapZoom > 4.f)
{
mGlobalMapZoom = currentGlobalZoom;
mLocalMapZoom = currentMinLocalMapZoom;
onWorldButtonClicked(nullptr);
updateLocalMap();
return; // the zoom in is too big
}
if (zoomOut && mGlobalMapZoom < currentMinGlobalMapZoom)
{
mGlobalMapZoom = currentGlobalZoom;
return; // the zoom out is too big, we have reach the borders of the widget
}
}
else
{
auto const currentLocalZoom = mLocalMapZoom;
mLocalMapZoom *= speedDiff;
if (zoomIn && mLocalMapZoom > 4.0f)
{
mLocalMapZoom = currentLocalZoom;
return; // the zoom in is too big
}
if (zoomOut && mLocalMapZoom < currentMinLocalMapZoom)
{
mLocalMapZoom = currentLocalZoom;
float zoomRatio = 4.f / mGlobalMapZoom;
mGlobalMapZoom = 4.f;
onWorldButtonClicked(nullptr);
zoomOnCursor(zoomRatio);
return; // the zoom out is too big, we switch to the global map
}
if (zoomOut)
mNeedDoorMarkersUpdate = true;
}
zoomOnCursor(speedDiff);
}
void MapWindow::zoomOnCursor(float speedDiff)
{
auto map = Settings::map().mGlobal ? mGlobalMap : mLocalMap;
auto cursor = MyGUI::InputManager::getInstance().getMousePosition() - map->getAbsolutePosition();
auto centerView = map->getViewOffset() - cursor;
Settings::map().mGlobal ? updateGlobalMap() : updateLocalMap();
map->setViewOffset(MyGUI::IntPoint(std::round(centerView.left * speedDiff) + cursor.left,
std::round(centerView.top * speedDiff) + cursor.top));
}
void MapWindow::updateGlobalMap()
{
resizeGlobalMap();
float x = mCurPos.x(), y = mCurPos.y();
if (!mActiveCell->isExterior())
{
auto pos = MWBase::Environment::get().getWorld()->getPlayer().getLastKnownExteriorPosition();
x = pos.x();
y = pos.y();
}
setGlobalMapPlayerPosition(x, y);
for (auto& [marker, col] : mGlobalMapMarkers)
{
marker.widget->setCoord(createMarkerCoords(marker.position.x(), marker.position.y(), col.size()));
marker.widget->setVisible(marker.widget->getHeight() >= 6);
}
}
void MapWindow::onChangeScrollWindowCoord(MyGUI::Widget* sender)
{
MyGUI::IntCoord currentCoordinates = sender->getCoord();
MyGUI::IntPoint currentViewPortCenter
= MyGUI::IntPoint(currentCoordinates.width / 2, currentCoordinates.height / 2);
MyGUI::IntPoint lastViewPortCenter
= MyGUI::IntPoint(mLastScrollWindowCoordinates.width / 2, mLastScrollWindowCoordinates.height / 2);
MyGUI::IntPoint viewPortCenterDiff = currentViewPortCenter - lastViewPortCenter;
mLocalMap->setViewOffset(mLocalMap->getViewOffset() + viewPortCenterDiff);
mGlobalMap->setViewOffset(mGlobalMap->getViewOffset() + viewPortCenterDiff);
mLastScrollWindowCoordinates = currentCoordinates;
}
void MapWindow::setVisible(bool visible)
{
WindowBase::setVisible(visible);
mButton->setVisible(visible && MWBase::Environment::get().getWindowManager()->getMode() != MWGui::GM_None);
}
void MapWindow::renderGlobalMap()
{
mGlobalMapRender->render();
resizeGlobalMap();
}
MapWindow::~MapWindow() = default;
void MapWindow::setCellName(const std::string& cellName)
{
setTitle("#{sCell=" + cellName + "}");
}
MyGUI::IntCoord MapWindow::createMarkerCoords(float x, float y, float agregatedWeight) const
{
float worldX, worldY;
worldPosToGlobalMapImageSpace(
(x + 0.5f) * Constants::CellSizeInUnits, (y + 0.5f) * Constants::CellSizeInUnits, worldX, worldY);
const float markerSize = getMarkerSize(agregatedWeight);
const float halfMarkerSize = markerSize / 2.0f;
return MyGUI::IntCoord(static_cast<int>(worldX - halfMarkerSize), static_cast<int>(worldY - halfMarkerSize),
markerSize, markerSize);
}
MyGUI::Widget* MapWindow::createMarker(const std::string& name, float x, float y, float agregatedWeight)
{
MyGUI::Widget* markerWidget = mGlobalMap->createWidget<MyGUI::Widget>(
"MarkerButton", createMarkerCoords(x, y, agregatedWeight), MyGUI::Align::Default);
markerWidget->setVisible(markerWidget->getHeight() >= 6.0);
markerWidget->setUserString("Caption_TextOneLine", "#{sCell=" + name + "}");
setGlobalMapMarkerTooltip(markerWidget, x, y);
markerWidget->setUserString("ToolTipLayout", "TextToolTipOneLine");
markerWidget->setNeedMouseFocus(true);
markerWidget->setColour(
MyGUI::Colour::parse(MyGUI::LanguageManager::getInstance().replaceTags("#{fontcolour=normal}")));
markerWidget->setDepth(Global_MarkerLayer);
markerWidget->eventMouseDrag += MyGUI::newDelegate(this, &MapWindow::onMouseDrag);
if (Settings::map().mAllowZooming)
markerWidget->eventMouseWheel += MyGUI::newDelegate(this, &MapWindow::onMapZoomed);
markerWidget->eventMouseButtonPressed += MyGUI::newDelegate(this, &MapWindow::onDragStart);
return markerWidget;
}
void MapWindow::addVisitedLocation(const std::string& name, int x, int y)
{
CellId cell;
cell.first = x;
cell.second = y;
if (mMarkers.insert(cell).second)
{
MapMarkerType mapMarkerWidget = { osg::Vec2f(x, y), createMarker(name, x, y, 0) };
mGlobalMapMarkers.emplace(mapMarkerWidget, std::vector<MapMarkerType>());
std::string name_ = name.substr(0, name.find(','));
auto& entry = mGlobalMapMarkersByName[name_];
if (!entry.widget)
{
entry = { osg::Vec2f(x, y), entry.widget }; // update the coords
entry.widget = createMarker(name_, entry.position.x(), entry.position.y(), 1);
mGlobalMapMarkers.emplace(entry, std::vector<MapMarkerType>{ entry });
}
else
{
auto it = mGlobalMapMarkers.find(entry);
auto& marker = const_cast<MapMarkerType&>(it->first);
auto& elements = it->second;
elements.emplace_back(mapMarkerWidget);
// we compute the barycenter of the entry elements => it will be the place on the world map for the
// agregated widget
marker.position = std::accumulate(elements.begin(), elements.end(), osg::Vec2f(0.f, 0.f),
[](const auto& left, const auto& right) { return left + right.position; })
/ float(elements.size());
marker.widget->setCoord(createMarkerCoords(marker.position.x(), marker.position.y(), elements.size()));
marker.widget->setVisible(marker.widget->getHeight() >= 6);
}
}
}
void MapWindow::cellExplored(int x, int y)
{
mGlobalMapRender->cleanupCameras();
mGlobalMapRender->exploreCell(x, y, mLocalMapRender->getMapTexture(x, y));
}
void MapWindow::onFrame(float dt)
{
LocalMapBase::onFrame(dt);
NoDrop::onFrame(dt);
}
void MapWindow::setGlobalMapMarkerTooltip(MyGUI::Widget* markerWidget, int x, int y)
{
ESM::RefId cellRefId = ESM::RefId::esm3ExteriorCell(x, y);
CustomMarkerCollection::RangeType markers = mCustomMarkers.getMarkers(cellRefId);
std::vector<std::string> destNotes;
for (CustomMarkerCollection::ContainerType::const_iterator it = markers.first; it != markers.second; ++it)
destNotes.push_back(it->second.mNote);
if (!destNotes.empty())
{
MarkerUserData data(nullptr);
std::swap(data.notes, destNotes);
data.caption = markerWidget->getUserString("Caption_TextOneLine");
markerWidget->setUserData(data);
markerWidget->setUserString("ToolTipType", "MapMarker");
}
else
{
markerWidget->setUserString("ToolTipType", "Layout");
}
}
float MapWindow::getMarkerSize(size_t agregatedWeight) const
{
float markerSize = 12.f * mGlobalMapZoom;
if (mGlobalMapZoom < 1)
return markerSize * std::sqrt(agregatedWeight); // we want to see agregated object
return agregatedWeight ? 0 : markerSize; // we want to see only original markers (i.e. non agregated)
}
void MapWindow::resizeGlobalMap()
{
mGlobalMap->setCanvasSize(
mGlobalMapRender->getWidth() * mGlobalMapZoom, mGlobalMapRender->getHeight() * mGlobalMapZoom);
mGlobalMapImage->setSize(
mGlobalMapRender->getWidth() * mGlobalMapZoom, mGlobalMapRender->getHeight() * mGlobalMapZoom);
}
void MapWindow::worldPosToGlobalMapImageSpace(float x, float y, float& imageX, float& imageY) const
{
mGlobalMapRender->worldPosToImageSpace(x, y, imageX, imageY);
imageX *= mGlobalMapZoom;
imageY *= mGlobalMapZoom;
}
void MapWindow::updateCustomMarkers()
{
LocalMapBase::updateCustomMarkers();
for (auto& [widgetPair, ignore] : mGlobalMapMarkers)
setGlobalMapMarkerTooltip(widgetPair.widget, widgetPair.position.x(), widgetPair.position.y());
}
void MapWindow::onDragStart(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
{
if (_id != MyGUI::MouseButton::Left)
return;
mLastDragPos = MyGUI::IntPoint(_left, _top);
}
void MapWindow::onMouseDrag(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
{
if (_id != MyGUI::MouseButton::Left)
return;
MyGUI::IntPoint diff = MyGUI::IntPoint(_left, _top) - mLastDragPos;
if (!Settings::map().mGlobal)
{
mNeedDoorMarkersUpdate = true;
mLocalMap->setViewOffset(mLocalMap->getViewOffset() + diff);
}
else
mGlobalMap->setViewOffset(mGlobalMap->getViewOffset() + diff);
mLastDragPos = MyGUI::IntPoint(_left, _top);
}
void MapWindow::onWorldButtonClicked(MyGUI::Widget* _sender)
{
const bool global = !Settings::map().mGlobal;
Settings::map().mGlobal.set(global);
mGlobalMap->setVisible(global);
mLocalMap->setVisible(!global);
mButton->setCaptionWithReplacing(global ? "#{sLocal}" : "#{sWorld}");
}
void MapWindow::onPinToggled()
{
Settings::windows().mMapPin.set(mPinned);
MWBase::Environment::get().getWindowManager()->setMinimapVisibility(!mPinned);
}
void MapWindow::onTitleDoubleClicked()
{
if (MyGUI::InputManager::getInstance().isShiftPressed())
MWBase::Environment::get().getWindowManager()->toggleMaximized(this);
else if (!mPinned)
MWBase::Environment::get().getWindowManager()->toggleVisible(GW_Map);
}
void MapWindow::onOpen()
{
ensureGlobalMapLoaded();
globalMapUpdatePlayer();
}
void MapWindow::globalMapUpdatePlayer()
{
// For interiors, position is set by WindowManager via setGlobalMapPlayerPosition
if (MWBase::Environment::get().getWorld()->isCellExterior())
{
osg::Vec3f pos = MWBase::Environment::get().getWorld()->getPlayerPtr().getRefData().getPosition().asVec3();
setGlobalMapPlayerPosition(pos.x(), pos.y());
}
}
void MapWindow::notifyPlayerUpdate()
{
globalMapUpdatePlayer();
setGlobalMapPlayerDir(mLastDirectionX, mLastDirectionY);
}
void MapWindow::centerView()
{
LocalMapBase::centerView();
// set the view offset so that player is in the center
MyGUI::IntSize viewsize = mGlobalMap->getSize();
MyGUI::IntPoint pos = mPlayerArrowGlobal->getPosition() + MyGUI::IntPoint{ 16, 16 };
MyGUI::IntPoint viewoffs(
static_cast<int>(viewsize.width * 0.5f - pos.left), static_cast<int>(viewsize.height * 0.5f - pos.top));
mGlobalMap->setViewOffset(viewoffs);
}
void MapWindow::setGlobalMapPlayerPosition(float worldX, float worldY)
{
float x, y;
worldPosToGlobalMapImageSpace(worldX, worldY, x, y);
mPlayerArrowGlobal->setPosition(MyGUI::IntPoint(static_cast<int>(x - 16), static_cast<int>(y - 16)));
}
void MapWindow::setGlobalMapPlayerDir(const float x, const float y)
{
MyGUI::ISubWidget* main = mPlayerArrowGlobal->getSubWidgetMain();
MyGUI::RotatingSkin* rotatingSubskin = main->castType<MyGUI::RotatingSkin>();
rotatingSubskin->setCenter(MyGUI::IntPoint(16, 16));
float angle = std::atan2(x, y);
rotatingSubskin->setAngle(angle);
}
void MapWindow::ensureGlobalMapLoaded()
{
if (!mGlobalMapTexture.get())
{
mGlobalMapTexture = std::make_unique<osgMyGUI::OSGTexture>(mGlobalMapRender->getBaseTexture());
mGlobalMapImage->setRenderItemTexture(mGlobalMapTexture.get());
mGlobalMapImage->getSubWidgetMain()->_setUVSet(MyGUI::FloatRect(0.f, 0.f, 1.f, 1.f));
mGlobalMapOverlayTexture = std::make_unique<osgMyGUI::OSGTexture>(mGlobalMapRender->getOverlayTexture());
mGlobalMapOverlay->setRenderItemTexture(mGlobalMapOverlayTexture.get());
mGlobalMapOverlay->getSubWidgetMain()->_setUVSet(MyGUI::FloatRect(0.f, 0.f, 1.f, 1.f));
// Redraw children in proper order
mGlobalMap->getParent()->_updateChilds();
}
}
void MapWindow::clear()
{
mMarkers.clear();
mGlobalMapRender->clear();
mActiveCell = nullptr;
for (auto& widgetPair : mGlobalMapMarkers)
MyGUI::Gui::getInstance().destroyWidget(widgetPair.first.widget);
mGlobalMapMarkers.clear();
mGlobalMapMarkersByName.clear();
}
void MapWindow::write(ESM::ESMWriter& writer, Loading::Listener& progress)
{
ESM::GlobalMap map;
mGlobalMapRender->write(map);
map.mMarkers = mMarkers;
writer.startRecord(ESM::REC_GMAP);
map.save(writer);
writer.endRecord(ESM::REC_GMAP);
}
void MapWindow::readRecord(ESM::ESMReader& reader, uint32_t type)
{
if (type == ESM::REC_GMAP)
{
ESM::GlobalMap map;
map.load(reader);
mGlobalMapRender->read(map);
for (const ESM::GlobalMap::CellId& cellId : map.mMarkers)
{
const ESM::Cell* cell
= MWBase::Environment::get().getESMStore()->get<ESM::Cell>().search(cellId.first, cellId.second);
if (cell && !cell->mName.empty())
addVisitedLocation(cell->mName, cellId.first, cellId.second);
}
}
}
void MapWindow::setAlpha(float alpha)
{
NoDrop::setAlpha(alpha);
// can't allow showing map with partial transparency, as the fog of war will also go transparent
// and reveal parts of the map you shouldn't be able to see
for (MapEntry& entry : mMaps)
entry.mMapWidget->setVisible(alpha == 1);
}
void MapWindow::customMarkerCreated(MyGUI::Widget* marker)
{
marker->eventMouseDrag += MyGUI::newDelegate(this, &MapWindow::onMouseDrag);
marker->eventMouseButtonPressed += MyGUI::newDelegate(this, &MapWindow::onDragStart);
marker->eventMouseButtonDoubleClick += MyGUI::newDelegate(this, &MapWindow::onCustomMarkerDoubleClicked);
if (Settings::map().mAllowZooming)
marker->eventMouseWheel += MyGUI::newDelegate(this, &MapWindow::onMapZoomed);
}
void MapWindow::doorMarkerCreated(MyGUI::Widget* marker)
{
marker->eventMouseDrag += MyGUI::newDelegate(this, &MapWindow::onMouseDrag);
marker->eventMouseButtonPressed += MyGUI::newDelegate(this, &MapWindow::onDragStart);
if (Settings::map().mAllowZooming)
marker->eventMouseWheel += MyGUI::newDelegate(this, &MapWindow::onMapZoomed);
}
void MapWindow::asyncPrepareSaveMap()
{
mGlobalMapRender->asyncWritePng();
}
// -------------------------------------------------------------------
EditNoteDialog::EditNoteDialog()
: WindowModal("openmw_edit_note.layout")
{
getWidget(mOkButton, "OkButton");
getWidget(mCancelButton, "CancelButton");
getWidget(mDeleteButton, "DeleteButton");
getWidget(mTextEdit, "TextEdit");
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &EditNoteDialog::onCancelButtonClicked);
mOkButton->eventMouseButtonClick += MyGUI::newDelegate(this, &EditNoteDialog::onOkButtonClicked);
mDeleteButton->eventMouseButtonClick += MyGUI::newDelegate(this, &EditNoteDialog::onDeleteButtonClicked);
}
void EditNoteDialog::showDeleteButton(bool show)
{
mDeleteButton->setVisible(show);
}
bool EditNoteDialog::getDeleteButtonShown()
{
return mDeleteButton->getVisible();
}
void EditNoteDialog::setText(const std::string& text)
{
mTextEdit->setCaption(MyGUI::TextIterator::toTagsString(text));
}
std::string EditNoteDialog::getText()
{
return MyGUI::TextIterator::getOnlyText(mTextEdit->getCaption());
}
void EditNoteDialog::onOpen()
{
WindowModal::onOpen();
center();
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mTextEdit);
}
void EditNoteDialog::onCancelButtonClicked(MyGUI::Widget* sender)
{
setVisible(false);
}
void EditNoteDialog::onOkButtonClicked(MyGUI::Widget* sender)
{
eventOkClicked();
}
void EditNoteDialog::onDeleteButtonClicked(MyGUI::Widget* sender)
{
eventDeleteClicked();
}
bool LocalMapBase::MarkerUserData::isPositionExplored() const
{
if (!mLocalMapRender)
return true;
return mLocalMapRender->isPositionExplored(nX, nY, cellX, cellY);
}
}
| 53,326
|
C++
|
.cpp
| 1,189
| 34.923465
| 120
| 0.629976
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,468
|
journalwindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/journalwindow.cpp
|
#include "journalwindow.hpp"
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <MyGUI_Button.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_TextBox.h>
#include <components/misc/strings/algorithm.hpp>
#include <components/widgets/imagebutton.hpp>
#include <components/widgets/list.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/journal.hpp"
#include "../mwbase/windowmanager.hpp"
#include "bookpage.hpp"
#include "journalbooks.hpp"
#include "journalviewmodel.hpp"
#include "windowbase.hpp"
namespace
{
static constexpr std::string_view OptionsOverlay = "OptionsOverlay";
static constexpr std::string_view OptionsBTN = "OptionsBTN";
static constexpr std::string_view PrevPageBTN = "PrevPageBTN";
static constexpr std::string_view NextPageBTN = "NextPageBTN";
static constexpr std::string_view CloseBTN = "CloseBTN";
static constexpr std::string_view JournalBTN = "JournalBTN";
static constexpr std::string_view TopicsBTN = "TopicsBTN";
static constexpr std::string_view QuestsBTN = "QuestsBTN";
static constexpr std::string_view CancelBTN = "CancelBTN";
static constexpr std::string_view ShowAllBTN = "ShowAllBTN";
static constexpr std::string_view ShowActiveBTN = "ShowActiveBTN";
static constexpr std::string_view PageOneNum = "PageOneNum";
static constexpr std::string_view PageTwoNum = "PageTwoNum";
static constexpr std::string_view TopicsList = "TopicsList";
static constexpr std::string_view QuestsList = "QuestsList";
static constexpr std::string_view LeftBookPage = "LeftBookPage";
static constexpr std::string_view RightBookPage = "RightBookPage";
static constexpr std::string_view LeftTopicIndex = "LeftTopicIndex";
static constexpr std::string_view CenterTopicIndex = "CenterTopicIndex";
static constexpr std::string_view RightTopicIndex = "RightTopicIndex";
struct JournalWindowImpl : MWGui::JournalBooks, MWGui::JournalWindow
{
struct DisplayState
{
unsigned int mPage;
Book mBook;
};
typedef std::stack<DisplayState> DisplayStateStack;
DisplayStateStack mStates;
Book mTopicIndexBook;
bool mQuestMode;
bool mOptionsMode;
bool mTopicsMode;
bool mAllQuests;
template <typename T>
T* getWidget(std::string_view name)
{
T* widget;
WindowBase::getWidget(widget, name);
return widget;
}
template <typename value_type>
void setText(std::string_view name, value_type const& value)
{
getWidget<MyGUI::TextBox>(name)->setCaption(MyGUI::utility::toString(value));
}
void setVisible(std::string_view name, bool visible) { getWidget<MyGUI::Widget>(name)->setVisible(visible); }
void adviseButtonClick(std::string_view name, void (JournalWindowImpl::*handler)(MyGUI::Widget*))
{
getWidget<MyGUI::Widget>(name)->eventMouseButtonClick += newDelegate(this, handler);
}
void adviseKeyPress(
std::string_view name, void (JournalWindowImpl::*handler)(MyGUI::Widget*, MyGUI::KeyCode, MyGUI::Char))
{
getWidget<MyGUI::Widget>(name)->eventKeyButtonPressed += newDelegate(this, handler);
}
MWGui::BookPage* getPage(std::string_view name) { return getWidget<MWGui::BookPage>(name); }
JournalWindowImpl(MWGui::JournalViewModel::Ptr model, bool questList, ToUTF8::FromType encoding)
: JournalBooks(std::move(model), encoding)
, JournalWindow()
{
center();
adviseButtonClick(OptionsBTN, &JournalWindowImpl::notifyOptions);
adviseButtonClick(PrevPageBTN, &JournalWindowImpl::notifyPrevPage);
adviseButtonClick(NextPageBTN, &JournalWindowImpl::notifyNextPage);
adviseButtonClick(CloseBTN, &JournalWindowImpl::notifyClose);
adviseButtonClick(JournalBTN, &JournalWindowImpl::notifyJournal);
adviseButtonClick(TopicsBTN, &JournalWindowImpl::notifyTopics);
adviseButtonClick(QuestsBTN, &JournalWindowImpl::notifyQuests);
adviseButtonClick(CancelBTN, &JournalWindowImpl::notifyCancel);
adviseButtonClick(ShowAllBTN, &JournalWindowImpl::notifyShowAll);
adviseButtonClick(ShowActiveBTN, &JournalWindowImpl::notifyShowActive);
adviseKeyPress(OptionsBTN, &JournalWindowImpl::notifyKeyPress);
adviseKeyPress(PrevPageBTN, &JournalWindowImpl::notifyKeyPress);
adviseKeyPress(NextPageBTN, &JournalWindowImpl::notifyKeyPress);
adviseKeyPress(CloseBTN, &JournalWindowImpl::notifyKeyPress);
adviseKeyPress(JournalBTN, &JournalWindowImpl::notifyKeyPress);
Gui::MWList* list = getWidget<Gui::MWList>(QuestsList);
list->eventItemSelected += MyGUI::newDelegate(this, &JournalWindowImpl::notifyQuestClicked);
Gui::MWList* topicsList = getWidget<Gui::MWList>(TopicsList);
topicsList->eventItemSelected += MyGUI::newDelegate(this, &JournalWindowImpl::notifyTopicSelected);
{
MWGui::BookPage::ClickCallback callback = [this](intptr_t linkId) { notifyTopicClicked(linkId); };
getPage(LeftBookPage)->adviseLinkClicked(callback);
getPage(RightBookPage)->adviseLinkClicked(std::move(callback));
getPage(LeftBookPage)->eventMouseWheel
+= MyGUI::newDelegate(this, &JournalWindowImpl::notifyMouseWheel);
getPage(RightBookPage)->eventMouseWheel
+= MyGUI::newDelegate(this, &JournalWindowImpl::notifyMouseWheel);
}
{
MWGui::BookPage::ClickCallback callback
= [this](MWGui::TypesetBook::InteractiveId index) { notifyIndexLinkClicked(index); };
getPage(LeftTopicIndex)->adviseLinkClicked(callback);
getPage(CenterTopicIndex)->adviseLinkClicked(callback);
getPage(RightTopicIndex)->adviseLinkClicked(std::move(callback));
}
adjustButton(PrevPageBTN);
float nextButtonScale = adjustButton(NextPageBTN);
adjustButton(CloseBTN);
adjustButton(CancelBTN);
adjustButton(JournalBTN);
Gui::ImageButton* optionsButton = getWidget<Gui::ImageButton>(OptionsBTN);
Gui::ImageButton* showActiveButton = getWidget<Gui::ImageButton>(ShowActiveBTN);
Gui::ImageButton* showAllButton = getWidget<Gui::ImageButton>(ShowAllBTN);
Gui::ImageButton* questsButton = getWidget<Gui::ImageButton>(QuestsBTN);
Gui::ImageButton* nextButton = getWidget<Gui::ImageButton>(NextPageBTN);
if (nextButton->getSize().width == 64)
{
// english button has a 7 pixel wide strip of garbage on its right edge
nextButton->setSize(64 - 7, nextButton->getSize().height);
nextButton->setImageCoord(
MyGUI::IntCoord(0, 0, (64 - 7) * nextButtonScale, nextButton->getSize().height * nextButtonScale));
}
if (!questList)
{
// If tribunal is not installed (-> no options button), we still want the Topics button available,
// so place it where the options button would have been
Gui::ImageButton* topicsButton = getWidget<Gui::ImageButton>(TopicsBTN);
topicsButton->detachFromWidget();
topicsButton->attachToWidget(optionsButton->getParent());
topicsButton->setPosition(optionsButton->getPosition());
topicsButton->eventMouseButtonClick.clear();
topicsButton->eventMouseButtonClick += MyGUI::newDelegate(this, &JournalWindowImpl::notifyOptions);
optionsButton->setVisible(false);
showActiveButton->setVisible(false);
showAllButton->setVisible(false);
questsButton->setVisible(false);
adjustButton(TopicsBTN);
}
else
{
optionsButton->setImage("textures/tx_menubook_options.dds");
showActiveButton->setImage("textures/tx_menubook_quests_active.dds");
showAllButton->setImage("textures/tx_menubook_quests_all.dds");
questsButton->setImage("textures/tx_menubook_quests.dds");
adjustButton(ShowAllBTN);
adjustButton(ShowActiveBTN);
adjustButton(OptionsBTN);
adjustButton(QuestsBTN);
adjustButton(TopicsBTN);
int topicsWidth = getWidget<MyGUI::Widget>(TopicsBTN)->getSize().width;
int cancelLeft = getWidget<MyGUI::Widget>(CancelBTN)->getPosition().left;
int cancelRight = getWidget<MyGUI::Widget>(CancelBTN)->getPosition().left
+ getWidget<MyGUI::Widget>(CancelBTN)->getSize().width;
getWidget<MyGUI::Widget>(QuestsBTN)->setPosition(
cancelRight, getWidget<MyGUI::Widget>(QuestsBTN)->getPosition().top);
// Usually Topics, Quests, and Cancel buttons have the 64px width, so we can place the Topics left-up
// from the Cancel button, and the Quests right-up from the Cancel button. But in some installations,
// e.g. German one, the Topics button has the 128px width, so we should place it exactly left from the
// Quests button.
if (topicsWidth == 64)
{
getWidget<MyGUI::Widget>(TopicsBTN)->setPosition(
cancelLeft - topicsWidth, getWidget<MyGUI::Widget>(TopicsBTN)->getPosition().top);
}
else
{
int questLeft = getWidget<MyGUI::Widget>(QuestsBTN)->getPosition().left;
getWidget<MyGUI::Widget>(TopicsBTN)->setPosition(
questLeft - topicsWidth, getWidget<MyGUI::Widget>(TopicsBTN)->getPosition().top);
}
}
mQuestMode = false;
mAllQuests = false;
mOptionsMode = false;
mTopicsMode = false;
}
void onOpen() override
{
mModel->load();
setBookMode();
Book journalBook;
if (mModel->isEmpty())
journalBook = createEmptyJournalBook();
else
journalBook = createJournalBook();
pushBook(journalBook, 0);
// fast forward to the last page
if (!mStates.empty())
{
unsigned int& page = mStates.top().mPage;
page = mStates.top().mBook->pageCount() - 1;
if (page % 2)
--page;
}
updateShowingPages();
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(getWidget<MyGUI::Widget>(CloseBTN));
}
void onClose() override
{
mModel->unload();
getPage(LeftBookPage)->showPage(Book(), 0);
getPage(RightBookPage)->showPage(Book(), 0);
while (!mStates.empty())
mStates.pop();
mTopicIndexBook.reset();
}
void setVisible(bool newValue) override { WindowBase::setVisible(newValue); }
void setBookMode()
{
mOptionsMode = false;
mTopicsMode = false;
setVisible(OptionsBTN, true);
setVisible(OptionsOverlay, false);
updateShowingPages();
updateCloseJournalButton();
}
void setOptionsMode()
{
mOptionsMode = true;
mTopicsMode = false;
setVisible(OptionsBTN, false);
setVisible(OptionsOverlay, true);
setVisible(PrevPageBTN, false);
setVisible(NextPageBTN, false);
setVisible(CloseBTN, false);
setVisible(JournalBTN, false);
setVisible(TopicsList, false);
setVisible(QuestsList, mQuestMode);
setVisible(LeftTopicIndex, !mQuestMode);
setVisible(CenterTopicIndex, !mQuestMode);
setVisible(RightTopicIndex, !mQuestMode);
setVisible(ShowAllBTN, mQuestMode && !mAllQuests);
setVisible(ShowActiveBTN, mQuestMode && mAllQuests);
// TODO: figure out how to make "options" page overlay book page
// correctly, so that text may show underneath
getPage(RightBookPage)->showPage(Book(), 0);
// If in quest mode, ensure the quest list is updated
if (mQuestMode)
notifyQuests(getWidget<MyGUI::Widget>(QuestsList));
else
notifyTopics(getWidget<MyGUI::Widget>(TopicsList));
}
void pushBook(Book& book, unsigned int page)
{
DisplayState bs;
bs.mPage = page;
bs.mBook = book;
mStates.push(bs);
updateShowingPages();
updateCloseJournalButton();
}
void replaceBook(Book& book, unsigned int page)
{
assert(!mStates.empty());
mStates.top().mBook = book;
mStates.top().mPage = page;
updateShowingPages();
}
void popBook()
{
mStates.pop();
updateShowingPages();
updateCloseJournalButton();
}
void updateCloseJournalButton()
{
setVisible(CloseBTN, mStates.size() < 2);
setVisible(JournalBTN, mStates.size() >= 2);
}
void updateShowingPages()
{
Book book;
unsigned int page;
unsigned int relPages;
if (!mStates.empty())
{
book = mStates.top().mBook;
page = mStates.top().mPage;
relPages = book->pageCount() - page;
}
else
{
page = 0;
relPages = 0;
}
MyGUI::Widget* nextPageBtn = getWidget<MyGUI::Widget>(NextPageBTN);
MyGUI::Widget* prevPageBtn = getWidget<MyGUI::Widget>(PrevPageBTN);
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
bool nextPageVisible = relPages > 2;
nextPageBtn->setVisible(nextPageVisible);
bool prevPageVisible = page > 0;
prevPageBtn->setVisible(prevPageVisible);
if (focus == nextPageBtn && !nextPageVisible && prevPageVisible)
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(prevPageBtn);
else if (focus == prevPageBtn && !prevPageVisible && nextPageVisible)
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(nextPageBtn);
setVisible(PageOneNum, relPages > 0);
setVisible(PageTwoNum, relPages > 1);
getPage(LeftBookPage)->showPage((relPages > 0) ? book : Book(), page + 0);
getPage(RightBookPage)->showPage((relPages > 0) ? std::move(book) : Book(), page + 1);
setText(PageOneNum, page + 1);
setText(PageTwoNum, page + 2);
}
void notifyKeyPress(MyGUI::Widget* sender, MyGUI::KeyCode key, MyGUI::Char character)
{
if (key == MyGUI::KeyCode::ArrowUp)
notifyPrevPage(sender);
else if (key == MyGUI::KeyCode::ArrowDown)
notifyNextPage(sender);
}
void notifyTopicClicked(intptr_t linkId)
{
Book topicBook = createTopicBook(linkId);
if (mStates.size() > 1)
replaceBook(topicBook, 0);
else
pushBook(topicBook, 0);
setVisible(OptionsOverlay, false);
setVisible(OptionsBTN, true);
setVisible(JournalBTN, true);
mOptionsMode = false;
mTopicsMode = false;
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("book page"));
}
void notifyTopicSelected(const std::string& topicIdString, int id)
{
ESM::RefId topic = ESM::RefId::stringRefId(topicIdString);
const MWBase::Journal* journal = MWBase::Environment::get().getJournal();
intptr_t topicId = 0; /// \todo get rid of intptr ids
for (MWBase::Journal::TTopicIter i = journal->topicBegin(); i != journal->topicEnd(); ++i)
{
if (i->first == topic)
topicId = intptr_t(&i->second);
}
notifyTopicClicked(topicId);
}
void notifyQuestClicked(const std::string& name, int id)
{
Book book = createQuestBook(name);
if (mStates.size() > 1)
replaceBook(book, 0);
else
pushBook(book, 0);
setVisible(OptionsOverlay, false);
setVisible(OptionsBTN, true);
setVisible(JournalBTN, true);
mOptionsMode = false;
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("book page"));
}
void notifyOptions(MyGUI::Widget* _sender)
{
setOptionsMode();
if (!mTopicIndexBook)
mTopicIndexBook = createTopicIndexBook();
if (mIndexPagesCount == 3)
{
getPage(LeftTopicIndex)->showPage(mTopicIndexBook, 0);
getPage(CenterTopicIndex)->showPage(mTopicIndexBook, 1);
getPage(RightTopicIndex)->showPage(mTopicIndexBook, 2);
}
else
{
getPage(LeftTopicIndex)->showPage(mTopicIndexBook, 0);
getPage(RightTopicIndex)->showPage(mTopicIndexBook, 1);
}
}
void notifyJournal(MyGUI::Widget* _sender)
{
assert(mStates.size() > 1);
popBook();
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("book page"));
}
void notifyIndexLinkClicked(MWGui::TypesetBook::InteractiveId index)
{
setVisible(LeftTopicIndex, false);
setVisible(CenterTopicIndex, false);
setVisible(RightTopicIndex, false);
setVisible(TopicsList, true);
mTopicsMode = true;
Gui::MWList* list = getWidget<Gui::MWList>(TopicsList);
list->clear();
AddNamesToList add(list);
mModel->visitTopicNamesStartingWith(index, add);
list->adjustSize();
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("book page"));
}
void notifyTopics(MyGUI::Widget* _sender)
{
mQuestMode = false;
mTopicsMode = false;
setVisible(LeftTopicIndex, true);
setVisible(CenterTopicIndex, true);
setVisible(RightTopicIndex, true);
setVisible(TopicsList, false);
setVisible(QuestsList, false);
setVisible(ShowAllBTN, false);
setVisible(ShowActiveBTN, false);
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("book page"));
}
struct AddNamesToList
{
AddNamesToList(Gui::MWList* list)
: mList(list)
{
}
Gui::MWList* mList;
void operator()(std::string_view name, bool finished = false) { mList->addItem(name); }
};
struct SetNamesInactive
{
SetNamesInactive(Gui::MWList* list)
: mList(list)
{
}
Gui::MWList* mList;
void operator()(std::string_view name, bool finished)
{
if (finished)
{
mList->getItemWidget(name)->setStateSelected(true);
}
}
};
void notifyQuests(MyGUI::Widget* _sender)
{
mQuestMode = true;
setVisible(LeftTopicIndex, false);
setVisible(CenterTopicIndex, false);
setVisible(RightTopicIndex, false);
setVisible(TopicsList, false);
setVisible(QuestsList, true);
setVisible(ShowAllBTN, !mAllQuests);
setVisible(ShowActiveBTN, mAllQuests);
Gui::MWList* list = getWidget<Gui::MWList>(QuestsList);
list->clear();
AddNamesToList add(list);
mModel->visitQuestNames(!mAllQuests, add);
list->sort();
list->adjustSize();
if (mAllQuests)
{
SetNamesInactive setInactive(list);
mModel->visitQuestNames(false, setInactive);
}
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("book page"));
}
void notifyShowAll(MyGUI::Widget* _sender)
{
mAllQuests = true;
notifyQuests(_sender);
}
void notifyShowActive(MyGUI::Widget* _sender)
{
mAllQuests = false;
notifyQuests(_sender);
}
void notifyCancel(MyGUI::Widget* _sender)
{
if (mTopicsMode)
{
notifyTopics(_sender);
}
else
{
setBookMode();
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("book page"));
}
}
void notifyClose(MyGUI::Widget* _sender)
{
MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager();
winMgr->playSound(ESM::RefId::stringRefId("book close"));
winMgr->popGuiMode();
}
void notifyMouseWheel(MyGUI::Widget* sender, int rel)
{
if (rel < 0)
notifyNextPage(sender);
else
notifyPrevPage(sender);
}
void notifyNextPage(MyGUI::Widget* _sender)
{
if (mOptionsMode)
return;
if (!mStates.empty())
{
unsigned int& page = mStates.top().mPage;
Book book = mStates.top().mBook;
if (page + 2 < book->pageCount())
{
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("book page"));
page += 2;
updateShowingPages();
}
}
}
void notifyPrevPage(MyGUI::Widget* _sender)
{
if (mOptionsMode)
return;
if (!mStates.empty())
{
unsigned int& page = mStates.top().mPage;
if (page >= 2)
{
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("book page"));
page -= 2;
updateShowingPages();
}
}
}
};
}
// glue the implementation to the interface
std::unique_ptr<MWGui::JournalWindow> MWGui::JournalWindow::create(
JournalViewModel::Ptr Model, bool questList, ToUTF8::FromType encoding)
{
return std::make_unique<JournalWindowImpl>(Model, questList, encoding);
}
MWGui::JournalWindow::JournalWindow()
: BookWindowBase("openmw_journal.layout")
{
}
| 23,807
|
C++
|
.cpp
| 536
| 31.985075
| 119
| 0.588286
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,469
|
draganddrop.cpp
|
OpenMW_openmw/apps/openmw/mwgui/draganddrop.cpp
|
#include "draganddrop.hpp"
#include <MyGUI_ControllerManager.h>
#include <MyGUI_Gui.h>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/class.hpp"
#include "controllers.hpp"
#include "inventorywindow.hpp"
#include "itemview.hpp"
#include "itemwidget.hpp"
#include "sortfilteritemmodel.hpp"
namespace MWGui
{
DragAndDrop::DragAndDrop()
: mIsOnDragAndDrop(false)
, mDraggedWidget(nullptr)
, mSourceModel(nullptr)
, mSourceView(nullptr)
, mSourceSortModel(nullptr)
, mDraggedCount(0)
{
}
void DragAndDrop::startDrag(
int index, SortFilterItemModel* sortModel, ItemModel* sourceModel, ItemView* sourceView, int count)
{
mItem = sourceModel->getItem(index);
mDraggedCount = count;
mSourceModel = sourceModel;
mSourceView = sourceView;
mSourceSortModel = sortModel;
// If picking up an item that isn't from the player's inventory, the item gets added to player inventory backend
// immediately, even though it's still floating beneath the mouse cursor. A bit counterintuitive,
// but this is how it works in vanilla, and not doing so would break quests (BM_beasts for instance).
ItemModel* playerModel = MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getModel();
if (mSourceModel != playerModel)
{
MWWorld::Ptr item = mSourceModel->moveItem(mItem, mDraggedCount, playerModel);
playerModel->update();
ItemModel::ModelIndex newIndex = -1;
for (size_t i = 0; i < playerModel->getItemCount(); ++i)
{
if (playerModel->getItem(i).mBase == item)
{
newIndex = i;
break;
}
}
mItem = playerModel->getItem(newIndex);
mSourceModel = playerModel;
SortFilterItemModel* playerFilterModel
= MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getSortFilterModel();
mSourceSortModel = playerFilterModel;
}
const ESM::RefId& sound = mItem.mBase.getClass().getUpSoundId(mItem.mBase);
MWBase::Environment::get().getWindowManager()->playSound(sound);
if (mSourceSortModel)
{
mSourceSortModel->clearDragItems();
mSourceSortModel->addDragItem(mItem.mBase, count);
}
ItemWidget* baseWidget = MyGUI::Gui::getInstance().createWidget<ItemWidget>(
"MW_ItemIcon", 0, 0, 42, 42, MyGUI::Align::Default, "DragAndDrop");
Controllers::ControllerFollowMouse* controller
= MyGUI::ControllerManager::getInstance()
.createItem(Controllers::ControllerFollowMouse::getClassTypeName())
->castType<Controllers::ControllerFollowMouse>();
MyGUI::ControllerManager::getInstance().addItem(baseWidget, controller);
mDraggedWidget = baseWidget;
baseWidget->setItem(mItem.mBase);
baseWidget->setNeedMouseFocus(false);
baseWidget->setCount(count);
sourceView->update();
MWBase::Environment::get().getWindowManager()->setDragDrop(true);
mIsOnDragAndDrop = true;
}
void DragAndDrop::drop(ItemModel* targetModel, ItemView* targetView)
{
const ESM::RefId& sound = mItem.mBase.getClass().getDownSoundId(mItem.mBase);
MWBase::Environment::get().getWindowManager()->playSound(sound);
// We can't drop a conjured item to the ground; the target container should always be the source container
if (mItem.mFlags & ItemStack::Flag_Bound && targetModel != mSourceModel)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sBarterDialog12}");
return;
}
// If item is dropped where it was taken from, we don't need to do anything -
// otherwise, do the transfer
if (targetModel != mSourceModel)
{
mSourceModel->moveItem(mItem, mDraggedCount, targetModel);
}
mSourceModel->update();
finish();
if (targetView)
targetView->update();
MWBase::Environment::get().getWindowManager()->getInventoryWindow()->updateItemView();
// We need to update the view since an other item could be auto-equipped.
mSourceView->update();
}
void DragAndDrop::onFrame()
{
if (mIsOnDragAndDrop && mItem.mBase.getCellRef().getCount() == 0)
finish();
}
void DragAndDrop::finish()
{
mIsOnDragAndDrop = false;
mSourceSortModel->clearDragItems();
// since mSourceView doesn't get updated in drag()
MWBase::Environment::get().getWindowManager()->getInventoryWindow()->updateItemView();
MyGUI::Gui::getInstance().destroyWidget(mDraggedWidget);
mDraggedWidget = nullptr;
MWBase::Environment::get().getWindowManager()->setDragDrop(false);
}
}
| 5,064
|
C++
|
.cpp
| 115
| 34.947826
| 120
| 0.646473
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,470
|
tradeitemmodel.cpp
|
OpenMW_openmw/apps/openmw/mwgui/tradeitemmodel.cpp
|
#include "tradeitemmodel.hpp"
#include <components/misc/strings/algorithm.hpp>
#include <components/settings/values.hpp>
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/inventorystore.hpp"
namespace MWGui
{
TradeItemModel::TradeItemModel(std::unique_ptr<ItemModel> sourceModel, const MWWorld::Ptr& merchant)
: mMerchant(merchant)
{
mSourceModel = std::move(sourceModel);
}
bool TradeItemModel::allowedToUseItems() const
{
return true;
}
ItemStack TradeItemModel::getItem(ModelIndex index)
{
if (index < 0)
throw std::runtime_error("Invalid index supplied");
if (mItems.size() <= static_cast<size_t>(index))
throw std::runtime_error("Item index out of range");
return mItems[index];
}
size_t TradeItemModel::getItemCount()
{
return mItems.size();
}
void TradeItemModel::borrowImpl(const ItemStack& item, std::vector<ItemStack>& out)
{
bool found = false;
for (ItemStack& itemStack : out)
{
if (itemStack.mBase == item.mBase)
{
itemStack.mCount += item.mCount;
found = true;
break;
}
}
if (!found)
out.push_back(item);
}
void TradeItemModel::unborrowImpl(const ItemStack& item, size_t count, std::vector<ItemStack>& out)
{
std::vector<ItemStack>::iterator it = out.begin();
bool found = false;
for (; it != out.end(); ++it)
{
if (it->mBase == item.mBase)
{
if (it->mCount < count)
throw std::runtime_error("Not enough borrowed items to return");
it->mCount -= count;
if (it->mCount == 0)
out.erase(it);
found = true;
break;
}
}
if (!found)
throw std::runtime_error("Can't find borrowed item to return");
}
void TradeItemModel::borrowItemFromUs(ModelIndex itemIndex, size_t count)
{
ItemStack item = getItem(itemIndex);
item.mCount = count;
borrowImpl(item, mBorrowedFromUs);
}
void TradeItemModel::borrowItemToUs(ModelIndex itemIndex, ItemModel* source, size_t count)
{
ItemStack item = source->getItem(itemIndex);
item.mCount = count;
borrowImpl(item, mBorrowedToUs);
}
void TradeItemModel::returnItemBorrowedToUs(ModelIndex itemIndex, size_t count)
{
ItemStack item = getItem(itemIndex);
unborrowImpl(item, count, mBorrowedToUs);
}
void TradeItemModel::returnItemBorrowedFromUs(ModelIndex itemIndex, ItemModel* source, size_t count)
{
ItemStack item = source->getItem(itemIndex);
unborrowImpl(item, count, mBorrowedFromUs);
}
void TradeItemModel::adjustEncumbrance(float& encumbrance)
{
for (ItemStack& itemStack : mBorrowedToUs)
{
MWWorld::Ptr& item = itemStack.mBase;
encumbrance += item.getClass().getWeight(item) * itemStack.mCount;
}
for (ItemStack& itemStack : mBorrowedFromUs)
{
MWWorld::Ptr& item = itemStack.mBase;
encumbrance -= item.getClass().getWeight(item) * itemStack.mCount;
}
encumbrance = std::max(0.f, encumbrance);
}
void TradeItemModel::abort()
{
mBorrowedFromUs.clear();
mBorrowedToUs.clear();
}
const std::vector<ItemStack> TradeItemModel::getItemsBorrowedToUs() const
{
return mBorrowedToUs;
}
void TradeItemModel::transferItems()
{
for (ItemStack& itemStack : mBorrowedToUs)
{
// get index in the source model
ItemModel* sourceModel = itemStack.mCreator;
size_t i = 0;
for (; i < sourceModel->getItemCount(); ++i)
{
if (itemStack.mBase == sourceModel->getItem(i).mBase)
break;
}
if (i == sourceModel->getItemCount())
throw std::runtime_error("The borrowed item disappeared");
sourceModel->moveItem(
sourceModel->getItem(i), itemStack.mCount, this, !Settings::game().mPreventMerchantEquipping);
}
mBorrowedToUs.clear();
mBorrowedFromUs.clear();
}
void TradeItemModel::update()
{
mSourceModel->update();
int services = 0;
if (!mMerchant.isEmpty())
services = mMerchant.getClass().getServices(mMerchant);
mItems.clear();
// add regular items
for (size_t i = 0; i < mSourceModel->getItemCount(); ++i)
{
ItemStack item = mSourceModel->getItem(i);
if (!mMerchant.isEmpty())
{
MWWorld::Ptr base = item.mBase;
if (base.getCellRef().getRefId() == MWWorld::ContainerStore::sGoldId)
continue;
if (!base.getClass().showsInInventory(base))
return;
if (!base.getClass().canSell(base, services))
continue;
// Bound items may not be bought
if (item.mFlags & ItemStack::Flag_Bound)
continue;
// don't show equipped items
if (mMerchant.getClass().hasInventoryStore(mMerchant))
{
MWWorld::InventoryStore& store = mMerchant.getClass().getInventoryStore(mMerchant);
if (store.isEquipped(base))
continue;
}
}
// don't show items that we borrowed to someone else
for (ItemStack& itemStack : mBorrowedFromUs)
{
if (itemStack.mBase == item.mBase)
{
if (item.mCount < itemStack.mCount)
throw std::runtime_error("Lent more items than present");
item.mCount -= itemStack.mCount;
}
}
if (item.mCount > 0)
mItems.push_back(item);
}
// add items borrowed to us
for (ItemStack& itemStack : mBorrowedToUs)
{
itemStack.mType = ItemStack::Type_Barter;
mItems.push_back(itemStack);
}
}
}
| 6,448
|
C++
|
.cpp
| 181
| 25.093923
| 110
| 0.564283
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,471
|
spellbuyingwindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/spellbuyingwindow.cpp
|
#include "spellbuyingwindow.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_Gui.h>
#include <MyGUI_ScrollView.h>
#include <components/esm3/loadgmst.hpp>
#include <components/esm3/loadrace.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/spells.hpp"
namespace MWGui
{
SpellBuyingWindow::SpellBuyingWindow()
: WindowBase("openmw_spell_buying_window.layout")
, mCurrentY(0)
{
getWidget(mCancelButton, "CancelButton");
getWidget(mPlayerGold, "PlayerGold");
getWidget(mSpellsView, "SpellsView");
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &SpellBuyingWindow::onCancelButtonClicked);
}
bool SpellBuyingWindow::sortSpells(const ESM::Spell* left, const ESM::Spell* right)
{
return Misc::StringUtils::ciLess(left->mName, right->mName);
}
void SpellBuyingWindow::addSpell(const ESM::Spell& spell)
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
int price = std::max(1,
static_cast<int>(
spell.mData.mCost * store.get<ESM::GameSetting>().find("fSpellValueMult")->mValue.getFloat()));
price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr, price, true);
MWWorld::Ptr player = MWMechanics::getPlayer();
int playerGold = player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId);
// TODO: refactor to use MyGUI::ListBox
const int lineHeight = Settings::gui().mFontSize + 2;
MyGUI::Button* toAdd = mSpellsView->createWidget<MyGUI::Button>(price <= playerGold
? "SandTextButton"
: "SandTextButtonDisabled", // can't use setEnabled since that removes tooltip
0, mCurrentY, 200, lineHeight, MyGUI::Align::Default);
mCurrentY += lineHeight;
toAdd->setUserData(price);
toAdd->setCaptionWithReplacing(spell.mName + " - " + MyGUI::utility::toString(price) + "#{sgp}");
toAdd->setSize(mSpellsView->getWidth(), lineHeight);
toAdd->eventMouseWheel += MyGUI::newDelegate(this, &SpellBuyingWindow::onMouseWheel);
toAdd->setUserString("ToolTipType", "Spell");
toAdd->setUserString("Spell", spell.mId.serialize());
toAdd->setUserString("SpellCost", std::to_string(spell.mData.mCost));
toAdd->eventMouseButtonClick += MyGUI::newDelegate(this, &SpellBuyingWindow::onSpellButtonClick);
mSpellsWidgetMap.insert(std::make_pair(toAdd, spell.mId));
}
void SpellBuyingWindow::clearSpells()
{
mSpellsView->setViewOffset(MyGUI::IntPoint(0, 0));
mCurrentY = 0;
while (mSpellsView->getChildCount())
MyGUI::Gui::getInstance().destroyWidget(mSpellsView->getChildAt(0));
mSpellsWidgetMap.clear();
}
void SpellBuyingWindow::setPtr(const MWWorld::Ptr& actor)
{
setPtr(actor, 0);
}
void SpellBuyingWindow::setPtr(const MWWorld::Ptr& actor, int startOffset)
{
if (actor.isEmpty() || !actor.getClass().isActor())
throw std::runtime_error("Invalid argument in SpellBuyingWindow::setPtr");
center();
mPtr = actor;
clearSpells();
MWMechanics::Spells& merchantSpells = actor.getClass().getCreatureStats(actor).getSpells();
std::vector<const ESM::Spell*> spellsToSort;
for (const ESM::Spell* spell : merchantSpells)
{
if (spell->mData.mType != ESM::Spell::ST_Spell)
continue; // don't try to sell diseases, curses or powers
if (actor.getClass().isNpc())
{
const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(
actor.get<ESM::NPC>()->mBase->mRace);
if (race->mPowers.exists(spell->mId))
continue;
}
if (playerHasSpell(spell->mId))
continue;
spellsToSort.push_back(spell);
}
std::stable_sort(spellsToSort.begin(), spellsToSort.end(), sortSpells);
for (const ESM::Spell* spell : spellsToSort)
{
addSpell(*spell);
}
spellsToSort.clear();
updateLabels();
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
// scrollbar is hidden
mSpellsView->setVisibleVScroll(false);
mSpellsView->setCanvasSize(
MyGUI::IntSize(mSpellsView->getWidth(), std::max(mSpellsView->getHeight(), mCurrentY)));
mSpellsView->setVisibleVScroll(true);
mSpellsView->setViewOffset(MyGUI::IntPoint(0, startOffset));
}
bool SpellBuyingWindow::playerHasSpell(const ESM::RefId& id)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
return player.getClass().getCreatureStats(player).getSpells().hasSpell(id);
}
void SpellBuyingWindow::onSpellButtonClick(MyGUI::Widget* _sender)
{
int price = *_sender->getUserData<int>();
MWWorld::Ptr player = MWMechanics::getPlayer();
if (price > player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId))
return;
MWMechanics::CreatureStats& stats = player.getClass().getCreatureStats(player);
MWMechanics::Spells& spells = stats.getSpells();
auto spell = mSpellsWidgetMap.find(_sender);
assert(spell != mSpellsWidgetMap.end());
spells.add(spell->second);
player.getClass().getContainerStore(player).remove(MWWorld::ContainerStore::sGoldId, price);
// add gold to NPC trading gold pool
MWMechanics::CreatureStats& npcStats = mPtr.getClass().getCreatureStats(mPtr);
npcStats.setGoldPool(npcStats.getGoldPool() + price);
setPtr(mPtr, mSpellsView->getViewOffset().top);
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Item Gold Up"));
}
void SpellBuyingWindow::onCancelButtonClicked(MyGUI::Widget* _sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(MWGui::GM_SpellBuying);
}
void SpellBuyingWindow::updateLabels()
{
MWWorld::Ptr player = MWMechanics::getPlayer();
int playerGold = player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId);
mPlayerGold->setCaptionWithReplacing("#{sGold}: " + MyGUI::utility::toString(playerGold));
mPlayerGold->setCoord(8, mPlayerGold->getTop(), mPlayerGold->getTextSize().width, mPlayerGold->getHeight());
}
void SpellBuyingWindow::onReferenceUnavailable()
{
// remove both Spells and Dialogue (since you always trade with the NPC/creature that you have previously talked
// to)
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_SpellBuying);
MWBase::Environment::get().getWindowManager()->exitCurrentGuiMode();
}
void SpellBuyingWindow::onMouseWheel(MyGUI::Widget* _sender, int _rel)
{
if (mSpellsView->getViewOffset().top + _rel * 0.3 > 0)
mSpellsView->setViewOffset(MyGUI::IntPoint(0, 0));
else
mSpellsView->setViewOffset(
MyGUI::IntPoint(0, static_cast<int>(mSpellsView->getViewOffset().top + _rel * 0.3f)));
}
}
| 7,701
|
C++
|
.cpp
| 158
| 40.398734
| 120
| 0.664622
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,472
|
console.cpp
|
OpenMW_openmw/apps/openmw/mwgui/console.cpp
|
#include "console.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_LayerManager.h>
#include <filesystem>
#include <fstream>
#include <regex>
#include <components/compiler/exception.hpp>
#include <components/compiler/extensions0.hpp>
#include <components/compiler/lineparser.hpp>
#include <components/compiler/locals.hpp>
#include <components/compiler/scanner.hpp>
#include <components/files/conversion.hpp>
#include <components/interpreter/interpreter.hpp>
#include <components/misc/utf8stream.hpp>
#include <components/settings/values.hpp>
#include "apps/openmw/mwgui/textcolours.hpp"
#include "../mwscript/extensions.hpp"
#include "../mwscript/interpretercontext.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/luamanager.hpp"
#include "../mwbase/scriptmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
namespace MWGui
{
class ConsoleInterpreterContext : public MWScript::InterpreterContext
{
Console& mConsole;
public:
ConsoleInterpreterContext(Console& console, MWWorld::Ptr reference);
void report(const std::string& message) override;
};
ConsoleInterpreterContext::ConsoleInterpreterContext(Console& console, MWWorld::Ptr reference)
: MWScript::InterpreterContext(reference.isEmpty() ? nullptr : &reference.getRefData().getLocals(), reference)
, mConsole(console)
{
}
void ConsoleInterpreterContext::report(const std::string& message)
{
mConsole.printOK(message);
}
bool Console::compile(const std::string& cmd, Compiler::Output& output)
{
try
{
ErrorHandler::reset();
std::istringstream input(cmd + '\n');
Compiler::Scanner scanner(*this, input, mCompilerContext.getExtensions());
Compiler::LineParser parser(
*this, mCompilerContext, output.getLocals(), output.getLiterals(), output.getCode(), true);
scanner.scan(parser);
return isGood();
}
catch (const Compiler::SourceException&)
{
// error has already been reported via error handler
}
catch (const std::exception& error)
{
printError(std::string("Error: ") + error.what());
}
return false;
}
void Console::report(const std::string& message, const Compiler::TokenLoc& loc, Type type)
{
std::ostringstream error;
error << "column " << loc.mColumn << " (" << loc.mLiteral << "):";
printError(error.str());
printError((type == ErrorMessage ? "error: " : "warning: ") + message);
}
void Console::report(const std::string& message, Type type)
{
printError((type == ErrorMessage ? "error: " : "warning: ") + message);
}
void Console::listNames()
{
if (mNames.empty())
{
// keywords
std::istringstream input;
Compiler::Scanner scanner(*this, input, mCompilerContext.getExtensions());
scanner.listKeywords(mNames);
// identifier
const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore();
std::vector<ESM::RefId> ids;
for (const auto* store : esmStore)
{
store->listIdentifier(ids);
for (auto id : ids)
{
if (id.is<ESM::StringRefId>())
mNames.push_back(id.getRefIdString());
}
ids.clear();
}
// exterior cell names and editor IDs aren't technically identifiers,
// but since the COC function accepts them, we should list them too
for (auto it = esmStore.get<ESM::Cell>().extBegin(); it != esmStore.get<ESM::Cell>().extEnd(); ++it)
{
if (!it->mName.empty())
mNames.push_back(it->mName);
}
for (const auto& cell : esmStore.get<ESM4::Cell>())
{
if (!cell.mEditorId.empty())
mNames.push_back(cell.mEditorId);
}
// sort
std::sort(mNames.begin(), mNames.end());
// remove duplicates
mNames.erase(std::unique(mNames.begin(), mNames.end()), mNames.end());
}
}
Console::Console(int w, int h, bool consoleOnlyScripts, Files::ConfigurationManager& cfgMgr)
: WindowBase("openmw_console.layout")
, mCaseSensitiveSearch(false)
, mRegExSearch(false)
, mCompilerContext(MWScript::CompilerContext::Type_Console)
, mConsoleOnlyScripts(consoleOnlyScripts)
, mCfgMgr(cfgMgr)
{
setCoord(10, 10, w - 10, h / 2);
getWidget(mCommandLine, "edit_Command");
getWidget(mHistory, "list_History");
getWidget(mSearchTerm, "edit_SearchTerm");
getWidget(mNextButton, "button_Next");
getWidget(mPreviousButton, "button_Previous");
getWidget(mCaseSensitiveToggleButton, "button_CaseSensitive");
getWidget(mRegExSearchToggleButton, "button_RegExSearch");
// Set up the command line box
mCommandLine->eventEditSelectAccept += newDelegate(this, &Console::acceptCommand);
mCommandLine->eventKeyButtonPressed += newDelegate(this, &Console::commandBoxKeyPress);
// Set up the search term box
mSearchTerm->eventEditSelectAccept += newDelegate(this, &Console::acceptSearchTerm);
mNextButton->eventMouseButtonClick += newDelegate(this, &Console::findNextOccurrence);
mPreviousButton->eventMouseButtonClick += newDelegate(this, &Console::findPreviousOccurrence);
mCaseSensitiveToggleButton->eventMouseButtonClick += newDelegate(this, &Console::toggleCaseSensitiveSearch);
mRegExSearchToggleButton->eventMouseButtonClick += newDelegate(this, &Console::toggleRegExSearch);
// Set up the log window
mHistory->setOverflowToTheLeft(true);
// compiler
Compiler::registerExtensions(mExtensions, mConsoleOnlyScripts);
mCompilerContext.setExtensions(&mExtensions);
// command history file
initConsoleHistory();
}
Console::~Console()
{
if (mCommandHistoryFile && mCommandHistoryFile.is_open())
mCommandHistoryFile.close();
}
void Console::onOpen()
{
// Give keyboard focus to the combo box whenever the console is
// turned on and place it over other widgets
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mCommandLine);
MyGUI::LayerManager::getInstance().upLayerItem(mMainWidget);
}
void Console::print(const std::string& msg, std::string_view color)
{
mHistory->addText(std::string(color) + MyGUI::TextIterator::toTagsString(msg));
}
void Console::printOK(const std::string& msg)
{
print(msg + "\n", MWBase::WindowManager::sConsoleColor_Success);
}
void Console::printError(const std::string& msg)
{
print(msg + "\n", MWBase::WindowManager::sConsoleColor_Error);
}
void Console::execute(const std::string& command)
{
// Log the command
if (mConsoleMode.empty())
print("> " + command + "\n");
else
print(mConsoleMode + " " + command + "\n");
if (!mConsoleMode.empty() || (command.size() >= 3 && std::string_view(command).substr(0, 3) == "lua"))
{
MWBase::Environment::get().getLuaManager()->handleConsoleCommand(mConsoleMode, command, mPtr);
return;
}
Compiler::Locals locals;
if (!mPtr.isEmpty())
{
const ESM::RefId& script = mPtr.getClass().getScript(mPtr);
if (!script.empty())
locals = MWBase::Environment::get().getScriptManager()->getLocals(script);
}
Compiler::Output output(locals);
if (compile(command + "\n", output))
{
try
{
ConsoleInterpreterContext interpreterContext(*this, mPtr);
Interpreter::Interpreter interpreter;
MWScript::installOpcodes(interpreter, mConsoleOnlyScripts);
const Interpreter::Program program = output.getProgram();
interpreter.run(program, interpreterContext);
}
catch (const std::exception& error)
{
printError(std::string("Error: ") + error.what());
}
}
}
void Console::executeFile(const std::filesystem::path& path)
{
std::ifstream stream(path);
if (!stream.is_open())
{
printError("Failed to open script file \"" + Files::pathToUnicodeString(path)
+ "\": " + std::generic_category().message(errno));
return;
}
std::string line;
while (std::getline(stream, line))
execute(line);
}
void Console::clear()
{
resetReference();
}
bool isWhitespace(char c)
{
return c == ' ' || c == '\t';
}
void Console::commandBoxKeyPress(MyGUI::Widget* _sender, MyGUI::KeyCode key, MyGUI::Char _char)
{
if (MyGUI::InputManager::getInstance().isControlPressed())
{
if (key == MyGUI::KeyCode::W)
{
auto caption = mCommandLine->getOnlyText();
if (caption.empty())
return;
size_t max = mCommandLine->getTextCursor();
while (max > 0 && (isWhitespace(caption[max - 1]) || caption[max - 1] == '>'))
max--;
while (max > 0 && !isWhitespace(caption[max - 1]) && caption[max - 1] != '>')
max--;
size_t length = mCommandLine->getTextCursor() - max;
if (length > 0)
{
caption.erase(max, length);
mCommandLine->setOnlyText(caption);
mCommandLine->setTextCursor(max);
}
}
else if (key == MyGUI::KeyCode::U)
{
if (mCommandLine->getTextCursor() > 0)
{
auto text = mCommandLine->getOnlyText();
text.erase(0, mCommandLine->getTextCursor());
mCommandLine->setOnlyText(text);
mCommandLine->setTextCursor(0);
}
}
}
else if (key == MyGUI::KeyCode::Tab && mConsoleMode.empty())
{
std::vector<std::string> matches;
listNames();
std::string oldCaption = mCommandLine->getOnlyText();
std::string newCaption = complete(mCommandLine->getOnlyText(), matches);
mCommandLine->setOnlyText(newCaption);
// List candidates if repeatedly pressing tab
if (oldCaption == newCaption && !matches.empty())
{
int i = 0;
printOK({});
for (std::string& match : matches)
{
if (i == 50)
break;
printOK(match);
i++;
}
}
}
if (mCommandHistory.empty())
return;
// Traverse history with up and down arrows
if (key == MyGUI::KeyCode::ArrowUp)
{
// If the user was editing a string, store it for later
if (mCurrent == mCommandHistory.end())
mEditString = mCommandLine->getOnlyText();
if (mCurrent != mCommandHistory.begin())
{
--mCurrent;
mCommandLine->setOnlyText(*mCurrent);
}
}
else if (key == MyGUI::KeyCode::ArrowDown)
{
if (mCurrent != mCommandHistory.end())
{
++mCurrent;
if (mCurrent != mCommandHistory.end())
mCommandLine->setOnlyText(*mCurrent);
else
// Restore the edit string
mCommandLine->setOnlyText(mEditString);
}
}
}
void Console::acceptCommand(MyGUI::EditBox* _sender)
{
const std::string& cm = mCommandLine->getOnlyText();
if (cm.empty())
return;
// Add the command to the history, and set the current pointer to
// the end of the list
if (mCommandHistory.empty() || mCommandHistory.back() != cm)
{
mCommandHistory.push_back(cm);
if (mCommandHistoryFile && mCommandHistoryFile.good())
mCommandHistoryFile << cm << std::endl;
}
mCurrent = mCommandHistory.end();
mEditString.clear();
mHistory->setTextCursor(mHistory->getTextLength());
// Reset the command line before the command execution.
// It prevents the re-triggering of the acceptCommand() event for the same command
// during the actual command execution
mCommandLine->setCaption({});
execute(cm);
}
void Console::toggleCaseSensitiveSearch(MyGUI::Widget* _sender)
{
mCaseSensitiveSearch = !mCaseSensitiveSearch;
// Reset console search highlight position search parameters have changed
mCurrentOccurrenceIndex = std::string::npos;
// Adjust color to reflect toggled status
const TextColours& textColours{ MWBase::Environment::get().getWindowManager()->getTextColours() };
mCaseSensitiveToggleButton->setTextColour(mCaseSensitiveSearch ? textColours.link : textColours.normal);
}
void Console::toggleRegExSearch(MyGUI::Widget* _sender)
{
mRegExSearch = !mRegExSearch;
// Reset console search highlight position search parameters have changed
mCurrentOccurrenceIndex = std::string::npos;
// Adjust color to reflect toggled status
const TextColours& textColours{ MWBase::Environment::get().getWindowManager()->getTextColours() };
mRegExSearchToggleButton->setTextColour(mRegExSearch ? textColours.link : textColours.normal);
// RegEx searches are always case sensitive
mCaseSensitiveSearch = mRegExSearch;
// Dim case sensitive and set disabled if regex search toggled on, restore when toggled off
mCaseSensitiveToggleButton->setTextColour(mCaseSensitiveSearch ? textColours.linkPressed : textColours.normal);
mCaseSensitiveToggleButton->setEnabled(!mRegExSearch);
}
void Console::acceptSearchTerm(MyGUI::EditBox* _sender)
{
const std::string& searchTerm = mSearchTerm->getOnlyText();
if (searchTerm.empty())
{
return;
}
std::string newSearchTerm = mCaseSensitiveSearch ? searchTerm : Utf8Stream::lowerCaseUtf8(searchTerm);
// If new search term reset position, otherwise continue from current position
if (newSearchTerm != mCurrentSearchTerm)
{
mCurrentSearchTerm = std::move(newSearchTerm);
mCurrentOccurrenceIndex = std::string::npos;
}
findNextOccurrence(nullptr);
}
enum class Console::SearchDirection
{
Forward,
Reverse
};
void Console::findNextOccurrence(MyGUI::Widget* _sender)
{
findOccurrence(SearchDirection::Forward);
}
void Console::findPreviousOccurrence(MyGUI::Widget* _sender)
{
findOccurrence(SearchDirection::Reverse);
}
void Console::findOccurrence(const SearchDirection direction)
{
if (mCurrentSearchTerm.empty())
{
return;
}
const auto historyText{ mCaseSensitiveSearch ? mHistory->getOnlyText().asUTF8()
: Utf8Stream::lowerCaseUtf8(mHistory->getOnlyText().asUTF8()) };
// Setup default search range
size_t firstIndex{ 0 };
size_t lastIndex{ historyText.length() };
// If search is not the first adjust the range based on the direction and previous occurrence.
if (mCurrentOccurrenceIndex != std::string::npos)
{
if (direction == SearchDirection::Forward && mCurrentOccurrenceIndex > 1)
{
firstIndex = mCurrentOccurrenceIndex + mCurrentOccurrenceLength;
}
else if (direction == SearchDirection::Reverse
&& (historyText.length() - mCurrentOccurrenceIndex) > mCurrentOccurrenceLength)
{
lastIndex = mCurrentOccurrenceIndex - 1;
}
}
findInHistoryText(historyText, direction, firstIndex, lastIndex);
// If the last search did not find anything AND...
if (mCurrentOccurrenceIndex == std::string::npos)
{
if (direction == SearchDirection::Forward && firstIndex != 0)
{
// ... We didn't start at the beginning, we apply the search to the other half of the text.
findInHistoryText(historyText, direction, 0, firstIndex);
}
else if (direction == SearchDirection::Reverse && lastIndex != historyText.length())
{
// ... We didn't search to the end, we apply the search to the other half of the text.
findInHistoryText(historyText, direction, lastIndex, historyText.length());
}
}
// Only scroll & select if we actually found something
if (mCurrentOccurrenceIndex != std::string::npos)
{
markOccurrence(mCurrentOccurrenceIndex, mCurrentOccurrenceLength);
}
else
{
markOccurrence(0, 0);
}
}
void Console::findInHistoryText(const std::string& historyText, const SearchDirection direction,
const size_t firstIndex, const size_t lastIndex)
{
if (mRegExSearch)
{
findWithRegex(historyText, direction, firstIndex, lastIndex);
}
else
{
findWithStringSearch(historyText, direction, firstIndex, lastIndex);
}
}
void Console::findWithRegex(const std::string& historyText, const SearchDirection direction,
const size_t firstIndex, const size_t lastIndex)
{
// Search text for regex match in given interval
const std::regex pattern{ mCurrentSearchTerm };
std::sregex_iterator match{ (historyText.cbegin() + firstIndex), (historyText.cbegin() + lastIndex), pattern };
const std::sregex_iterator end{};
// If reverse search get last result in interval
if (direction == SearchDirection::Reverse)
{
std::sregex_iterator lastMatch{ end };
while (match != end)
{
lastMatch = match;
++match;
}
match = lastMatch;
}
// If regex match is found in text, set new current occurrence values
if (match != end)
{
mCurrentOccurrenceIndex = match->position() + firstIndex;
mCurrentOccurrenceLength = match->length();
}
else
{
mCurrentOccurrenceIndex = std::string::npos;
mCurrentOccurrenceLength = 0;
}
}
void Console::findWithStringSearch(const std::string& historyText, const SearchDirection direction,
const size_t firstIndex, const size_t lastIndex)
{
// Search in given text interval for search term
const size_t substringLength{ (lastIndex - firstIndex) + 1 };
const std::string_view historyTextView((historyText.c_str() + firstIndex), substringLength);
if (direction == SearchDirection::Forward)
{
mCurrentOccurrenceIndex = historyTextView.find(mCurrentSearchTerm);
}
else
{
mCurrentOccurrenceIndex = historyTextView.rfind(mCurrentSearchTerm);
}
// If search term is found in text, set new current occurrence values
if (mCurrentOccurrenceIndex != std::string::npos)
{
mCurrentOccurrenceIndex += firstIndex;
mCurrentOccurrenceLength = mCurrentSearchTerm.length();
}
else
{
mCurrentOccurrenceLength = 0;
}
}
void Console::markOccurrence(const size_t textPosition, const size_t length)
{
if (textPosition == 0 && length == 0)
{
mHistory->setTextSelection(0, 0);
mHistory->setVScrollPosition(mHistory->getVScrollRange());
return;
}
const auto historyText = mHistory->getOnlyText();
const size_t upperLimit = std::min(historyText.length(), textPosition);
// Since MyGUI::EditBox.setVScrollPosition() works on pixels instead of text positions
// we need to calculate the actual pixel position by counting lines.
size_t lineNumber = 0;
for (size_t i = 0; i < upperLimit; i++)
{
if (historyText[i] == '\n')
{
lineNumber++;
}
}
// Make some space before the actual result
if (lineNumber >= 2)
{
lineNumber -= 2;
}
mHistory->setTextSelection(textPosition, textPosition + length);
mHistory->setVScrollPosition(mHistory->getFontHeight() * lineNumber);
}
std::string Console::complete(std::string input, std::vector<std::string>& matches)
{
std::string output = input;
std::string tmp = input;
bool has_front_quote = false;
/* Does the input string contain things that don't have to be completed? If yes erase them. */
/* Erase a possible call to an explicit reference. */
size_t explicitPos = tmp.find("->");
if (explicitPos != std::string::npos)
{
tmp.erase(0, explicitPos + 2);
}
/* Are there quotation marks? */
if (tmp.find('"') != std::string::npos)
{
int numquotes = 0;
for (std::string::iterator it = tmp.begin(); it < tmp.end(); ++it)
{
if (*it == '"')
numquotes++;
}
/* Is it terminated?*/
if (numquotes % 2)
{
tmp.erase(0, tmp.rfind('"') + 1);
has_front_quote = true;
}
else
{
size_t pos;
if ((((pos = tmp.rfind(' ')) != std::string::npos)) && (pos > tmp.rfind('"')))
{
tmp.erase(0, tmp.rfind(' ') + 1);
}
else
{
tmp.clear();
}
has_front_quote = false;
}
}
/* No quotation marks. Are there spaces?*/
else
{
size_t rpos;
if ((rpos = tmp.rfind(' ')) != std::string::npos)
{
if (rpos == 0)
{
tmp.clear();
}
else
{
tmp.erase(0, rpos + 1);
}
}
}
/* Erase the input from the output string so we can easily append the completed form later. */
output.erase(output.end() - tmp.length(), output.end());
/* Is there still something in the input string? If not just display all commands and return the unchanged
* input. */
if (tmp.length() == 0)
{
matches = mNames;
return input;
}
/* Iterate through the vector. */
for (std::string& name : mNames)
{
bool string_different = false;
/* Is the string shorter than the input string? If yes skip it. */
if (name.length() < tmp.length())
continue;
/* Is the beginning of the string different from the input string? If yes skip it. */
for (std::string::iterator iter = tmp.begin(), iter2 = name.begin(); iter < tmp.end(); ++iter, ++iter2)
{
if (Misc::StringUtils::toLower(*iter) != Misc::StringUtils::toLower(*iter2))
{
string_different = true;
break;
}
}
if (string_different)
continue;
/* The beginning of the string matches the input string, save it for the next test. */
matches.push_back(name);
}
/* There are no matches. Return the unchanged input. */
if (matches.empty())
{
return input;
}
/* Only one match. We're done. */
if (matches.size() == 1)
{
/* Adding quotation marks when the input string started with a quotation mark or has spaces in it*/
if ((matches.front().find(' ') != std::string::npos))
{
if (!has_front_quote)
output += '"';
return output.append(matches.front() + std::string("\" "));
}
else if (has_front_quote)
{
return output.append(matches.front() + std::string("\" "));
}
else
{
return output.append(matches.front() + std::string(" "));
}
}
/* Check if all matching strings match further than input. If yes complete to this match. */
int i = tmp.length();
for (std::string::iterator iter = matches.front().begin() + tmp.length(); iter < matches.front().end();
++iter, ++i)
{
for (std::string& match : matches)
{
if (Misc::StringUtils::toLower(match[i]) != Misc::StringUtils::toLower(*iter))
{
/* Append the longest match to the end of the output string*/
output.append(matches.front().substr(0, i));
return output;
}
}
}
/* All keywords match with the shortest. Append it to the output string and return it. */
return output.append(matches.front());
}
void Console::updateSelectedObjectPtr(const MWWorld::Ptr& currentPtr, const MWWorld::Ptr& newPtr)
{
if (mPtr == currentPtr)
mPtr = newPtr;
}
void Console::setSelectedObject(const MWWorld::Ptr& object)
{
if (!object.isEmpty())
{
if (object == mPtr)
mPtr = MWWorld::Ptr();
else
mPtr = object;
// User clicked on an object. Restore focus to the console command line.
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mCommandLine);
}
else
mPtr = MWWorld::Ptr();
updateConsoleTitle();
}
void Console::updateConsoleTitle()
{
std::string title = "#{OMWEngine:ConsoleWindow}";
if (!mConsoleMode.empty())
title = mConsoleMode + " " + title;
if (!mPtr.isEmpty())
title.append(" (" + mPtr.getCellRef().getRefId().toDebugString() + ")");
setTitle(title);
}
void Console::setConsoleMode(std::string_view mode)
{
mConsoleMode = std::string(mode);
updateConsoleTitle();
}
void Console::onReferenceUnavailable()
{
setSelectedObject(MWWorld::Ptr());
}
void Console::resetReference()
{
ReferenceInterface::resetReference();
setSelectedObject(MWWorld::Ptr());
}
void Console::initConsoleHistory()
{
const auto filePath = mCfgMgr.getUserConfigPath() / "console_history.txt";
const size_t retrievalLimit = Settings::general().mConsoleHistoryBufferSize;
// Read the previous session's commands from the file
if (retrievalLimit > 0)
{
std::ifstream historyFile(filePath);
std::string line;
while (std::getline(historyFile, line))
{
// Truncate the list if it exceeds the retrieval limit
if (mCommandHistory.size() >= retrievalLimit)
mCommandHistory.pop_front();
mCommandHistory.push_back(line);
}
historyFile.close();
}
mCurrent = mCommandHistory.end();
try
{
mCommandHistoryFile.exceptions(std::fstream::failbit | std::fstream::badbit);
mCommandHistoryFile.open(filePath, std::ios_base::trunc);
// Update the history file
for (const auto& histObj : mCommandHistory)
mCommandHistoryFile << histObj << std::endl;
mCommandHistoryFile.close();
mCommandHistoryFile.open(filePath, std::ios_base::app);
}
catch (const std::ios_base::failure& e)
{
Log(Debug::Error) << "Error: Failed to write to console history file " << filePath << " : " << e.what()
<< " : " << std::generic_category().message(errno);
}
}
}
| 29,310
|
C++
|
.cpp
| 737
| 29.008141
| 119
| 0.574065
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,473
|
statswindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/statswindow.cpp
|
#include "statswindow.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_Gui.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_LanguageManager.h>
#include <MyGUI_ProgressBar.h>
#include <MyGUI_ScrollView.h>
#include <MyGUI_TextIterator.h>
#include <MyGUI_Window.h>
#include <components/debug/debuglog.hpp>
#include <components/esm3/loadbsgn.hpp>
#include <components/esm3/loadclas.hpp>
#include <components/esm3/loadfact.hpp>
#include <components/esm3/loadgmst.hpp>
#include <components/esm3/loadrace.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/player.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "tooltips.hpp"
namespace MWGui
{
StatsWindow::StatsWindow(DragAndDrop* drag)
: WindowPinnableBase("openmw_stats_window.layout")
, NoDrop(drag, mMainWidget)
, mSkillView(nullptr)
, mReputation(0)
, mBounty(0)
, mChanged(true)
, mMinFullWidth(mMainWidget->getSize().width)
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
MyGUI::Widget* attributeView = getWidget("AttributeView");
MyGUI::IntCoord coord{ 0, 0, 204, 18 };
const MyGUI::Align alignment = MyGUI::Align::Left | MyGUI::Align::Top | MyGUI::Align::HStretch;
for (const ESM::Attribute& attribute : store.get<ESM::Attribute>())
{
auto* box = attributeView->createWidget<MyGUI::Button>({}, coord, alignment);
box->setUserString("ToolTipType", "Layout");
box->setUserString("ToolTipLayout", "AttributeToolTip");
box->setUserString("Caption_AttributeName", attribute.mName);
box->setUserString("Caption_AttributeDescription", attribute.mDescription);
box->setUserString("ImageTexture_AttributeImage", attribute.mIcon);
coord.top += coord.height;
auto* name = box->createWidget<MyGUI::TextBox>("SandText", { 0, 0, 160, 18 }, alignment);
name->setNeedMouseFocus(false);
name->setCaption(attribute.mName);
auto* value = box->createWidget<MyGUI::TextBox>(
"SandTextRight", { 160, 0, 44, 18 }, MyGUI::Align::Right | MyGUI::Align::Top);
value->setNeedMouseFocus(false);
mAttributeWidgets.emplace(attribute.mId, value);
}
getWidget(mSkillView, "SkillView");
getWidget(mLeftPane, "LeftPane");
getWidget(mRightPane, "RightPane");
for (const ESM::Skill& skill : store.get<ESM::Skill>())
{
mSkillValues.emplace(skill.mId, MWMechanics::SkillValue());
mSkillWidgetMap.emplace(skill.mId, std::make_pair<MyGUI::TextBox*, MyGUI::TextBox*>(nullptr, nullptr));
}
MyGUI::Window* t = mMainWidget->castType<MyGUI::Window>();
t->eventWindowChangeCoord += MyGUI::newDelegate(this, &StatsWindow::onWindowResize);
onWindowResize(t);
}
void StatsWindow::onMouseWheel(MyGUI::Widget* _sender, int _rel)
{
if (mSkillView->getViewOffset().top + _rel * 0.3 > 0)
mSkillView->setViewOffset(MyGUI::IntPoint(0, 0));
else
mSkillView->setViewOffset(
MyGUI::IntPoint(0, static_cast<int>(mSkillView->getViewOffset().top + _rel * 0.3)));
}
void StatsWindow::onWindowResize(MyGUI::Window* window)
{
int windowWidth = window->getSize().width;
int windowHeight = window->getSize().height;
// initial values defined in openmw_stats_window.layout, if custom options are not present in .layout, a default
// is loaded
float leftPaneRatio = 0.44f;
if (mLeftPane->isUserString("LeftPaneRatio"))
leftPaneRatio = MyGUI::utility::parseFloat(mLeftPane->getUserString("LeftPaneRatio"));
int leftOffsetWidth = 24;
if (mLeftPane->isUserString("LeftOffsetWidth"))
leftOffsetWidth = MyGUI::utility::parseInt(mLeftPane->getUserString("LeftOffsetWidth"));
float rightPaneRatio = 1.f - leftPaneRatio;
int minLeftWidth = static_cast<int>(mMinFullWidth * leftPaneRatio);
int minLeftOffsetWidth = minLeftWidth + leftOffsetWidth;
// if there's no space for right pane
mRightPane->setVisible(windowWidth >= minLeftOffsetWidth);
if (!mRightPane->getVisible())
{
mLeftPane->setCoord(MyGUI::IntCoord(0, 0, windowWidth - leftOffsetWidth, windowHeight));
}
// if there's some space for right pane
else if (windowWidth < mMinFullWidth)
{
mLeftPane->setCoord(MyGUI::IntCoord(0, 0, minLeftWidth, windowHeight));
mRightPane->setCoord(MyGUI::IntCoord(minLeftWidth, 0, windowWidth - minLeftWidth, windowHeight));
}
// if there's enough space for both panes
else
{
mLeftPane->setCoord(MyGUI::IntCoord(0, 0, static_cast<int>(leftPaneRatio * windowWidth), windowHeight));
mRightPane->setCoord(MyGUI::IntCoord(static_cast<int>(leftPaneRatio * windowWidth), 0,
static_cast<int>(rightPaneRatio * windowWidth), windowHeight));
}
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
// scrollbar is hidden
mSkillView->setVisibleVScroll(false);
mSkillView->setCanvasSize(mSkillView->getWidth(), mSkillView->getCanvasSize().height);
mSkillView->setVisibleVScroll(true);
}
void StatsWindow::setBar(const std::string& name, const std::string& tname, int val, int max)
{
MyGUI::ProgressBar* pt;
getWidget(pt, name);
std::stringstream out;
out << val << "/" << max;
setText(tname, out.str());
pt->setProgressRange(std::max(0, max));
pt->setProgressPosition(std::max(0, val));
}
void StatsWindow::setPlayerName(const std::string& playerName)
{
mMainWidget->castType<MyGUI::Window>()->setCaption(playerName);
}
void StatsWindow::setAttribute(ESM::RefId id, const MWMechanics::AttributeValue& value)
{
auto it = mAttributeWidgets.find(id);
if (it != mAttributeWidgets.end())
{
MyGUI::TextBox* box = it->second;
box->setCaption(std::to_string(static_cast<int>(value.getModified())));
if (value.getModified() > value.getBase())
box->_setWidgetState("increased");
else if (value.getModified() < value.getBase())
box->_setWidgetState("decreased");
else
box->_setWidgetState("normal");
}
}
void StatsWindow::setValue(std::string_view id, const MWMechanics::DynamicStat<float>& value)
{
int current = static_cast<int>(value.getCurrent());
int modified = static_cast<int>(value.getModified(false));
// Fatigue can be negative
if (id != "FBar")
current = std::max(0, current);
setBar(std::string(id), std::string(id) + "T", current, modified);
// health, magicka, fatigue tooltip
MyGUI::Widget* w;
std::string valStr = MyGUI::utility::toString(current) + " / " + MyGUI::utility::toString(modified);
if (id == "HBar")
{
getWidget(w, "Health");
w->setUserString("Caption_HealthDescription", "#{sHealthDesc}\n" + valStr);
}
else if (id == "MBar")
{
getWidget(w, "Magicka");
w->setUserString("Caption_HealthDescription", "#{sMagDesc}\n" + valStr);
}
else if (id == "FBar")
{
getWidget(w, "Fatigue");
w->setUserString("Caption_HealthDescription", "#{sFatDesc}\n" + valStr);
}
}
void StatsWindow::setValue(std::string_view id, const std::string& value)
{
if (id == "name")
setPlayerName(value);
else if (id == "race")
setText("RaceText", value);
else if (id == "class")
setText("ClassText", value);
}
void StatsWindow::setValue(std::string_view id, int value)
{
if (id == "level")
{
std::ostringstream text;
text << value;
setText("LevelText", text.str());
}
}
void setSkillProgress(MyGUI::Widget* w, float progress, ESM::RefId skillId)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore();
float progressRequirement = player.getClass().getNpcStats(player).getSkillProgressRequirement(
skillId, *esmStore.get<ESM::Class>().find(player.get<ESM::NPC>()->mBase->mClass));
// This is how vanilla MW displays the progress bar (I think). Note it's slightly inaccurate,
// due to the int casting in the skill levelup logic. Also the progress label could in rare cases
// reach 100% without the skill levelling up.
// Leaving the original display logic for now, for consistency with ess-imported savegames.
int progressPercent = int(float(progress) / float(progressRequirement) * 100.f + 0.5f);
w->setUserString("Caption_SkillProgressText", MyGUI::utility::toString(progressPercent) + "/100");
w->setUserString("RangePosition_SkillProgress", MyGUI::utility::toString(progressPercent));
}
void StatsWindow::setValue(ESM::RefId id, const MWMechanics::SkillValue& value)
{
mSkillValues[id] = value;
std::pair<MyGUI::TextBox*, MyGUI::TextBox*> widgets = mSkillWidgetMap[id];
MyGUI::TextBox* valueWidget = widgets.second;
MyGUI::TextBox* nameWidget = widgets.first;
if (valueWidget && nameWidget)
{
int modified = value.getModified(), base = value.getBase();
std::string text = MyGUI::utility::toString(modified);
std::string state = "normal";
if (modified > base)
state = "increased";
else if (modified < base)
state = "decreased";
int widthBefore = valueWidget->getTextSize().width;
valueWidget->setCaption(text);
valueWidget->_setWidgetState(state);
int widthAfter = valueWidget->getTextSize().width;
if (widthBefore != widthAfter)
{
valueWidget->setCoord(valueWidget->getLeft() - (widthAfter - widthBefore), valueWidget->getTop(),
valueWidget->getWidth() + (widthAfter - widthBefore), valueWidget->getHeight());
nameWidget->setSize(nameWidget->getWidth() - (widthAfter - widthBefore), nameWidget->getHeight());
}
if (value.getBase() < 100)
{
nameWidget->setUserString("Visible_SkillMaxed", "false");
nameWidget->setUserString("UserData^Hidden_SkillMaxed", "true");
nameWidget->setUserString("Visible_SkillProgressVBox", "true");
nameWidget->setUserString("UserData^Hidden_SkillProgressVBox", "false");
valueWidget->setUserString("Visible_SkillMaxed", "false");
valueWidget->setUserString("UserData^Hidden_SkillMaxed", "true");
valueWidget->setUserString("Visible_SkillProgressVBox", "true");
valueWidget->setUserString("UserData^Hidden_SkillProgressVBox", "false");
setSkillProgress(nameWidget, value.getProgress(), id);
setSkillProgress(valueWidget, value.getProgress(), id);
}
else
{
nameWidget->setUserString("Visible_SkillMaxed", "true");
nameWidget->setUserString("UserData^Hidden_SkillMaxed", "false");
nameWidget->setUserString("Visible_SkillProgressVBox", "false");
nameWidget->setUserString("UserData^Hidden_SkillProgressVBox", "true");
valueWidget->setUserString("Visible_SkillMaxed", "true");
valueWidget->setUserString("UserData^Hidden_SkillMaxed", "false");
valueWidget->setUserString("Visible_SkillProgressVBox", "false");
valueWidget->setUserString("UserData^Hidden_SkillProgressVBox", "true");
}
}
}
void StatsWindow::configureSkills(const std::vector<ESM::RefId>& major, const std::vector<ESM::RefId>& minor)
{
mMajorSkills = major;
mMinorSkills = minor;
// Update misc skills with the remaining skills not in major or minor
std::set<ESM::RefId> skillSet;
std::copy(major.begin(), major.end(), std::inserter(skillSet, skillSet.begin()));
std::copy(minor.begin(), minor.end(), std::inserter(skillSet, skillSet.begin()));
mMiscSkills.clear();
const auto& store = MWBase::Environment::get().getWorld()->getStore().get<ESM::Skill>();
for (const auto& skill : store)
{
if (!skillSet.contains(skill.mId))
mMiscSkills.push_back(skill.mId);
}
updateSkillArea();
}
void StatsWindow::onFrame(float dt)
{
NoDrop::onFrame(dt);
MWWorld::Ptr player = MWMechanics::getPlayer();
const MWMechanics::NpcStats& PCstats = player.getClass().getNpcStats(player);
const auto& store = MWBase::Environment::get().getESMStore();
std::stringstream detail;
bool first = true;
for (const auto& attribute : store->get<ESM::Attribute>())
{
float mult = PCstats.getLevelupAttributeMultiplier(attribute.mId);
mult = std::min(mult, 100 - PCstats.getAttribute(attribute.mId).getBase());
if (mult > 1)
{
if (!first)
detail << '\n';
detail << attribute.mName << " x" << MyGUI::utility::toString(mult);
first = false;
}
}
std::string detailText = detail.str();
// level progress
MyGUI::Widget* levelWidget;
for (int i = 0; i < 2; ++i)
{
int max = store->get<ESM::GameSetting>().find("iLevelUpTotal")->mValue.getInteger();
getWidget(levelWidget, i == 0 ? "Level_str" : "LevelText");
levelWidget->setUserString(
"RangePosition_LevelProgress", MyGUI::utility::toString(PCstats.getLevelProgress()));
levelWidget->setUserString("Range_LevelProgress", MyGUI::utility::toString(max));
levelWidget->setUserString("Caption_LevelProgressText",
MyGUI::utility::toString(PCstats.getLevelProgress()) + "/" + MyGUI::utility::toString(max));
levelWidget->setUserString("Caption_LevelDetailText", detailText);
}
setFactions(PCstats.getFactionRanks());
setExpelled(PCstats.getExpelled());
const auto& signId = MWBase::Environment::get().getWorld()->getPlayer().getBirthSign();
setBirthSign(signId);
setReputation(PCstats.getReputation());
setBounty(PCstats.getBounty());
if (mChanged)
updateSkillArea();
}
void StatsWindow::setFactions(const FactionList& factions)
{
if (mFactions != factions)
{
mFactions = factions;
mChanged = true;
}
}
void StatsWindow::setExpelled(const std::set<ESM::RefId>& expelled)
{
if (mExpelled != expelled)
{
mExpelled = expelled;
mChanged = true;
}
}
void StatsWindow::setBirthSign(const ESM::RefId& signId)
{
if (signId != mBirthSignId)
{
mBirthSignId = signId;
mChanged = true;
}
}
void StatsWindow::addSeparator(MyGUI::IntCoord& coord1, MyGUI::IntCoord& coord2)
{
MyGUI::ImageBox* separator = mSkillView->createWidget<MyGUI::ImageBox>("MW_HLine",
MyGUI::IntCoord(10, coord1.top, coord1.width + coord2.width - 4, 18),
MyGUI::Align::Left | MyGUI::Align::Top | MyGUI::Align::HStretch);
separator->eventMouseWheel += MyGUI::newDelegate(this, &StatsWindow::onMouseWheel);
mSkillWidgets.push_back(separator);
coord1.top += separator->getHeight();
coord2.top += separator->getHeight();
}
void StatsWindow::addGroup(std::string_view label, MyGUI::IntCoord& coord1, MyGUI::IntCoord& coord2)
{
MyGUI::TextBox* groupWidget = mSkillView->createWidget<MyGUI::TextBox>("SandBrightText",
MyGUI::IntCoord(0, coord1.top, coord1.width + coord2.width, coord1.height),
MyGUI::Align::Left | MyGUI::Align::Top | MyGUI::Align::HStretch);
groupWidget->setCaption(MyGUI::UString(label));
groupWidget->eventMouseWheel += MyGUI::newDelegate(this, &StatsWindow::onMouseWheel);
mSkillWidgets.push_back(groupWidget);
const int lineHeight = Settings::gui().mFontSize + 2;
coord1.top += lineHeight;
coord2.top += lineHeight;
}
std::pair<MyGUI::TextBox*, MyGUI::TextBox*> StatsWindow::addValueItem(std::string_view text,
const std::string& value, const std::string& state, MyGUI::IntCoord& coord1, MyGUI::IntCoord& coord2)
{
MyGUI::TextBox *skillNameWidget, *skillValueWidget;
skillNameWidget = mSkillView->createWidget<MyGUI::TextBox>(
"SandText", coord1, MyGUI::Align::Left | MyGUI::Align::Top | MyGUI::Align::HStretch);
skillNameWidget->setCaption(MyGUI::UString(text));
skillNameWidget->eventMouseWheel += MyGUI::newDelegate(this, &StatsWindow::onMouseWheel);
skillValueWidget = mSkillView->createWidget<MyGUI::TextBox>(
"SandTextRight", coord2, MyGUI::Align::Right | MyGUI::Align::Top);
skillValueWidget->setCaption(value);
skillValueWidget->_setWidgetState(state);
skillValueWidget->eventMouseWheel += MyGUI::newDelegate(this, &StatsWindow::onMouseWheel);
// resize dynamically according to text size
int textWidthPlusMargin = skillValueWidget->getTextSize().width + 12;
skillValueWidget->setCoord(
coord2.left + coord2.width - textWidthPlusMargin, coord2.top, textWidthPlusMargin, coord2.height);
skillNameWidget->setSize(skillNameWidget->getSize() + MyGUI::IntSize(coord2.width - textWidthPlusMargin, 0));
mSkillWidgets.push_back(skillNameWidget);
mSkillWidgets.push_back(skillValueWidget);
const int lineHeight = Settings::gui().mFontSize + 2;
coord1.top += lineHeight;
coord2.top += lineHeight;
return std::make_pair(skillNameWidget, skillValueWidget);
}
MyGUI::Widget* StatsWindow::addItem(const std::string& text, MyGUI::IntCoord& coord1, MyGUI::IntCoord& coord2)
{
MyGUI::TextBox* skillNameWidget;
skillNameWidget = mSkillView->createWidget<MyGUI::TextBox>("SandText", coord1, MyGUI::Align::Default);
skillNameWidget->setCaption(text);
skillNameWidget->eventMouseWheel += MyGUI::newDelegate(this, &StatsWindow::onMouseWheel);
int textWidth = skillNameWidget->getTextSize().width;
skillNameWidget->setSize(textWidth, skillNameWidget->getHeight());
mSkillWidgets.push_back(skillNameWidget);
const int lineHeight = Settings::gui().mFontSize + 2;
coord1.top += lineHeight;
coord2.top += lineHeight;
return skillNameWidget;
}
void StatsWindow::addSkills(const std::vector<ESM::RefId>& skills, const std::string& titleId,
const std::string& titleDefault, MyGUI::IntCoord& coord1, MyGUI::IntCoord& coord2)
{
// Add a line separator if there are items above
if (!mSkillWidgets.empty())
{
addSeparator(coord1, coord2);
}
addGroup(
MWBase::Environment::get().getWindowManager()->getGameSettingString(titleId, titleDefault), coord1, coord2);
const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore();
for (const ESM::RefId& skillId : skills)
{
const ESM::Skill* skill = esmStore.get<ESM::Skill>().search(skillId);
if (!skill) // Skip unknown skills
continue;
auto skillValue = mSkillValues.find(skill->mId);
if (skillValue == mSkillValues.end())
{
Log(Debug::Error) << "Failed to update stats window: can not find value for skill " << skill->mId;
continue;
}
const ESM::Attribute* attr
= esmStore.get<ESM::Attribute>().find(ESM::Attribute::indexToRefId(skill->mData.mAttribute));
std::pair<MyGUI::TextBox*, MyGUI::TextBox*> widgets
= addValueItem(skill->mName, {}, "normal", coord1, coord2);
mSkillWidgetMap[skill->mId] = std::move(widgets);
for (int i = 0; i < 2; ++i)
{
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString("ToolTipType", "Layout");
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString("ToolTipLayout", "SkillToolTip");
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString(
"Caption_SkillName", MyGUI::TextIterator::toTagsString(skill->mName));
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString(
"Caption_SkillDescription", skill->mDescription);
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString("Caption_SkillAttribute",
"#{sGoverningAttribute}: " + MyGUI::TextIterator::toTagsString(attr->mName));
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString("ImageTexture_SkillImage", skill->mIcon);
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString("Range_SkillProgress", "100");
}
setValue(skill->mId, skillValue->second);
}
}
void StatsWindow::updateSkillArea()
{
mChanged = false;
for (MyGUI::Widget* widget : mSkillWidgets)
{
MyGUI::Gui::getInstance().destroyWidget(widget);
}
mSkillWidgets.clear();
const int valueSize = 40;
MyGUI::IntCoord coord1(10, 0, mSkillView->getWidth() - (10 + valueSize) - 24, 18);
MyGUI::IntCoord coord2(coord1.left + coord1.width, coord1.top, valueSize, coord1.height);
if (!mMajorSkills.empty())
addSkills(mMajorSkills, "sSkillClassMajor", "Major Skills", coord1, coord2);
if (!mMinorSkills.empty())
addSkills(mMinorSkills, "sSkillClassMinor", "Minor Skills", coord1, coord2);
if (!mMiscSkills.empty())
addSkills(mMiscSkills, "sSkillClassMisc", "Misc Skills", coord1, coord2);
MWBase::World* world = MWBase::Environment::get().getWorld();
const MWWorld::ESMStore& store = world->getStore();
const ESM::NPC* player = world->getPlayerPtr().get<ESM::NPC>()->mBase;
// race tooltip
const ESM::Race* playerRace = store.get<ESM::Race>().find(player->mRace);
MyGUI::Widget* raceWidget;
getWidget(raceWidget, "RaceText");
ToolTips::createRaceToolTip(raceWidget, playerRace);
getWidget(raceWidget, "Race_str");
ToolTips::createRaceToolTip(raceWidget, playerRace);
// class tooltip
MyGUI::Widget* classWidget;
const ESM::Class* playerClass = store.get<ESM::Class>().find(player->mClass);
getWidget(classWidget, "ClassText");
ToolTips::createClassToolTip(classWidget, *playerClass);
getWidget(classWidget, "Class_str");
ToolTips::createClassToolTip(classWidget, *playerClass);
if (!mFactions.empty())
{
MWWorld::Ptr playerPtr = MWMechanics::getPlayer();
const MWMechanics::NpcStats& PCstats = playerPtr.getClass().getNpcStats(playerPtr);
const std::set<ESM::RefId>& expelled = PCstats.getExpelled();
bool firstFaction = true;
for (const auto& [factionId, factionRank] : mFactions)
{
const ESM::Faction* faction = store.get<ESM::Faction>().find(factionId);
if (faction->mData.mIsHidden == 1)
continue;
if (firstFaction)
{
// Add a line separator if there are items above
if (!mSkillWidgets.empty())
addSeparator(coord1, coord2);
addGroup(MWBase::Environment::get().getWindowManager()->getGameSettingString("sFaction", "Faction"),
coord1, coord2);
firstFaction = false;
}
MyGUI::Widget* w = addItem(faction->mName, coord1, coord2);
std::string text;
text += std::string("#{fontcolourhtml=header}") + faction->mName;
if (expelled.find(factionId) != expelled.end())
text += "\n#{fontcolourhtml=normal}#{sExpelled}";
else
{
const auto rank = static_cast<size_t>(std::max(0, factionRank));
if (rank < faction->mRanks.size())
text += std::string("\n#{fontcolourhtml=normal}") + faction->mRanks[rank];
if (rank + 1 < faction->mRanks.size() && !faction->mRanks[rank + 1].empty())
{
// player doesn't have max rank yet
text += std::string("\n\n#{fontcolourhtml=header}#{sNextRank} ") + faction->mRanks[rank + 1];
const ESM::RankData& rankData = faction->mData.mRankData[rank + 1];
const ESM::Attribute* attr1 = store.get<ESM::Attribute>().find(
ESM::Attribute::indexToRefId(faction->mData.mAttribute[0]));
const ESM::Attribute* attr2 = store.get<ESM::Attribute>().find(
ESM::Attribute::indexToRefId(faction->mData.mAttribute[1]));
text += "\n#{fontcolourhtml=normal}" + MyGUI::TextIterator::toTagsString(attr1->mName) + ": "
+ MyGUI::utility::toString(rankData.mAttribute1) + ", "
+ MyGUI::TextIterator::toTagsString(attr2->mName) + ": "
+ MyGUI::utility::toString(rankData.mAttribute2);
text += "\n\n#{fontcolourhtml=header}#{sFavoriteSkills}";
text += "\n#{fontcolourhtml=normal}";
bool firstSkill = true;
for (int id : faction->mData.mSkills)
{
const ESM::Skill* skill = store.get<ESM::Skill>().search(ESM::Skill::indexToRefId(id));
if (skill)
{
if (!firstSkill)
text += ", ";
firstSkill = false;
text += MyGUI::TextIterator::toTagsString(skill->mName);
}
}
text += "\n";
if (rankData.mPrimarySkill > 0)
text += "\n#{sNeedOneSkill} " + MyGUI::utility::toString(rankData.mPrimarySkill);
if (rankData.mFavouredSkill > 0)
text += " #{sand} #{sNeedTwoSkills} " + MyGUI::utility::toString(rankData.mFavouredSkill);
}
}
w->setUserString("ToolTipType", "Layout");
w->setUserString("ToolTipLayout", "FactionToolTip");
w->setUserString("Caption_FactionText", text);
}
}
if (!mBirthSignId.empty())
{
// Add a line separator if there are items above
if (!mSkillWidgets.empty())
addSeparator(coord1, coord2);
addGroup(MWBase::Environment::get().getWindowManager()->getGameSettingString("sBirthSign", "Sign"), coord1,
coord2);
const ESM::BirthSign* sign = store.get<ESM::BirthSign>().find(mBirthSignId);
MyGUI::Widget* w = addItem(sign->mName, coord1, coord2);
ToolTips::createBirthsignToolTip(w, mBirthSignId);
}
// Add a line separator if there are items above
if (!mSkillWidgets.empty())
addSeparator(coord1, coord2);
addValueItem(MWBase::Environment::get().getWindowManager()->getGameSettingString("sReputation", "Reputation"),
MyGUI::utility::toString(static_cast<int>(mReputation)), "normal", coord1, coord2);
for (int i = 0; i < 2; ++i)
{
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString("ToolTipType", "Layout");
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString("ToolTipLayout", "TextToolTip");
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString("Caption_Text", "#{sSkillsMenuReputationHelp}");
}
addValueItem(MWBase::Environment::get().getWindowManager()->getGameSettingString("sBounty", "Bounty"),
MyGUI::utility::toString(static_cast<int>(mBounty)), "normal", coord1, coord2);
for (int i = 0; i < 2; ++i)
{
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString("ToolTipType", "Layout");
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString("ToolTipLayout", "TextToolTip");
mSkillWidgets[mSkillWidgets.size() - 1 - i]->setUserString("Caption_Text", "#{sCrimeHelp}");
}
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
// scrollbar is hidden
mSkillView->setVisibleVScroll(false);
mSkillView->setCanvasSize(mSkillView->getWidth(), std::max(mSkillView->getHeight(), coord1.top));
mSkillView->setVisibleVScroll(true);
}
void StatsWindow::onPinToggled()
{
Settings::windows().mStatsPin.set(mPinned);
MWBase::Environment::get().getWindowManager()->setHMSVisibility(!mPinned);
}
void StatsWindow::onTitleDoubleClicked()
{
if (MyGUI::InputManager::getInstance().isShiftPressed())
{
MWBase::Environment::get().getWindowManager()->toggleMaximized(this);
MyGUI::Window* t = mMainWidget->castType<MyGUI::Window>();
onWindowResize(t);
}
else if (!mPinned)
MWBase::Environment::get().getWindowManager()->toggleVisible(GW_Stats);
}
}
| 30,891
|
C++
|
.cpp
| 601
| 40.008319
| 120
| 0.609216
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,474
|
windowmanagerimp.cpp
|
OpenMW_openmw/apps/openmw/mwgui/windowmanagerimp.cpp
|
#include "windowmanagerimp.hpp"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <filesystem>
#include <thread>
#include <osgViewer/Viewer>
#include <MyGUI_ClipboardManager.h>
#include <MyGUI_FactoryManager.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_LanguageManager.h>
#include <MyGUI_PointerManager.h>
#include <MyGUI_UString.h>
// For BT_NO_PROFILE
#include <LinearMath/btQuickprof.h>
#include <SDL_clipboard.h>
#include <SDL_keyboard.h>
#include <components/debug/debuglog.hpp>
#include <components/esm3/esmreader.hpp>
#include <components/esm3/esmwriter.hpp>
#include <components/fontloader/fontloader.hpp>
#include <components/resource/imagemanager.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/resource/scenemanager.hpp>
#include <components/sceneutil/workqueue.hpp>
#include <components/translation/translation.hpp>
#include <components/myguiplatform/additivelayer.hpp>
#include <components/myguiplatform/myguiplatform.hpp>
#include <components/myguiplatform/myguirendermanager.hpp>
#include <components/myguiplatform/scalinglayer.hpp>
#include <components/vfs/manager.hpp>
#include <components/widgets/tags.hpp>
#include <components/widgets/widgets.hpp>
#include <components/misc/frameratelimiter.hpp>
#include <components/l10n/manager.hpp>
#include <components/lua_ui/util.hpp>
#include <components/lua_ui/widget.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/inputmanager.hpp"
#include "../mwbase/luamanager.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/statemanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwrender/vismask.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/globals.hpp"
#include "../mwworld/player.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "../mwrender/postprocessor.hpp"
#include "alchemywindow.hpp"
#include "backgroundimage.hpp"
#include "bookpage.hpp"
#include "bookwindow.hpp"
#include "companionwindow.hpp"
#include "confirmationdialog.hpp"
#include "console.hpp"
#include "container.hpp"
#include "controllers.hpp"
#include "countdialog.hpp"
#include "cursor.hpp"
#include "debugwindow.hpp"
#include "dialogue.hpp"
#include "enchantingdialog.hpp"
#include "exposedwindow.hpp"
#include "hud.hpp"
#include "inventorywindow.hpp"
#include "itemchargeview.hpp"
#include "itemview.hpp"
#include "itemwidget.hpp"
#include "jailscreen.hpp"
#include "journalviewmodel.hpp"
#include "journalwindow.hpp"
#include "keyboardnavigation.hpp"
#include "levelupdialog.hpp"
#include "loadingscreen.hpp"
#include "mainmenu.hpp"
#include "merchantrepair.hpp"
#include "postprocessorhud.hpp"
#include "quickkeysmenu.hpp"
#include "recharge.hpp"
#include "repair.hpp"
#include "resourceskin.hpp"
#include "screenfader.hpp"
#include "scrollwindow.hpp"
#include "settingswindow.hpp"
#include "spellbuyingwindow.hpp"
#include "spellview.hpp"
#include "spellwindow.hpp"
#include "statswindow.hpp"
#include "tradewindow.hpp"
#include "trainingwindow.hpp"
#include "travelwindow.hpp"
#include "videowidget.hpp"
#include "waitdialog.hpp"
namespace MWGui
{
namespace
{
Settings::SettingValue<bool>* findHiddenSetting(GuiWindow window)
{
switch (window)
{
case GW_Inventory:
return &Settings::windows().mInventoryHidden;
case GW_Map:
return &Settings::windows().mMapHidden;
case GW_Magic:
return &Settings::windows().mSpellsHidden;
case GW_Stats:
return &Settings::windows().mStatsHidden;
default:
return nullptr;
}
}
}
WindowManager::WindowManager(SDL_Window* window, osgViewer::Viewer* viewer, osg::Group* guiRoot,
Resource::ResourceSystem* resourceSystem, SceneUtil::WorkQueue* workQueue, const std::filesystem::path& logpath,
bool consoleOnlyScripts, Translation::Storage& translationDataStorage, ToUTF8::FromType encoding,
const std::string& versionDescription, bool useShaders, Files::ConfigurationManager& cfgMgr)
: mOldUpdateMask(0)
, mOldCullMask(0)
, mStore(nullptr)
, mResourceSystem(resourceSystem)
, mWorkQueue(workQueue)
, mViewer(viewer)
, mConsoleOnlyScripts(consoleOnlyScripts)
, mCurrentModals()
, mHud(nullptr)
, mMap(nullptr)
, mStatsWindow(nullptr)
, mConsole(nullptr)
, mDialogueWindow(nullptr)
, mInventoryWindow(nullptr)
, mScrollWindow(nullptr)
, mBookWindow(nullptr)
, mCountDialog(nullptr)
, mTradeWindow(nullptr)
, mSettingsWindow(nullptr)
, mConfirmationDialog(nullptr)
, mSpellWindow(nullptr)
, mQuickKeysMenu(nullptr)
, mLoadingScreen(nullptr)
, mWaitDialog(nullptr)
, mVideoBackground(nullptr)
, mVideoWidget(nullptr)
, mWerewolfFader(nullptr)
, mBlindnessFader(nullptr)
, mHitFader(nullptr)
, mScreenFader(nullptr)
, mDebugWindow(nullptr)
, mPostProcessorHud(nullptr)
, mJailScreen(nullptr)
, mContainerWindow(nullptr)
, mTranslationDataStorage(translationDataStorage)
, mInputBlocker(nullptr)
, mHudEnabled(true)
, mCursorVisible(true)
, mCursorActive(true)
, mPlayerBounty(-1)
, mGuiModes()
, mGarbageDialogs()
, mShown(GW_ALL)
, mForceHidden(GW_None)
, mAllowed(GW_ALL)
, mRestAllowed(true)
, mEncoding(encoding)
, mVersionDescription(versionDescription)
, mWindowVisible(true)
, mCfgMgr(cfgMgr)
{
int w, h;
SDL_GetWindowSize(window, &w, &h);
int dw, dh;
SDL_GL_GetDrawableSize(window, &dw, &dh);
mScalingFactor = Settings::gui().mScalingFactor * (dw / w);
mGuiPlatform = std::make_unique<osgMyGUI::Platform>(viewer, guiRoot, resourceSystem->getImageManager(),
resourceSystem->getVFS(), mScalingFactor, "mygui", logpath / "MyGUI.log");
mGui = std::make_unique<MyGUI::Gui>();
mGui->initialise({});
createTextures();
MyGUI::LanguageManager::getInstance().eventRequestTag = MyGUI::newDelegate(this, &WindowManager::onRetrieveTag);
// Load fonts
mFontLoader = std::make_unique<Gui::FontLoader>(encoding, resourceSystem->getVFS(), mScalingFactor);
// Register own widgets with MyGUI
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Widgets::MWSkill>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Widgets::MWAttribute>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Widgets::MWSpell>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Widgets::MWEffectList>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Widgets::MWSpellEffect>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Widgets::MWDynamicStat>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Window>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<VideoWidget>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<BackgroundImage>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<osgMyGUI::AdditiveLayer>("Layer");
MyGUI::FactoryManager::getInstance().registerFactory<osgMyGUI::ScalingLayer>("Layer");
BookPage::registerMyGUIComponents();
PostProcessorHud::registerMyGUIComponents();
ItemView::registerComponents();
ItemChargeView::registerComponents();
ItemWidget::registerComponents();
SpellView::registerComponents();
Gui::registerAllWidgets();
LuaUi::registerAllWidgets();
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Controllers::ControllerFollowMouse>("Controller");
MyGUI::FactoryManager::getInstance().registerFactory<ResourceImageSetPointerFix>(
"Resource", "ResourceImageSetPointer");
MyGUI::FactoryManager::getInstance().registerFactory<AutoSizedResourceSkin>(
"Resource", "AutoSizedResourceSkin");
MyGUI::ResourceManager::getInstance().load("core.xml");
const bool keyboardNav = Settings::gui().mKeyboardNavigation;
mKeyboardNavigation = std::make_unique<KeyboardNavigation>();
mKeyboardNavigation->setEnabled(keyboardNav);
Gui::ImageButton::setDefaultNeedKeyFocus(keyboardNav);
auto loadingScreen = std::make_unique<LoadingScreen>(mResourceSystem, mViewer);
mLoadingScreen = loadingScreen.get();
mWindows.push_back(std::move(loadingScreen));
// set up the hardware cursor manager
mCursorManager = std::make_unique<SDLUtil::SDLCursorManager>();
MyGUI::PointerManager::getInstance().eventChangeMousePointer
+= MyGUI::newDelegate(this, &WindowManager::onCursorChange);
MyGUI::InputManager::getInstance().eventChangeKeyFocus
+= MyGUI::newDelegate(this, &WindowManager::onKeyFocusChanged);
// Create all cursors in advance
createCursors();
onCursorChange(MyGUI::PointerManager::getInstance().getDefaultPointer());
mCursorManager->setEnabled(true);
// hide mygui's pointer
MyGUI::PointerManager::getInstance().setVisible(false);
mVideoBackground = MyGUI::Gui::getInstance().createWidgetReal<MyGUI::ImageBox>(
"ImageBox", 0, 0, 1, 1, MyGUI::Align::Default, "Video");
mVideoBackground->setImageTexture("black");
mVideoBackground->setVisible(false);
mVideoBackground->setNeedMouseFocus(true);
mVideoBackground->setNeedKeyFocus(true);
mVideoWidget = mVideoBackground->createWidgetReal<VideoWidget>("ImageBox", 0, 0, 1, 1, MyGUI::Align::Default);
mVideoWidget->setNeedMouseFocus(true);
mVideoWidget->setNeedKeyFocus(true);
mVideoWidget->setVFS(resourceSystem->getVFS());
// Removes default MyGUI system clipboard implementation, which supports windows only
MyGUI::ClipboardManager::getInstance().eventClipboardChanged.clear();
MyGUI::ClipboardManager::getInstance().eventClipboardRequested.clear();
MyGUI::ClipboardManager::getInstance().eventClipboardChanged
+= MyGUI::newDelegate(this, &WindowManager::onClipboardChanged);
MyGUI::ClipboardManager::getInstance().eventClipboardRequested
+= MyGUI::newDelegate(this, &WindowManager::onClipboardRequested);
mVideoWrapper = std::make_unique<SDLUtil::VideoWrapper>(window, viewer);
mVideoWrapper->setGammaContrast(Settings::video().mGamma, Settings::video().mContrast);
if (useShaders)
mGuiPlatform->getRenderManagerPtr()->enableShaders(mResourceSystem->getSceneManager()->getShaderManager());
mStatsWatcher = std::make_unique<StatsWatcher>();
}
void WindowManager::initUI()
{
// Get size info from the Gui object
int w = MyGUI::RenderManager::getInstance().getViewSize().width;
int h = MyGUI::RenderManager::getInstance().getViewSize().height;
mTextColours.loadColours();
mDragAndDrop = std::make_unique<DragAndDrop>();
auto recharge = std::make_unique<Recharge>();
mGuiModeStates[GM_Recharge] = GuiModeState(recharge.get());
mWindows.push_back(std::move(recharge));
auto menu = std::make_unique<MainMenu>(w, h, mResourceSystem->getVFS(), mVersionDescription);
mGuiModeStates[GM_MainMenu] = GuiModeState(menu.get());
mWindows.push_back(std::move(menu));
mLocalMapRender = std::make_unique<MWRender::LocalMap>(mViewer->getSceneData()->asGroup());
auto map = std::make_unique<MapWindow>(mCustomMarkers, mDragAndDrop.get(), mLocalMapRender.get(), mWorkQueue);
mMap = map.get();
mWindows.push_back(std::move(map));
mMap->renderGlobalMap();
trackWindow(mMap, makeMapWindowSettingValues());
auto statsWindow = std::make_unique<StatsWindow>(mDragAndDrop.get());
mStatsWindow = statsWindow.get();
mWindows.push_back(std::move(statsWindow));
trackWindow(mStatsWindow, makeStatsWindowSettingValues());
auto inventoryWindow = std::make_unique<InventoryWindow>(
mDragAndDrop.get(), mViewer->getSceneData()->asGroup(), mResourceSystem);
mInventoryWindow = inventoryWindow.get();
mWindows.push_back(std::move(inventoryWindow));
auto spellWindow = std::make_unique<SpellWindow>(mDragAndDrop.get());
mSpellWindow = spellWindow.get();
mWindows.push_back(std::move(spellWindow));
trackWindow(mSpellWindow, makeSpellsWindowSettingValues());
mGuiModeStates[GM_Inventory] = GuiModeState({ mMap, mInventoryWindow, mSpellWindow, mStatsWindow });
mGuiModeStates[GM_None] = GuiModeState({ mMap, mInventoryWindow, mSpellWindow, mStatsWindow });
auto tradeWindow = std::make_unique<TradeWindow>();
mTradeWindow = tradeWindow.get();
mWindows.push_back(std::move(tradeWindow));
trackWindow(mTradeWindow, makeBarterWindowSettingValues());
mGuiModeStates[GM_Barter] = GuiModeState({ mInventoryWindow, mTradeWindow });
auto console = std::make_unique<Console>(w, h, mConsoleOnlyScripts, mCfgMgr);
mConsole = console.get();
mWindows.push_back(std::move(console));
trackWindow(mConsole, makeConsoleWindowSettingValues());
constexpr VFS::Path::NormalizedView menubookOptionsOverTexture("textures/tx_menubook_options_over.dds");
const bool questList = mResourceSystem->getVFS()->exists(menubookOptionsOverTexture);
auto journal = JournalWindow::create(JournalViewModel::create(), questList, mEncoding);
mGuiModeStates[GM_Journal] = GuiModeState(journal.get());
mWindows.push_back(std::move(journal));
mMessageBoxManager = std::make_unique<MessageBoxManager>(
mStore->get<ESM::GameSetting>().find("fMessageTimePerChar")->mValue.getFloat());
auto spellBuyingWindow = std::make_unique<SpellBuyingWindow>();
mGuiModeStates[GM_SpellBuying] = GuiModeState(spellBuyingWindow.get());
mWindows.push_back(std::move(spellBuyingWindow));
auto travelWindow = std::make_unique<TravelWindow>();
mGuiModeStates[GM_Travel] = GuiModeState(travelWindow.get());
mWindows.push_back(std::move(travelWindow));
auto dialogueWindow = std::make_unique<DialogueWindow>();
mDialogueWindow = dialogueWindow.get();
mWindows.push_back(std::move(dialogueWindow));
trackWindow(mDialogueWindow, makeDialogueWindowSettingValues());
mGuiModeStates[GM_Dialogue] = GuiModeState(mDialogueWindow);
mTradeWindow->eventTradeDone += MyGUI::newDelegate(mDialogueWindow, &DialogueWindow::onTradeComplete);
auto containerWindow = std::make_unique<ContainerWindow>(mDragAndDrop.get());
mContainerWindow = containerWindow.get();
mWindows.push_back(std::move(containerWindow));
trackWindow(mContainerWindow, makeContainerWindowSettingValues());
mGuiModeStates[GM_Container] = GuiModeState({ mContainerWindow, mInventoryWindow });
auto hud = std::make_unique<HUD>(mCustomMarkers, mDragAndDrop.get(), mLocalMapRender.get());
mHud = hud.get();
mWindows.push_back(std::move(hud));
mToolTips = std::make_unique<ToolTips>();
auto scrollWindow = std::make_unique<ScrollWindow>();
mScrollWindow = scrollWindow.get();
mWindows.push_back(std::move(scrollWindow));
mGuiModeStates[GM_Scroll] = GuiModeState(mScrollWindow);
auto bookWindow = std::make_unique<BookWindow>();
mBookWindow = bookWindow.get();
mWindows.push_back(std::move(bookWindow));
mGuiModeStates[GM_Book] = GuiModeState(mBookWindow);
auto countDialog = std::make_unique<CountDialog>();
mCountDialog = countDialog.get();
mWindows.push_back(std::move(countDialog));
auto settingsWindow = std::make_unique<SettingsWindow>();
mSettingsWindow = settingsWindow.get();
mWindows.push_back(std::move(settingsWindow));
trackWindow(mSettingsWindow, makeSettingsWindowSettingValues());
auto confirmationDialog = std::make_unique<ConfirmationDialog>();
mConfirmationDialog = confirmationDialog.get();
mWindows.push_back(std::move(confirmationDialog));
auto alchemyWindow = std::make_unique<AlchemyWindow>();
trackWindow(alchemyWindow.get(), makeAlchemyWindowSettingValues());
mGuiModeStates[GM_Alchemy] = GuiModeState(alchemyWindow.get());
mWindows.push_back(std::move(alchemyWindow));
auto quickKeysMenu = std::make_unique<QuickKeysMenu>();
mQuickKeysMenu = quickKeysMenu.get();
mWindows.push_back(std::move(quickKeysMenu));
mGuiModeStates[GM_QuickKeysMenu] = GuiModeState(mQuickKeysMenu);
auto levelupDialog = std::make_unique<LevelupDialog>();
mGuiModeStates[GM_Levelup] = GuiModeState(levelupDialog.get());
mWindows.push_back(std::move(levelupDialog));
auto waitDialog = std::make_unique<WaitDialog>();
mWaitDialog = waitDialog.get();
mWindows.push_back(std::move(waitDialog));
mGuiModeStates[GM_Rest] = GuiModeState({ mWaitDialog->getProgressBar(), mWaitDialog });
auto spellCreationDialog = std::make_unique<SpellCreationDialog>();
mGuiModeStates[GM_SpellCreation] = GuiModeState(spellCreationDialog.get());
mWindows.push_back(std::move(spellCreationDialog));
auto enchantingDialog = std::make_unique<EnchantingDialog>();
mGuiModeStates[GM_Enchanting] = GuiModeState(enchantingDialog.get());
mWindows.push_back(std::move(enchantingDialog));
auto trainingWindow = std::make_unique<TrainingWindow>();
mGuiModeStates[GM_Training] = GuiModeState({ trainingWindow->getProgressBar(), trainingWindow.get() });
mWindows.push_back(std::move(trainingWindow));
auto merchantRepair = std::make_unique<MerchantRepair>();
mGuiModeStates[GM_MerchantRepair] = GuiModeState(merchantRepair.get());
mWindows.push_back(std::move(merchantRepair));
auto repair = std::make_unique<Repair>();
mGuiModeStates[GM_Repair] = GuiModeState(repair.get());
mWindows.push_back(std::move(repair));
mSoulgemDialog = std::make_unique<SoulgemDialog>(mMessageBoxManager.get());
auto companionWindow = std::make_unique<CompanionWindow>(mDragAndDrop.get(), mMessageBoxManager.get());
trackWindow(companionWindow.get(), makeCompanionWindowSettingValues());
mGuiModeStates[GM_Companion] = GuiModeState({ mInventoryWindow, companionWindow.get() });
mWindows.push_back(std::move(companionWindow));
auto jailScreen = std::make_unique<JailScreen>();
mJailScreen = jailScreen.get();
mWindows.push_back(std::move(jailScreen));
mGuiModeStates[GM_Jail] = GuiModeState(mJailScreen);
std::string werewolfFaderTex = "textures\\werewolfoverlay.dds";
if (mResourceSystem->getVFS()->exists(werewolfFaderTex))
{
auto werewolfFader = std::make_unique<ScreenFader>(werewolfFaderTex);
mWerewolfFader = werewolfFader.get();
mWindows.push_back(std::move(werewolfFader));
}
auto blindnessFader = std::make_unique<ScreenFader>("black");
mBlindnessFader = blindnessFader.get();
mWindows.push_back(std::move(blindnessFader));
// fall back to player_hit_01.dds if bm_player_hit_01.dds is not available
std::string hitFaderTexture = "textures\\bm_player_hit_01.dds";
const std::string hitFaderLayout = "openmw_screen_fader_hit.layout";
MyGUI::FloatCoord hitFaderCoord(0, 0, 1, 1);
if (!mResourceSystem->getVFS()->exists(hitFaderTexture))
{
hitFaderTexture = "textures\\player_hit_01.dds";
hitFaderCoord = MyGUI::FloatCoord(0.2, 0.25, 0.6, 0.5);
}
auto hitFader = std::make_unique<ScreenFader>(hitFaderTexture, hitFaderLayout, hitFaderCoord);
mHitFader = hitFader.get();
mWindows.push_back(std::move(hitFader));
auto screenFader = std::make_unique<ScreenFader>("black");
mScreenFader = screenFader.get();
mWindows.push_back(std::move(screenFader));
auto debugWindow = std::make_unique<DebugWindow>();
mDebugWindow = debugWindow.get();
mWindows.push_back(std::move(debugWindow));
trackWindow(mDebugWindow, makeDebugWindowSettingValues());
auto postProcessorHud = std::make_unique<PostProcessorHud>();
mPostProcessorHud = postProcessorHud.get();
mWindows.push_back(std::move(postProcessorHud));
trackWindow(mPostProcessorHud, makePostprocessorWindowSettingValues());
mInputBlocker = MyGUI::Gui::getInstance().createWidget<MyGUI::Widget>(
{}, 0, 0, w, h, MyGUI::Align::Stretch, "InputBlocker");
mHud->setVisible(true);
mCharGen = std::make_unique<CharacterCreation>(mViewer->getSceneData()->asGroup(), mResourceSystem);
updatePinnedWindows();
// Set up visibility
updateVisible();
mStatsWatcher->addListener(mHud);
mStatsWatcher->addListener(mStatsWindow);
mStatsWatcher->addListener(mCharGen.get());
for (auto& window : mWindows)
{
std::string_view id = window->getWindowIdForLua();
if (!id.empty())
mLuaIdToWindow.emplace(id, window.get());
}
}
void WindowManager::setNewGame(bool newgame)
{
if (newgame)
{
disallowAll();
mStatsWatcher->removeListener(mCharGen.get());
mCharGen = std::make_unique<CharacterCreation>(mViewer->getSceneData()->asGroup(), mResourceSystem);
mStatsWatcher->addListener(mCharGen.get());
}
else
allow(GW_ALL);
mStatsWatcher->forceUpdate();
}
WindowManager::~WindowManager()
{
try
{
LuaUi::clearGameInterface();
LuaUi::clearMenuInterface();
mStatsWatcher.reset();
MyGUI::LanguageManager::getInstance().eventRequestTag.clear();
MyGUI::PointerManager::getInstance().eventChangeMousePointer.clear();
MyGUI::InputManager::getInstance().eventChangeKeyFocus.clear();
MyGUI::ClipboardManager::getInstance().eventClipboardChanged.clear();
MyGUI::ClipboardManager::getInstance().eventClipboardRequested.clear();
mWindows.clear();
mMessageBoxManager.reset();
mToolTips.reset();
mCharGen.reset();
mKeyboardNavigation.reset();
cleanupGarbage();
mFontLoader.reset();
mGui->shutdown();
mGuiPlatform->shutdown();
}
catch (const MyGUI::Exception& e)
{
Log(Debug::Error) << "Error in the destructor: " << e.what();
}
}
void WindowManager::setStore(const MWWorld::ESMStore& store)
{
mStore = &store;
}
void WindowManager::cleanupGarbage()
{
// Delete any dialogs which are no longer in use
mGarbageDialogs.clear();
}
void WindowManager::enableScene(bool enable)
{
unsigned int disablemask = MWRender::Mask_GUI | MWRender::Mask_PreCompile;
if (!enable && getCullMask() != disablemask)
{
mOldUpdateMask = mViewer->getUpdateVisitor()->getTraversalMask();
mOldCullMask = getCullMask();
mViewer->getUpdateVisitor()->setTraversalMask(disablemask);
setCullMask(disablemask);
}
else if (enable && getCullMask() == disablemask)
{
mViewer->getUpdateVisitor()->setTraversalMask(mOldUpdateMask);
setCullMask(mOldCullMask);
}
}
void WindowManager::updateConsoleObjectPtr(const MWWorld::Ptr& currentPtr, const MWWorld::Ptr& newPtr)
{
mConsole->updateSelectedObjectPtr(currentPtr, newPtr);
}
void WindowManager::updateVisible()
{
bool loading = (getMode() == GM_Loading || getMode() == GM_LoadingWallpaper);
bool mainmenucover = containsMode(GM_MainMenu)
&& MWBase::Environment::get().getStateManager()->getState() == MWBase::StateManager::State_NoGame;
enableScene(!loading && !mainmenucover);
if (!mMap)
return; // UI not created yet
mHud->setVisible(mHudEnabled && !loading);
mToolTips->setVisible(mHudEnabled && !loading);
bool gameMode = !isGuiMode();
MWBase::Environment::get().getInputManager()->changeInputMode(!gameMode);
mInputBlocker->setVisible(gameMode);
if (loading)
setCursorVisible(mMessageBoxManager && mMessageBoxManager->isInteractiveMessageBox());
else
setCursorVisible(!gameMode);
if (gameMode)
setKeyFocusWidget(nullptr);
// Icons of forced hidden windows are displayed
setMinimapVisibility((mAllowed & GW_Map) && (!mMap->pinned() || (mForceHidden & GW_Map)));
setWeaponVisibility(
(mAllowed & GW_Inventory) && (!mInventoryWindow->pinned() || (mForceHidden & GW_Inventory)));
setSpellVisibility((mAllowed & GW_Magic) && (!mSpellWindow->pinned() || (mForceHidden & GW_Magic)));
setHMSVisibility((mAllowed & GW_Stats) && (!mStatsWindow->pinned() || (mForceHidden & GW_Stats)));
mInventoryWindow->setGuiMode(getMode());
// If in game mode (or interactive messagebox), show the pinned windows
if (mGuiModes.empty())
{
mMap->setVisible(mMap->pinned() && !isConsoleMode() && !(mForceHidden & GW_Map) && (mAllowed & GW_Map));
mStatsWindow->setVisible(
mStatsWindow->pinned() && !isConsoleMode() && !(mForceHidden & GW_Stats) && (mAllowed & GW_Stats));
mInventoryWindow->setVisible(mInventoryWindow->pinned() && !isConsoleMode()
&& !(mForceHidden & GW_Inventory) && (mAllowed & GW_Inventory));
mSpellWindow->setVisible(
mSpellWindow->pinned() && !isConsoleMode() && !(mForceHidden & GW_Magic) && (mAllowed & GW_Magic));
return;
}
else if (getMode() != GM_Inventory)
{
mMap->setVisible(false);
mStatsWindow->setVisible(false);
mSpellWindow->setVisible(false);
mHud->setDrowningBarVisible(false);
mInventoryWindow->setVisible(
getMode() == GM_Container || getMode() == GM_Barter || getMode() == GM_Companion);
}
GuiMode mode = mGuiModes.back();
mInventoryWindow->setTrading(mode == GM_Barter);
if (getMode() == GM_Inventory)
{
// For the inventory mode, compute the effective set of windows to show.
// This is controlled both by what windows the
// user has opened/closed (the 'shown' variable) and by what
// windows we are allowed to show (the 'allowed' var.)
int eff = mShown & mAllowed & ~mForceHidden;
mMap->setVisible(eff & GW_Map);
mInventoryWindow->setVisible(eff & GW_Inventory);
mSpellWindow->setVisible(eff & GW_Magic);
mStatsWindow->setVisible(eff & GW_Stats);
}
switch (mode)
{
// FIXME: refactor chargen windows to use modes properly (or not use them at all)
case GM_Name:
case GM_Race:
case GM_Class:
case GM_ClassPick:
case GM_ClassCreate:
case GM_Birth:
case GM_ClassGenerate:
case GM_Review:
mCharGen->spawnDialog(mode);
break;
default:
break;
}
}
void WindowManager::setDrowningTimeLeft(float time, float maxTime)
{
mHud->setDrowningTimeLeft(time, maxTime);
}
void WindowManager::removeDialog(std::unique_ptr<Layout>&& dialog)
{
if (!dialog)
return;
dialog->setVisible(false);
mGarbageDialogs.push_back(std::move(dialog));
}
void WindowManager::exitCurrentGuiMode()
{
if (mDragAndDrop && mDragAndDrop->mIsOnDragAndDrop)
{
mDragAndDrop->finish();
return;
}
GuiModeState& state = mGuiModeStates[mGuiModes.back()];
for (const auto& window : state.mWindows)
{
if (!window->exit())
{
// unable to exit window, but give access to main menu
if (!MyGUI::InputManager::getInstance().isModalAny() && getMode() != GM_MainMenu)
pushGuiMode(GM_MainMenu);
return;
}
}
popGuiMode();
}
void WindowManager::interactiveMessageBox(
std::string_view message, const std::vector<std::string>& buttons, bool block, int defaultFocus)
{
mMessageBoxManager->createInteractiveMessageBox(message, buttons, block, defaultFocus);
updateVisible();
if (block)
{
Misc::FrameRateLimiter frameRateLimiter
= Misc::makeFrameRateLimiter(MWBase::Environment::get().getFrameRateLimit());
while (mMessageBoxManager->readPressedButton(false) == -1
&& !MWBase::Environment::get().getStateManager()->hasQuitRequest())
{
const double dt
= std::chrono::duration_cast<std::chrono::duration<double>>(frameRateLimiter.getLastFrameDuration())
.count();
mKeyboardNavigation->onFrame();
mMessageBoxManager->onFrame(dt);
MWBase::Environment::get().getInputManager()->update(dt, true, false);
if (!mWindowVisible)
std::this_thread::sleep_for(std::chrono::milliseconds(5));
else
{
mViewer->eventTraversal();
mViewer->updateTraversal();
mViewer->renderingTraversals();
}
// at the time this function is called we are in the middle of a frame,
// so out of order calls are necessary to get a correct frameNumber for the next frame.
// refer to the advance() and frame() order in Engine::go()
mViewer->advance(mViewer->getFrameStamp()->getSimulationTime());
frameRateLimiter.limit();
}
mMessageBoxManager->resetInteractiveMessageBox();
}
}
void WindowManager::messageBox(std::string_view message, enum MWGui::ShowInDialogueMode showInDialogueMode)
{
if (getMode() == GM_Dialogue && showInDialogueMode != MWGui::ShowInDialogueMode_Never)
{
MyGUI::UString text = MyGUI::LanguageManager::getInstance().replaceTags(MyGUI::UString(message));
mDialogueWindow->addMessageBox(text);
}
else if (showInDialogueMode != MWGui::ShowInDialogueMode_Only)
{
mMessageBoxManager->createMessageBox(message);
}
}
void WindowManager::scheduleMessageBox(std::string message, enum MWGui::ShowInDialogueMode showInDialogueMode)
{
mScheduledMessageBoxes.lock()->emplace_back(std::move(message), showInDialogueMode);
}
void WindowManager::staticMessageBox(std::string_view message)
{
mMessageBoxManager->createMessageBox(message, true);
}
void WindowManager::removeStaticMessageBox()
{
mMessageBoxManager->removeStaticMessageBox();
}
int WindowManager::readPressedButton()
{
return mMessageBoxManager->readPressedButton();
}
std::string_view WindowManager::getGameSettingString(std::string_view id, std::string_view default_)
{
const ESM::GameSetting* setting = mStore->get<ESM::GameSetting>().search(id);
if (setting && setting->mValue.getType() == ESM::VT_String)
return setting->mValue.getString();
return default_;
}
void WindowManager::updateMap()
{
if (!mLocalMapRender)
return;
MWWorld::ConstPtr player = MWMechanics::getPlayer();
osg::Vec3f playerPosition = player.getRefData().getPosition().asVec3();
osg::Quat playerOrientation(-player.getRefData().getPosition().rot[2], osg::Vec3(0, 0, 1));
osg::Vec3f playerdirection;
int x, y;
float u, v;
mLocalMapRender->updatePlayer(playerPosition, playerOrientation, u, v, x, y, playerdirection);
if (!player.getCell()->isExterior())
{
setActiveMap(*player.getCell()->getCell());
}
// else: need to know the current grid center, call setActiveMap from changeCell
mMap->setPlayerDir(playerdirection.x(), playerdirection.y());
mMap->setPlayerPos(x, y, u, v);
mHud->setPlayerDir(playerdirection.x(), playerdirection.y());
mHud->setPlayerPos(x, y, u, v);
}
void WindowManager::update(float frameDuration)
{
handleScheduledMessageBoxes();
bool gameRunning
= MWBase::Environment::get().getStateManager()->getState() != MWBase::StateManager::State_NoGame;
if (gameRunning)
updateMap();
if (!mGuiModes.empty())
{
GuiModeState& state = mGuiModeStates[mGuiModes.back()];
for (WindowBase* window : state.mWindows)
window->onFrame(frameDuration);
}
else
{
// update pinned windows if visible
for (WindowBase* window : mGuiModeStates[GM_Inventory].mWindows)
if (window->isVisible())
window->onFrame(frameDuration);
}
// Make sure message boxes are always in front
// This is an awful workaround for a series of awfully interwoven issues that couldn't be worked around
// in a better way because of an impressive number of even more awfully interwoven issues.
if (mMessageBoxManager && mMessageBoxManager->isInteractiveMessageBox()
&& mCurrentModals.back() != mMessageBoxManager->getInteractiveMessageBox())
{
std::vector<WindowModal*>::iterator found = std::find(
mCurrentModals.begin(), mCurrentModals.end(), mMessageBoxManager->getInteractiveMessageBox());
if (found != mCurrentModals.end())
{
WindowModal* msgbox = *found;
std::swap(*found, mCurrentModals.back());
MyGUI::InputManager::getInstance().addWidgetModal(msgbox->mMainWidget);
mKeyboardNavigation->setModalWindow(msgbox->mMainWidget);
mKeyboardNavigation->setDefaultFocus(msgbox->mMainWidget, msgbox->getDefaultKeyFocus());
}
}
if (!mCurrentModals.empty())
mCurrentModals.back()->onFrame(frameDuration);
mKeyboardNavigation->onFrame();
if (mMessageBoxManager)
mMessageBoxManager->onFrame(frameDuration);
mToolTips->onFrame(frameDuration);
if (mLocalMapRender)
mLocalMapRender->cleanupCameras();
mDebugWindow->onFrame(frameDuration);
if (isConsoleMode())
mConsole->onFrame(frameDuration);
if (isSettingsWindowVisible())
mSettingsWindow->onFrame(frameDuration);
if (!gameRunning)
return;
// We should display message about crime only once per frame, even if there are several crimes.
// Otherwise we will get message spam when stealing several items via Take All button.
const MWWorld::Ptr player = MWMechanics::getPlayer();
const MWWorld::Class& playerCls = player.getClass();
int currentBounty = playerCls.getNpcStats(player).getBounty();
if (currentBounty != mPlayerBounty)
{
if (mPlayerBounty >= 0 && currentBounty > mPlayerBounty)
messageBox("#{sCrimeMessage}");
mPlayerBounty = currentBounty;
}
MWBase::LuaManager::ActorControls* playerControls
= MWBase::Environment::get().getLuaManager()->getActorControls(player);
bool triedToMove = playerControls
&& (playerControls->mMovement != 0 || playerControls->mSideMovement != 0 || playerControls->mJump);
if (mMessageBoxManager && triedToMove && playerCls.getEncumbrance(player) > playerCls.getCapacity(player))
{
const auto& msgboxs = mMessageBoxManager->getActiveMessageBoxes();
auto it
= std::find_if(msgboxs.begin(), msgboxs.end(), [](const std::unique_ptr<MWGui::MessageBox>& msgbox) {
return (msgbox->getMessage() == "#{sNotifyMessage59}");
});
// if an overencumbered messagebox is already present, reset its expiry timer,
// otherwise create a new one.
if (it != msgboxs.end())
(*it)->mCurrentTime = 0;
else
messageBox("#{sNotifyMessage59}");
}
mDragAndDrop->onFrame();
mHud->onFrame(frameDuration);
mPostProcessorHud->onFrame(frameDuration);
if (mCharGen)
mCharGen->onFrame(frameDuration);
updateActivatedQuickKey();
mStatsWatcher->update();
cleanupGarbage();
}
void WindowManager::changeCell(const MWWorld::CellStore* cell)
{
mMap->requestMapRender(cell);
std::string name{ MWBase::Environment::get().getWorld()->getCellName(cell) };
mMap->setCellName(name);
mHud->setCellName(name);
auto cellCommon = cell->getCell();
if (cellCommon->isExterior())
{
if (!cellCommon->getNameId().empty())
mMap->addVisitedLocation(name, cellCommon->getGridX(), cellCommon->getGridY());
mMap->cellExplored(cellCommon->getGridX(), cellCommon->getGridY());
}
else
{
osg::Vec3f worldPos;
if (!MWBase::Environment::get().getWorld()->findInteriorPositionInWorldSpace(cell, worldPos))
worldPos = MWBase::Environment::get().getWorld()->getPlayer().getLastKnownExteriorPosition();
else
MWBase::Environment::get().getWorld()->getPlayer().setLastKnownExteriorPosition(worldPos);
mMap->setGlobalMapPlayerPosition(worldPos.x(), worldPos.y());
}
setActiveMap(*cellCommon);
}
void WindowManager::setActiveMap(const MWWorld::Cell& cell)
{
mMap->setActiveCell(cell);
mHud->setActiveCell(cell);
}
void WindowManager::setDrowningBarVisibility(bool visible)
{
mHud->setDrowningBarVisible(visible);
}
void WindowManager::setHMSVisibility(bool visible)
{
mHud->setHmsVisible(visible);
}
void WindowManager::setMinimapVisibility(bool visible)
{
mHud->setMinimapVisible(visible);
}
bool WindowManager::toggleFogOfWar()
{
mMap->toggleFogOfWar();
return mHud->toggleFogOfWar();
}
void WindowManager::setFocusObject(const MWWorld::Ptr& focus)
{
mToolTips->setFocusObject(focus);
const int showOwned = Settings::game().mShowOwned;
if (mHud && (showOwned == 2 || showOwned == 3))
{
bool owned = mToolTips->checkOwned();
mHud->setCrosshairOwned(owned);
}
}
void WindowManager::setFocusObjectScreenCoords(float min_x, float min_y, float max_x, float max_y)
{
mToolTips->setFocusObjectScreenCoords(min_x, min_y, max_x, max_y);
}
bool WindowManager::toggleFullHelp()
{
return mToolTips->toggleFullHelp();
}
bool WindowManager::getFullHelp() const
{
return mToolTips->getFullHelp();
}
void WindowManager::setWeaponVisibility(bool visible)
{
mHud->setWeapVisible(visible);
}
void WindowManager::setSpellVisibility(bool visible)
{
mHud->setSpellVisible(visible);
mHud->setEffectVisible(visible);
}
void WindowManager::setSneakVisibility(bool visible)
{
mHud->setSneakVisible(visible);
}
void WindowManager::setDragDrop(bool dragDrop)
{
mToolTips->setEnabled(!dragDrop);
MWBase::Environment::get().getInputManager()->setDragDrop(dragDrop);
}
void WindowManager::setCursorVisible(bool visible)
{
mCursorVisible = visible;
}
void WindowManager::setCursorActive(bool active)
{
mCursorActive = active;
}
void WindowManager::onRetrieveTag(const MyGUI::UString& _tag, MyGUI::UString& _result)
{
std::string_view tag = _tag;
std::string_view MyGuiPrefix = "setting=";
std::string_view tokenToFind = "sCell=";
if (tag.starts_with(MyGuiPrefix))
{
tag = tag.substr(MyGuiPrefix.length());
size_t comma_pos = tag.find(',');
if (comma_pos == std::string_view::npos)
throw std::runtime_error("Invalid setting tag (expected comma): " + std::string(tag));
std::string_view settingSection = tag.substr(0, comma_pos);
std::string_view settingTag = tag.substr(comma_pos + 1, tag.length());
_result = Settings::get<MyGUI::Colour>(settingSection, settingTag).get().print();
}
else if (tag.starts_with(tokenToFind))
{
std::string_view cellName = mTranslationDataStorage.translateCellName(tag.substr(tokenToFind.length()));
_result.assign(cellName.data(), cellName.size());
_result = MyGUI::TextIterator::toTagsString(_result);
}
else if (Gui::replaceTag(tag, _result))
{
return;
}
else
{
std::vector<std::string> split;
Misc::StringUtils::split(tag, split, ":");
l10n::Manager& l10nManager = *MWBase::Environment::get().getL10nManager();
// If a key has a "Context:KeyName" format, use YAML to translate data
if (split.size() == 2)
{
_result = l10nManager.getContext(split[0])->formatMessage(split[1], {}, {});
return;
}
// If not, treat is as GMST name from legacy localization
if (!mStore)
{
Log(Debug::Error) << "Error: WindowManager::onRetrieveTag: no Store set up yet, can not replace '"
<< tag << "'";
_result.assign(tag.data(), tag.size());
return;
}
const ESM::GameSetting* setting = mStore->get<ESM::GameSetting>().search(tag);
if (setting && setting->mValue.getType() == ESM::VT_String)
_result = setting->mValue.getString();
else
_result.assign(tag.data(), tag.size());
}
}
void WindowManager::processChangedSettings(const Settings::CategorySettingVector& changed)
{
bool changeRes = false;
for (const auto& setting : changed)
{
if (setting.first == "GUI" && setting.second == "menu transparency")
setMenuTransparency(Settings::gui().mMenuTransparency);
else if (setting.first == "Video"
&& (setting.second == "resolution x" || setting.second == "resolution y"
|| setting.second == "window mode" || setting.second == "window border"))
changeRes = true;
else if (setting.first == "Video" && setting.second == "vsync mode")
mVideoWrapper->setSyncToVBlank(Settings::video().mVsyncMode);
else if (setting.first == "Video" && (setting.second == "gamma" || setting.second == "contrast"))
mVideoWrapper->setGammaContrast(Settings::video().mGamma, Settings::video().mContrast);
}
if (changeRes)
{
mVideoWrapper->setVideoMode(Settings::video().mResolutionX, Settings::video().mResolutionY,
Settings::video().mWindowMode, Settings::video().mWindowBorder);
}
}
void WindowManager::windowResized(int x, int y)
{
Settings::video().mResolutionX.set(x);
Settings::video().mResolutionY.set(y);
// We only want to process changes to window-size related settings.
Settings::CategorySettingVector filter = { { "Video", "resolution x" }, { "Video", "resolution y" } };
// If the HUD has not been initialised, the World singleton will not be available.
if (mHud)
{
MWBase::Environment::get().getWorld()->processChangedSettings(Settings::Manager::getPendingChanges(filter));
}
Settings::Manager::resetPendingChanges(filter);
mGuiPlatform->getRenderManagerPtr()->setViewSize(x, y);
// scaled size
const MyGUI::IntSize& viewSize = MyGUI::RenderManager::getInstance().getViewSize();
x = viewSize.width;
y = viewSize.height;
sizeVideo(x, y);
if (!mHud)
return; // UI not initialized yet
for (const auto& [window, settings] : mTrackedWindows)
{
const WindowRectSettingValues& rect = settings.mIsMaximized ? settings.mMaximized : settings.mRegular;
window->setPosition(MyGUI::IntPoint(static_cast<int>(rect.mX * x), static_cast<int>(rect.mY * y)));
window->setSize(MyGUI::IntSize(static_cast<int>(rect.mW * x), static_cast<int>(rect.mH * y)));
WindowBase::clampWindowCoordinates(window);
}
for (const auto& window : mWindows)
window->onResChange(x, y);
// TODO: check if any windows are now off-screen and move them back if so
}
bool WindowManager::isWindowVisible()
{
return mWindowVisible;
}
void WindowManager::windowVisibilityChange(bool visible)
{
mWindowVisible = visible;
}
void WindowManager::windowClosed()
{
MWBase::Environment::get().getStateManager()->requestQuit();
}
void WindowManager::onCursorChange(std::string_view name)
{
mCursorManager->cursorChanged(name);
}
void WindowManager::pushGuiMode(GuiMode mode)
{
pushGuiMode(mode, MWWorld::Ptr());
}
void WindowManager::pushGuiMode(GuiMode mode, const MWWorld::Ptr& arg)
{
pushGuiMode(mode, arg, false);
}
void WindowManager::forceLootMode(const MWWorld::Ptr& ptr)
{
pushGuiMode(MWGui::GM_Container, ptr, true);
}
void WindowManager::pushGuiMode(GuiMode mode, const MWWorld::Ptr& arg, bool force)
{
if (mode == GM_Inventory && mAllowed == GW_None)
return;
if (mGuiModes.empty() || mGuiModes.back() != mode)
{
// If this mode already exists somewhere in the stack, just bring it to the front.
if (std::find(mGuiModes.begin(), mGuiModes.end(), mode) != mGuiModes.end())
{
mGuiModes.erase(std::find(mGuiModes.begin(), mGuiModes.end(), mode));
}
if (!mGuiModes.empty())
{
mKeyboardNavigation->saveFocus(mGuiModes.back());
mGuiModeStates[mGuiModes.back()].update(false);
}
mGuiModes.push_back(mode);
mGuiModeStates[mode].update(true);
}
if (force)
mContainerWindow->treatNextOpenAsLoot();
try
{
for (WindowBase* window : mGuiModeStates[mode].mWindows)
window->setPtr(arg);
}
catch (...)
{
popGuiMode();
throw;
}
mKeyboardNavigation->restoreFocus(mode);
updateVisible();
MWBase::Environment::get().getLuaManager()->uiModeChanged(arg);
}
void WindowManager::setCullMask(uint32_t mask)
{
mViewer->getCamera()->setCullMask(mask);
// We could check whether stereo is enabled here, but these methods are
// trivial and have no effect in mono or multiview so just call them regardless.
mViewer->getCamera()->setCullMaskLeft(mask);
mViewer->getCamera()->setCullMaskRight(mask);
}
uint32_t WindowManager::getCullMask()
{
return mViewer->getCamera()->getCullMask();
}
void WindowManager::popGuiMode(bool forceExit)
{
if (mDragAndDrop && mDragAndDrop->mIsOnDragAndDrop)
{
mDragAndDrop->finish();
}
if (!mGuiModes.empty())
{
const GuiMode mode = mGuiModes.back();
if (forceExit)
{
GuiModeState& state = mGuiModeStates[mode];
for (const auto& window : state.mWindows)
window->exit();
}
mKeyboardNavigation->saveFocus(mode);
if (containsMode(mode))
{
mGuiModes.pop_back();
mGuiModeStates[mode].update(false);
MWBase::Environment::get().getLuaManager()->uiModeChanged(MWWorld::Ptr());
}
}
if (!mGuiModes.empty())
{
const GuiMode mode = mGuiModes.back();
mGuiModeStates[mode].update(true);
mKeyboardNavigation->restoreFocus(mode);
}
updateVisible();
// To make sure that console window get focus again
if (mConsole && mConsole->isVisible())
mConsole->onOpen();
}
void WindowManager::removeGuiMode(GuiMode mode)
{
if (!mGuiModes.empty() && mGuiModes.back() == mode)
{
popGuiMode();
return;
}
std::vector<GuiMode>::iterator it = mGuiModes.begin();
while (it != mGuiModes.end())
{
if (*it == mode)
it = mGuiModes.erase(it);
else
++it;
}
updateVisible();
MWBase::Environment::get().getLuaManager()->uiModeChanged(MWWorld::Ptr());
}
void WindowManager::goToJail(int days)
{
pushGuiMode(MWGui::GM_Jail);
mJailScreen->goToJail(days);
}
void WindowManager::setSelectedSpell(const ESM::RefId& spellId, int successChancePercent)
{
mSelectedSpell = spellId;
mSelectedEnchantItem = MWWorld::Ptr();
mHud->setSelectedSpell(spellId, successChancePercent);
const ESM::Spell* spell = mStore->get<ESM::Spell>().find(spellId);
mSpellWindow->setTitle(spell->mName);
}
void WindowManager::setSelectedEnchantItem(const MWWorld::Ptr& item)
{
mSelectedEnchantItem = item;
mSelectedSpell = ESM::RefId();
const ESM::Enchantment* ench = mStore->get<ESM::Enchantment>().find(item.getClass().getEnchantment(item));
int chargePercent = static_cast<int>(item.getCellRef().getNormalizedEnchantmentCharge(*ench) * 100);
mHud->setSelectedEnchantItem(item, chargePercent);
mSpellWindow->setTitle(item.getClass().getName(item));
}
const MWWorld::Ptr& WindowManager::getSelectedEnchantItem() const
{
return mSelectedEnchantItem;
}
void WindowManager::setSelectedWeapon(const MWWorld::Ptr& item)
{
mSelectedWeapon = item;
int durabilityPercent = 100;
if (item.getClass().hasItemHealth(item))
{
durabilityPercent = static_cast<int>(item.getClass().getItemNormalizedHealth(item) * 100);
}
mHud->setSelectedWeapon(item, durabilityPercent);
mInventoryWindow->setTitle(item.getClass().getName(item));
}
const MWWorld::Ptr& WindowManager::getSelectedWeapon() const
{
return mSelectedWeapon;
}
void WindowManager::unsetSelectedSpell()
{
mSelectedSpell = ESM::RefId();
mSelectedEnchantItem = MWWorld::Ptr();
mHud->unsetSelectedSpell();
MWWorld::Player* player = &MWBase::Environment::get().getWorld()->getPlayer();
if (player->getDrawState() == MWMechanics::DrawState::Spell)
player->setDrawState(MWMechanics::DrawState::Nothing);
mSpellWindow->setTitle("#{Interface:None}");
}
void WindowManager::unsetSelectedWeapon()
{
mSelectedWeapon = MWWorld::Ptr();
mHud->unsetSelectedWeapon();
mInventoryWindow->setTitle("#{sSkillHandtohand}");
}
void WindowManager::getMousePosition(int& x, int& y)
{
const MyGUI::IntPoint& pos = MyGUI::InputManager::getInstance().getMousePosition();
x = pos.left;
y = pos.top;
}
void WindowManager::getMousePosition(float& x, float& y)
{
const MyGUI::IntPoint& pos = MyGUI::InputManager::getInstance().getMousePosition();
x = static_cast<float>(pos.left);
y = static_cast<float>(pos.top);
const MyGUI::IntSize& viewSize = MyGUI::RenderManager::getInstance().getViewSize();
x /= viewSize.width;
y /= viewSize.height;
}
bool WindowManager::getWorldMouseOver()
{
return mHud->getWorldMouseOver();
}
float WindowManager::getScalingFactor() const
{
return mScalingFactor;
}
void WindowManager::executeInConsole(const std::filesystem::path& path)
{
mConsole->executeFile(path);
}
MWGui::InventoryWindow* WindowManager::getInventoryWindow()
{
return mInventoryWindow;
}
MWGui::CountDialog* WindowManager::getCountDialog()
{
return mCountDialog;
}
MWGui::ConfirmationDialog* WindowManager::getConfirmationDialog()
{
return mConfirmationDialog;
}
MWGui::TradeWindow* WindowManager::getTradeWindow()
{
return mTradeWindow;
}
MWGui::PostProcessorHud* WindowManager::getPostProcessorHud()
{
return mPostProcessorHud;
}
void WindowManager::useItem(const MWWorld::Ptr& item, bool bypassBeastRestrictions)
{
if (mInventoryWindow)
mInventoryWindow->useItem(item, bypassBeastRestrictions);
}
bool WindowManager::isAllowed(GuiWindow wnd) const
{
return (mAllowed & wnd) != 0;
}
void WindowManager::allow(GuiWindow wnd)
{
mAllowed = (GuiWindow)(mAllowed | wnd);
if (wnd & GW_Inventory)
{
mBookWindow->setInventoryAllowed(true);
mScrollWindow->setInventoryAllowed(true);
}
updateVisible();
}
void WindowManager::disallowAll()
{
mAllowed = GW_None;
mRestAllowed = false;
mBookWindow->setInventoryAllowed(false);
mScrollWindow->setInventoryAllowed(false);
updateVisible();
}
void WindowManager::toggleVisible(GuiWindow wnd)
{
if (getMode() != GM_Inventory)
return;
if (Settings::SettingValue<bool>* const hidden = findHiddenSetting(wnd))
hidden->set(!hidden->get());
mShown = (GuiWindow)(mShown ^ wnd);
updateVisible();
}
void WindowManager::forceHide(GuiWindow wnd)
{
mForceHidden = (GuiWindow)(mForceHidden | wnd);
updateVisible();
}
void WindowManager::unsetForceHide(GuiWindow wnd)
{
mForceHidden = (GuiWindow)(mForceHidden & ~wnd);
updateVisible();
}
bool WindowManager::isGuiMode() const
{
return !mGuiModes.empty() || isConsoleMode() || isPostProcessorHudVisible() || isInteractiveMessageBoxActive();
}
bool WindowManager::isConsoleMode() const
{
return mConsole && mConsole->isVisible();
}
bool WindowManager::isPostProcessorHudVisible() const
{
return mPostProcessorHud && mPostProcessorHud->isVisible();
}
bool WindowManager::isSettingsWindowVisible() const
{
return mSettingsWindow && mSettingsWindow->isVisible();
}
bool WindowManager::isInteractiveMessageBoxActive() const
{
return mMessageBoxManager && mMessageBoxManager->isInteractiveMessageBox();
}
MWGui::GuiMode WindowManager::getMode() const
{
if (mGuiModes.empty())
return GM_None;
return mGuiModes.back();
}
void WindowManager::disallowMouse()
{
mInputBlocker->setVisible(true);
}
void WindowManager::allowMouse()
{
mInputBlocker->setVisible(!isGuiMode());
}
void WindowManager::notifyInputActionBound()
{
mSettingsWindow->updateControlsBox();
allowMouse();
}
bool WindowManager::containsMode(GuiMode mode) const
{
if (mGuiModes.empty())
return false;
return std::find(mGuiModes.begin(), mGuiModes.end(), mode) != mGuiModes.end();
}
void WindowManager::showCrosshair(bool show)
{
if (mHud)
mHud->setCrosshairVisible(show && Settings::hud().mCrosshair);
}
void WindowManager::updateActivatedQuickKey()
{
mQuickKeysMenu->updateActivatedQuickKey();
}
void WindowManager::activateQuickKey(int index)
{
mQuickKeysMenu->activateQuickKey(index);
}
bool WindowManager::setHudVisibility(bool show)
{
mHudEnabled = show;
updateVisible();
mMessageBoxManager->setVisible(mHudEnabled);
return mHudEnabled;
}
bool WindowManager::getRestEnabled()
{
// Enable rest dialogue if character creation finished
if (mRestAllowed == false
&& MWBase::Environment::get().getWorld()->getGlobalFloat(MWWorld::Globals::sCharGenState) == -1)
mRestAllowed = true;
return mRestAllowed;
}
bool WindowManager::getPlayerSleeping()
{
return mWaitDialog->getSleeping();
}
void WindowManager::wakeUpPlayer()
{
mWaitDialog->wakeUp();
}
void WindowManager::addVisitedLocation(const std::string& name, int x, int y)
{
mMap->addVisitedLocation(name, x, y);
}
const Translation::Storage& WindowManager::getTranslationDataStorage() const
{
return mTranslationDataStorage;
}
void WindowManager::changePointer(const std::string& name)
{
MyGUI::PointerManager::getInstance().setPointer(name);
onCursorChange(name);
}
void WindowManager::showSoulgemDialog(MWWorld::Ptr item)
{
mSoulgemDialog->show(item);
updateVisible();
}
void WindowManager::updatePlayer()
{
mInventoryWindow->updatePlayer();
const MWWorld::Ptr player = MWMechanics::getPlayer();
if (player.getClass().getNpcStats(player).isWerewolf())
{
setWerewolfOverlay(true);
forceHide((GuiWindow)(MWGui::GW_Inventory | MWGui::GW_Magic));
}
}
// Remove this wrapper once onKeyFocusChanged call is rendered unnecessary
void WindowManager::setKeyFocusWidget(MyGUI::Widget* widget)
{
MyGUI::InputManager::getInstance().setKeyFocusWidget(widget);
onKeyFocusChanged(widget);
}
void WindowManager::onKeyFocusChanged(MyGUI::Widget* widget)
{
bool isEditBox = widget && widget->castType<MyGUI::EditBox>(false);
LuaUi::WidgetExtension* luaWidget = dynamic_cast<LuaUi::WidgetExtension*>(widget);
bool capturesInput = luaWidget ? luaWidget->isTextInput() : isEditBox;
if (widget && capturesInput)
SDL_StartTextInput();
else
SDL_StopTextInput();
}
void WindowManager::setEnemy(const MWWorld::Ptr& enemy)
{
mHud->setEnemy(enemy);
}
std::size_t WindowManager::getMessagesCount() const
{
std::size_t count = 0;
if (mMessageBoxManager)
count = mMessageBoxManager->getMessagesCount();
return count;
}
Loading::Listener* WindowManager::getLoadingScreen()
{
return mLoadingScreen;
}
bool WindowManager::getCursorVisible()
{
return mCursorVisible && mCursorActive;
}
void WindowManager::trackWindow(Layout* layout, const WindowSettingValues& settings)
{
MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize();
const WindowRectSettingValues& rect = settings.mIsMaximized ? settings.mMaximized : settings.mRegular;
MyGUI::Window* window = layout->mMainWidget->castType<MyGUI::Window>();
window->setPosition(
MyGUI::IntPoint(static_cast<int>(rect.mX * viewSize.width), static_cast<int>(rect.mY * viewSize.height)));
window->setSize(
MyGUI::IntSize(static_cast<int>(rect.mW * viewSize.width), static_cast<int>(rect.mH * viewSize.height)));
window->eventWindowChangeCoord += MyGUI::newDelegate(this, &WindowManager::onWindowChangeCoord);
WindowBase::clampWindowCoordinates(window);
mTrackedWindows.emplace(window, settings);
}
void WindowManager::toggleMaximized(Layout* layout)
{
MyGUI::Window* window = layout->mMainWidget->castType<MyGUI::Window>();
const auto it = mTrackedWindows.find(window);
if (it == mTrackedWindows.end())
return;
const WindowSettingValues& settings = it->second;
const WindowRectSettingValues& rect = settings.mIsMaximized ? settings.mRegular : settings.mMaximized;
MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize();
const float x = rect.mX * viewSize.width;
const float y = rect.mY * viewSize.height;
const float w = rect.mW * viewSize.width;
const float h = rect.mH * viewSize.height;
window->setCoord(x, y, w, h);
settings.mIsMaximized.set(!settings.mIsMaximized.get());
}
void WindowManager::onWindowChangeCoord(MyGUI::Window* window)
{
const auto it = mTrackedWindows.find(window);
if (it == mTrackedWindows.end())
return;
WindowBase::clampWindowCoordinates(window);
const WindowSettingValues& settings = it->second;
MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize();
settings.mRegular.mX.set(window->getPosition().left / static_cast<float>(viewSize.width));
settings.mRegular.mY.set(window->getPosition().top / static_cast<float>(viewSize.height));
settings.mRegular.mW.set(window->getSize().width / static_cast<float>(viewSize.width));
settings.mRegular.mH.set(window->getSize().height / static_cast<float>(viewSize.height));
settings.mIsMaximized.set(false);
}
void WindowManager::clear()
{
mPlayerBounty = -1;
for (const auto& window : mWindows)
{
window->clear();
window->setDisabledByLua(false);
}
if (mLocalMapRender)
mLocalMapRender->clear();
mMessageBoxManager->clear();
mToolTips->clear();
mSelectedSpell = ESM::RefId();
mCustomMarkers.clear();
mForceHidden = GW_None;
mRestAllowed = true;
while (!mGuiModes.empty())
popGuiMode();
updateVisible();
}
void WindowManager::write(ESM::ESMWriter& writer, Loading::Listener& progress)
{
mMap->write(writer, progress);
mQuickKeysMenu->write(writer);
if (!mSelectedSpell.empty())
{
writer.startRecord(ESM::REC_ASPL);
writer.writeHNRefId("ID__", mSelectedSpell);
writer.endRecord(ESM::REC_ASPL);
}
for (CustomMarkerCollection::ContainerType::const_iterator it = mCustomMarkers.begin();
it != mCustomMarkers.end(); ++it)
{
writer.startRecord(ESM::REC_MARK);
it->second.save(writer);
writer.endRecord(ESM::REC_MARK);
}
}
void WindowManager::readRecord(ESM::ESMReader& reader, uint32_t type)
{
if (type == ESM::REC_GMAP)
mMap->readRecord(reader, type);
else if (type == ESM::REC_KEYS)
mQuickKeysMenu->readRecord(reader, type);
else if (type == ESM::REC_ASPL)
{
reader.getSubNameIs("ID__");
ESM::RefId spell = reader.getRefId();
if (mStore->get<ESM::Spell>().search(spell))
mSelectedSpell = spell;
}
else if (type == ESM::REC_MARK)
{
ESM::CustomMarker marker;
marker.load(reader);
mCustomMarkers.addMarker(marker, false);
}
}
int WindowManager::countSavedGameRecords() const
{
return 1 // Global map
+ 1 // QuickKeysMenu
+ mCustomMarkers.size() + (!mSelectedSpell.empty() ? 1 : 0);
}
bool WindowManager::isSavingAllowed() const
{
return !MyGUI::InputManager::getInstance().isModalAny()
&& !isConsoleMode()
// TODO: remove this, once we have properly serialized the state of open windows
&& (!isGuiMode() || (mGuiModes.size() == 1 && (getMode() == GM_MainMenu || getMode() == GM_Rest)));
}
void WindowManager::playVideo(std::string_view name, bool allowSkipping, bool overrideSounds)
{
mVideoWidget->playVideo("video\\" + std::string{ name });
mVideoWidget->eventKeyButtonPressed.clear();
mVideoBackground->eventKeyButtonPressed.clear();
if (allowSkipping)
{
mVideoWidget->eventKeyButtonPressed += MyGUI::newDelegate(this, &WindowManager::onVideoKeyPressed);
mVideoBackground->eventKeyButtonPressed += MyGUI::newDelegate(this, &WindowManager::onVideoKeyPressed);
}
enableScene(false);
MyGUI::IntSize screenSize = MyGUI::RenderManager::getInstance().getViewSize();
sizeVideo(screenSize.width, screenSize.height);
MyGUI::Widget* oldKeyFocus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
setKeyFocusWidget(mVideoWidget);
mVideoBackground->setVisible(true);
bool cursorWasVisible = mCursorVisible;
setCursorVisible(false);
if (overrideSounds && mVideoWidget->hasAudioStream())
MWBase::Environment::get().getSoundManager()->pauseSounds(
MWSound::VideoPlayback, ~MWSound::Type::Movie & MWSound::Type::Mask);
Misc::FrameRateLimiter frameRateLimiter
= Misc::makeFrameRateLimiter(MWBase::Environment::get().getFrameRateLimit());
while (mVideoWidget->update() && !MWBase::Environment::get().getStateManager()->hasQuitRequest())
{
const double dt
= std::chrono::duration_cast<std::chrono::duration<double>>(frameRateLimiter.getLastFrameDuration())
.count();
MWBase::Environment::get().getInputManager()->update(dt, true, false);
if (!mWindowVisible)
{
mVideoWidget->pause();
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
else
{
if (mVideoWidget->isPaused())
mVideoWidget->resume();
mViewer->eventTraversal();
mViewer->updateTraversal();
mViewer->renderingTraversals();
}
// at the time this function is called we are in the middle of a frame,
// so out of order calls are necessary to get a correct frameNumber for the next frame.
// refer to the advance() and frame() order in Engine::go()
mViewer->advance(mViewer->getFrameStamp()->getSimulationTime());
frameRateLimiter.limit();
}
mVideoWidget->stop();
MWBase::Environment::get().getSoundManager()->resumeSounds(MWSound::VideoPlayback);
setKeyFocusWidget(oldKeyFocus);
setCursorVisible(cursorWasVisible);
// Restore normal rendering
updateVisible();
mVideoBackground->setVisible(false);
}
void WindowManager::sizeVideo(int screenWidth, int screenHeight)
{
// Use black bars to correct aspect ratio
mVideoBackground->setSize(screenWidth, screenHeight);
mVideoWidget->autoResize(Settings::gui().mStretchMenuBackground);
}
void WindowManager::exitCurrentModal()
{
if (!mCurrentModals.empty())
{
WindowModal* window = mCurrentModals.back();
if (!window->exit())
return;
window->setVisible(false);
}
}
void WindowManager::addCurrentModal(WindowModal* input)
{
if (mCurrentModals.empty())
mKeyboardNavigation->saveFocus(getMode());
mCurrentModals.push_back(input);
mKeyboardNavigation->restoreFocus(-1);
mKeyboardNavigation->setModalWindow(input->mMainWidget);
mKeyboardNavigation->setDefaultFocus(input->mMainWidget, input->getDefaultKeyFocus());
}
void WindowManager::removeCurrentModal(WindowModal* input)
{
if (!mCurrentModals.empty())
{
if (input == mCurrentModals.back())
{
mCurrentModals.pop_back();
mKeyboardNavigation->saveFocus(-1);
}
else
{
auto found = std::find(mCurrentModals.begin(), mCurrentModals.end(), input);
if (found != mCurrentModals.end())
mCurrentModals.erase(found);
else
Log(Debug::Warning) << "Warning: can't find modal window " << input;
}
}
if (mCurrentModals.empty())
{
mKeyboardNavigation->setModalWindow(nullptr);
mKeyboardNavigation->restoreFocus(getMode());
}
else
mKeyboardNavigation->setModalWindow(mCurrentModals.back()->mMainWidget);
}
void WindowManager::onVideoKeyPressed(MyGUI::Widget* _sender, MyGUI::KeyCode _key, MyGUI::Char _char)
{
if (_key == MyGUI::KeyCode::Escape)
mVideoWidget->stop();
}
void WindowManager::updatePinnedWindows()
{
mInventoryWindow->setPinned(Settings::windows().mInventoryPin);
if (Settings::windows().mInventoryHidden)
mShown = (GuiWindow)(mShown ^ GW_Inventory);
mMap->setPinned(Settings::windows().mMapPin);
if (Settings::windows().mMapHidden)
mShown = (GuiWindow)(mShown ^ GW_Map);
mSpellWindow->setPinned(Settings::windows().mSpellsPin);
if (Settings::windows().mSpellsHidden)
mShown = (GuiWindow)(mShown ^ GW_Magic);
mStatsWindow->setPinned(Settings::windows().mStatsPin);
if (Settings::windows().mStatsHidden)
mShown = (GuiWindow)(mShown ^ GW_Stats);
}
void WindowManager::pinWindow(GuiWindow window)
{
switch (window)
{
case GW_Inventory:
mInventoryWindow->setPinned(true);
break;
case GW_Map:
mMap->setPinned(true);
break;
case GW_Magic:
mSpellWindow->setPinned(true);
break;
case GW_Stats:
mStatsWindow->setPinned(true);
break;
default:
break;
}
updateVisible();
}
void WindowManager::fadeScreenIn(const float time, bool clearQueue, float delay)
{
if (clearQueue)
mScreenFader->clearQueue();
mScreenFader->fadeOut(time, delay);
}
void WindowManager::fadeScreenOut(const float time, bool clearQueue, float delay)
{
if (clearQueue)
mScreenFader->clearQueue();
mScreenFader->fadeIn(time, delay);
}
void WindowManager::fadeScreenTo(const int percent, const float time, bool clearQueue, float delay)
{
if (clearQueue)
mScreenFader->clearQueue();
mScreenFader->fadeTo(percent, time, delay);
}
void WindowManager::setBlindness(const int percent)
{
mBlindnessFader->notifyAlphaChanged(percent / 100.f);
}
void WindowManager::activateHitOverlay(bool interrupt)
{
if (!Settings::gui().mHitFader)
return;
if (!interrupt && !mHitFader->isEmpty())
return;
mHitFader->clearQueue();
mHitFader->fadeTo(100, 0.0f);
mHitFader->fadeTo(0, 0.5f);
}
void WindowManager::setWerewolfOverlay(bool set)
{
if (!Settings::gui().mWerewolfOverlay)
return;
if (mWerewolfFader)
mWerewolfFader->notifyAlphaChanged(set ? 1.0f : 0.0f);
}
void WindowManager::onClipboardChanged(std::string_view _type, std::string_view _data)
{
if (_type == "Text")
SDL_SetClipboardText(MyGUI::TextIterator::getOnlyText(MyGUI::UString(_data)).asUTF8().c_str());
}
void WindowManager::onClipboardRequested(std::string_view _type, std::string& _data)
{
if (_type != "Text")
return;
char* text = nullptr;
text = SDL_GetClipboardText();
if (text)
_data = MyGUI::TextIterator::toTagsString(text);
SDL_free(text);
}
void WindowManager::toggleConsole()
{
bool visible = mConsole->isVisible();
if (!visible && !mGuiModes.empty())
mKeyboardNavigation->saveFocus(mGuiModes.back());
mConsole->setVisible(!visible);
if (visible && !mGuiModes.empty())
mKeyboardNavigation->restoreFocus(mGuiModes.back());
updateVisible();
}
void WindowManager::toggleDebugWindow()
{
mDebugWindow->setVisible(!mDebugWindow->isVisible());
}
void WindowManager::togglePostProcessorHud()
{
if (!MWBase::Environment::get().getWorld()->getPostProcessor()->isEnabled())
{
messageBox("#{OMWEngine:PostProcessingIsNotEnabled}");
return;
}
bool visible = mPostProcessorHud->isVisible();
if (!visible && !mGuiModes.empty())
mKeyboardNavigation->saveFocus(mGuiModes.back());
mPostProcessorHud->setVisible(!visible);
if (visible && !mGuiModes.empty())
mKeyboardNavigation->restoreFocus(mGuiModes.back());
updateVisible();
}
void WindowManager::toggleSettingsWindow()
{
bool visible = mSettingsWindow->isVisible();
if (!visible && !mGuiModes.empty())
mKeyboardNavigation->saveFocus(mGuiModes.back());
mSettingsWindow->setVisible(!visible);
if (visible && !mGuiModes.empty())
mKeyboardNavigation->restoreFocus(mGuiModes.back());
updateVisible();
}
void WindowManager::cycleSpell(bool next)
{
if (!isGuiMode())
mSpellWindow->cycle(next);
}
void WindowManager::cycleWeapon(bool next)
{
if (!isGuiMode())
mInventoryWindow->cycle(next);
}
void WindowManager::playSound(const ESM::RefId& soundId, float volume, float pitch)
{
if (soundId.empty())
return;
MWBase::Environment::get().getSoundManager()->playSound(
soundId, volume, pitch, MWSound::Type::Sfx, MWSound::PlayMode::NoEnvNoScaling);
}
void WindowManager::updateSpellWindow()
{
if (mSpellWindow)
mSpellWindow->updateSpells();
}
void WindowManager::setConsoleSelectedObject(const MWWorld::Ptr& object)
{
mConsole->setSelectedObject(object);
}
MWWorld::Ptr WindowManager::getConsoleSelectedObject() const
{
return mConsole->getSelectedObject();
}
void WindowManager::printToConsole(const std::string& msg, std::string_view color)
{
mConsole->print(msg, color);
}
void WindowManager::setConsoleMode(std::string_view mode)
{
mConsole->setConsoleMode(mode);
}
const std::string& WindowManager::getConsoleMode()
{
return mConsole->getConsoleMode();
}
void WindowManager::createCursors()
{
MyGUI::ResourceManager::EnumeratorPtr enumerator = MyGUI::ResourceManager::getInstance().getEnumerator();
while (enumerator.next())
{
MyGUI::IResource* resource = enumerator.current().second;
ResourceImageSetPointerFix* imgSetPointer = resource->castType<ResourceImageSetPointerFix>(false);
if (!imgSetPointer)
continue;
const VFS::Path::Normalized path(imgSetPointer->getImageSet()->getIndexInfo(0, 0).texture);
osg::ref_ptr<osg::Image> image = mResourceSystem->getImageManager()->getImage(path);
if (image.valid())
{
// everything looks good, send it to the cursor manager
Uint8 hotspot_x = imgSetPointer->getHotSpot().left;
Uint8 hotspot_y = imgSetPointer->getHotSpot().top;
int rotation = imgSetPointer->getRotation();
MyGUI::IntSize pointerSize = imgSetPointer->getSize();
mCursorManager->createCursor(imgSetPointer->getResourceName(), rotation, image, hotspot_x, hotspot_y,
pointerSize.width, pointerSize.height);
}
}
}
void WindowManager::createTextures()
{
{
MyGUI::ITexture* tex = MyGUI::RenderManager::getInstance().createTexture("white");
tex->createManual(8, 8, MyGUI::TextureUsage::Write, MyGUI::PixelFormat::R8G8B8);
unsigned char* data = reinterpret_cast<unsigned char*>(tex->lock(MyGUI::TextureUsage::Write));
for (int x = 0; x < 8; ++x)
for (int y = 0; y < 8; ++y)
{
*(data++) = 255;
*(data++) = 255;
*(data++) = 255;
}
tex->unlock();
}
{
MyGUI::ITexture* tex = MyGUI::RenderManager::getInstance().createTexture("black");
tex->createManual(8, 8, MyGUI::TextureUsage::Write, MyGUI::PixelFormat::R8G8B8);
unsigned char* data = reinterpret_cast<unsigned char*>(tex->lock(MyGUI::TextureUsage::Write));
for (int x = 0; x < 8; ++x)
for (int y = 0; y < 8; ++y)
{
*(data++) = 0;
*(data++) = 0;
*(data++) = 0;
}
tex->unlock();
}
{
MyGUI::ITexture* tex = MyGUI::RenderManager::getInstance().createTexture("transparent");
tex->createManual(8, 8, MyGUI::TextureUsage::Write, MyGUI::PixelFormat::R8G8B8A8);
setMenuTransparency(Settings::gui().mMenuTransparency);
}
}
void WindowManager::setMenuTransparency(float value)
{
MyGUI::ITexture* tex = MyGUI::RenderManager::getInstance().getTexture("transparent");
unsigned char* data = reinterpret_cast<unsigned char*>(tex->lock(MyGUI::TextureUsage::Write));
for (int x = 0; x < 8; ++x)
for (int y = 0; y < 8; ++y)
{
*(data++) = 255;
*(data++) = 255;
*(data++) = 255;
*(data++) = static_cast<unsigned char>(value * 255);
}
tex->unlock();
}
void WindowManager::addCell(MWWorld::CellStore* cell)
{
mLocalMapRender->addCell(cell);
}
void WindowManager::removeCell(MWWorld::CellStore* cell)
{
mLocalMapRender->removeCell(cell);
}
void WindowManager::writeFog(MWWorld::CellStore* cell)
{
mLocalMapRender->saveFogOfWar(cell);
}
const MWGui::TextColours& WindowManager::getTextColours()
{
return mTextColours;
}
bool WindowManager::injectKeyPress(MyGUI::KeyCode key, unsigned int text, bool repeat)
{
if (!mKeyboardNavigation->injectKeyPress(key, text, repeat))
{
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
bool widgetActive = MyGUI::InputManager::getInstance().injectKeyPress(key, text);
if (!widgetActive || !focus)
return false;
// FIXME: MyGUI doesn't allow widgets to state if a given key was actually used, so make a guess
if (focus->getTypeName().find("Button") != std::string::npos)
{
switch (key.getValue())
{
case MyGUI::KeyCode::ArrowDown:
case MyGUI::KeyCode::ArrowUp:
case MyGUI::KeyCode::ArrowLeft:
case MyGUI::KeyCode::ArrowRight:
case MyGUI::KeyCode::Return:
case MyGUI::KeyCode::NumpadEnter:
case MyGUI::KeyCode::Space:
return true;
default:
return false;
}
}
return false;
}
else
return true;
}
bool WindowManager::injectKeyRelease(MyGUI::KeyCode key)
{
return MyGUI::InputManager::getInstance().injectKeyRelease(key);
}
void WindowManager::GuiModeState::update(bool visible)
{
for (const auto& window : mWindows)
window->setVisible(visible);
}
void WindowManager::watchActor(const MWWorld::Ptr& ptr)
{
mStatsWatcher->watchActor(ptr);
}
MWWorld::Ptr WindowManager::getWatchedActor() const
{
return mStatsWatcher->getWatchedActor();
}
const std::string& WindowManager::getVersionDescription() const
{
return mVersionDescription;
}
void WindowManager::handleScheduledMessageBoxes()
{
const auto scheduledMessageBoxes = mScheduledMessageBoxes.lock();
for (const ScheduledMessageBox& v : *scheduledMessageBoxes)
messageBox(v.mMessage, v.mShowInDialogueMode);
scheduledMessageBoxes->clear();
}
void WindowManager::onDeleteCustomData(const MWWorld::Ptr& ptr)
{
for (const auto& window : mWindows)
window->onDeleteCustomData(ptr);
}
void WindowManager::asyncPrepareSaveMap()
{
mMap->asyncPrepareSaveMap();
}
void WindowManager::setDisabledByLua(std::string_view windowId, bool disabled)
{
mLuaIdToWindow.at(windowId)->setDisabledByLua(disabled);
updateVisible();
}
std::vector<std::string_view> WindowManager::getAllWindowIds() const
{
std::vector<std::string_view> res;
for (const auto& [id, _] : mLuaIdToWindow)
res.push_back(id);
return res;
}
std::vector<std::string_view> WindowManager::getAllowedWindowIds(GuiMode mode) const
{
std::vector<std::string_view> res;
if (mode == GM_Inventory)
{
if (mAllowed & GW_Map)
res.push_back(mMap->getWindowIdForLua());
if (mAllowed & GW_Inventory)
res.push_back(mInventoryWindow->getWindowIdForLua());
if (mAllowed & GW_Magic)
res.push_back(mSpellWindow->getWindowIdForLua());
if (mAllowed & GW_Stats)
res.push_back(mStatsWindow->getWindowIdForLua());
}
else
{
auto it = mGuiModeStates.find(mode);
if (it != mGuiModeStates.end())
{
for (const auto* w : it->second.mWindows)
if (!w->getWindowIdForLua().empty())
res.push_back(w->getWindowIdForLua());
}
}
return res;
}
}
| 84,220
|
C++
|
.cpp
| 2,000
| 32.803
| 120
| 0.633497
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,475
|
trainingwindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/trainingwindow.cpp
|
#include "trainingwindow.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_Gui.h>
#include <MyGUI_TextIterator.h>
#include "../mwbase/environment.hpp"
#include "../mwbase/luamanager.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/npcstats.hpp"
#include <components/esm3/loadclas.hpp>
#include <components/settings/values.hpp>
#include "tooltips.hpp"
namespace MWGui
{
TrainingWindow::TrainingWindow()
: WindowBase("openmw_trainingwindow.layout")
, mTimeAdvancer(0.05f)
{
getWidget(mTrainingOptions, "TrainingOptions");
getWidget(mCancelButton, "CancelButton");
getWidget(mPlayerGold, "PlayerGold");
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &TrainingWindow::onCancelButtonClicked);
mTimeAdvancer.eventProgressChanged += MyGUI::newDelegate(this, &TrainingWindow::onTrainingProgressChanged);
mTimeAdvancer.eventFinished += MyGUI::newDelegate(this, &TrainingWindow::onTrainingFinished);
}
void TrainingWindow::onOpen()
{
if (mTimeAdvancer.isRunning())
{
mProgressBar.setVisible(true);
setVisible(false);
}
else
mProgressBar.setVisible(false);
center();
}
void TrainingWindow::setPtr(const MWWorld::Ptr& actor)
{
if (actor.isEmpty() || !actor.getClass().isActor())
throw std::runtime_error("Invalid argument in TrainingWindow::setPtr");
mPtr = actor;
MWWorld::Ptr player = MWMechanics::getPlayer();
int playerGold = player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId);
mPlayerGold->setCaptionWithReplacing("#{sGold}: " + MyGUI::utility::toString(playerGold));
const auto& store = MWBase::Environment::get().getESMStore();
const MWWorld::Store<ESM::GameSetting>& gmst = store->get<ESM::GameSetting>();
const MWWorld::Store<ESM::Skill>& skillStore = store->get<ESM::Skill>();
// NPC can train you in their best 3 skills
constexpr size_t maxSkills = 3;
std::vector<std::pair<const ESM::Skill*, float>> skills;
skills.reserve(maxSkills);
const auto sortByValue
= [](const std::pair<const ESM::Skill*, float>& lhs, const std::pair<const ESM::Skill*, float>& rhs) {
return lhs.second > rhs.second;
};
// Maintain a sorted vector of max maxSkills elements, ordering skills by value and content file order
const MWMechanics::NpcStats& actorStats = actor.getClass().getNpcStats(actor);
for (const ESM::Skill& skill : skillStore)
{
float value = getSkillForTraining(actorStats, skill.mId);
if (skills.size() < maxSkills)
{
skills.emplace_back(&skill, value);
std::stable_sort(skills.begin(), skills.end(), sortByValue);
}
else
{
auto& lowest = skills[maxSkills - 1];
if (lowest.second < value)
{
lowest.first = &skill;
lowest.second = value;
std::stable_sort(skills.begin(), skills.end(), sortByValue);
}
}
}
MyGUI::EnumeratorWidgetPtr widgets = mTrainingOptions->getEnumerator();
MyGUI::Gui::getInstance().destroyWidgets(widgets);
MWMechanics::NpcStats& pcStats = player.getClass().getNpcStats(player);
const int lineHeight = Settings::gui().mFontSize + 2;
for (size_t i = 0; i < skills.size(); ++i)
{
const ESM::Skill* skill = skills[i].first;
int price = static_cast<int>(
pcStats.getSkill(skill->mId).getBase() * gmst.find("iTrainingMod")->mValue.getInteger());
price = std::max(1, price);
price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr, price, true);
MyGUI::Button* button = mTrainingOptions->createWidget<MyGUI::Button>(price <= playerGold
? "SandTextButton"
: "SandTextButtonDisabled", // can't use setEnabled since that removes tooltip
MyGUI::IntCoord(5, 5 + i * lineHeight, mTrainingOptions->getWidth() - 10, lineHeight),
MyGUI::Align::Default);
button->setUserData(skills[i].first);
button->eventMouseButtonClick += MyGUI::newDelegate(this, &TrainingWindow::onTrainingSelected);
button->setCaptionWithReplacing(
MyGUI::TextIterator::toTagsString(skill->mName) + " - " + MyGUI::utility::toString(price));
button->setSize(button->getTextSize().width + 12, button->getSize().height);
ToolTips::createSkillToolTip(button, skill->mId);
}
center();
}
void TrainingWindow::onReferenceUnavailable()
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Training);
}
void TrainingWindow::onCancelButtonClicked(MyGUI::Widget* sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Training);
}
void TrainingWindow::onTrainingSelected(MyGUI::Widget* sender)
{
const ESM::Skill* skill = *sender->getUserData<const ESM::Skill*>();
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
MWMechanics::NpcStats& pcStats = player.getClass().getNpcStats(player);
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
int price = pcStats.getSkill(skill->mId).getBase()
* store.get<ESM::GameSetting>().find("iTrainingMod")->mValue.getInteger();
price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr, price, true);
if (price > player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId))
return;
if (getSkillForTraining(mPtr.getClass().getNpcStats(mPtr), skill->mId)
<= pcStats.getSkill(skill->mId).getBase())
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sServiceTrainingWords}");
return;
}
// You can not train a skill above its governing attribute
if (pcStats.getSkill(skill->mId).getBase()
>= pcStats.getAttribute(ESM::Attribute::indexToRefId(skill->mData.mAttribute)).getModified())
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage17}");
return;
}
// increase skill
MWBase::Environment::get().getLuaManager()->skillLevelUp(player, skill->mId, "trainer");
// remove gold
player.getClass().getContainerStore(player).remove(MWWorld::ContainerStore::sGoldId, price);
// add gold to NPC trading gold pool
MWMechanics::NpcStats& npcStats = mPtr.getClass().getNpcStats(mPtr);
npcStats.setGoldPool(npcStats.getGoldPool() + price);
setVisible(false);
mProgressBar.setVisible(true);
mProgressBar.setProgress(0, 2);
mTimeAdvancer.run(2);
MWBase::Environment::get().getWindowManager()->fadeScreenOut(0.2f);
MWBase::Environment::get().getWindowManager()->fadeScreenIn(0.2f, false, 0.2f);
}
void TrainingWindow::onTrainingProgressChanged(int cur, int total)
{
mProgressBar.setProgress(cur, total);
}
void TrainingWindow::onTrainingFinished()
{
mProgressBar.setVisible(false);
// advance time
MWBase::Environment::get().getMechanicsManager()->rest(2, false);
MWBase::Environment::get().getWorld()->advanceTime(2);
// go back to game mode
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Training);
MWBase::Environment::get().getWindowManager()->exitCurrentGuiMode();
}
float TrainingWindow::getSkillForTraining(const MWMechanics::NpcStats& stats, ESM::RefId id) const
{
if (Settings::game().mTrainersTrainingSkillsBasedOnBaseSkill)
return stats.getSkill(id).getBase();
return stats.getSkill(id).getModified();
}
void TrainingWindow::onFrame(float dt)
{
checkReferenceAvailable();
mTimeAdvancer.onFrame(dt);
}
bool TrainingWindow::exit()
{
return !mTimeAdvancer.isRunning();
}
}
| 8,646
|
C++
|
.cpp
| 182
| 38.296703
| 115
| 0.644759
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,476
|
settings.cpp
|
OpenMW_openmw/apps/openmw/mwgui/settings.cpp
|
#include "settings.hpp"
#include "components/settings/values.hpp"
namespace MWGui
{
WindowSettingValues makeAlchemyWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mAlchemyX,
.mY = Settings::windows().mAlchemyY,
.mW = Settings::windows().mAlchemyW,
.mH = Settings::windows().mAlchemyH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mAlchemyMaximizedX,
.mY = Settings::windows().mAlchemyMaximizedY,
.mW = Settings::windows().mAlchemyMaximizedW,
.mH = Settings::windows().mAlchemyMaximizedH,
},
.mIsMaximized = Settings::windows().mAlchemyMaximized,
};
}
WindowSettingValues makeBarterWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mBarterX,
.mY = Settings::windows().mBarterY,
.mW = Settings::windows().mBarterW,
.mH = Settings::windows().mBarterH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mBarterMaximizedX,
.mY = Settings::windows().mBarterMaximizedY,
.mW = Settings::windows().mBarterMaximizedW,
.mH = Settings::windows().mBarterMaximizedH,
},
.mIsMaximized = Settings::windows().mBarterMaximized,
};
}
WindowSettingValues makeCompanionWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mCompanionX,
.mY = Settings::windows().mCompanionY,
.mW = Settings::windows().mCompanionW,
.mH = Settings::windows().mCompanionH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mCompanionMaximizedX,
.mY = Settings::windows().mCompanionMaximizedY,
.mW = Settings::windows().mCompanionMaximizedW,
.mH = Settings::windows().mCompanionMaximizedH,
},
.mIsMaximized = Settings::windows().mCompanionMaximized,
};
}
WindowSettingValues makeConsoleWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mConsoleX,
.mY = Settings::windows().mConsoleY,
.mW = Settings::windows().mConsoleW,
.mH = Settings::windows().mConsoleH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mConsoleMaximizedX,
.mY = Settings::windows().mConsoleMaximizedY,
.mW = Settings::windows().mConsoleMaximizedW,
.mH = Settings::windows().mConsoleMaximizedH,
},
.mIsMaximized = Settings::windows().mConsoleMaximized,
};
}
WindowSettingValues makeContainerWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mContainerX,
.mY = Settings::windows().mContainerY,
.mW = Settings::windows().mContainerW,
.mH = Settings::windows().mContainerH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mContainerMaximizedX,
.mY = Settings::windows().mContainerMaximizedY,
.mW = Settings::windows().mContainerMaximizedW,
.mH = Settings::windows().mContainerMaximizedH,
},
.mIsMaximized = Settings::windows().mContainerMaximized,
};
}
WindowSettingValues makeDebugWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mDebugX,
.mY = Settings::windows().mDebugY,
.mW = Settings::windows().mDebugW,
.mH = Settings::windows().mDebugH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mDebugMaximizedX,
.mY = Settings::windows().mDebugMaximizedY,
.mW = Settings::windows().mDebugMaximizedW,
.mH = Settings::windows().mDebugMaximizedH,
},
.mIsMaximized = Settings::windows().mDebugMaximized,
};
}
WindowSettingValues makeDialogueWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mDialogueX,
.mY = Settings::windows().mDialogueY,
.mW = Settings::windows().mDialogueW,
.mH = Settings::windows().mDialogueH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mDialogueMaximizedX,
.mY = Settings::windows().mDialogueMaximizedY,
.mW = Settings::windows().mDialogueMaximizedW,
.mH = Settings::windows().mDialogueMaximizedH,
},
.mIsMaximized = Settings::windows().mDialogueMaximized,
};
}
WindowSettingValues makeInventoryWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mInventoryX,
.mY = Settings::windows().mInventoryY,
.mW = Settings::windows().mInventoryW,
.mH = Settings::windows().mInventoryH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mInventoryMaximizedX,
.mY = Settings::windows().mInventoryMaximizedY,
.mW = Settings::windows().mInventoryMaximizedW,
.mH = Settings::windows().mInventoryMaximizedH,
},
.mIsMaximized = Settings::windows().mInventoryMaximized,
};
}
WindowSettingValues makeInventoryBarterWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mInventoryBarterX,
.mY = Settings::windows().mInventoryBarterY,
.mW = Settings::windows().mInventoryBarterW,
.mH = Settings::windows().mInventoryBarterH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mInventoryBarterMaximizedX,
.mY = Settings::windows().mInventoryBarterMaximizedY,
.mW = Settings::windows().mInventoryBarterMaximizedW,
.mH = Settings::windows().mInventoryBarterMaximizedH,
},
.mIsMaximized = Settings::windows().mInventoryBarterMaximized,
};
}
WindowSettingValues makeInventoryCompanionWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mInventoryCompanionX,
.mY = Settings::windows().mInventoryCompanionY,
.mW = Settings::windows().mInventoryCompanionW,
.mH = Settings::windows().mInventoryCompanionH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mInventoryCompanionMaximizedX,
.mY = Settings::windows().mInventoryCompanionMaximizedY,
.mW = Settings::windows().mInventoryCompanionMaximizedW,
.mH = Settings::windows().mInventoryCompanionMaximizedH,
},
.mIsMaximized = Settings::windows().mInventoryCompanionMaximized,
};
}
WindowSettingValues makeInventoryContainerWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mInventoryContainerX,
.mY = Settings::windows().mInventoryContainerY,
.mW = Settings::windows().mInventoryContainerW,
.mH = Settings::windows().mInventoryContainerH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mInventoryContainerMaximizedX,
.mY = Settings::windows().mInventoryContainerMaximizedY,
.mW = Settings::windows().mInventoryContainerMaximizedW,
.mH = Settings::windows().mInventoryContainerMaximizedH,
},
.mIsMaximized = Settings::windows().mInventoryContainerMaximized,
};
}
WindowSettingValues makeMapWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mMapX,
.mY = Settings::windows().mMapY,
.mW = Settings::windows().mMapW,
.mH = Settings::windows().mMapH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mMapMaximizedX,
.mY = Settings::windows().mMapMaximizedY,
.mW = Settings::windows().mMapMaximizedW,
.mH = Settings::windows().mMapMaximizedH,
},
.mIsMaximized = Settings::windows().mMapMaximized,
};
}
WindowSettingValues makePostprocessorWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mPostprocessorX,
.mY = Settings::windows().mPostprocessorY,
.mW = Settings::windows().mPostprocessorW,
.mH = Settings::windows().mPostprocessorH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mPostprocessorMaximizedX,
.mY = Settings::windows().mPostprocessorMaximizedY,
.mW = Settings::windows().mPostprocessorMaximizedW,
.mH = Settings::windows().mPostprocessorMaximizedH,
},
.mIsMaximized = Settings::windows().mPostprocessorMaximized,
};
}
WindowSettingValues makeSettingsWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mSettingsX,
.mY = Settings::windows().mSettingsY,
.mW = Settings::windows().mSettingsW,
.mH = Settings::windows().mSettingsH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mSettingsMaximizedX,
.mY = Settings::windows().mSettingsMaximizedY,
.mW = Settings::windows().mSettingsMaximizedW,
.mH = Settings::windows().mSettingsMaximizedH,
},
.mIsMaximized = Settings::windows().mSettingsMaximized,
};
}
WindowSettingValues makeSpellsWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mSpellsX,
.mY = Settings::windows().mSpellsY,
.mW = Settings::windows().mSpellsW,
.mH = Settings::windows().mSpellsH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mSpellsMaximizedX,
.mY = Settings::windows().mSpellsMaximizedY,
.mW = Settings::windows().mSpellsMaximizedW,
.mH = Settings::windows().mSpellsMaximizedH,
},
.mIsMaximized = Settings::windows().mSpellsMaximized,
};
}
WindowSettingValues makeStatsWindowSettingValues()
{
return WindowSettingValues{
.mRegular = WindowRectSettingValues {
.mX = Settings::windows().mStatsX,
.mY = Settings::windows().mStatsY,
.mW = Settings::windows().mStatsW,
.mH = Settings::windows().mStatsH,
},
.mMaximized = WindowRectSettingValues {
.mX = Settings::windows().mStatsMaximizedX,
.mY = Settings::windows().mStatsMaximizedY,
.mW = Settings::windows().mStatsMaximizedW,
.mH = Settings::windows().mStatsMaximizedH,
},
.mIsMaximized = Settings::windows().mStatsMaximized,
};
}
}
| 12,844
|
C++
|
.cpp
| 293
| 30.979522
| 77
| 0.576239
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,477
|
resourceskin.cpp
|
OpenMW_openmw/apps/openmw/mwgui/resourceskin.cpp
|
#include "resourceskin.hpp"
#include <MyGUI_RenderManager.h>
#include <components/misc/strings/algorithm.hpp>
namespace MWGui
{
void resizeSkin(MyGUI::xml::ElementPtr _node)
{
_node->setAttribute("type", "ResourceSkin");
if (!_node->findAttribute("size").empty())
return;
auto textureName = _node->findAttribute("texture");
if (textureName.empty())
return;
MyGUI::ITexture* texture = MyGUI::RenderManager::getInstance().getTexture(std::string{ textureName });
if (!texture)
return;
MyGUI::IntCoord coord(0, 0, texture->getWidth(), texture->getHeight());
MyGUI::xml::ElementEnumerator basis = _node->getElementEnumerator();
const std::string textureSize = std::to_string(coord.width) + " " + std::to_string(coord.height);
_node->addAttribute("size", textureSize);
while (basis.next())
{
if (basis->getName() != "BasisSkin")
continue;
auto basisSkinType = basis->findAttribute("type");
if (Misc::StringUtils::ciEqual(basisSkinType, "SimpleText"))
continue;
bool isTileRect = Misc::StringUtils::ciEqual(basisSkinType, "TileRect");
if (!basis->findAttribute("offset").empty())
continue;
basis->addAttribute("offset", coord);
MyGUI::xml::ElementEnumerator state = basis->getElementEnumerator();
while (state.next())
{
if (state->getName() == "State")
{
if (!state->findAttribute("offset").empty())
continue;
state->addAttribute("offset", coord);
if (isTileRect)
{
MyGUI::xml::ElementEnumerator property = state->getElementEnumerator();
bool hasTileSize = false;
while (property.next("Property"))
{
if (property->findAttribute("key") != "TileSize")
continue;
hasTileSize = true;
}
if (!hasTileSize)
{
MyGUI::xml::ElementPtr tileSizeProperty = state->createChild("Property");
tileSizeProperty->addAttribute("key", "TileSize");
tileSizeProperty->addAttribute("value", textureSize);
}
}
}
}
}
}
void AutoSizedResourceSkin::deserialization(MyGUI::xml::ElementPtr _node, MyGUI::Version _version)
{
resizeSkin(_node);
Base::deserialization(_node, _version);
}
}
| 2,848
|
C++
|
.cpp
| 66
| 28.545455
| 110
| 0.518064
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,478
|
enchantingdialog.cpp
|
OpenMW_openmw/apps/openmw/mwgui/enchantingdialog.cpp
|
#include "enchantingdialog.hpp"
#include <iomanip>
#include <MyGUI_Button.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_ScrollView.h>
#include <MyGUI_UString.h>
#include <components/misc/strings/format.hpp>
#include <components/settings/values.hpp>
#include <components/widgets/list.hpp>
#include <components/esm3/loadgmst.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "itemselection.hpp"
#include "itemwidget.hpp"
#include "sortfilteritemmodel.hpp"
namespace MWGui
{
EnchantingDialog::EnchantingDialog()
: WindowBase("openmw_enchanting_dialog.layout")
, EffectEditorBase(EffectEditorBase::Enchanting)
{
getWidget(mName, "NameEdit");
getWidget(mCancelButton, "CancelButton");
getWidget(mAvailableEffectsList, "AvailableEffects");
getWidget(mUsedEffectsView, "UsedEffects");
getWidget(mItemBox, "ItemBox");
getWidget(mSoulBox, "SoulBox");
getWidget(mEnchantmentPoints, "Enchantment");
getWidget(mCastCost, "CastCost");
getWidget(mCharge, "Charge");
getWidget(mSuccessChance, "SuccessChance");
getWidget(mChanceLayout, "ChanceLayout");
getWidget(mTypeButton, "TypeButton");
getWidget(mBuyButton, "BuyButton");
getWidget(mPrice, "PriceLabel");
getWidget(mPriceText, "PriceTextLabel");
setWidgets(mAvailableEffectsList, mUsedEffectsView);
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &EnchantingDialog::onCancelButtonClicked);
mItemBox->eventMouseButtonClick += MyGUI::newDelegate(this, &EnchantingDialog::onSelectItem);
mSoulBox->eventMouseButtonClick += MyGUI::newDelegate(this, &EnchantingDialog::onSelectSoul);
mBuyButton->eventMouseButtonClick += MyGUI::newDelegate(this, &EnchantingDialog::onBuyButtonClicked);
mTypeButton->eventMouseButtonClick += MyGUI::newDelegate(this, &EnchantingDialog::onTypeButtonClicked);
mName->eventEditSelectAccept += MyGUI::newDelegate(this, &EnchantingDialog::onAccept);
}
void EnchantingDialog::onOpen()
{
center();
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mName);
}
void EnchantingDialog::setSoulGem(const MWWorld::Ptr& gem)
{
if (gem.isEmpty())
{
mSoulBox->setItem(MWWorld::Ptr());
mSoulBox->clearUserStrings();
mEnchanting.setSoulGem(MWWorld::Ptr());
}
else
{
mSoulBox->setItem(gem);
mSoulBox->setUserString("ToolTipType", "ItemPtr");
mSoulBox->setUserData(MWWorld::Ptr(gem));
mEnchanting.setSoulGem(gem);
}
}
void EnchantingDialog::setItem(const MWWorld::Ptr& item)
{
if (item.isEmpty())
{
mItemBox->setItem(MWWorld::Ptr());
mItemBox->clearUserStrings();
mEnchanting.setOldItem(MWWorld::Ptr());
}
else
{
std::string_view name = item.getClass().getName(item);
mName->setCaption(MyGUI::UString(name));
mItemBox->setItem(item);
mItemBox->setUserString("ToolTipType", "ItemPtr");
mItemBox->setUserData(MWWorld::Ptr(item));
mEnchanting.setOldItem(item);
}
}
void EnchantingDialog::updateLabels()
{
mEnchantmentPoints->setCaption(std::to_string(static_cast<int>(mEnchanting.getEnchantPoints(false))) + " / "
+ std::to_string(mEnchanting.getMaxEnchantValue()));
mCharge->setCaption(std::to_string(mEnchanting.getGemCharge()));
mSuccessChance->setCaption(std::to_string(std::clamp(mEnchanting.getEnchantChance(), 0, 100)));
mCastCost->setCaption(std::to_string(mEnchanting.getEffectiveCastCost()));
mPrice->setCaption(std::to_string(mEnchanting.getEnchantPrice()));
switch (mEnchanting.getCastStyle())
{
case ESM::Enchantment::CastOnce:
mTypeButton->setCaption(MyGUI::UString(
MWBase::Environment::get().getWindowManager()->getGameSettingString("sItemCastOnce", "Cast Once")));
setConstantEffect(false);
break;
case ESM::Enchantment::WhenStrikes:
mTypeButton->setCaption(
MyGUI::UString(MWBase::Environment::get().getWindowManager()->getGameSettingString(
"sItemCastWhenStrikes", "When Strikes")));
setConstantEffect(false);
break;
case ESM::Enchantment::WhenUsed:
mTypeButton->setCaption(
MyGUI::UString(MWBase::Environment::get().getWindowManager()->getGameSettingString(
"sItemCastWhenUsed", "When Used")));
setConstantEffect(false);
break;
case ESM::Enchantment::ConstantEffect:
mTypeButton->setCaption(
MyGUI::UString(MWBase::Environment::get().getWindowManager()->getGameSettingString(
"sItemCastConstant", "Cast Constant")));
setConstantEffect(true);
break;
}
}
void EnchantingDialog::setPtr(const MWWorld::Ptr& ptr)
{
if (ptr.isEmpty() || (ptr.getType() != ESM::REC_MISC && !ptr.getClass().isActor()))
throw std::runtime_error("Invalid argument in EnchantingDialog::setPtr");
mName->setCaption({});
if (ptr.getClass().isActor())
{
mEnchanting.setSelfEnchanting(false);
mEnchanting.setEnchanter(ptr);
mBuyButton->setCaptionWithReplacing("#{sBuy}");
mChanceLayout->setVisible(false);
mPtr = ptr;
setSoulGem(MWWorld::Ptr());
mPrice->setVisible(true);
mPriceText->setVisible(true);
}
else
{
mEnchanting.setSelfEnchanting(true);
mEnchanting.setEnchanter(MWMechanics::getPlayer());
mBuyButton->setCaptionWithReplacing("#{sCreate}");
mChanceLayout->setVisible(Settings::game().mShowEnchantChance);
mPtr = MWMechanics::getPlayer();
setSoulGem(ptr);
mPrice->setVisible(false);
mPriceText->setVisible(false);
}
setItem(MWWorld::Ptr());
startEditing();
updateLabels();
}
void EnchantingDialog::onReferenceUnavailable()
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Enchanting);
resetReference();
}
void EnchantingDialog::resetReference()
{
ReferenceInterface::resetReference();
setItem(MWWorld::Ptr());
setSoulGem(MWWorld::Ptr());
mPtr = MWWorld::Ptr();
mEnchanting.setEnchanter(MWWorld::Ptr());
}
void EnchantingDialog::onCancelButtonClicked(MyGUI::Widget* sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Enchanting);
}
void EnchantingDialog::onSelectItem(MyGUI::Widget* sender)
{
if (mEnchanting.getOldItem().isEmpty())
{
mItemSelectionDialog = std::make_unique<ItemSelectionDialog>("#{sEnchantItems}");
mItemSelectionDialog->eventItemSelected += MyGUI::newDelegate(this, &EnchantingDialog::onItemSelected);
mItemSelectionDialog->eventDialogCanceled += MyGUI::newDelegate(this, &EnchantingDialog::onItemCancel);
mItemSelectionDialog->setVisible(true);
mItemSelectionDialog->openContainer(MWMechanics::getPlayer());
mItemSelectionDialog->setFilter(SortFilterItemModel::Filter_OnlyEnchantable);
}
else
{
setItem(MWWorld::Ptr());
updateLabels();
}
}
void EnchantingDialog::onItemSelected(MWWorld::Ptr item)
{
mItemSelectionDialog->setVisible(false);
setItem(item);
MWBase::Environment::get().getWindowManager()->playSound(item.getClass().getDownSoundId(item));
mEnchanting.nextCastStyle();
updateLabels();
}
void EnchantingDialog::onItemCancel()
{
mItemSelectionDialog->setVisible(false);
}
void EnchantingDialog::onSoulSelected(MWWorld::Ptr item)
{
mItemSelectionDialog->setVisible(false);
mEnchanting.setSoulGem(item);
if (mEnchanting.getGemCharge() == 0)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage32}");
return;
}
setSoulGem(item);
MWBase::Environment::get().getWindowManager()->playSound(item.getClass().getDownSoundId(item));
updateLabels();
}
void EnchantingDialog::onSoulCancel()
{
mItemSelectionDialog->setVisible(false);
}
void EnchantingDialog::onSelectSoul(MyGUI::Widget* sender)
{
if (mEnchanting.getGem().isEmpty())
{
mItemSelectionDialog = std::make_unique<ItemSelectionDialog>("#{sSoulGemsWithSouls}");
mItemSelectionDialog->eventItemSelected += MyGUI::newDelegate(this, &EnchantingDialog::onSoulSelected);
mItemSelectionDialog->eventDialogCanceled += MyGUI::newDelegate(this, &EnchantingDialog::onSoulCancel);
mItemSelectionDialog->setVisible(true);
mItemSelectionDialog->openContainer(MWMechanics::getPlayer());
mItemSelectionDialog->setFilter(SortFilterItemModel::Filter_OnlyChargedSoulstones);
// MWBase::Environment::get().getWindowManager()->messageBox("#{sInventorySelectNoSoul}");
}
else
{
setSoulGem(MWWorld::Ptr());
mEnchanting.nextCastStyle();
updateLabels();
updateEffectsView();
}
}
void EnchantingDialog::notifyEffectsChanged()
{
mEffectList.populate(mEffects);
mEnchanting.setEffect(mEffectList);
updateLabels();
}
void EnchantingDialog::onTypeButtonClicked(MyGUI::Widget* sender)
{
mEnchanting.nextCastStyle();
updateLabels();
updateEffectsView();
}
void EnchantingDialog::onAccept(MyGUI::EditBox* sender)
{
onBuyButtonClicked(sender);
// To do not spam onAccept() again and again
MWBase::Environment::get().getWindowManager()->injectKeyRelease(MyGUI::KeyCode::None);
}
void EnchantingDialog::onBuyButtonClicked(MyGUI::Widget* sender)
{
if (mEffects.size() <= 0)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sEnchantmentMenu11}");
return;
}
if (mName->getCaption().empty())
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage10}");
return;
}
if (mEnchanting.soulEmpty())
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage52}");
return;
}
if (mEnchanting.itemEmpty())
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage11}");
return;
}
if (static_cast<int>(mEnchanting.getEnchantPoints(false)) > mEnchanting.getMaxEnchantValue())
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage29}");
return;
}
mEnchanting.setNewItemName(mName->getCaption());
mEnchanting.setEffect(mEffectList);
MWWorld::Ptr player = MWMechanics::getPlayer();
int playerGold = player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId);
if (mPtr != player && mEnchanting.getEnchantPrice() > playerGold)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage18}");
return;
}
// check if the player is attempting to use a soulstone or item that was stolen from this actor
if (mPtr != player)
{
for (int i = 0; i < 2; ++i)
{
MWWorld::Ptr item = (i == 0) ? mEnchanting.getOldItem() : mEnchanting.getGem();
if (MWBase::Environment::get().getMechanicsManager()->isItemStolenFrom(
item.getCellRef().getRefId(), mPtr))
{
std::string msg = MWBase::Environment::get()
.getESMStore()
->get<ESM::GameSetting>()
.find("sNotifyMessage49")
->mValue.getString();
msg = Misc::StringUtils::format(msg, item.getClass().getName(item));
MWBase::Environment::get().getWindowManager()->messageBox(msg);
MWBase::Environment::get().getMechanicsManager()->confiscateStolenItemToOwner(
player, item, mPtr, 1);
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Enchanting);
MWBase::Environment::get().getWindowManager()->exitCurrentGuiMode();
return;
}
}
}
if (mEnchanting.create())
{
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("enchant success"));
MWBase::Environment::get().getWindowManager()->messageBox("#{sEnchantmentMenu12}");
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Enchanting);
}
else
{
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("enchant fail"));
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage34}");
if (!mEnchanting.getGem().isEmpty() && !mEnchanting.getGem().getCellRef().getCount())
{
setSoulGem(MWWorld::Ptr());
mEnchanting.nextCastStyle();
updateLabels();
updateEffectsView();
}
}
}
}
| 14,325
|
C++
|
.cpp
| 335
| 32.346269
| 120
| 0.619943
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,479
|
bookwindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/bookwindow.cpp
|
#include "bookwindow.hpp"
#include <MyGUI_InputManager.h>
#include <MyGUI_TextBox.h>
#include <components/esm3/loadbook.hpp>
#include <components/esm4/loadbook.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwworld/actiontake.hpp"
#include "../mwworld/class.hpp"
#include "formatting.hpp"
namespace MWGui
{
BookWindow::BookWindow()
: BookWindowBase("openmw_book.layout")
, mCurrentPage(0)
, mTakeButtonShow(true)
, mTakeButtonAllowed(true)
{
getWidget(mCloseButton, "CloseButton");
mCloseButton->eventMouseButtonClick += MyGUI::newDelegate(this, &BookWindow::onCloseButtonClicked);
getWidget(mTakeButton, "TakeButton");
mTakeButton->eventMouseButtonClick += MyGUI::newDelegate(this, &BookWindow::onTakeButtonClicked);
getWidget(mNextPageButton, "NextPageBTN");
mNextPageButton->eventMouseButtonClick += MyGUI::newDelegate(this, &BookWindow::onNextPageButtonClicked);
getWidget(mPrevPageButton, "PrevPageBTN");
mPrevPageButton->eventMouseButtonClick += MyGUI::newDelegate(this, &BookWindow::onPrevPageButtonClicked);
getWidget(mLeftPageNumber, "LeftPageNumber");
getWidget(mRightPageNumber, "RightPageNumber");
getWidget(mLeftPage, "LeftPage");
getWidget(mRightPage, "RightPage");
adjustButton("CloseButton");
adjustButton("TakeButton");
adjustButton("PrevPageBTN");
float scale = adjustButton("NextPageBTN");
mLeftPage->setNeedMouseFocus(true);
mLeftPage->eventMouseWheel += MyGUI::newDelegate(this, &BookWindow::onMouseWheel);
mRightPage->setNeedMouseFocus(true);
mRightPage->eventMouseWheel += MyGUI::newDelegate(this, &BookWindow::onMouseWheel);
mNextPageButton->eventKeyButtonPressed += MyGUI::newDelegate(this, &BookWindow::onKeyButtonPressed);
mPrevPageButton->eventKeyButtonPressed += MyGUI::newDelegate(this, &BookWindow::onKeyButtonPressed);
mTakeButton->eventKeyButtonPressed += MyGUI::newDelegate(this, &BookWindow::onKeyButtonPressed);
mCloseButton->eventKeyButtonPressed += MyGUI::newDelegate(this, &BookWindow::onKeyButtonPressed);
if (mNextPageButton->getSize().width == 64)
{
// english button has a 7 pixel wide strip of garbage on its right edge
mNextPageButton->setSize(64 - 7, mNextPageButton->getSize().height);
mNextPageButton->setImageCoord(
MyGUI::IntCoord(0, 0, (64 - 7) * scale, mNextPageButton->getSize().height * scale));
}
center();
}
void BookWindow::onMouseWheel(MyGUI::Widget* _sender, int _rel)
{
if (_rel < 0)
nextPage();
else
prevPage();
}
void BookWindow::clearPages()
{
mPages.clear();
}
void BookWindow::setPtr(const MWWorld::Ptr& book)
{
if (book.isEmpty() || (book.getType() != ESM::REC_BOOK && book.getType() != ESM::REC_BOOK4))
throw std::runtime_error("Invalid argument in BookWindow::setPtr");
mBook = book;
MWWorld::Ptr player = MWMechanics::getPlayer();
bool showTakeButton = book.getContainerStore() != &player.getClass().getContainerStore(player);
clearPages();
mCurrentPage = 0;
const std::string* text;
if (book.getType() == ESM::REC_BOOK)
text = &book.get<ESM::Book>()->mBase->mText;
else
text = &book.get<ESM4::Book>()->mBase->mText;
bool shrinkTextAtLastTag = book.getType() == ESM::REC_BOOK;
Formatting::BookFormatter formatter;
mPages = formatter.markupToWidget(mLeftPage, *text, shrinkTextAtLastTag);
formatter.markupToWidget(mRightPage, *text, shrinkTextAtLastTag);
updatePages();
setTakeButtonShow(showTakeButton);
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mCloseButton);
}
void BookWindow::setTakeButtonShow(bool show)
{
mTakeButtonShow = show;
mTakeButton->setVisible(mTakeButtonShow && mTakeButtonAllowed);
}
void BookWindow::onKeyButtonPressed(MyGUI::Widget* sender, MyGUI::KeyCode key, MyGUI::Char character)
{
if (key == MyGUI::KeyCode::ArrowUp)
prevPage();
else if (key == MyGUI::KeyCode::ArrowDown)
nextPage();
}
void BookWindow::setInventoryAllowed(bool allowed)
{
mTakeButtonAllowed = allowed;
mTakeButton->setVisible(mTakeButtonShow && mTakeButtonAllowed);
}
void BookWindow::onCloseButtonClicked(MyGUI::Widget* sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Book);
}
void BookWindow::onTakeButtonClicked(MyGUI::Widget* sender)
{
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Item Book Up"));
MWWorld::ActionTake take(mBook);
take.execute(MWMechanics::getPlayer());
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Book);
}
void BookWindow::onNextPageButtonClicked(MyGUI::Widget* sender)
{
nextPage();
}
void BookWindow::onPrevPageButtonClicked(MyGUI::Widget* sender)
{
prevPage();
}
void BookWindow::updatePages()
{
mLeftPageNumber->setCaption(MyGUI::utility::toString(mCurrentPage * 2 + 1));
mRightPageNumber->setCaption(MyGUI::utility::toString(mCurrentPage * 2 + 2));
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
bool nextPageVisible = (mCurrentPage + 1) * 2 < mPages.size();
mNextPageButton->setVisible(nextPageVisible);
bool prevPageVisible = mCurrentPage != 0;
mPrevPageButton->setVisible(prevPageVisible);
if (focus == mNextPageButton && !nextPageVisible && prevPageVisible)
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mPrevPageButton);
else if (focus == mPrevPageButton && !prevPageVisible && nextPageVisible)
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mNextPageButton);
if (mPages.empty())
return;
MyGUI::Widget* paper;
paper = mLeftPage->getChildAt(0);
paper->setCoord(paper->getPosition().left, -mPages[mCurrentPage * 2].first, paper->getWidth(),
mPages[mCurrentPage * 2].second);
paper = mRightPage->getChildAt(0);
if ((mCurrentPage + 1) * 2 <= mPages.size())
{
paper->setCoord(paper->getPosition().left, -mPages[mCurrentPage * 2 + 1].first, paper->getWidth(),
mPages[mCurrentPage * 2 + 1].second);
paper->setVisible(true);
}
else
{
paper->setVisible(false);
}
}
void BookWindow::nextPage()
{
if ((mCurrentPage + 1) * 2 < mPages.size())
{
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("book page2"));
++mCurrentPage;
updatePages();
}
}
void BookWindow::prevPage()
{
if (mCurrentPage > 0)
{
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("book page"));
--mCurrentPage;
updatePages();
}
}
}
| 7,451
|
C++
|
.cpp
| 171
| 35.28655
| 113
| 0.656293
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,480
|
review.cpp
|
OpenMW_openmw/apps/openmw/mwgui/review.cpp
|
#include "review.hpp"
#include <cmath>
#include <MyGUI_Button.h>
#include <MyGUI_Gui.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_ScrollView.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadbsgn.hpp>
#include <components/esm3/loadrace.hpp>
#include <components/esm3/loadspel.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwmechanics/autocalcspell.hpp"
#include "../mwworld/esmstore.hpp"
#include "tooltips.hpp"
namespace
{
void adjustButtonSize(MyGUI::Button* button)
{
// adjust size of button to fit its text
MyGUI::IntSize size = button->getTextSize();
button->setSize(size.width + 24, button->getSize().height);
}
}
namespace MWGui
{
ReviewDialog::ReviewDialog()
: WindowModal("openmw_chargen_review.layout")
, mUpdateSkillArea(false)
{
// Centre dialog
center();
// Setup static stats
MyGUI::Button* button;
getWidget(mNameWidget, "NameText");
getWidget(button, "NameButton");
adjustButtonSize(button);
button->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onNameClicked);
getWidget(mRaceWidget, "RaceText");
getWidget(button, "RaceButton");
adjustButtonSize(button);
button->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onRaceClicked);
getWidget(mClassWidget, "ClassText");
getWidget(button, "ClassButton");
adjustButtonSize(button);
button->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onClassClicked);
getWidget(mBirthSignWidget, "SignText");
getWidget(button, "SignButton");
adjustButtonSize(button);
button->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onBirthSignClicked);
// Setup dynamic stats
getWidget(mHealth, "Health");
mHealth->setTitle(MWBase::Environment::get().getWindowManager()->getGameSettingString("sHealth", {}));
mHealth->setValue(45, 45);
getWidget(mMagicka, "Magicka");
mMagicka->setTitle(MWBase::Environment::get().getWindowManager()->getGameSettingString("sMagic", {}));
mMagicka->setValue(50, 50);
getWidget(mFatigue, "Fatigue");
mFatigue->setTitle(MWBase::Environment::get().getWindowManager()->getGameSettingString("sFatigue", {}));
mFatigue->setValue(160, 160);
// Setup attributes
MyGUI::Widget* attributes = getWidget("Attributes");
const auto& store = MWBase::Environment::get().getWorld()->getStore().get<ESM::Attribute>();
MyGUI::IntCoord coord{ 8, 4, 250, 18 };
for (const ESM::Attribute& attribute : store)
{
auto* widget
= attributes->createWidget<Widgets::MWAttribute>("MW_StatNameValue", coord, MyGUI::Align::Default);
mAttributeWidgets.emplace(attribute.mId, widget);
widget->setUserString("ToolTipType", "Layout");
widget->setUserString("ToolTipLayout", "AttributeToolTip");
widget->setUserString("Caption_AttributeName", attribute.mName);
widget->setUserString("Caption_AttributeDescription", attribute.mDescription);
widget->setUserString("ImageTexture_AttributeImage", attribute.mIcon);
widget->setAttributeId(attribute.mId);
widget->setAttributeValue(Widgets::MWAttribute::AttributeValue());
coord.top += coord.height;
}
// Setup skills
getWidget(mSkillView, "SkillView");
mSkillView->eventMouseWheel += MyGUI::newDelegate(this, &ReviewDialog::onMouseWheel);
for (const ESM::Skill& skill : MWBase::Environment::get().getESMStore()->get<ESM::Skill>())
{
mSkillValues.emplace(skill.mId, MWMechanics::SkillValue());
mSkillWidgetMap.emplace(skill.mId, static_cast<MyGUI::TextBox*>(nullptr));
}
MyGUI::Button* backButton;
getWidget(backButton, "BackButton");
backButton->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onBackClicked);
MyGUI::Button* okButton;
getWidget(okButton, "OKButton");
okButton->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onOkClicked);
}
void ReviewDialog::onOpen()
{
WindowModal::onOpen();
mUpdateSkillArea = true;
}
void ReviewDialog::onFrame(float /*duration*/)
{
if (mUpdateSkillArea)
{
updateSkillArea();
mUpdateSkillArea = false;
}
}
void ReviewDialog::setPlayerName(const std::string& name)
{
mNameWidget->setCaption(name);
}
void ReviewDialog::setRace(const ESM::RefId& raceId)
{
mRaceId = raceId;
const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().search(mRaceId);
if (race)
{
ToolTips::createRaceToolTip(mRaceWidget, race);
mRaceWidget->setCaption(race->mName);
}
mUpdateSkillArea = true;
}
void ReviewDialog::setClass(const ESM::Class& playerClass)
{
mClass = playerClass;
mClassWidget->setCaption(mClass.mName);
ToolTips::createClassToolTip(mClassWidget, mClass);
}
void ReviewDialog::setBirthSign(const ESM::RefId& signId)
{
mBirthSignId = signId;
const ESM::BirthSign* sign
= MWBase::Environment::get().getESMStore()->get<ESM::BirthSign>().search(mBirthSignId);
if (sign)
{
mBirthSignWidget->setCaption(sign->mName);
ToolTips::createBirthsignToolTip(mBirthSignWidget, mBirthSignId);
}
mUpdateSkillArea = true;
}
void ReviewDialog::setHealth(const MWMechanics::DynamicStat<float>& value)
{
int current = std::max(0, static_cast<int>(value.getCurrent()));
int modified = static_cast<int>(value.getModified());
mHealth->setValue(current, modified);
std::string valStr = MyGUI::utility::toString(current) + " / " + MyGUI::utility::toString(modified);
mHealth->setUserString("Caption_HealthDescription", "#{sHealthDesc}\n" + valStr);
}
void ReviewDialog::setMagicka(const MWMechanics::DynamicStat<float>& value)
{
int current = std::max(0, static_cast<int>(value.getCurrent()));
int modified = static_cast<int>(value.getModified());
mMagicka->setValue(current, modified);
std::string valStr = MyGUI::utility::toString(current) + " / " + MyGUI::utility::toString(modified);
mMagicka->setUserString("Caption_HealthDescription", "#{sMagDesc}\n" + valStr);
}
void ReviewDialog::setFatigue(const MWMechanics::DynamicStat<float>& value)
{
int current = static_cast<int>(value.getCurrent());
int modified = static_cast<int>(value.getModified());
mFatigue->setValue(current, modified);
std::string valStr = MyGUI::utility::toString(current) + " / " + MyGUI::utility::toString(modified);
mFatigue->setUserString("Caption_HealthDescription", "#{sFatDesc}\n" + valStr);
}
void ReviewDialog::setAttribute(ESM::RefId attributeId, const MWMechanics::AttributeValue& value)
{
auto attr = mAttributeWidgets.find(attributeId);
if (attr == mAttributeWidgets.end())
return;
if (attr->second->getAttributeValue() != value)
{
attr->second->setAttributeValue(value);
mUpdateSkillArea = true;
}
}
void ReviewDialog::setSkillValue(ESM::RefId id, const MWMechanics::SkillValue& value)
{
mSkillValues[id] = value;
MyGUI::TextBox* widget = mSkillWidgetMap[id];
if (widget)
{
float modified = value.getModified();
float base = value.getBase();
std::string text = MyGUI::utility::toString(std::floor(modified));
std::string state = "normal";
if (modified > base)
state = "increased";
else if (modified < base)
state = "decreased";
widget->setCaption(text);
widget->_setWidgetState(state);
}
mUpdateSkillArea = true;
}
void ReviewDialog::configureSkills(const std::vector<ESM::RefId>& major, const std::vector<ESM::RefId>& minor)
{
mMajorSkills = major;
mMinorSkills = minor;
// Update misc skills with the remaining skills not in major or minor
std::set<ESM::RefId> skillSet;
std::copy(major.begin(), major.end(), std::inserter(skillSet, skillSet.begin()));
std::copy(minor.begin(), minor.end(), std::inserter(skillSet, skillSet.begin()));
mMiscSkills.clear();
const auto& store = MWBase::Environment::get().getWorld()->getStore().get<ESM::Skill>();
for (const ESM::Skill& skill : store)
{
if (!skillSet.contains(skill.mId))
mMiscSkills.push_back(skill.mId);
}
mUpdateSkillArea = true;
}
void ReviewDialog::addSeparator(MyGUI::IntCoord& coord1, MyGUI::IntCoord& coord2)
{
MyGUI::ImageBox* separator = mSkillView->createWidget<MyGUI::ImageBox>(
"MW_HLine", MyGUI::IntCoord(10, coord1.top, coord1.width + coord2.width - 4, 18), MyGUI::Align::Default);
separator->eventMouseWheel += MyGUI::newDelegate(this, &ReviewDialog::onMouseWheel);
mSkillWidgets.push_back(separator);
coord1.top += separator->getHeight();
coord2.top += separator->getHeight();
}
void ReviewDialog::addGroup(std::string_view label, MyGUI::IntCoord& coord1, MyGUI::IntCoord& coord2)
{
MyGUI::TextBox* groupWidget = mSkillView->createWidget<MyGUI::TextBox>("SandBrightText",
MyGUI::IntCoord(0, coord1.top, coord1.width + coord2.width, coord1.height), MyGUI::Align::Default);
groupWidget->eventMouseWheel += MyGUI::newDelegate(this, &ReviewDialog::onMouseWheel);
groupWidget->setCaption(MyGUI::UString(label));
mSkillWidgets.push_back(groupWidget);
const int lineHeight = Settings::gui().mFontSize + 2;
coord1.top += lineHeight;
coord2.top += lineHeight;
}
MyGUI::TextBox* ReviewDialog::addValueItem(std::string_view text, const std::string& value,
const std::string& state, MyGUI::IntCoord& coord1, MyGUI::IntCoord& coord2)
{
MyGUI::TextBox* skillNameWidget;
MyGUI::TextBox* skillValueWidget;
skillNameWidget = mSkillView->createWidget<MyGUI::TextBox>("SandText", coord1, MyGUI::Align::Default);
skillNameWidget->setCaption(MyGUI::UString(text));
skillNameWidget->eventMouseWheel += MyGUI::newDelegate(this, &ReviewDialog::onMouseWheel);
skillValueWidget = mSkillView->createWidget<MyGUI::TextBox>("SandTextRight", coord2, MyGUI::Align::Default);
skillValueWidget->setCaption(value);
skillValueWidget->_setWidgetState(state);
skillValueWidget->eventMouseWheel += MyGUI::newDelegate(this, &ReviewDialog::onMouseWheel);
mSkillWidgets.push_back(skillNameWidget);
mSkillWidgets.push_back(skillValueWidget);
const int lineHeight = Settings::gui().mFontSize + 2;
coord1.top += lineHeight;
coord2.top += lineHeight;
return skillValueWidget;
}
void ReviewDialog::addItem(const std::string& text, MyGUI::IntCoord& coord1, MyGUI::IntCoord& coord2)
{
MyGUI::TextBox* skillNameWidget;
skillNameWidget = mSkillView->createWidget<MyGUI::TextBox>(
"SandText", coord1 + MyGUI::IntSize(coord2.width, 0), MyGUI::Align::Default);
skillNameWidget->setCaption(text);
skillNameWidget->eventMouseWheel += MyGUI::newDelegate(this, &ReviewDialog::onMouseWheel);
mSkillWidgets.push_back(skillNameWidget);
const int lineHeight = Settings::gui().mFontSize + 2;
coord1.top += lineHeight;
coord2.top += lineHeight;
}
void ReviewDialog::addItem(const ESM::Spell* spell, MyGUI::IntCoord& coord1, MyGUI::IntCoord& coord2)
{
Widgets::MWSpellPtr widget = mSkillView->createWidget<Widgets::MWSpell>(
"MW_StatName", coord1 + MyGUI::IntSize(coord2.width, 0), MyGUI::Align::Default);
widget->setSpellId(spell->mId);
widget->setUserString("ToolTipType", "Spell");
widget->setUserString("Spell", spell->mId.serialize());
widget->eventMouseWheel += MyGUI::newDelegate(this, &ReviewDialog::onMouseWheel);
mSkillWidgets.push_back(widget);
const int lineHeight = Settings::gui().mFontSize + 2;
coord1.top += lineHeight;
coord2.top += lineHeight;
}
void ReviewDialog::addSkills(const std::vector<ESM::RefId>& skills, const std::string& titleId,
const std::string& titleDefault, MyGUI::IntCoord& coord1, MyGUI::IntCoord& coord2)
{
// Add a line separator if there are items above
if (!mSkillWidgets.empty())
{
addSeparator(coord1, coord2);
}
addGroup(
MWBase::Environment::get().getWindowManager()->getGameSettingString(titleId, titleDefault), coord1, coord2);
for (const ESM::RefId& skillId : skills)
{
const ESM::Skill* skill = MWBase::Environment::get().getESMStore()->get<ESM::Skill>().search(skillId);
if (!skill) // Skip unknown skills
continue;
auto skillValue = mSkillValues.find(skill->mId);
if (skillValue == mSkillValues.end())
{
Log(Debug::Error) << "Failed to update stats review window: can not find value for skill "
<< skill->mId;
continue;
}
const MWMechanics::SkillValue& stat = skillValue->second;
int base = stat.getBase();
int modified = stat.getModified();
std::string state = "normal";
if (modified > base)
state = "increased";
else if (modified < base)
state = "decreased";
MyGUI::TextBox* widget = addValueItem(
skill->mName, MyGUI::utility::toString(static_cast<int>(modified)), state, coord1, coord2);
for (int i = 0; i < 2; ++i)
{
ToolTips::createSkillToolTip(mSkillWidgets[mSkillWidgets.size() - 1 - i], skill->mId);
}
mSkillWidgetMap[skill->mId] = widget;
}
}
void ReviewDialog::updateSkillArea()
{
for (MyGUI::Widget* skillWidget : mSkillWidgets)
{
MyGUI::Gui::getInstance().destroyWidget(skillWidget);
}
mSkillWidgets.clear();
const int valueSize = 40;
MyGUI::IntCoord coord1(10, 0, mSkillView->getWidth() - (10 + valueSize) - 24, 18);
MyGUI::IntCoord coord2(coord1.left + coord1.width, coord1.top, valueSize, coord1.height);
if (!mMajorSkills.empty())
addSkills(mMajorSkills, "sSkillClassMajor", "Major Skills", coord1, coord2);
if (!mMinorSkills.empty())
addSkills(mMinorSkills, "sSkillClassMinor", "Minor Skills", coord1, coord2);
if (!mMiscSkills.empty())
addSkills(mMiscSkills, "sSkillClassMisc", "Misc Skills", coord1, coord2);
// starting spells
std::vector<ESM::RefId> spells;
const ESM::Race* race = nullptr;
if (!mRaceId.empty())
race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(mRaceId);
std::map<ESM::RefId, MWMechanics::AttributeValue> attributes;
for (const auto& [key, value] : mAttributeWidgets)
attributes[key] = value->getAttributeValue();
std::vector<ESM::RefId> selectedSpells = MWMechanics::autoCalcPlayerSpells(mSkillValues, attributes, race);
for (ESM::RefId& spellId : selectedSpells)
{
if (std::find(spells.begin(), spells.end(), spellId) == spells.end())
spells.push_back(spellId);
}
if (race)
{
for (const ESM::RefId& spellId : race->mPowers.mList)
{
if (std::find(spells.begin(), spells.end(), spellId) == spells.end())
spells.push_back(spellId);
}
}
if (!mBirthSignId.empty())
{
const ESM::BirthSign* sign
= MWBase::Environment::get().getESMStore()->get<ESM::BirthSign>().find(mBirthSignId);
for (const auto& spellId : sign->mPowers.mList)
{
if (std::find(spells.begin(), spells.end(), spellId) == spells.end())
spells.push_back(spellId);
}
}
if (!mSkillWidgets.empty())
addSeparator(coord1, coord2);
addGroup(MWBase::Environment::get().getWindowManager()->getGameSettingString("sTypeAbility", "Abilities"),
coord1, coord2);
for (auto& spellId : spells)
{
const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().find(spellId);
if (spell->mData.mType == ESM::Spell::ST_Ability)
addItem(spell, coord1, coord2);
}
addSeparator(coord1, coord2);
addGroup(MWBase::Environment::get().getWindowManager()->getGameSettingString("sTypePower", "Powers"), coord1,
coord2);
for (auto& spellId : spells)
{
const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().find(spellId);
if (spell->mData.mType == ESM::Spell::ST_Power)
addItem(spell, coord1, coord2);
}
addSeparator(coord1, coord2);
addGroup(MWBase::Environment::get().getWindowManager()->getGameSettingString("sTypeSpell", "Spells"), coord1,
coord2);
for (auto& spellId : spells)
{
const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().find(spellId);
if (spell->mData.mType == ESM::Spell::ST_Spell)
addItem(spell, coord1, coord2);
}
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
// scrollbar is hidden
mSkillView->setVisibleVScroll(false);
mSkillView->setCanvasSize(mSkillView->getWidth(), std::max(mSkillView->getHeight(), coord1.top));
mSkillView->setVisibleVScroll(true);
}
// widget controls
void ReviewDialog::onOkClicked(MyGUI::Widget* _sender)
{
eventDone(this);
}
void ReviewDialog::onBackClicked(MyGUI::Widget* _sender)
{
eventBack();
}
void ReviewDialog::onNameClicked(MyGUI::Widget* _sender)
{
eventActivateDialog(NAME_DIALOG);
}
void ReviewDialog::onRaceClicked(MyGUI::Widget* _sender)
{
eventActivateDialog(RACE_DIALOG);
}
void ReviewDialog::onClassClicked(MyGUI::Widget* _sender)
{
eventActivateDialog(CLASS_DIALOG);
}
void ReviewDialog::onBirthSignClicked(MyGUI::Widget* _sender)
{
eventActivateDialog(BIRTHSIGN_DIALOG);
}
void ReviewDialog::onMouseWheel(MyGUI::Widget* _sender, int _rel)
{
if (mSkillView->getViewOffset().top + _rel * 0.3 > 0)
mSkillView->setViewOffset(MyGUI::IntPoint(0, 0));
else
mSkillView->setViewOffset(
MyGUI::IntPoint(0, static_cast<int>(mSkillView->getViewOffset().top + _rel * 0.3)));
}
}
| 19,706
|
C++
|
.cpp
| 431
| 36.508121
| 120
| 0.633909
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,481
|
containeritemmodel.cpp
|
OpenMW_openmw/apps/openmw/mwgui/containeritemmodel.cpp
|
#include "containeritemmodel.hpp"
#include <algorithm>
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/manualref.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
namespace
{
bool stacks(const MWWorld::Ptr& left, const MWWorld::Ptr& right)
{
if (left == right)
return true;
// If one of the items is in an inventory and currently equipped, we need to check stacking both ways to be sure
if (left.getContainerStore() && right.getContainerStore())
return left.getContainerStore()->stacks(left, right) && right.getContainerStore()->stacks(left, right);
if (left.getContainerStore())
return left.getContainerStore()->stacks(left, right);
if (right.getContainerStore())
return right.getContainerStore()->stacks(left, right);
MWWorld::ContainerStore store;
return store.stacks(left, right);
}
}
namespace MWGui
{
ContainerItemModel::ContainerItemModel(
const std::vector<MWWorld::Ptr>& itemSources, const std::vector<MWWorld::Ptr>& worldItems)
: mWorldItems(worldItems)
, mTrading(true)
{
assert(!itemSources.empty());
// Tie resolution lifetimes to the ItemModel
mItemSources.reserve(itemSources.size());
for (const MWWorld::Ptr& source : itemSources)
{
MWWorld::ContainerStore& store = source.getClass().getContainerStore(source);
mItemSources.emplace_back(source, store.resolveTemporarily());
}
}
ContainerItemModel::ContainerItemModel(const MWWorld::Ptr& source)
: mTrading(false)
{
MWWorld::ContainerStore& store = source.getClass().getContainerStore(source);
mItemSources.emplace_back(source, store.resolveTemporarily());
}
bool ContainerItemModel::allowedToUseItems() const
{
if (mItemSources.empty())
return true;
MWWorld::Ptr ptr = MWMechanics::getPlayer();
MWWorld::Ptr victim;
// Check if the player is allowed to use items from opened container
MWBase::MechanicsManager* mm = MWBase::Environment::get().getMechanicsManager();
return mm->isAllowedToUse(ptr, mItemSources[0].first, victim);
}
ItemStack ContainerItemModel::getItem(ModelIndex index)
{
if (index < 0)
throw std::runtime_error("Invalid index supplied");
if (mItems.size() <= static_cast<size_t>(index))
throw std::runtime_error("Item index out of range");
return mItems[index];
}
size_t ContainerItemModel::getItemCount()
{
return mItems.size();
}
ItemModel::ModelIndex ContainerItemModel::getIndex(const ItemStack& item)
{
size_t i = 0;
for (ItemStack& itemStack : mItems)
{
if (itemStack == item)
return i;
++i;
}
return -1;
}
MWWorld::Ptr ContainerItemModel::addItem(const ItemStack& item, size_t count, bool allowAutoEquip)
{
auto& source = mItemSources[0];
MWWorld::ContainerStore& store = source.first.getClass().getContainerStore(source.first);
if (item.mBase.getContainerStore() == &store)
throw std::runtime_error("Item to add needs to be from a different container!");
return *store.add(item.mBase, count, allowAutoEquip);
}
MWWorld::Ptr ContainerItemModel::copyItem(const ItemStack& item, size_t count, bool allowAutoEquip)
{
auto& source = mItemSources[0];
MWWorld::ContainerStore& store = source.first.getClass().getContainerStore(source.first);
if (item.mBase.getContainerStore() == &store)
throw std::runtime_error("Item to copy needs to be from a different container!");
MWWorld::ManualRef newRef(*MWBase::Environment::get().getESMStore(), item.mBase, count);
return *store.add(newRef.getPtr(), count, allowAutoEquip);
}
void ContainerItemModel::removeItem(const ItemStack& item, size_t count)
{
int toRemove = count;
for (auto& source : mItemSources)
{
MWWorld::ContainerStore& store = source.first.getClass().getContainerStore(source.first);
for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it)
{
if (stacks(*it, item.mBase))
{
int quantity = it->mRef->mRef.getCount(false);
// If this is a restocking quantity, just don't remove it
if (quantity < 0 && mTrading)
toRemove += quantity;
else
toRemove -= store.remove(*it, toRemove);
if (toRemove <= 0)
return;
}
}
}
for (MWWorld::Ptr& source : mWorldItems)
{
if (stacks(source, item.mBase))
{
int refCount = source.getCellRef().getCount();
if (refCount - toRemove <= 0)
MWBase::Environment::get().getWorld()->deleteObject(source);
else
source.getCellRef().setCount(std::max(0, refCount - toRemove));
toRemove -= refCount;
if (toRemove <= 0)
return;
}
}
throw std::runtime_error("Not enough items to remove could be found");
}
void ContainerItemModel::update()
{
mItems.clear();
for (auto& source : mItemSources)
{
MWWorld::ContainerStore& store = source.first.getClass().getContainerStore(source.first);
for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it)
{
if (!(*it).getClass().showsInInventory(*it))
continue;
bool found = false;
for (ItemStack& itemStack : mItems)
{
if (stacks(*it, itemStack.mBase))
{
// we already have an item stack of this kind, add to it
itemStack.mCount += it->getCellRef().getCount();
found = true;
break;
}
}
if (!found)
{
// no stack yet, create one
ItemStack newItem(*it, this, it->getCellRef().getCount());
mItems.push_back(newItem);
}
}
}
for (MWWorld::Ptr& source : mWorldItems)
{
bool found = false;
for (ItemStack& itemStack : mItems)
{
if (stacks(source, itemStack.mBase))
{
// we already have an item stack of this kind, add to it
itemStack.mCount += source.getCellRef().getCount();
found = true;
break;
}
}
if (!found)
{
// no stack yet, create one
ItemStack newItem(source, this, source.getCellRef().getCount());
mItems.push_back(newItem);
}
}
}
bool ContainerItemModel::onDropItem(const MWWorld::Ptr& item, int count)
{
if (mItemSources.empty())
return false;
MWWorld::Ptr target = mItemSources[0].first;
if (target.getType() != ESM::Container::sRecordId)
return true;
// check container organic flag
MWWorld::LiveCellRef<ESM::Container>* ref = target.get<ESM::Container>();
if (ref->mBase->mFlags & ESM::Container::Organic)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sContentsMessage2}");
return false;
}
// check that we don't exceed container capacity
float weight = item.getClass().getWeight(item) * count;
if (target.getClass().getCapacity(target) < target.getClass().getEncumbrance(target) + weight)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sContentsMessage3}");
return false;
}
return true;
}
bool ContainerItemModel::onTakeItem(const MWWorld::Ptr& item, int count)
{
if (mItemSources.empty())
return false;
MWWorld::Ptr target = mItemSources[0].first;
// Looting a dead corpse is considered OK
if (target.getClass().isActor() && target.getClass().getCreatureStats(target).isDead())
return true;
MWWorld::Ptr player = MWMechanics::getPlayer();
MWBase::Environment::get().getMechanicsManager()->itemTaken(player, item, target, count);
return true;
}
bool ContainerItemModel::usesContainer(const MWWorld::Ptr& container)
{
for (const auto& source : mItemSources)
{
if (source.first == container)
return true;
}
return false;
}
}
| 9,329
|
C++
|
.cpp
| 232
| 29.362069
| 120
| 0.57807
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,482
|
levelupdialog.cpp
|
OpenMW_openmw/apps/openmw/mwgui/levelupdialog.cpp
|
#include "levelupdialog.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_ScrollView.h>
#include <MyGUI_TextBox.h>
#include <MyGUI_UString.h>
#include <components/fallback/fallback.hpp>
#include <components/widgets/box.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "../mwsound/constants.hpp"
#include "class.hpp"
namespace
{
constexpr unsigned int sMaxCoins = 3;
constexpr int sColumnOffsets[] = { 32, 218 };
}
namespace MWGui
{
LevelupDialog::LevelupDialog()
: WindowBase("openmw_levelup_dialog.layout")
, mCoinCount(sMaxCoins)
{
getWidget(mOkButton, "OkButton");
getWidget(mClassImage, "ClassImage");
getWidget(mLevelText, "LevelText");
getWidget(mLevelDescription, "LevelDescription");
getWidget(mCoinBox, "Coins");
getWidget(mAssignWidget, "AssignWidget");
mOkButton->eventMouseButtonClick += MyGUI::newDelegate(this, &LevelupDialog::onOkButtonClicked);
{
const auto& store = MWBase::Environment::get().getESMStore()->get<ESM::Attribute>();
const size_t perCol
= static_cast<size_t>(std::ceil(store.getSize() / static_cast<float>(std::size(sColumnOffsets))));
size_t i = 0;
for (const ESM::Attribute& attribute : store)
{
const int offset = sColumnOffsets[i / perCol];
const int row = static_cast<int>(i % perCol);
Widgets widgets;
widgets.mMultiplier = mAssignWidget->createWidget<MyGUI::TextBox>(
"SandTextVCenter", { offset, 20 * row, 100, 20 }, MyGUI::Align::Default);
auto* hbox = mAssignWidget->createWidget<Gui::HBox>(
{}, { offset + 20, 20 * row, 200, 20 }, MyGUI::Align::Default);
widgets.mButton = hbox->createWidget<Gui::AutoSizedButton>("SandTextButton", {}, MyGUI::Align::Default);
widgets.mButton->setUserData(attribute.mId);
widgets.mButton->eventMouseButtonClick += MyGUI::newDelegate(this, &LevelupDialog::onAttributeClicked);
widgets.mButton->setUserString("TextPadding", "0 0");
widgets.mButton->setUserString("ToolTipType", "Layout");
widgets.mButton->setUserString("ToolTipLayout", "AttributeToolTip");
widgets.mButton->setUserString("Caption_AttributeName", attribute.mName);
widgets.mButton->setUserString("Caption_AttributeDescription", attribute.mDescription);
widgets.mButton->setUserString("ImageTexture_AttributeImage", attribute.mIcon);
widgets.mButton->setCaption(attribute.mName);
widgets.mValue = hbox->createWidget<Gui::AutoSizedTextBox>("SandText", {}, MyGUI::Align::Default);
mAttributeWidgets.emplace(attribute.mId, widgets);
++i;
}
mAssignWidget->setVisibleVScroll(false);
mAssignWidget->setCanvasSize(MyGUI::IntSize(
mAssignWidget->getWidth(), std::max(mAssignWidget->getHeight(), static_cast<int>(20 * perCol))));
mAssignWidget->setVisibleVScroll(true);
mAssignWidget->setViewOffset(MyGUI::IntPoint());
}
for (unsigned int i = 0; i < sMaxCoins; ++i)
{
MyGUI::ImageBox* image = mCoinBox->createWidget<MyGUI::ImageBox>(
"ImageBox", MyGUI::IntCoord(0, 0, 16, 16), MyGUI::Align::Default);
image->setImageTexture("icons\\tx_goldicon.dds");
mCoins.push_back(image);
}
center();
}
void LevelupDialog::setAttributeValues()
{
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
MWMechanics::CreatureStats& creatureStats = player.getClass().getCreatureStats(player);
MWMechanics::NpcStats& pcStats = player.getClass().getNpcStats(player);
for (const ESM::Attribute& attribute : MWBase::Environment::get().getESMStore()->get<ESM::Attribute>())
{
int val = creatureStats.getAttribute(attribute.mId).getBase();
if (std::find(mSpentAttributes.begin(), mSpentAttributes.end(), attribute.mId) != mSpentAttributes.end())
{
val += pcStats.getLevelupAttributeMultiplier(attribute.mId);
}
if (val >= 100)
val = 100;
mAttributeWidgets[attribute.mId].mValue->setCaption(MyGUI::utility::toString(val));
}
}
void LevelupDialog::resetCoins()
{
constexpr int coinSpacing = 33;
int curX = mCoinBox->getWidth() / 2 - (coinSpacing * (mCoinCount - 1) + 16 * mCoinCount) / 2;
for (unsigned int i = 0; i < sMaxCoins; ++i)
{
MyGUI::ImageBox* image = mCoins[i];
image->detachFromWidget();
image->attachToWidget(mCoinBox);
if (i < mCoinCount)
{
mCoins[i]->setVisible(true);
image->setCoord(MyGUI::IntCoord(curX, 0, 16, 16));
curX += 16 + coinSpacing;
}
else
mCoins[i]->setVisible(false);
}
}
void LevelupDialog::assignCoins()
{
resetCoins();
for (size_t i = 0; i < mSpentAttributes.size(); ++i)
{
MyGUI::ImageBox* image = mCoins[i];
image->detachFromWidget();
image->attachToWidget(mAssignWidget);
const auto& attribute = mSpentAttributes[i];
const auto& widgets = mAttributeWidgets[attribute];
const int xdiff = widgets.mMultiplier->getCaption().empty() ? 0 : 20;
const auto* hbox = widgets.mButton->getParent();
MyGUI::IntPoint pos = hbox->getPosition();
pos.left -= 22 + xdiff;
pos.top += (hbox->getHeight() - image->getHeight()) / 2;
image->setPosition(pos);
}
setAttributeValues();
}
void LevelupDialog::onOpen()
{
MWBase::World* world = MWBase::Environment::get().getWorld();
MWWorld::Ptr player = world->getPlayerPtr();
const MWMechanics::CreatureStats& creatureStats = player.getClass().getCreatureStats(player);
const MWMechanics::NpcStats& pcStats = player.getClass().getNpcStats(player);
setClassImage(mClassImage,
ESM::RefId::stringRefId(
getLevelupClassImage(pcStats.getSkillIncreasesForSpecialization(ESM::Class::Specialization::Combat),
pcStats.getSkillIncreasesForSpecialization(ESM::Class::Specialization::Magic),
pcStats.getSkillIncreasesForSpecialization(ESM::Class::Specialization::Stealth))));
int level = creatureStats.getLevel() + 1;
mLevelText->setCaptionWithReplacing("#{sLevelUpMenu1} " + MyGUI::utility::toString(level));
std::string_view levelupdescription;
levelupdescription = Fallback::Map::getString("Level_Up_Level" + MyGUI::utility::toString(level));
if (levelupdescription.empty())
levelupdescription = Fallback::Map::getString("Level_Up_Default");
mLevelDescription->setCaption(MyGUI::UString(levelupdescription));
unsigned int availableAttributes = 0;
for (const ESM::Attribute& attribute : MWBase::Environment::get().getESMStore()->get<ESM::Attribute>())
{
const auto& widgets = mAttributeWidgets[attribute.mId];
if (pcStats.getAttribute(attribute.mId).getBase() < 100)
{
widgets.mButton->setEnabled(true);
widgets.mValue->setEnabled(true);
availableAttributes++;
float mult = pcStats.getLevelupAttributeMultiplier(attribute.mId);
mult = std::min(mult, 100 - pcStats.getAttribute(attribute.mId).getBase());
if (mult <= 1)
widgets.mMultiplier->setCaption({});
else
widgets.mMultiplier->setCaption("x" + MyGUI::utility::toString(mult));
}
else
{
widgets.mButton->setEnabled(false);
widgets.mValue->setEnabled(false);
widgets.mMultiplier->setCaption({});
}
}
mCoinCount = std::min(sMaxCoins, availableAttributes);
mSpentAttributes.clear();
resetCoins();
setAttributeValues();
center();
// Play LevelUp Music
MWBase::Environment::get().getSoundManager()->streamMusic(MWSound::triumphMusic, MWSound::MusicType::Normal);
}
void LevelupDialog::onOkButtonClicked(MyGUI::Widget* sender)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
MWMechanics::NpcStats& pcStats = player.getClass().getNpcStats(player);
if (mSpentAttributes.size() < mCoinCount)
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage36}");
else
{
// increase attributes
for (unsigned int i = 0; i < mCoinCount; ++i)
{
MWMechanics::AttributeValue attribute = pcStats.getAttribute(mSpentAttributes[i]);
attribute.setBase(attribute.getBase() + pcStats.getLevelupAttributeMultiplier(mSpentAttributes[i]));
if (attribute.getBase() >= 100)
attribute.setBase(100);
pcStats.setAttribute(mSpentAttributes[i], attribute);
}
pcStats.levelUp();
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Levelup);
}
}
void LevelupDialog::onAttributeClicked(MyGUI::Widget* sender)
{
auto attribute = *sender->getUserData<ESM::Attribute::AttributeID>();
auto found = std::find(mSpentAttributes.begin(), mSpentAttributes.end(), attribute);
if (found != mSpentAttributes.end())
mSpentAttributes.erase(found);
else
{
if (mSpentAttributes.size() == mCoinCount)
mSpentAttributes[mCoinCount - 1] = attribute;
else
mSpentAttributes.push_back(attribute);
}
assignCoins();
}
std::string_view LevelupDialog::getLevelupClassImage(
const int combatIncreases, const int magicIncreases, const int stealthIncreases)
{
std::string_view ret = "acrobat";
int total = combatIncreases + magicIncreases + stealthIncreases;
if (total == 0)
return ret;
int combatFraction = static_cast<int>(static_cast<float>(combatIncreases) / total * 10.f);
int magicFraction = static_cast<int>(static_cast<float>(magicIncreases) / total * 10.f);
int stealthFraction = static_cast<int>(static_cast<float>(stealthIncreases) / total * 10.f);
if (combatFraction > 7)
ret = "warrior";
else if (magicFraction > 7)
ret = "mage";
else if (stealthFraction > 7)
ret = "thief";
switch (combatFraction)
{
case 7:
ret = "warrior";
break;
case 6:
if (stealthFraction == 1)
ret = "barbarian";
else if (stealthFraction == 3)
ret = "crusader";
else
ret = "knight";
break;
case 5:
if (stealthFraction == 3)
ret = "scout";
else
ret = "archer";
break;
case 4:
ret = "rogue";
break;
default:
break;
}
switch (magicFraction)
{
case 7:
ret = "mage";
break;
case 6:
if (combatFraction == 2)
ret = "sorcerer";
else if (combatIncreases == 3)
ret = "healer";
else
ret = "battlemage";
break;
case 5:
ret = "witchhunter";
break;
case 4:
ret = "spellsword";
// In vanilla there's also code for "nightblade", however it seems to be unreachable.
break;
default:
break;
}
switch (stealthFraction)
{
case 7:
ret = "thief";
break;
case 6:
if (magicFraction == 1)
ret = "agent";
else if (magicIncreases == 3)
ret = "assassin";
else
ret = "acrobat";
break;
case 5:
if (magicIncreases == 3)
ret = "monk";
else
ret = "pilgrim";
break;
case 3:
if (magicFraction == 3)
ret = "bard";
break;
default:
break;
}
return ret;
}
}
| 13,492
|
C++
|
.cpp
| 314
| 31
| 120
| 0.571537
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,483
|
widgets.cpp
|
OpenMW_openmw/apps/openmw/mwgui/widgets.cpp
|
#include "widgets.hpp"
#include <iomanip>
#include <MyGUI_Button.h>
#include <MyGUI_ControllerManager.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_ProgressBar.h>
#include <MyGUI_UString.h>
#include <components/esm/attr.hpp>
#include <components/esm3/loadmgef.hpp>
#include <components/esm3/loadspel.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/resource/resourcesystem.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwmechanics/magiceffects.hpp"
#include "../mwworld/esmstore.hpp"
namespace MWGui::Widgets
{
/* MWSkill */
MWSkill::MWSkill()
: mSkillNameWidget(nullptr)
, mSkillValueWidget(nullptr)
{
}
void MWSkill::setSkillId(ESM::RefId skill)
{
mSkillId = skill;
updateWidgets();
}
void MWSkill::setSkillValue(const SkillValue& value)
{
mValue = value;
updateWidgets();
}
void MWSkill::updateWidgets()
{
if (mSkillNameWidget)
{
const ESM::Skill* skill = MWBase::Environment::get().getESMStore()->get<ESM::Skill>().search(mSkillId);
if (skill == nullptr)
mSkillNameWidget->setCaption({});
else
mSkillNameWidget->setCaption(skill->mName);
}
if (mSkillValueWidget)
{
SkillValue::Type modified = mValue.getModified(), base = mValue.getBase();
mSkillValueWidget->setCaption(MyGUI::utility::toString(modified));
if (modified > base)
mSkillValueWidget->_setWidgetState("increased");
else if (modified < base)
mSkillValueWidget->_setWidgetState("decreased");
else
mSkillValueWidget->_setWidgetState("normal");
}
}
void MWSkill::onClicked(MyGUI::Widget* _sender)
{
eventClicked(this);
}
MWSkill::~MWSkill() {}
void MWSkill::initialiseOverride()
{
Base::initialiseOverride();
assignWidget(mSkillNameWidget, "StatName");
assignWidget(mSkillValueWidget, "StatValue");
MyGUI::Button* button;
assignWidget(button, "StatNameButton");
if (button)
{
mSkillNameWidget = button;
button->eventMouseButtonClick += MyGUI::newDelegate(this, &MWSkill::onClicked);
}
button = nullptr;
assignWidget(button, "StatValueButton");
if (button)
{
mSkillValueWidget = button;
button->eventMouseButtonClick += MyGUI::newDelegate(this, &MWSkill::onClicked);
}
}
/* MWAttribute */
MWAttribute::MWAttribute()
: mAttributeNameWidget(nullptr)
, mAttributeValueWidget(nullptr)
{
}
void MWAttribute::setAttributeId(ESM::RefId attributeId)
{
mId = attributeId;
updateWidgets();
}
void MWAttribute::setAttributeValue(const AttributeValue& value)
{
mValue = value;
updateWidgets();
}
void MWAttribute::onClicked(MyGUI::Widget* _sender)
{
eventClicked(this);
}
void MWAttribute::updateWidgets()
{
if (mAttributeNameWidget)
{
const ESM::Attribute* attribute
= MWBase::Environment::get().getESMStore()->get<ESM::Attribute>().search(mId);
if (!attribute)
{
mAttributeNameWidget->setCaption({});
}
else
{
mAttributeNameWidget->setCaption(MyGUI::UString(attribute->mName));
}
}
if (mAttributeValueWidget)
{
int modified = mValue.getModified(), base = mValue.getBase();
mAttributeValueWidget->setCaption(MyGUI::utility::toString(modified));
if (modified > base)
mAttributeValueWidget->_setWidgetState("increased");
else if (modified < base)
mAttributeValueWidget->_setWidgetState("decreased");
else
mAttributeValueWidget->_setWidgetState("normal");
}
}
void MWAttribute::initialiseOverride()
{
Base::initialiseOverride();
assignWidget(mAttributeNameWidget, "StatName");
assignWidget(mAttributeValueWidget, "StatValue");
MyGUI::Button* button;
assignWidget(button, "StatNameButton");
if (button)
{
mAttributeNameWidget = button;
button->eventMouseButtonClick += MyGUI::newDelegate(this, &MWAttribute::onClicked);
}
button = nullptr;
assignWidget(button, "StatValueButton");
if (button)
{
mAttributeValueWidget = button;
button->eventMouseButtonClick += MyGUI::newDelegate(this, &MWAttribute::onClicked);
}
}
/* MWSpell */
MWSpell::MWSpell()
: mSpellNameWidget(nullptr)
{
}
void MWSpell::setSpellId(const ESM::RefId& spellId)
{
mId = spellId;
updateWidgets();
}
void MWSpell::createEffectWidgets(
std::vector<MyGUI::Widget*>& effects, MyGUI::Widget* creator, MyGUI::IntCoord& coord, int flags)
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
const ESM::Spell* spell = store.get<ESM::Spell>().search(mId);
MYGUI_ASSERT(spell, "spell with id '" << mId << "' not found");
for (const ESM::IndexedENAMstruct& effectInfo : spell->mEffects.mList)
{
MWSpellEffectPtr effect
= creator->createWidget<MWSpellEffect>("MW_EffectImage", coord, MyGUI::Align::Default);
SpellEffectParams params;
params.mEffectID = effectInfo.mData.mEffectID;
params.mSkill = ESM::Skill::indexToRefId(effectInfo.mData.mSkill);
params.mAttribute = ESM::Attribute::indexToRefId(effectInfo.mData.mAttribute);
params.mDuration = effectInfo.mData.mDuration;
params.mMagnMin = effectInfo.mData.mMagnMin;
params.mMagnMax = effectInfo.mData.mMagnMax;
params.mRange = effectInfo.mData.mRange;
params.mIsConstant = (flags & MWEffectList::EF_Constant) != 0;
params.mNoTarget = (flags & MWEffectList::EF_NoTarget);
params.mNoMagnitude = (flags & MWEffectList::EF_NoMagnitude);
effect->setSpellEffect(params);
effects.push_back(effect);
coord.top += effect->getHeight();
coord.width = std::max(coord.width, effect->getRequestedWidth());
}
}
void MWSpell::updateWidgets()
{
if (mSpellNameWidget && MWBase::Environment::get().getWindowManager())
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
const ESM::Spell* spell = store.get<ESM::Spell>().search(mId);
if (spell)
mSpellNameWidget->setCaption(spell->mName);
else
mSpellNameWidget->setCaption({});
}
}
void MWSpell::initialiseOverride()
{
Base::initialiseOverride();
assignWidget(mSpellNameWidget, "StatName");
}
MWSpell::~MWSpell() {}
/* MWEffectList */
MWEffectList::MWEffectList()
: mEffectList(0)
{
}
void MWEffectList::setEffectList(const SpellEffectList& list)
{
mEffectList = list;
updateWidgets();
}
void MWEffectList::createEffectWidgets(
std::vector<MyGUI::Widget*>& effects, MyGUI::Widget* creator, MyGUI::IntCoord& coord, bool center, int flags)
{
// We don't know the width of all the elements beforehand, so we do it in
// 2 steps: first, create all widgets and check their width....
MWSpellEffectPtr effect = nullptr;
int maxwidth = coord.width;
for (auto& effectInfo : mEffectList)
{
effect = creator->createWidget<MWSpellEffect>("MW_EffectImage", coord, MyGUI::Align::Default);
effectInfo.mIsConstant = (flags & EF_Constant) || effectInfo.mIsConstant;
effectInfo.mNoTarget = (flags & EF_NoTarget) || effectInfo.mNoTarget;
effectInfo.mNoMagnitude = (flags & EF_NoMagnitude) || effectInfo.mNoMagnitude;
effect->setSpellEffect(effectInfo);
effects.push_back(effect);
if (effect->getRequestedWidth() > maxwidth)
maxwidth = effect->getRequestedWidth();
coord.top += effect->getHeight();
}
// ... then adjust the size for all widgets
for (MyGUI::Widget* effectWidget : effects)
{
effect = effectWidget->castType<MWSpellEffect>();
bool needcenter = center && (maxwidth > effect->getRequestedWidth());
int diff = maxwidth - effect->getRequestedWidth();
if (needcenter)
{
effect->setCoord(
diff / 2, effect->getCoord().top, effect->getRequestedWidth(), effect->getCoord().height);
}
else
{
effect->setCoord(0, effect->getCoord().top, effect->getRequestedWidth(), effect->getCoord().height);
}
}
// inform the parent about width
coord.width = maxwidth;
}
void MWEffectList::updateWidgets() {}
void MWEffectList::initialiseOverride()
{
Base::initialiseOverride();
}
MWEffectList::~MWEffectList() {}
SpellEffectList MWEffectList::effectListFromESM(const ESM::EffectList* effects)
{
SpellEffectList result;
for (const ESM::IndexedENAMstruct& effectInfo : effects->mList)
{
SpellEffectParams params;
params.mEffectID = effectInfo.mData.mEffectID;
params.mSkill = ESM::Skill::indexToRefId(effectInfo.mData.mSkill);
params.mAttribute = ESM::Attribute::indexToRefId(effectInfo.mData.mAttribute);
params.mDuration = effectInfo.mData.mDuration;
params.mMagnMin = effectInfo.mData.mMagnMin;
params.mMagnMax = effectInfo.mData.mMagnMax;
params.mRange = effectInfo.mData.mRange;
params.mArea = effectInfo.mData.mArea;
result.push_back(params);
}
return result;
}
/* MWSpellEffect */
MWSpellEffect::MWSpellEffect()
: mImageWidget(nullptr)
, mTextWidget(nullptr)
, mRequestedWidth(0)
{
}
void MWSpellEffect::setSpellEffect(const SpellEffectParams& params)
{
mEffectParams = params;
updateWidgets();
}
void MWSpellEffect::updateWidgets()
{
if (!mEffectParams.mKnown)
{
mTextWidget->setCaption("?");
mTextWidget->setCoord(sIconOffset / 2, mTextWidget->getCoord().top, mTextWidget->getCoord().width,
mTextWidget->getCoord().height); // Compensates for the missing image when effect is not known
mRequestedWidth = mTextWidget->getTextSize().width + sIconOffset;
mImageWidget->setImageTexture({});
return;
}
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
const ESM::MagicEffect* magicEffect = store.get<ESM::MagicEffect>().find(mEffectParams.mEffectID);
const ESM::Attribute* attribute = store.get<ESM::Attribute>().search(mEffectParams.mAttribute);
const ESM::Skill* skill = store.get<ESM::Skill>().search(mEffectParams.mSkill);
auto windowManager = MWBase::Environment::get().getWindowManager();
std::string_view pt = windowManager->getGameSettingString("spoint", {});
std::string_view pts = windowManager->getGameSettingString("spoints", {});
std::string_view pct = windowManager->getGameSettingString("spercent", {});
std::string_view ft = windowManager->getGameSettingString("sfeet", {});
std::string_view lvl = windowManager->getGameSettingString("sLevel", {});
std::string_view lvls = windowManager->getGameSettingString("sLevels", {});
std::string to = " " + std::string{ windowManager->getGameSettingString("sTo", {}) } + " ";
std::string sec = " " + std::string{ windowManager->getGameSettingString("ssecond", {}) };
std::string secs = " " + std::string{ windowManager->getGameSettingString("sseconds", {}) };
std::string spellLine = MWMechanics::getMagicEffectString(*magicEffect, attribute, skill);
if ((mEffectParams.mMagnMin || mEffectParams.mMagnMax) && !mEffectParams.mNoMagnitude)
{
ESM::MagicEffect::MagnitudeDisplayType displayType = magicEffect->getMagnitudeDisplayType();
if (displayType == ESM::MagicEffect::MDT_TimesInt)
{
std::string_view timesInt = windowManager->getGameSettingString("sXTimesINT", {});
std::stringstream formatter;
formatter << std::fixed << std::setprecision(1) << " " << (mEffectParams.mMagnMin / 10.0f);
if (mEffectParams.mMagnMin != mEffectParams.mMagnMax)
formatter << to << (mEffectParams.mMagnMax / 10.0f);
formatter << timesInt;
spellLine += formatter.str();
}
else if (displayType != ESM::MagicEffect::MDT_None)
{
spellLine += " " + MyGUI::utility::toString(mEffectParams.mMagnMin);
if (mEffectParams.mMagnMin != mEffectParams.mMagnMax)
spellLine += to + MyGUI::utility::toString(mEffectParams.mMagnMax);
if (displayType == ESM::MagicEffect::MDT_Percentage)
spellLine += pct;
else if (displayType == ESM::MagicEffect::MDT_Feet)
{
spellLine += ' ';
spellLine += ft;
}
else if (displayType == ESM::MagicEffect::MDT_Level)
{
spellLine += ' ';
if (mEffectParams.mMagnMin == mEffectParams.mMagnMax && std::abs(mEffectParams.mMagnMin) == 1)
spellLine += lvl;
else
spellLine += lvls;
}
else // ESM::MagicEffect::MDT_Points
{
spellLine += ' ';
if (mEffectParams.mMagnMin == mEffectParams.mMagnMax && std::abs(mEffectParams.mMagnMin) == 1)
spellLine += pt;
else
spellLine += pts;
}
}
}
// constant effects have no duration and no target
if (!mEffectParams.mIsConstant)
{
if (!(magicEffect->mData.mFlags & ESM::MagicEffect::AppliedOnce))
mEffectParams.mDuration = std::max(1, mEffectParams.mDuration);
if (mEffectParams.mDuration > 0 && !(magicEffect->mData.mFlags & ESM::MagicEffect::NoDuration))
{
spellLine += ' ';
spellLine += windowManager->getGameSettingString("sfor", {});
spellLine += ' ' + MyGUI::utility::toString(mEffectParams.mDuration)
+ ((mEffectParams.mDuration == 1) ? sec : secs);
}
if (mEffectParams.mArea > 0)
{
spellLine += " #{sin} " + MyGUI::utility::toString(mEffectParams.mArea) + " #{sfootarea}";
}
// potions have no target
if (!mEffectParams.mNoTarget)
{
spellLine += ' ';
spellLine += windowManager->getGameSettingString("sonword", {});
spellLine += ' ';
if (mEffectParams.mRange == ESM::RT_Self)
spellLine += windowManager->getGameSettingString("sRangeSelf", {});
else if (mEffectParams.mRange == ESM::RT_Touch)
spellLine += windowManager->getGameSettingString("sRangeTouch", {});
else if (mEffectParams.mRange == ESM::RT_Target)
spellLine += windowManager->getGameSettingString("sRangeTarget", {});
}
}
mTextWidget->setCaptionWithReplacing(spellLine);
mRequestedWidth = mTextWidget->getTextSize().width + sIconOffset;
mImageWidget->setImageTexture(Misc::ResourceHelpers::correctIconPath(
magicEffect->mIcon, MWBase::Environment::get().getResourceSystem()->getVFS()));
}
MWSpellEffect::~MWSpellEffect() {}
void MWSpellEffect::initialiseOverride()
{
Base::initialiseOverride();
assignWidget(mTextWidget, "Text");
assignWidget(mImageWidget, "Image");
}
/* MWDynamicStat */
MWDynamicStat::MWDynamicStat()
: mValue(0)
, mMax(1)
, mTextWidget(nullptr)
, mBarWidget(nullptr)
, mBarTextWidget(nullptr)
{
}
void MWDynamicStat::setValue(int cur, int max)
{
mValue = cur;
mMax = max;
if (mBarWidget)
{
mBarWidget->setProgressRange(std::max(0, mMax));
mBarWidget->setProgressPosition(std::max(0, mValue));
}
if (mBarTextWidget)
{
std::stringstream out;
out << mValue << "/" << mMax;
mBarTextWidget->setCaption(out.str());
}
}
void MWDynamicStat::setTitle(std::string_view text)
{
if (mTextWidget)
mTextWidget->setCaption(MyGUI::UString(text));
}
MWDynamicStat::~MWDynamicStat() {}
void MWDynamicStat::initialiseOverride()
{
Base::initialiseOverride();
assignWidget(mTextWidget, "Text");
assignWidget(mBarWidget, "Bar");
assignWidget(mBarTextWidget, "BarText");
}
}
| 17,800
|
C++
|
.cpp
| 437
| 30.423341
| 117
| 0.597234
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,484
|
tooltips.cpp
|
OpenMW_openmw/apps/openmw/mwgui/tooltips.cpp
|
#include "tooltips.hpp"
#include <iomanip>
#include <MyGUI_Gui.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_RenderManager.h>
#include <MyGUI_TextIterator.h>
#include <MyGUI_UString.h>
#include <components/esm/records.hpp>
#include <components/l10n/manager.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/settings/values.hpp>
#include <components/widgets/box.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/spellutil.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "inventorywindow.hpp"
#include "mapwindow.hpp"
#include "itemmodel.hpp"
namespace MWGui
{
ToolTips::ToolTips()
: Layout("openmw_tooltips.layout")
, mFocusToolTipX(0.0)
, mFocusToolTipY(0.0)
, mHorizontalScrollIndex(0)
, mRemainingDelay(Settings::gui().mTooltipDelay)
, mLastMouseX(0)
, mLastMouseY(0)
, mEnabled(true)
, mFullHelp(false)
, mFrameDuration(0.f)
{
getWidget(mDynamicToolTipBox, "DynamicToolTipBox");
mDynamicToolTipBox->setVisible(false);
// turn off mouse focus so that getMouseFocusWidget returns the correct widget,
// even if the mouse is over the tooltip
mDynamicToolTipBox->setNeedMouseFocus(false);
mMainWidget->setNeedMouseFocus(false);
for (unsigned int i = 0; i < mMainWidget->getChildCount(); ++i)
{
mMainWidget->getChildAt(i)->setVisible(false);
}
}
void ToolTips::setEnabled(bool enabled)
{
mEnabled = enabled;
}
void ToolTips::onFrame(float frameDuration)
{
mFrameDuration = frameDuration;
}
void ToolTips::update(float frameDuration)
{
while (mDynamicToolTipBox->getChildCount())
{
MyGUI::Gui::getInstance().destroyWidget(mDynamicToolTipBox->getChildAt(0));
}
// start by hiding everything
for (unsigned int i = 0; i < mMainWidget->getChildCount(); ++i)
{
mMainWidget->getChildAt(i)->setVisible(false);
}
const MyGUI::IntSize& viewSize = MyGUI::RenderManager::getInstance().getViewSize();
if (!mEnabled)
{
return;
}
MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager();
bool guiMode = winMgr->isGuiMode();
if (guiMode)
{
if (!winMgr->getCursorVisible())
return;
const MyGUI::IntPoint& mousePos = MyGUI::InputManager::getInstance().getMousePosition();
if (winMgr->getWorldMouseOver()
&& (winMgr->isConsoleMode() || (winMgr->getMode() == GM_Container)
|| (winMgr->getMode() == GM_Inventory)))
{
if (mFocusObject.isEmpty())
return;
const MWWorld::Class& objectclass = mFocusObject.getClass();
MyGUI::IntSize tooltipSize;
if (!objectclass.hasToolTip(mFocusObject) && winMgr->isConsoleMode())
{
setCoord(0, 0, 300, 300);
mDynamicToolTipBox->setVisible(true);
ToolTipInfo info;
info.caption = mFocusObject.getClass().getName(mFocusObject);
if (info.caption.empty())
info.caption = mFocusObject.getCellRef().getRefId().toDebugString();
info.icon.clear();
tooltipSize = createToolTip(info, checkOwned());
}
else
tooltipSize = getToolTipViaPtr(mFocusObject.getCellRef().getCount(), true);
MyGUI::IntPoint tooltipPosition = MyGUI::InputManager::getInstance().getMousePosition();
position(tooltipPosition, tooltipSize, viewSize);
setCoord(tooltipPosition.left, tooltipPosition.top, tooltipSize.width, tooltipSize.height);
}
else
{
if (mousePos.left == mLastMouseX && mousePos.top == mLastMouseY)
{
mRemainingDelay -= frameDuration;
}
else
{
mHorizontalScrollIndex = 0;
mRemainingDelay = Settings::gui().mTooltipDelay;
}
mLastMouseX = mousePos.left;
mLastMouseY = mousePos.top;
if (mRemainingDelay > 0)
return;
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getMouseFocusWidget();
if (focus == nullptr)
return;
MyGUI::IntSize tooltipSize;
// try to go 1 level up until there is a widget that has tooltip
// this is necessary because some skin elements are actually separate widgets
while (!focus->isUserString("ToolTipType"))
{
focus = focus->getParent();
if (!focus)
return;
}
std::string_view type = focus->getUserString("ToolTipType");
if (type.empty())
{
return;
}
// special handling for markers on the local map: the tooltip should only be visible
// if the marker is not hidden due to the fog of war.
if (type == "MapMarker")
{
LocalMapBase::MarkerUserData data = *focus->getUserData<LocalMapBase::MarkerUserData>();
if (!data.isPositionExplored())
return;
ToolTipInfo info;
info.text = data.caption;
info.notes = data.notes;
tooltipSize = createToolTip(info);
}
else if (type == "ItemPtr")
{
mFocusObject = *focus->getUserData<MWWorld::Ptr>();
if (mFocusObject.isEmpty())
return;
tooltipSize = getToolTipViaPtr(mFocusObject.getCellRef().getCount(), false, checkOwned());
}
else if (type == "ItemModelIndex")
{
std::pair<ItemModel::ModelIndex, ItemModel*> pair
= *focus->getUserData<std::pair<ItemModel::ModelIndex, ItemModel*>>();
mFocusObject = pair.second->getItem(pair.first).mBase;
bool isAllowedToUse = pair.second->allowedToUseItems();
tooltipSize = getToolTipViaPtr(pair.second->getItem(pair.first).mCount, false, !isAllowedToUse);
}
else if (type == "ToolTipInfo")
{
tooltipSize = createToolTip(*focus->getUserData<MWGui::ToolTipInfo>());
}
else if (type == "AvatarItemSelection")
{
MyGUI::IntCoord avatarPos = focus->getAbsoluteCoord();
MyGUI::IntPoint relMousePos = MyGUI::InputManager::getInstance().getMousePosition()
- MyGUI::IntPoint(avatarPos.left, avatarPos.top);
MWWorld::Ptr item
= winMgr->getInventoryWindow()->getAvatarSelectedItem(relMousePos.left, relMousePos.top);
mFocusObject = item;
if (!mFocusObject.isEmpty())
tooltipSize = getToolTipViaPtr(mFocusObject.getCellRef().getCount(), false);
}
else if (type == "Spell")
{
ToolTipInfo info;
const auto& store = MWBase::Environment::get().getESMStore();
const ESM::Spell* spell
= store->get<ESM::Spell>().find(ESM::RefId::deserialize(focus->getUserString("Spell")));
info.caption = spell->mName;
Widgets::SpellEffectList effects;
for (const ESM::IndexedENAMstruct& spellEffect : spell->mEffects.mList)
{
Widgets::SpellEffectParams params;
params.mEffectID = spellEffect.mData.mEffectID;
params.mSkill = ESM::Skill::indexToRefId(spellEffect.mData.mSkill);
params.mAttribute = ESM::Attribute::indexToRefId(spellEffect.mData.mAttribute);
params.mDuration = spellEffect.mData.mDuration;
params.mMagnMin = spellEffect.mData.mMagnMin;
params.mMagnMax = spellEffect.mData.mMagnMax;
params.mRange = spellEffect.mData.mRange;
params.mArea = spellEffect.mData.mArea;
params.mIsConstant = (spell->mData.mType == ESM::Spell::ST_Ability);
params.mNoTarget = false;
effects.push_back(params);
}
// display school of spells that contribute to skill progress
if (MWMechanics::spellIncreasesSkill(spell))
{
ESM::RefId id = MWMechanics::getSpellSchool(spell, MWMechanics::getPlayer());
if (!id.empty())
{
const auto& school = store->get<ESM::Skill>().find(id)->mSchool;
info.text = "#{sSchool}: " + MyGUI::TextIterator::toTagsString(school->mName).asUTF8();
}
}
auto cost = focus->getUserString("SpellCost");
if (!cost.empty() && cost != "0")
info.text
+= MWGui::ToolTips::getValueString(MWMechanics::calcSpellCost(*spell), "#{sCastCost}");
info.effects = std::move(effects);
tooltipSize = createToolTip(info);
}
else if (type == "Layout")
{
// tooltip defined in the layout
MyGUI::Widget* tooltip;
getWidget(tooltip, focus->getUserString("ToolTipLayout"));
tooltip->setVisible(true);
const auto& userStrings = focus->getUserStrings();
for (auto& userStringPair : userStrings)
{
size_t underscorePos = userStringPair.first.find('_');
if (underscorePos == std::string::npos)
continue;
std::string key = userStringPair.first.substr(0, underscorePos);
std::string_view first = userStringPair.first;
std::string_view widgetName = first.substr(underscorePos + 1);
type = "Property";
size_t caretPos = key.find('^');
if (caretPos != std::string::npos)
{
type = first.substr(0, caretPos);
key.erase(key.begin(), key.begin() + caretPos + 1);
}
MyGUI::Widget* w;
getWidget(w, widgetName);
if (type == "Property")
w->setProperty(key, userStringPair.second);
else if (type == "UserData")
w->setUserString(key, userStringPair.second);
}
tooltipSize = tooltip->getSize();
tooltip->setCoord(0, 0, tooltipSize.width, tooltipSize.height);
}
else
throw std::runtime_error("unknown tooltip type");
MyGUI::IntPoint tooltipPosition = MyGUI::InputManager::getInstance().getMousePosition();
position(tooltipPosition, tooltipSize, viewSize);
setCoord(tooltipPosition.left, tooltipPosition.top, tooltipSize.width, tooltipSize.height);
}
}
else
{
if (!mFocusObject.isEmpty())
{
MyGUI::IntSize tooltipSize = getToolTipViaPtr(mFocusObject.getCellRef().getCount(), true, checkOwned());
setCoord(viewSize.width / 2 - tooltipSize.width / 2,
std::max(0, int(mFocusToolTipY * viewSize.height - tooltipSize.height)), tooltipSize.width,
tooltipSize.height);
mDynamicToolTipBox->setVisible(true);
}
}
}
void ToolTips::position(MyGUI::IntPoint& position, MyGUI::IntSize size, MyGUI::IntSize viewportSize)
{
position += MyGUI::IntPoint(0, 32)
- MyGUI::IntPoint(static_cast<int>(MyGUI::InputManager::getInstance().getMousePosition().left
/ float(viewportSize.width) * size.width),
0);
if ((position.left + size.width) > viewportSize.width)
{
position.left = viewportSize.width - size.width;
}
if ((position.top + size.height) > viewportSize.height)
{
position.top = MyGUI::InputManager::getInstance().getMousePosition().top - size.height - 8;
}
}
void ToolTips::clear()
{
mFocusObject = MWWorld::Ptr();
while (mDynamicToolTipBox->getChildCount())
{
MyGUI::Gui::getInstance().destroyWidget(mDynamicToolTipBox->getChildAt(0));
}
for (unsigned int i = 0; i < mMainWidget->getChildCount(); ++i)
{
mMainWidget->getChildAt(i)->setVisible(false);
}
}
void ToolTips::setFocusObject(const MWWorld::Ptr& focus)
{
mFocusObject = focus;
update(mFrameDuration);
}
MyGUI::IntSize ToolTips::getToolTipViaPtr(int count, bool image, bool isOwned)
{
// this the maximum width of the tooltip before it starts word-wrapping
setCoord(0, 0, 300, 300);
MyGUI::IntSize tooltipSize;
const MWWorld::Class& object = mFocusObject.getClass();
if (!object.hasToolTip(mFocusObject))
{
mDynamicToolTipBox->setVisible(false);
}
else
{
mDynamicToolTipBox->setVisible(true);
ToolTipInfo info = object.getToolTipInfo(mFocusObject, count);
if (!image)
info.icon.clear();
tooltipSize = createToolTip(info, isOwned);
}
return tooltipSize;
}
bool ToolTips::checkOwned()
{
if (mFocusObject.isEmpty())
return false;
MWWorld::Ptr ptr = MWMechanics::getPlayer();
MWWorld::Ptr victim;
MWBase::MechanicsManager* mm = MWBase::Environment::get().getMechanicsManager();
return !mm->isAllowedToUse(ptr, mFocusObject, victim);
}
MyGUI::IntSize ToolTips::createToolTip(const MWGui::ToolTipInfo& info, bool isOwned)
{
mDynamicToolTipBox->setVisible(true);
const int showOwned = Settings::game().mShowOwned;
if ((showOwned == 1 || showOwned == 3) && isOwned)
mDynamicToolTipBox->changeWidgetSkin(MWBase::Environment::get().getWindowManager()->isGuiMode()
? "HUD_Box_NoTransp_Owned"
: "HUD_Box_Owned");
else
mDynamicToolTipBox->changeWidgetSkin(
MWBase::Environment::get().getWindowManager()->isGuiMode() ? "HUD_Box_NoTransp" : "HUD_Box");
const std::string& caption = info.caption;
const std::string& image = info.icon;
int imageSize = (!image.empty()) ? info.imageSize : 0;
std::string text = info.text;
std::string_view extra = info.extra;
// remove the first newline (easier this way)
if (!text.empty() && text[0] == '\n')
text.erase(0, 1);
if (!extra.empty() && extra[0] == '\n')
extra = extra.substr(1);
const ESM::Enchantment* enchant = nullptr;
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
if (!info.enchant.empty())
{
enchant = store.get<ESM::Enchantment>().search(info.enchant);
if (enchant)
{
if (enchant->mData.mType == ESM::Enchantment::CastOnce)
text += "\n#{sItemCastOnce}";
else if (enchant->mData.mType == ESM::Enchantment::WhenStrikes)
text += "\n#{sItemCastWhenStrikes}";
else if (enchant->mData.mType == ESM::Enchantment::WhenUsed)
text += "\n#{sItemCastWhenUsed}";
else if (enchant->mData.mType == ESM::Enchantment::ConstantEffect)
text += "\n#{sItemCastConstant}";
}
}
// this the maximum width of the tooltip before it starts word-wrapping
setCoord(0, 0, 300, 300);
const MyGUI::IntPoint padding(8, 8);
const int imageCaptionHPadding = !caption.empty() ? 8 : 0;
const int imageCaptionVPadding = !caption.empty() ? 4 : 0;
const int maximumWidth = MyGUI::RenderManager::getInstance().getViewSize().width - imageCaptionHPadding * 2;
const std::string realImage
= Misc::ResourceHelpers::correctIconPath(image, MWBase::Environment::get().getResourceSystem()->getVFS());
Gui::EditBox* captionWidget = mDynamicToolTipBox->createWidget<Gui::EditBox>(
"NormalText", MyGUI::IntCoord(0, 0, 300, 300), MyGUI::Align::Left | MyGUI::Align::Top, "ToolTipCaption");
captionWidget->setEditStatic(true);
captionWidget->setNeedKeyFocus(false);
captionWidget->setCaptionWithReplacing(caption);
MyGUI::IntSize captionSize = captionWidget->getTextSize();
int captionHeight = std::max(!caption.empty() ? captionSize.height : 0, imageSize);
Gui::EditBox* textWidget = mDynamicToolTipBox->createWidget<Gui::EditBox>("SandText",
MyGUI::IntCoord(0, captionHeight + imageCaptionVPadding, 300, 300 - captionHeight - imageCaptionVPadding),
MyGUI::Align::Stretch, "ToolTipText");
textWidget->setEditStatic(true);
textWidget->setEditMultiLine(true);
textWidget->setEditWordWrap(info.wordWrap);
textWidget->setCaptionWithReplacing(text);
textWidget->setTextAlign(MyGUI::Align::HCenter | MyGUI::Align::Top);
textWidget->setNeedKeyFocus(false);
MyGUI::IntSize textSize = textWidget->getTextSize();
captionSize += MyGUI::IntSize(imageSize, 0); // adjust for image
MyGUI::IntSize totalSize = MyGUI::IntSize(
std::min(std::max(textSize.width, captionSize.width + ((!image.empty()) ? imageCaptionHPadding : 0)),
maximumWidth),
(!text.empty() ? textSize.height + imageCaptionVPadding : 0) + captionHeight);
for (const std::string& note : info.notes)
{
MyGUI::ImageBox* icon = mDynamicToolTipBox->createWidget<MyGUI::ImageBox>("MarkerButton",
MyGUI::IntCoord(padding.left, totalSize.height + padding.top, 8, 8), MyGUI::Align::Default);
icon->setColour(MyGUI::Colour(1.0f, 0.3f, 0.3f));
Gui::EditBox* edit = mDynamicToolTipBox->createWidget<Gui::EditBox>("SandText",
MyGUI::IntCoord(padding.left + 8 + 4, totalSize.height + padding.top, 300 - padding.left - 8 - 4,
300 - totalSize.height),
MyGUI::Align::Default);
constexpr size_t maxLength = 60;
std::string shortenedNote = note.substr(0, std::min(maxLength, note.find('\n')));
if (shortenedNote.size() < note.size())
shortenedNote += " ...";
edit->setCaption(shortenedNote);
MyGUI::IntSize noteTextSize = edit->getTextSize();
edit->setSize(std::max(edit->getWidth(), noteTextSize.width), noteTextSize.height);
icon->setPosition(icon->getLeft(), (edit->getTop() + edit->getBottom()) / 2 - icon->getHeight() / 2);
totalSize.height += std::max(edit->getHeight(), icon->getHeight());
totalSize.width = std::max(totalSize.width, edit->getWidth() + 8 + 4);
}
if (!info.effects.empty())
{
MyGUI::Widget* effectArea = mDynamicToolTipBox->createWidget<MyGUI::Widget>({},
MyGUI::IntCoord(padding.left, totalSize.height, 300 - padding.left, 300 - totalSize.height),
MyGUI::Align::Stretch);
MyGUI::IntCoord coord(0, 6, totalSize.width, 24);
Widgets::MWEffectListPtr effectsWidget
= effectArea->createWidget<Widgets::MWEffectList>("MW_StatName", coord, MyGUI::Align::Default);
effectsWidget->setEffectList(info.effects);
std::vector<MyGUI::Widget*> effectItems;
int flag = info.isPotion ? Widgets::MWEffectList::EF_NoTarget : 0;
flag |= info.isIngredient ? Widgets::MWEffectList::EF_NoMagnitude : 0;
flag |= info.isIngredient ? Widgets::MWEffectList::EF_Constant : 0;
effectsWidget->createEffectWidgets(
effectItems, effectArea, coord, info.isPotion || info.isIngredient, flag);
totalSize.height += coord.top - 6;
totalSize.width = std::max(totalSize.width, coord.width);
}
if (enchant)
{
MyGUI::Widget* enchantArea = mDynamicToolTipBox->createWidget<MyGUI::Widget>({},
MyGUI::IntCoord(padding.left, totalSize.height, 300 - padding.left, 300 - totalSize.height),
MyGUI::Align::Stretch);
MyGUI::IntCoord coord(0, 6, totalSize.width, 24);
Widgets::MWEffectListPtr enchantWidget
= enchantArea->createWidget<Widgets::MWEffectList>("MW_StatName", coord, MyGUI::Align::Default);
enchantWidget->setEffectList(Widgets::MWEffectList::effectListFromESM(&enchant->mEffects));
std::vector<MyGUI::Widget*> enchantEffectItems;
int flag
= (enchant->mData.mType == ESM::Enchantment::ConstantEffect) ? Widgets::MWEffectList::EF_Constant : 0;
enchantWidget->createEffectWidgets(enchantEffectItems, enchantArea, coord, false, flag);
totalSize.height += coord.top - 6;
totalSize.width = std::max(totalSize.width, coord.width);
if (enchant->mData.mType == ESM::Enchantment::WhenStrikes
|| enchant->mData.mType == ESM::Enchantment::WhenUsed)
{
const int maxCharge = MWMechanics::getEnchantmentCharge(*enchant);
int charge = (info.remainingEnchantCharge == -1) ? maxCharge : info.remainingEnchantCharge;
const int chargeWidth = 204;
MyGUI::TextBox* chargeText = enchantArea->createWidget<MyGUI::TextBox>(
"SandText", MyGUI::IntCoord(0, 0, 10, 18), MyGUI::Align::Default, "ToolTipEnchantChargeText");
chargeText->setCaptionWithReplacing("#{sCharges}");
const int chargeTextWidth = chargeText->getTextSize().width + 5;
const int chargeAndTextWidth = chargeWidth + chargeTextWidth;
totalSize.width = std::max(totalSize.width, chargeAndTextWidth);
chargeText->setCoord((totalSize.width - chargeAndTextWidth) / 2, coord.top + 6, chargeTextWidth, 18);
MyGUI::IntCoord chargeCoord;
if (totalSize.width < chargeWidth)
{
totalSize.width = chargeWidth;
chargeCoord = MyGUI::IntCoord(0, coord.top + 6, chargeWidth, 18);
}
else
{
chargeCoord = MyGUI::IntCoord(
(totalSize.width - chargeAndTextWidth) / 2 + chargeTextWidth, coord.top + 6, chargeWidth, 18);
}
Widgets::MWDynamicStatPtr chargeWidget = enchantArea->createWidget<Widgets::MWDynamicStat>(
"MW_ChargeBar", chargeCoord, MyGUI::Align::Default);
chargeWidget->setValue(charge, maxCharge);
totalSize.height += 24;
}
}
if (!extra.empty())
{
Gui::EditBox* extraWidget = mDynamicToolTipBox->createWidget<Gui::EditBox>("SandText",
MyGUI::IntCoord(padding.left, totalSize.height + 12, 300 - padding.left, 300 - totalSize.height),
MyGUI::Align::Stretch, "ToolTipExtraText");
extraWidget->setEditStatic(true);
extraWidget->setEditMultiLine(true);
extraWidget->setEditWordWrap(info.wordWrap);
extraWidget->setCaptionWithReplacing(extra);
extraWidget->setTextAlign(MyGUI::Align::HCenter | MyGUI::Align::Top);
extraWidget->setNeedKeyFocus(false);
MyGUI::IntSize extraTextSize = extraWidget->getTextSize();
totalSize.height += extraTextSize.height + 4;
totalSize.width = std::max(totalSize.width, extraTextSize.width);
}
captionWidget->setCoord((totalSize.width - captionSize.width) / 2 + imageSize,
(captionHeight - captionSize.height) / 2, captionSize.width - imageSize, captionSize.height);
// if its too long we do hscroll with the caption
if (captionSize.width > maximumWidth)
{
mHorizontalScrollIndex = mHorizontalScrollIndex + 2;
if (mHorizontalScrollIndex > captionSize.width)
{
mHorizontalScrollIndex = -totalSize.width;
}
int horizontal_scroll = mHorizontalScrollIndex;
if (horizontal_scroll < 40)
{
horizontal_scroll = 40;
}
else
{
horizontal_scroll = 80 - mHorizontalScrollIndex;
}
captionWidget->setPosition(
MyGUI::IntPoint(horizontal_scroll, captionWidget->getPosition().top + padding.top));
}
else
{
captionWidget->setPosition(captionWidget->getPosition() + padding);
}
textWidget->setPosition(textWidget->getPosition()
+ MyGUI::IntPoint(0,
padding.top)); // only apply vertical padding, the horizontal works automatically due to Align::HCenter
if (!image.empty())
{
MyGUI::ImageBox* imageWidget = mDynamicToolTipBox->createWidget<MyGUI::ImageBox>("ImageBox",
MyGUI::IntCoord(
(totalSize.width - captionSize.width - imageCaptionHPadding) / 2, 0, imageSize, imageSize),
MyGUI::Align::Left | MyGUI::Align::Top);
imageWidget->setImageTexture(realImage);
imageWidget->setPosition(imageWidget->getPosition() + padding);
}
totalSize += MyGUI::IntSize(padding.left * 2, padding.top * 2);
return totalSize;
}
std::string ToolTips::toString(const float value)
{
std::ostringstream stream;
if (value != int(value))
stream << std::setprecision(3);
stream << value;
return stream.str();
}
std::string ToolTips::toString(const int value)
{
return std::to_string(value);
}
std::string ToolTips::getWeightString(const float weight, const std::string& prefix)
{
if (weight == 0)
return {};
else
return "\n" + prefix + ": " + toString(weight);
}
std::string ToolTips::getPercentString(const float value, const std::string& prefix)
{
if (value == 0)
return {};
else
return "\n" + prefix + ": " + toString(value * 100) + "%";
}
std::string ToolTips::getValueString(const int value, const std::string& prefix)
{
if (value == 0)
return {};
else
return "\n" + prefix + ": " + toString(value);
}
std::string ToolTips::getMiscString(const std::string& text, const std::string& prefix)
{
if (text.empty())
return {};
else
return "\n" + prefix + ": " + text;
}
std::string ToolTips::getCountString(const int value)
{
if (value == 1)
return {};
else
return " (" + MyGUI::utility::toString(value) + ")";
}
std::string ToolTips::getSoulString(const MWWorld::CellRef& cellref)
{
const ESM::RefId& soul = cellref.getSoul();
if (soul.empty())
return {};
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
const ESM::Creature* creature = store.get<ESM::Creature>().search(soul);
if (!creature)
return {};
if (creature->mName.empty())
return " (" + creature->mId.toDebugString() + ")";
return " (" + creature->mName + ")";
}
std::string ToolTips::getCellRefString(const MWWorld::CellRef& cellref)
{
std::string ret;
ret += getMiscString(cellref.getOwner().getRefIdString(), "Owner");
const ESM::RefId& factionId = cellref.getFaction();
if (!factionId.empty())
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
const ESM::Faction* fact = store.get<ESM::Faction>().search(factionId);
if (fact != nullptr)
{
ret += getMiscString(fact->mName.empty() ? factionId.getRefIdString() : fact->mName, "Owner Faction");
if (cellref.getFactionRank() >= 0)
{
int rank = cellref.getFactionRank();
const std::string& rankName = fact->mRanks[rank];
if (rankName.empty())
ret += getValueString(cellref.getFactionRank(), "Rank");
else
ret += getMiscString(rankName, "Rank");
}
}
}
std::vector<std::pair<ESM::RefId, int>> itemOwners
= MWBase::Environment::get().getMechanicsManager()->getStolenItemOwners(cellref.getRefId());
for (std::pair<ESM::RefId, int>& owner : itemOwners)
{
if (owner.second == std::numeric_limits<int>::max())
ret += std::string("\nStolen from ") + owner.first.toDebugString(); // for legacy (ESS) savegames
else
ret += std::string("\nStolen ") + MyGUI::utility::toString(owner.second) + " from "
+ owner.first.toDebugString();
}
ret += getMiscString(cellref.getGlobalVariable(), "Global");
return ret;
}
std::string ToolTips::getDurationString(float duration, const std::string& prefix)
{
auto l10n = MWBase::Environment::get().getL10nManager()->getContext("Interface");
std::string ret;
ret = prefix + ": ";
if (duration < 1.f)
{
ret += l10n->formatMessage("DurationSecond", { "seconds" }, { 0 });
return ret;
}
constexpr int secondsPerMinute = 60; // 60 seconds
constexpr int secondsPerHour = secondsPerMinute * 60; // 60 minutes
constexpr int secondsPerDay = secondsPerHour * 24; // 24 hours
constexpr int secondsPerMonth = secondsPerDay * 30; // 30 days
constexpr int secondsPerYear = secondsPerDay * 365;
int fullDuration = static_cast<int>(duration);
int units = 0;
int years = fullDuration / secondsPerYear;
int months = fullDuration % secondsPerYear / secondsPerMonth;
int days = fullDuration % secondsPerYear % secondsPerMonth
/ secondsPerDay; // Because a year is not exactly 12 "months"
int hours = fullDuration % secondsPerDay / secondsPerHour;
int minutes = fullDuration % secondsPerHour / secondsPerMinute;
int seconds = fullDuration % secondsPerMinute;
if (years)
{
units++;
ret += l10n->formatMessage("DurationYear", { "years" }, { years });
}
if (months)
{
units++;
ret += l10n->formatMessage("DurationMonth", { "months" }, { months });
}
if (units < 2 && days)
{
units++;
ret += l10n->formatMessage("DurationDay", { "days" }, { days });
}
if (units < 2 && hours)
{
units++;
ret += l10n->formatMessage("DurationHour", { "hours" }, { hours });
}
if (units >= 2)
return ret;
if (minutes)
ret += l10n->formatMessage("DurationMinute", { "minutes" }, { minutes });
if (seconds)
ret += l10n->formatMessage("DurationSecond", { "seconds" }, { seconds });
return ret;
}
bool ToolTips::toggleFullHelp()
{
mFullHelp = !mFullHelp;
return mFullHelp;
}
bool ToolTips::getFullHelp() const
{
return mFullHelp;
}
void ToolTips::setFocusObjectScreenCoords(float min_x, float min_y, float max_x, float max_y)
{
mFocusToolTipX = (min_x + max_x) / 2;
mFocusToolTipY = min_y;
}
void ToolTips::createSkillToolTip(MyGUI::Widget* widget, ESM::RefId skillId)
{
if (skillId.empty())
return;
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
const ESM::Skill* skill = store.get<ESM::Skill>().find(skillId);
const ESM::Attribute* attr
= store.get<ESM::Attribute>().find(ESM::Attribute::indexToRefId(skill->mData.mAttribute));
widget->setUserString("ToolTipType", "Layout");
widget->setUserString("ToolTipLayout", "SkillNoProgressToolTip");
widget->setUserString("Caption_SkillNoProgressName", MyGUI::TextIterator::toTagsString(skill->mName));
widget->setUserString("Caption_SkillNoProgressDescription", skill->mDescription);
widget->setUserString("Caption_SkillNoProgressAttribute",
"#{sGoverningAttribute}: " + MyGUI::TextIterator::toTagsString(attr->mName));
widget->setUserString("ImageTexture_SkillNoProgressImage", skill->mIcon);
}
void ToolTips::createAttributeToolTip(MyGUI::Widget* widget, ESM::RefId attributeId)
{
const ESM::Attribute* attribute
= MWBase::Environment::get().getESMStore()->get<ESM::Attribute>().search(attributeId);
if (!attribute)
return;
widget->setUserString("ToolTipType", "Layout");
widget->setUserString("ToolTipLayout", "AttributeToolTip");
widget->setUserString("Caption_AttributeName", MyGUI::TextIterator::toTagsString(attribute->mName));
widget->setUserString(
"Caption_AttributeDescription", MyGUI::TextIterator::toTagsString(attribute->mDescription));
widget->setUserString("ImageTexture_AttributeImage", attribute->mIcon);
}
void ToolTips::createSpecializationToolTip(MyGUI::Widget* widget, const std::string& name, int specId)
{
widget->setUserString("Caption_Caption", name);
std::string specText;
// get all skills of this specialisation
const MWWorld::Store<ESM::Skill>& skills = MWBase::Environment::get().getESMStore()->get<ESM::Skill>();
bool isFirst = true;
for (const auto& skill : skills)
{
if (skill.mData.mSpecialization == specId)
{
if (isFirst)
isFirst = false;
else
specText += "\n";
specText += MyGUI::TextIterator::toTagsString(skill.mName);
}
}
widget->setUserString("Caption_ColumnText", specText);
widget->setUserString("ToolTipLayout", "SpecializationToolTip");
widget->setUserString("ToolTipType", "Layout");
}
void ToolTips::createBirthsignToolTip(MyGUI::Widget* widget, const ESM::RefId& birthsignId)
{
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
const ESM::BirthSign* sign = store.get<ESM::BirthSign>().find(birthsignId);
const VFS::Manager* const vfs = MWBase::Environment::get().getResourceSystem()->getVFS();
widget->setUserString("ToolTipType", "Layout");
widget->setUserString("ToolTipLayout", "BirthSignToolTip");
widget->setUserString(
"ImageTexture_BirthSignImage", Misc::ResourceHelpers::correctTexturePath(sign->mTexture, vfs));
std::string text = sign->mName + "\n#{fontcolourhtml=normal}" + sign->mDescription;
std::vector<const ESM::Spell*> abilities, powers, spells;
for (const ESM::RefId& spellId : sign->mPowers.mList)
{
const ESM::Spell* spell = store.get<ESM::Spell>().search(spellId);
if (!spell)
continue; // Skip spells which cannot be found
ESM::Spell::SpellType type = static_cast<ESM::Spell::SpellType>(spell->mData.mType);
if (type != ESM::Spell::ST_Spell && type != ESM::Spell::ST_Ability && type != ESM::Spell::ST_Power)
continue; // We only want spell, ability and powers.
if (type == ESM::Spell::ST_Ability)
abilities.push_back(spell);
else if (type == ESM::Spell::ST_Power)
powers.push_back(spell);
else if (type == ESM::Spell::ST_Spell)
spells.push_back(spell);
}
using Category = std::pair<const std::vector<const ESM::Spell*>&, std::string_view>;
for (const auto& [category, label] : std::initializer_list<Category>{
{ abilities, "sBirthsignmenu1" }, { powers, "sPowers" }, { spells, "sBirthsignmenu2" } })
{
bool addHeader = true;
for (const ESM::Spell* spell : category)
{
if (addHeader)
{
text += "\n\n#{fontcolourhtml=header}#{";
text += label;
text += '}';
addHeader = false;
}
text += "\n#{fontcolourhtml=normal}" + spell->mName;
}
}
widget->setUserString("Caption_BirthSignText", text);
}
void ToolTips::createRaceToolTip(MyGUI::Widget* widget, const ESM::Race* playerRace)
{
widget->setUserString("Caption_CenteredCaption", playerRace->mName);
widget->setUserString("Caption_CenteredCaptionText", playerRace->mDescription);
widget->setUserString("ToolTipType", "Layout");
widget->setUserString("ToolTipLayout", "RaceToolTip");
}
void ToolTips::createClassToolTip(MyGUI::Widget* widget, const ESM::Class& playerClass)
{
if (playerClass.mName.empty())
return;
int spec = playerClass.mData.mSpecialization;
std::string specStr = "#{";
specStr += ESM::Class::sGmstSpecializationIds[spec];
specStr += '}';
widget->setUserString("Caption_ClassName", playerClass.mName);
widget->setUserString("Caption_ClassDescription", playerClass.mDescription);
widget->setUserString("Caption_ClassSpecialisation", "#{sSpecialization}: " + specStr);
widget->setUserString("ToolTipType", "Layout");
widget->setUserString("ToolTipLayout", "ClassToolTip");
}
void ToolTips::createMagicEffectToolTip(MyGUI::Widget* widget, short id)
{
const auto& store = MWBase::Environment::get().getESMStore();
const ESM::MagicEffect* effect = store->get<ESM::MagicEffect>().find(id);
const std::string& name = ESM::MagicEffect::indexToGmstString(id);
std::string icon = effect->mIcon;
int slashPos = icon.rfind('\\');
icon.insert(slashPos + 1, "b_");
icon = Misc::ResourceHelpers::correctIconPath(icon, MWBase::Environment::get().getResourceSystem()->getVFS());
widget->setUserString("ToolTipType", "Layout");
widget->setUserString("ToolTipLayout", "MagicEffectToolTip");
widget->setUserString("Caption_MagicEffectName", "#{" + name + "}");
widget->setUserString("Caption_MagicEffectDescription", effect->mDescription);
widget->setUserString("Caption_MagicEffectSchool",
"#{sSchool}: "
+ MyGUI::TextIterator::toTagsString(
store->get<ESM::Skill>().find(effect->mData.mSchool)->mSchool->mName));
widget->setUserString("ImageTexture_MagicEffectImage", icon);
}
}
| 40,833
|
C++
|
.cpp
| 836
| 35.952153
| 120
| 0.576455
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,485
|
repair.cpp
|
OpenMW_openmw/apps/openmw/mwgui/repair.cpp
|
#include "repair.hpp"
#include <iomanip>
#include <MyGUI_ScrollView.h>
#include <components/esm3/loadrepa.hpp>
#include <components/widgets/box.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwworld/class.hpp"
#include "inventoryitemmodel.hpp"
#include "itemchargeview.hpp"
#include "itemselection.hpp"
#include "itemwidget.hpp"
#include "sortfilteritemmodel.hpp"
namespace MWGui
{
Repair::Repair()
: WindowBase("openmw_repair.layout")
{
getWidget(mRepairBox, "RepairBox");
getWidget(mToolBox, "ToolBox");
getWidget(mToolIcon, "ToolIcon");
getWidget(mUsesLabel, "UsesLabel");
getWidget(mQualityLabel, "QualityLabel");
getWidget(mCancelButton, "CancelButton");
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &Repair::onCancel);
mRepairBox->eventItemClicked += MyGUI::newDelegate(this, &Repair::onRepairItem);
mRepairBox->setDisplayMode(ItemChargeView::DisplayMode_Health);
mToolIcon->eventMouseButtonClick += MyGUI::newDelegate(this, &Repair::onSelectItem);
}
void Repair::onOpen()
{
center();
SortFilterItemModel* model
= new SortFilterItemModel(std::make_unique<InventoryItemModel>(MWMechanics::getPlayer()));
model->setFilter(SortFilterItemModel::Filter_OnlyRepairable);
mRepairBox->setModel(model);
mRepairBox->update();
// Reset scrollbars
mRepairBox->resetScrollbars();
}
void Repair::setPtr(const MWWorld::Ptr& item)
{
if (item.isEmpty() || !item.getClass().isItem(item))
throw std::runtime_error("Invalid argument in Repair::setPtr");
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Item Repair Up"));
mRepair.setTool(item);
mToolIcon->setItem(item);
mToolIcon->setUserString("ToolTipType", "ItemPtr");
mToolIcon->setUserData(MWWorld::Ptr(item));
updateRepairView();
}
void Repair::updateRepairView()
{
MWWorld::LiveCellRef<ESM::Repair>* ref = mRepair.getTool().get<ESM::Repair>();
int uses = mRepair.getTool().getClass().getItemHealth(mRepair.getTool());
float quality = ref->mBase->mData.mQuality;
mToolIcon->setUserData(mRepair.getTool());
std::stringstream qualityStr;
qualityStr << std::setprecision(3) << quality;
mUsesLabel->setCaptionWithReplacing("#{sUses} " + MyGUI::utility::toString(uses));
mQualityLabel->setCaptionWithReplacing("#{sQuality} " + qualityStr.str());
bool toolBoxVisible = (mRepair.getTool().getCellRef().getCount() != 0);
mToolBox->setVisible(toolBoxVisible);
mToolBox->setUserString("Hidden", toolBoxVisible ? "false" : "true");
if (!toolBoxVisible)
{
mToolIcon->setItem(MWWorld::Ptr());
mToolIcon->clearUserStrings();
}
mRepairBox->update();
Gui::Box* box = dynamic_cast<Gui::Box*>(mMainWidget);
if (box == nullptr)
throw std::runtime_error("main widget must be a box");
box->notifyChildrenSizeChanged();
center();
}
void Repair::onSelectItem(MyGUI::Widget* sender)
{
mItemSelectionDialog = std::make_unique<ItemSelectionDialog>("#{sRepair}");
mItemSelectionDialog->eventItemSelected += MyGUI::newDelegate(this, &Repair::onItemSelected);
mItemSelectionDialog->eventDialogCanceled += MyGUI::newDelegate(this, &Repair::onItemCancel);
mItemSelectionDialog->setVisible(true);
mItemSelectionDialog->openContainer(MWMechanics::getPlayer());
mItemSelectionDialog->setFilter(SortFilterItemModel::Filter_OnlyRepairTools);
}
void Repair::onItemSelected(MWWorld::Ptr item)
{
mItemSelectionDialog->setVisible(false);
mToolIcon->setItem(item);
mToolIcon->setUserString("ToolTipType", "ItemPtr");
mToolIcon->setUserData(item);
mRepair.setTool(item);
MWBase::Environment::get().getWindowManager()->playSound(item.getClass().getDownSoundId(item));
updateRepairView();
}
void Repair::onItemCancel()
{
mItemSelectionDialog->setVisible(false);
}
void Repair::onCancel(MyGUI::Widget* /*sender*/)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Repair);
}
void Repair::onRepairItem(MyGUI::Widget* /*sender*/, const MWWorld::Ptr& ptr)
{
if (!mRepair.getTool().getCellRef().getCount())
return;
mRepair.repair(ptr);
updateRepairView();
}
}
| 4,727
|
C++
|
.cpp
| 112
| 34.803571
| 108
| 0.672715
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,486
|
scrollwindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/scrollwindow.cpp
|
#include "scrollwindow.hpp"
#include <MyGUI_ScrollView.h>
#include <components/esm3/loadbook.hpp>
#include <components/esm4/loadbook.hpp>
#include <components/widgets/imagebutton.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwworld/actiontake.hpp"
#include "../mwworld/class.hpp"
#include "formatting.hpp"
namespace MWGui
{
ScrollWindow::ScrollWindow()
: BookWindowBase("openmw_scroll.layout")
, mTakeButtonShow(true)
, mTakeButtonAllowed(true)
{
getWidget(mTextView, "TextView");
getWidget(mCloseButton, "CloseButton");
mCloseButton->eventMouseButtonClick += MyGUI::newDelegate(this, &ScrollWindow::onCloseButtonClicked);
getWidget(mTakeButton, "TakeButton");
mTakeButton->eventMouseButtonClick += MyGUI::newDelegate(this, &ScrollWindow::onTakeButtonClicked);
adjustButton("CloseButton");
adjustButton("TakeButton");
mCloseButton->eventKeyButtonPressed += MyGUI::newDelegate(this, &ScrollWindow::onKeyButtonPressed);
mTakeButton->eventKeyButtonPressed += MyGUI::newDelegate(this, &ScrollWindow::onKeyButtonPressed);
center();
}
void ScrollWindow::setPtr(const MWWorld::Ptr& scroll)
{
if (scroll.isEmpty() || (scroll.getType() != ESM::REC_BOOK && scroll.getType() != ESM::REC_BOOK4))
throw std::runtime_error("Invalid argument in ScrollWindow::setPtr");
mScroll = scroll;
MWWorld::Ptr player = MWMechanics::getPlayer();
bool showTakeButton = scroll.getContainerStore() != &player.getClass().getContainerStore(player);
const std::string* text;
if (scroll.getType() == ESM::REC_BOOK)
text = &scroll.get<ESM::Book>()->mBase->mText;
else
text = &scroll.get<ESM4::Book>()->mBase->mText;
bool shrinkTextAtLastTag = scroll.getType() == ESM::REC_BOOK;
Formatting::BookFormatter formatter;
formatter.markupToWidget(mTextView, *text, 390, mTextView->getHeight(), shrinkTextAtLastTag);
MyGUI::IntSize size = mTextView->getChildAt(0)->getSize();
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
// scrollbar is hidden
mTextView->setVisibleVScroll(false);
if (size.height > mTextView->getSize().height)
mTextView->setCanvasSize(mTextView->getWidth(), size.height);
else
mTextView->setCanvasSize(mTextView->getWidth(), mTextView->getSize().height);
mTextView->setVisibleVScroll(true);
mTextView->setViewOffset(MyGUI::IntPoint(0, 0));
setTakeButtonShow(showTakeButton);
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mCloseButton);
}
void ScrollWindow::onKeyButtonPressed(MyGUI::Widget* sender, MyGUI::KeyCode key, MyGUI::Char character)
{
int scroll = 0;
if (key == MyGUI::KeyCode::ArrowUp)
scroll = 40;
else if (key == MyGUI::KeyCode::ArrowDown)
scroll = -40;
if (scroll != 0)
mTextView->setViewOffset(mTextView->getViewOffset() + MyGUI::IntPoint(0, scroll));
}
void ScrollWindow::setTakeButtonShow(bool show)
{
mTakeButtonShow = show;
mTakeButton->setVisible(mTakeButtonShow && mTakeButtonAllowed);
}
void ScrollWindow::setInventoryAllowed(bool allowed)
{
mTakeButtonAllowed = allowed;
mTakeButton->setVisible(mTakeButtonShow && mTakeButtonAllowed);
}
void ScrollWindow::onCloseButtonClicked(MyGUI::Widget* _sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Scroll);
}
void ScrollWindow::onTakeButtonClicked(MyGUI::Widget* _sender)
{
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Item Book Up"));
MWWorld::ActionTake take(mScroll);
take.execute(MWMechanics::getPlayer());
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Scroll);
}
}
| 4,142
|
C++
|
.cpp
| 89
| 39.05618
| 117
| 0.684145
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,487
|
itemview.cpp
|
OpenMW_openmw/apps/openmw/mwgui/itemview.cpp
|
#include "itemview.hpp"
#include <cmath>
#include <MyGUI_FactoryManager.h>
#include <MyGUI_Gui.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_ScrollView.h>
#include "itemmodel.hpp"
#include "itemwidget.hpp"
namespace MWGui
{
ItemView::ItemView()
: mScrollView(nullptr)
{
}
void ItemView::setModel(std::unique_ptr<ItemModel> model)
{
mModel = std::move(model);
update();
}
void ItemView::initialiseOverride()
{
Base::initialiseOverride();
assignWidget(mScrollView, "ScrollView");
if (mScrollView == nullptr)
throw std::runtime_error("Item view needs a scroll view");
mScrollView->setCanvasAlign(MyGUI::Align::Left | MyGUI::Align::Top);
}
void ItemView::layoutWidgets()
{
if (!mScrollView->getChildCount())
return;
int x = 0;
int y = 0;
MyGUI::Widget* dragArea = mScrollView->getChildAt(0);
int maxHeight = mScrollView->getHeight();
int rows = maxHeight / 42;
rows = std::max(rows, 1);
bool showScrollbar = int(std::ceil(dragArea->getChildCount() / float(rows))) > mScrollView->getWidth() / 42;
if (showScrollbar)
maxHeight -= 18;
for (unsigned int i = 0; i < dragArea->getChildCount(); ++i)
{
MyGUI::Widget* w = dragArea->getChildAt(i);
w->setPosition(x, y);
y += 42;
if (y > maxHeight - 42 && i < dragArea->getChildCount() - 1)
{
x += 42;
y = 0;
}
}
x += 42;
MyGUI::IntSize size = MyGUI::IntSize(std::max(mScrollView->getSize().width, x), mScrollView->getSize().height);
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
// scrollbar is hidden
mScrollView->setVisibleVScroll(false);
mScrollView->setVisibleHScroll(false);
mScrollView->setCanvasSize(size);
mScrollView->setVisibleVScroll(true);
mScrollView->setVisibleHScroll(true);
dragArea->setSize(size);
}
void ItemView::update()
{
while (mScrollView->getChildCount())
MyGUI::Gui::getInstance().destroyWidget(mScrollView->getChildAt(0));
if (!mModel)
return;
mModel->update();
MyGUI::Widget* dragArea = mScrollView->createWidget<MyGUI::Widget>(
{}, 0, 0, mScrollView->getWidth(), mScrollView->getHeight(), MyGUI::Align::Stretch);
dragArea->setNeedMouseFocus(true);
dragArea->eventMouseButtonClick += MyGUI::newDelegate(this, &ItemView::onSelectedBackground);
dragArea->eventMouseWheel += MyGUI::newDelegate(this, &ItemView::onMouseWheelMoved);
for (ItemModel::ModelIndex i = 0; i < static_cast<int>(mModel->getItemCount()); ++i)
{
const ItemStack& item = mModel->getItem(i);
ItemWidget* itemWidget = dragArea->createWidget<ItemWidget>(
"MW_ItemIcon", MyGUI::IntCoord(0, 0, 42, 42), MyGUI::Align::Default);
itemWidget->setUserString("ToolTipType", "ItemModelIndex");
itemWidget->setUserData(std::make_pair(i, mModel.get()));
ItemWidget::ItemState state = ItemWidget::None;
if (item.mType == ItemStack::Type_Barter)
state = ItemWidget::Barter;
if (item.mType == ItemStack::Type_Equipped)
state = ItemWidget::Equip;
itemWidget->setItem(item.mBase, state);
itemWidget->setCount(item.mCount);
itemWidget->eventMouseButtonClick += MyGUI::newDelegate(this, &ItemView::onSelectedItem);
itemWidget->eventMouseWheel += MyGUI::newDelegate(this, &ItemView::onMouseWheelMoved);
}
layoutWidgets();
}
void ItemView::resetScrollBars()
{
mScrollView->setViewOffset(MyGUI::IntPoint(0, 0));
}
void ItemView::onSelectedItem(MyGUI::Widget* sender)
{
ItemModel::ModelIndex index = (*sender->getUserData<std::pair<ItemModel::ModelIndex, ItemModel*>>()).first;
eventItemClicked(index);
}
void ItemView::onSelectedBackground(MyGUI::Widget* sender)
{
eventBackgroundClicked();
}
void ItemView::onMouseWheelMoved(MyGUI::Widget* _sender, int _rel)
{
if (mScrollView->getViewOffset().left + _rel * 0.3f > 0)
mScrollView->setViewOffset(MyGUI::IntPoint(0, 0));
else
mScrollView->setViewOffset(
MyGUI::IntPoint(static_cast<int>(mScrollView->getViewOffset().left + _rel * 0.3f), 0));
}
void ItemView::setSize(const MyGUI::IntSize& _value)
{
bool changed = (_value.width != getWidth() || _value.height != getHeight());
Base::setSize(_value);
if (changed)
layoutWidgets();
}
void ItemView::setCoord(const MyGUI::IntCoord& _value)
{
bool changed = (_value.width != getWidth() || _value.height != getHeight());
Base::setCoord(_value);
if (changed)
layoutWidgets();
}
void ItemView::registerComponents()
{
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::ItemView>("Widget");
}
}
| 5,289
|
C++
|
.cpp
| 133
| 31.075188
| 119
| 0.613943
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
35,488
|
waitdialog.cpp
|
OpenMW_openmw/apps/openmw/mwgui/waitdialog.cpp
|
#include "waitdialog.hpp"
#include <MyGUI_InputManager.h>
#include <MyGUI_ProgressBar.h>
#include <MyGUI_ScrollBar.h>
#include <components/misc/rng.hpp>
#include <components/esm3/loadregn.hpp>
#include <components/misc/strings/format.hpp>
#include <components/settings/values.hpp>
#include <components/widgets/box.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/statemanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/datetimemanager.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/npcstats.hpp"
namespace MWGui
{
WaitDialogProgressBar::WaitDialogProgressBar()
: WindowBase("openmw_wait_dialog_progressbar.layout")
{
getWidget(mProgressBar, "ProgressBar");
getWidget(mProgressText, "ProgressText");
}
void WaitDialogProgressBar::onOpen()
{
center();
}
void WaitDialogProgressBar::setProgress(int cur, int total)
{
mProgressBar->setProgressRange(total);
mProgressBar->setProgressPosition(cur);
mProgressText->setCaption(MyGUI::utility::toString(cur) + "/" + MyGUI::utility::toString(total));
}
// ---------------------------------------------------------------------------------------------------------
WaitDialog::WaitDialog()
: WindowBase("openmw_wait_dialog.layout")
, mTimeAdvancer(0.05f)
, mSleeping(false)
, mHours(1)
, mManualHours(1)
, mFadeTimeRemaining(0)
, mInterruptAt(-1)
, mProgressBar()
{
getWidget(mDateTimeText, "DateTimeText");
getWidget(mRestText, "RestText");
getWidget(mHourText, "HourText");
getWidget(mUntilHealedButton, "UntilHealedButton");
getWidget(mWaitButton, "WaitButton");
getWidget(mCancelButton, "CancelButton");
getWidget(mHourSlider, "HourSlider");
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &WaitDialog::onCancelButtonClicked);
mUntilHealedButton->eventMouseButtonClick += MyGUI::newDelegate(this, &WaitDialog::onUntilHealedButtonClicked);
mWaitButton->eventMouseButtonClick += MyGUI::newDelegate(this, &WaitDialog::onWaitButtonClicked);
mHourSlider->eventScrollChangePosition += MyGUI::newDelegate(this, &WaitDialog::onHourSliderChangedPosition);
mCancelButton->eventKeyButtonPressed += MyGUI::newDelegate(this, &WaitDialog::onKeyButtonPressed);
mWaitButton->eventKeyButtonPressed += MyGUI::newDelegate(this, &WaitDialog::onKeyButtonPressed);
mUntilHealedButton->eventKeyButtonPressed += MyGUI::newDelegate(this, &WaitDialog::onKeyButtonPressed);
mTimeAdvancer.eventProgressChanged += MyGUI::newDelegate(this, &WaitDialog::onWaitingProgressChanged);
mTimeAdvancer.eventInterrupted += MyGUI::newDelegate(this, &WaitDialog::onWaitingInterrupted);
mTimeAdvancer.eventFinished += MyGUI::newDelegate(this, &WaitDialog::onWaitingFinished);
}
void WaitDialog::setPtr(const MWWorld::Ptr& ptr)
{
setCanRest(!ptr.isEmpty() || MWBase::Environment::get().getWorld()->canRest() == MWBase::World::Rest_Allowed);
if (ptr.isEmpty() && MWBase::Environment::get().getWorld()->canRest() == MWBase::World::Rest_PlayerIsInAir)
{
// Resting in air is not allowed unless you're using a bed
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage1}");
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Rest);
}
if (mUntilHealedButton->getVisible())
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mUntilHealedButton);
else
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mWaitButton);
}
bool WaitDialog::exit()
{
bool canExit = !mTimeAdvancer.isRunning(); // Only exit if not currently waiting
if (canExit)
{
clear();
stopWaiting();
}
return canExit;
}
void WaitDialog::clear()
{
mSleeping = false;
mHours = 1;
mManualHours = 1;
mFadeTimeRemaining = 0;
mInterruptAt = -1;
mTimeAdvancer.stop();
}
void WaitDialog::onOpen()
{
if (mTimeAdvancer.isRunning())
{
mProgressBar.setVisible(true);
setVisible(false);
return;
}
else
{
mProgressBar.setVisible(false);
}
if (!MWBase::Environment::get().getWindowManager()->getRestEnabled())
{
MWBase::Environment::get().getWindowManager()->popGuiMode();
}
MWBase::World::RestPermitted canRest = MWBase::Environment::get().getWorld()->canRest();
if (canRest == MWBase::World::Rest_EnemiesAreNearby)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage2}");
MWBase::Environment::get().getWindowManager()->popGuiMode();
}
else if (canRest == MWBase::World::Rest_PlayerIsUnderwater)
{
// resting underwater not allowed
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage1}");
MWBase::Environment::get().getWindowManager()->popGuiMode();
}
onHourSliderChangedPosition(mHourSlider, 0);
mHourSlider->setScrollPosition(0);
const MWWorld::DateTimeManager& timeManager = *MWBase::Environment::get().getWorld()->getTimeManager();
std::string_view month = timeManager.getMonthName();
int hour = static_cast<int>(timeManager.getTimeStamp().getHour());
bool pm = hour >= 12;
if (hour >= 13)
hour -= 12;
if (hour == 0)
hour = 12;
ESM::EpochTimeStamp currentDate = timeManager.getEpochTimeStamp();
std::string daysPassed = Misc::StringUtils::format("(#{Calendar:day} %i)", timeManager.getTimeStamp().getDay());
std::string_view formattedHour(pm ? "#{Calendar:pm}" : "#{Calendar:am}");
std::string dateTimeText
= Misc::StringUtils::format("%i %s %s %i %s", currentDate.mDay, month, daysPassed, hour, formattedHour);
mDateTimeText->setCaptionWithReplacing(dateTimeText);
}
void WaitDialog::onUntilHealedButtonClicked(MyGUI::Widget* sender)
{
int autoHours = MWBase::Environment::get().getMechanicsManager()->getHoursToRest();
startWaiting(autoHours);
}
void WaitDialog::onWaitButtonClicked(MyGUI::Widget* sender)
{
startWaiting(mManualHours);
}
void WaitDialog::startWaiting(int hoursToWait)
{
if (Settings::saves().mAutosave) // autosaves when enabled
MWBase::Environment::get().getStateManager()->quickSave("Autosave");
MWBase::World* world = MWBase::Environment::get().getWorld();
MWBase::Environment::get().getWindowManager()->fadeScreenOut(0.2f);
mFadeTimeRemaining = 0.4f;
setVisible(false);
mHours = hoursToWait;
// FIXME: move this somewhere else?
mInterruptAt = -1;
MWWorld::Ptr player = world->getPlayerPtr();
if (mSleeping && player.getCell()->isExterior())
{
const ESM::RefId& regionstr = player.getCell()->getCell()->getRegion();
if (!regionstr.empty())
{
const ESM::Region* region = world->getStore().get<ESM::Region>().find(regionstr);
if (!region->mSleepList.empty())
{
// figure out if player will be woken while sleeping
int x = Misc::Rng::rollDice(hoursToWait, world->getPrng());
float fSleepRandMod
= world->getStore().get<ESM::GameSetting>().find("fSleepRandMod")->mValue.getFloat();
if (x < fSleepRandMod * hoursToWait)
{
float fSleepRestMod
= world->getStore().get<ESM::GameSetting>().find("fSleepRestMod")->mValue.getFloat();
int interruptAtHoursRemaining = int(fSleepRestMod * hoursToWait);
if (interruptAtHoursRemaining != 0)
{
mInterruptAt = hoursToWait - interruptAtHoursRemaining;
mInterruptCreatureList = region->mSleepList;
}
}
}
}
}
mProgressBar.setProgress(0, hoursToWait);
}
void WaitDialog::onCancelButtonClicked(MyGUI::Widget* sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Rest);
}
void WaitDialog::onHourSliderChangedPosition(MyGUI::ScrollBar* sender, size_t position)
{
mHourText->setCaptionWithReplacing(MyGUI::utility::toString(position + 1) + " #{sRestMenu2}");
mManualHours = position + 1;
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mWaitButton);
}
void WaitDialog::onKeyButtonPressed(MyGUI::Widget* sender, MyGUI::KeyCode key, MyGUI::Char character)
{
if (key == MyGUI::KeyCode::ArrowUp)
mHourSlider->setScrollPosition(
std::min(mHourSlider->getScrollPosition() + 1, mHourSlider->getScrollRange() - 1));
else if (key == MyGUI::KeyCode::ArrowDown)
mHourSlider->setScrollPosition(std::max(static_cast<int>(mHourSlider->getScrollPosition()) - 1, 0));
else
return;
onHourSliderChangedPosition(mHourSlider, mHourSlider->getScrollPosition());
}
void WaitDialog::onWaitingProgressChanged(int cur, int total)
{
mProgressBar.setProgress(cur, total);
MWBase::Environment::get().getMechanicsManager()->rest(1, mSleeping);
MWBase::Environment::get().getWorld()->advanceTime(1);
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
if (player.getClass().getCreatureStats(player).isDead())
stopWaiting();
}
void WaitDialog::onWaitingInterrupted()
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sSleepInterrupt}");
MWBase::Environment::get().getWorld()->spawnRandomCreature(mInterruptCreatureList);
stopWaiting();
}
void WaitDialog::onWaitingFinished()
{
stopWaiting();
MWWorld::Ptr player = MWMechanics::getPlayer();
const MWMechanics::NpcStats& pcstats = player.getClass().getNpcStats(player);
// trigger levelup if possible
const MWWorld::Store<ESM::GameSetting>& gmst
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
if (mSleeping && pcstats.getLevelProgress() >= gmst.find("iLevelUpTotal")->mValue.getInteger())
{
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Levelup);
}
}
void WaitDialog::setCanRest(bool canRest)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
MWMechanics::CreatureStats& stats = player.getClass().getCreatureStats(player);
bool full = (stats.getHealth().getCurrent() >= stats.getHealth().getModified())
&& (stats.getMagicka().getCurrent() >= stats.getMagicka().getModified());
MWMechanics::NpcStats& npcstats = player.getClass().getNpcStats(player);
bool werewolf = npcstats.isWerewolf();
mUntilHealedButton->setVisible(canRest && !full);
mWaitButton->setCaptionWithReplacing(canRest ? "#{sRest}" : "#{sWait}");
mRestText->setCaptionWithReplacing(
canRest ? "#{sRestMenu3}" : (werewolf ? "#{sWerewolfRestMessage}" : "#{sRestIllegal}"));
mSleeping = canRest;
Gui::Box* box = dynamic_cast<Gui::Box*>(mMainWidget);
if (box == nullptr)
throw std::runtime_error("main widget must be a box");
box->notifyChildrenSizeChanged();
center();
}
void WaitDialog::onFrame(float dt)
{
mTimeAdvancer.onFrame(dt);
if (mFadeTimeRemaining <= 0)
return;
mFadeTimeRemaining -= dt;
if (mFadeTimeRemaining <= 0)
{
mProgressBar.setVisible(true);
mTimeAdvancer.run(mHours, mInterruptAt);
}
}
void WaitDialog::stopWaiting()
{
MWBase::Environment::get().getWindowManager()->fadeScreenIn(0.2f);
mProgressBar.setVisible(false);
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Rest);
mTimeAdvancer.stop();
}
void WaitDialog::wakeUp()
{
mSleeping = false;
if (mInterruptAt != -1)
onWaitingInterrupted();
else
stopWaiting();
}
}
| 13,002
|
C++
|
.cpp
| 291
| 35.573883
| 120
| 0.633059
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,489
|
companionwindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/companionwindow.cpp
|
#include "companionwindow.hpp"
#include <cmath>
#include <MyGUI_Button.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_InputManager.h>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/class.hpp"
#include "companionitemmodel.hpp"
#include "countdialog.hpp"
#include "draganddrop.hpp"
#include "itemview.hpp"
#include "messagebox.hpp"
#include "sortfilteritemmodel.hpp"
#include "tooltips.hpp"
#include "widgets.hpp"
namespace
{
int getProfit(const MWWorld::Ptr& actor)
{
const ESM::RefId& script = actor.getClass().getScript(actor);
if (!script.empty())
{
return actor.getRefData().getLocals().getIntVar(script, "minimumprofit");
}
return 0;
}
}
namespace MWGui
{
CompanionWindow::CompanionWindow(DragAndDrop* dragAndDrop, MessageBoxManager* manager)
: WindowBase("openmw_companion_window.layout")
, mSortModel(nullptr)
, mModel(nullptr)
, mSelectedItem(-1)
, mDragAndDrop(dragAndDrop)
, mMessageBoxManager(manager)
{
getWidget(mCloseButton, "CloseButton");
getWidget(mProfitLabel, "ProfitLabel");
getWidget(mEncumbranceBar, "EncumbranceBar");
getWidget(mFilterEdit, "FilterEdit");
getWidget(mItemView, "ItemView");
mItemView->eventBackgroundClicked += MyGUI::newDelegate(this, &CompanionWindow::onBackgroundSelected);
mItemView->eventItemClicked += MyGUI::newDelegate(this, &CompanionWindow::onItemSelected);
mFilterEdit->eventEditTextChange += MyGUI::newDelegate(this, &CompanionWindow::onNameFilterChanged);
mCloseButton->eventMouseButtonClick += MyGUI::newDelegate(this, &CompanionWindow::onCloseButtonClicked);
setCoord(200, 0, 600, 300);
}
void CompanionWindow::onItemSelected(int index)
{
if (mDragAndDrop->mIsOnDragAndDrop)
{
mDragAndDrop->drop(mModel, mItemView);
updateEncumbranceBar();
return;
}
const ItemStack& item = mSortModel->getItem(index);
// We can't take conjured items from a companion actor
if (item.mFlags & ItemStack::Flag_Bound)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sBarterDialog12}");
return;
}
MWWorld::Ptr object = item.mBase;
int count = item.mCount;
bool shift = MyGUI::InputManager::getInstance().isShiftPressed();
if (MyGUI::InputManager::getInstance().isControlPressed())
count = 1;
mSelectedItem = mSortModel->mapToSource(index);
if (count > 1 && !shift)
{
CountDialog* dialog = MWBase::Environment::get().getWindowManager()->getCountDialog();
std::string name{ object.getClass().getName(object) };
name += MWGui::ToolTips::getSoulString(object.getCellRef());
dialog->openCountDialog(name, "#{sTake}", count);
dialog->eventOkClicked.clear();
dialog->eventOkClicked += MyGUI::newDelegate(this, &CompanionWindow::dragItem);
}
else
dragItem(nullptr, count);
}
void CompanionWindow::onNameFilterChanged(MyGUI::EditBox* _sender)
{
mSortModel->setNameFilter(_sender->getCaption());
mItemView->update();
}
void CompanionWindow::dragItem(MyGUI::Widget* sender, int count)
{
mDragAndDrop->startDrag(mSelectedItem, mSortModel, mModel, mItemView, count);
}
void CompanionWindow::onBackgroundSelected()
{
if (mDragAndDrop->mIsOnDragAndDrop)
{
mDragAndDrop->drop(mModel, mItemView);
updateEncumbranceBar();
}
}
void CompanionWindow::setPtr(const MWWorld::Ptr& actor)
{
if (actor.isEmpty() || !actor.getClass().isActor())
throw std::runtime_error("Invalid argument in CompanionWindow::setPtr");
mPtr = actor;
updateEncumbranceBar();
auto model = std::make_unique<CompanionItemModel>(actor);
mModel = model.get();
auto sortModel = std::make_unique<SortFilterItemModel>(std::move(model));
mSortModel = sortModel.get();
mFilterEdit->setCaption({});
mItemView->setModel(std::move(sortModel));
mItemView->resetScrollBars();
setTitle(actor.getClass().getName(actor));
}
void CompanionWindow::onFrame(float dt)
{
checkReferenceAvailable();
updateEncumbranceBar();
}
void CompanionWindow::updateEncumbranceBar()
{
if (mPtr.isEmpty())
return;
float capacity = mPtr.getClass().getCapacity(mPtr);
float encumbrance = mPtr.getClass().getEncumbrance(mPtr);
mEncumbranceBar->setValue(std::ceil(encumbrance), static_cast<int>(capacity));
if (mModel && mModel->hasProfit(mPtr))
{
mProfitLabel->setCaptionWithReplacing("#{sProfitValue} " + MyGUI::utility::toString(getProfit(mPtr)));
}
else
mProfitLabel->setCaption({});
}
void CompanionWindow::onCloseButtonClicked(MyGUI::Widget* _sender)
{
if (exit())
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Companion);
}
bool CompanionWindow::exit()
{
if (mModel && mModel->hasProfit(mPtr) && getProfit(mPtr) < 0)
{
std::vector<std::string> buttons;
buttons.emplace_back("#{sCompanionWarningButtonOne}");
buttons.emplace_back("#{sCompanionWarningButtonTwo}");
mMessageBoxManager->createInteractiveMessageBox("#{sCompanionWarningMessage}", buttons);
mMessageBoxManager->eventButtonPressed
+= MyGUI::newDelegate(this, &CompanionWindow::onMessageBoxButtonClicked);
return false;
}
return true;
}
void CompanionWindow::onMessageBoxButtonClicked(int button)
{
if (button == 0)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Companion);
// Important for Calvus' contract script to work properly
MWBase::Environment::get().getWindowManager()->exitCurrentGuiMode();
}
}
void CompanionWindow::onReferenceUnavailable()
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Companion);
}
void CompanionWindow::resetReference()
{
ReferenceInterface::resetReference();
mItemView->setModel(nullptr);
mModel = nullptr;
mSortModel = nullptr;
}
}
| 6,597
|
C++
|
.cpp
| 173
| 30.196532
| 114
| 0.650501
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,490
|
messagebox.cpp
|
OpenMW_openmw/apps/openmw/mwgui/messagebox.cpp
|
#include "messagebox.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_LanguageManager.h>
#include <MyGUI_RenderManager.h>
#include <MyGUI_UString.h>
#include <components/debug/debuglog.hpp>
#include <components/misc/strings/algorithm.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/inputmanager.hpp"
#include "../mwbase/windowmanager.hpp"
namespace MWGui
{
MessageBoxManager::MessageBoxManager(float timePerChar)
{
mStaticMessageBox = nullptr;
mLastButtonPressed = -1;
mMessageBoxSpeed = timePerChar;
}
MessageBoxManager::~MessageBoxManager()
{
MessageBoxManager::clear();
}
std::size_t MessageBoxManager::getMessagesCount()
{
return mMessageBoxes.size();
}
void MessageBoxManager::clear()
{
if (mInterMessageBoxe)
{
mInterMessageBoxe->setVisible(false);
mInterMessageBoxe.reset();
}
mMessageBoxes.clear();
mStaticMessageBox = nullptr;
mLastButtonPressed = -1;
}
void MessageBoxManager::resetInteractiveMessageBox()
{
if (mInterMessageBoxe)
{
mInterMessageBoxe->setVisible(false);
mInterMessageBoxe.reset();
}
}
void MessageBoxManager::setLastButtonPressed(int index)
{
mLastButtonPressed = index;
}
void MessageBoxManager::onFrame(float frameDuration)
{
for (auto it = mMessageBoxes.begin(); it != mMessageBoxes.end();)
{
(*it)->mCurrentTime += frameDuration;
if ((*it)->mCurrentTime >= (*it)->mMaxTime && it->get() != mStaticMessageBox)
{
it = mMessageBoxes.erase(it);
}
else
++it;
}
float height = 0;
auto it = mMessageBoxes.begin();
while (it != mMessageBoxes.end())
{
(*it)->update(static_cast<int>(height));
height += (*it)->getHeight();
++it;
}
if (mInterMessageBoxe != nullptr && mInterMessageBoxe->mMarkedToDelete)
{
mLastButtonPressed = mInterMessageBoxe->readPressedButton();
mInterMessageBoxe->setVisible(false);
mInterMessageBoxe.reset();
MWBase::Environment::get().getInputManager()->changeInputMode(
MWBase::Environment::get().getWindowManager()->isGuiMode());
}
}
void MessageBoxManager::createMessageBox(std::string_view message, bool stat)
{
auto box = std::make_unique<MessageBox>(*this, message);
box->mCurrentTime = 0;
auto realMessage = MyGUI::LanguageManager::getInstance().replaceTags({ message.data(), message.size() });
box->mMaxTime = realMessage.length() * mMessageBoxSpeed;
if (stat)
mStaticMessageBox = box.get();
box->setVisible(mVisible);
mMessageBoxes.push_back(std::move(box));
if (mMessageBoxes.size() > 3)
{
mMessageBoxes.erase(mMessageBoxes.begin());
}
int height = 0;
for (const auto& messageBox : mMessageBoxes)
{
messageBox->update(height);
height += messageBox->getHeight();
}
}
void MessageBoxManager::removeStaticMessageBox()
{
removeMessageBox(mStaticMessageBox);
mStaticMessageBox = nullptr;
}
bool MessageBoxManager::createInteractiveMessageBox(
std::string_view message, const std::vector<std::string>& buttons, bool immediate, int defaultFocus)
{
if (mInterMessageBoxe != nullptr)
{
Log(Debug::Warning) << "Warning: replacing an interactive message box that was not answered yet";
mInterMessageBoxe->setVisible(false);
}
mInterMessageBoxe
= std::make_unique<InteractiveMessageBox>(*this, std::string{ message }, buttons, immediate, defaultFocus);
mLastButtonPressed = -1;
return true;
}
bool MessageBoxManager::isInteractiveMessageBox()
{
return mInterMessageBoxe != nullptr;
}
bool MessageBoxManager::removeMessageBox(MessageBox* msgbox)
{
for (auto it = mMessageBoxes.begin(); it != mMessageBoxes.end(); ++it)
{
if (it->get() == msgbox)
{
mMessageBoxes.erase(it);
return true;
}
}
return false;
}
const std::vector<std::unique_ptr<MessageBox>>& MessageBoxManager::getActiveMessageBoxes() const
{
return mMessageBoxes;
}
int MessageBoxManager::readPressedButton(bool reset)
{
int pressed = mLastButtonPressed;
if (reset)
mLastButtonPressed = -1;
return pressed;
}
void MessageBoxManager::setVisible(bool value)
{
mVisible = value;
for (const auto& messageBox : mMessageBoxes)
messageBox->setVisible(value);
}
MessageBox::MessageBox(MessageBoxManager& parMessageBoxManager, std::string_view message)
: Layout("openmw_messagebox.layout")
, mCurrentTime(0)
, mMaxTime(0)
, mMessageBoxManager(parMessageBoxManager)
, mMessage(message)
{
// defines
mBottomPadding = 48;
mNextBoxPadding = 4;
getWidget(mMessageWidget, "message");
mMessageWidget->setCaptionWithReplacing(mMessage);
}
void MessageBox::update(int height)
{
MyGUI::IntSize gameWindowSize = MyGUI::RenderManager::getInstance().getViewSize();
MyGUI::IntPoint pos;
pos.left = (gameWindowSize.width - mMainWidget->getWidth()) / 2;
pos.top = (gameWindowSize.height - mMainWidget->getHeight() - height - mBottomPadding);
mMainWidget->setPosition(pos);
}
int MessageBox::getHeight()
{
return mMainWidget->getHeight() + mNextBoxPadding;
}
void MessageBox::setVisible(bool value)
{
mMainWidget->setVisible(value);
}
InteractiveMessageBox::InteractiveMessageBox(MessageBoxManager& parMessageBoxManager, const std::string& message,
const std::vector<std::string>& buttons, bool immediate, int defaultFocus)
: WindowModal(MWBase::Environment::get().getWindowManager()->isGuiMode()
? "openmw_interactive_messagebox_notransp.layout"
: "openmw_interactive_messagebox.layout")
, mMessageBoxManager(parMessageBoxManager)
, mButtonPressed(-1)
, mDefaultFocus(defaultFocus)
, mImmediate(immediate)
{
int textPadding = 10; // padding between text-widget and main-widget
int textButtonPadding = 10; // padding between the text-widget und the button-widget
int buttonLeftPadding = 10; // padding between the buttons if horizontal
int buttonTopPadding = 10; // ^-- if vertical
int buttonLabelLeftPadding = 12; // padding between button label and button itself, from left
int buttonLabelTopPadding = 4; // padding between button label and button itself, from top
int buttonMainPadding = 10; // padding between buttons and bottom of the main widget
mMarkedToDelete = false;
getWidget(mMessageWidget, "message");
getWidget(mButtonsWidget, "buttons");
mMessageWidget->setSize(400, mMessageWidget->getHeight());
mMessageWidget->setCaptionWithReplacing(message);
MyGUI::IntSize textSize = mMessageWidget->getTextSize();
MyGUI::IntSize gameWindowSize = MyGUI::RenderManager::getInstance().getViewSize();
int biggestButtonWidth = 0;
int buttonsWidth = 0;
int buttonsHeight = 0;
int buttonHeight = 0;
MyGUI::IntCoord dummyCoord(0, 0, 0, 0);
for (const std::string& buttonId : buttons)
{
MyGUI::Button* button = mButtonsWidget->createWidget<MyGUI::Button>(
MyGUI::WidgetStyle::Child, std::string("MW_Button"), dummyCoord, MyGUI::Align::Default);
button->setCaptionWithReplacing(buttonId);
button->eventMouseButtonClick += MyGUI::newDelegate(this, &InteractiveMessageBox::mousePressed);
mButtons.push_back(button);
if (buttonsWidth != 0)
buttonsWidth += buttonLeftPadding;
int buttonWidth = button->getTextSize().width + 2 * buttonLabelLeftPadding;
buttonsWidth += buttonWidth;
buttonHeight = button->getTextSize().height + 2 * buttonLabelTopPadding;
if (buttonsHeight != 0)
buttonsHeight += buttonTopPadding;
buttonsHeight += buttonHeight;
if (buttonWidth > biggestButtonWidth)
{
biggestButtonWidth = buttonWidth;
}
}
MyGUI::IntSize mainWidgetSize;
if (buttonsWidth < textSize.width)
{
// on one line
mainWidgetSize.width = textSize.width + 3 * textPadding;
mainWidgetSize.height
= textPadding + textSize.height + textButtonPadding + buttonHeight + buttonMainPadding;
MyGUI::IntSize realSize = mainWidgetSize +
// To account for borders
(mMainWidget->getSize() - mMainWidget->getClientWidget()->getSize());
MyGUI::IntPoint absPos;
absPos.left = (gameWindowSize.width - realSize.width) / 2;
absPos.top = (gameWindowSize.height - realSize.height) / 2;
mMainWidget->setPosition(absPos);
mMainWidget->setSize(realSize);
MyGUI::IntCoord messageWidgetCoord;
messageWidgetCoord.left = (mainWidgetSize.width - textSize.width) / 2;
messageWidgetCoord.top = textPadding;
mMessageWidget->setCoord(messageWidgetCoord);
mMessageWidget->setSize(textSize);
MyGUI::IntCoord buttonCord;
MyGUI::IntSize buttonSize(0, buttonHeight);
int left = (mainWidgetSize.width - buttonsWidth) / 2;
for (MyGUI::Button* button : mButtons)
{
buttonCord.left = left;
buttonCord.top = messageWidgetCoord.top + textSize.height + textButtonPadding;
buttonSize.width = button->getTextSize().width + 2 * buttonLabelLeftPadding;
buttonSize.height = button->getTextSize().height + 2 * buttonLabelTopPadding;
button->setCoord(buttonCord);
button->setSize(buttonSize);
left += buttonSize.width + buttonLeftPadding;
}
}
else
{
// among each other
if (biggestButtonWidth > textSize.width)
{
mainWidgetSize.width = biggestButtonWidth + buttonTopPadding * 2;
}
else
{
mainWidgetSize.width = textSize.width + 3 * textPadding;
}
MyGUI::IntCoord buttonCord;
MyGUI::IntSize buttonSize(0, buttonHeight);
int top = textPadding + textSize.height + textButtonPadding;
for (MyGUI::Button* button : mButtons)
{
buttonSize.width = button->getTextSize().width + buttonLabelLeftPadding * 2;
buttonSize.height = button->getTextSize().height + buttonLabelTopPadding * 2;
buttonCord.top = top;
buttonCord.left = (mainWidgetSize.width - buttonSize.width) / 2;
button->setCoord(buttonCord);
button->setSize(buttonSize);
top += buttonSize.height + buttonTopPadding;
}
mainWidgetSize.height
= textPadding + textSize.height + textButtonPadding + buttonsHeight + buttonMainPadding;
mMainWidget->setSize(mainWidgetSize +
// To account for borders
(mMainWidget->getSize() - mMainWidget->getClientWidget()->getSize()));
MyGUI::IntPoint absPos;
absPos.left = (gameWindowSize.width - mainWidgetSize.width) / 2;
absPos.top = (gameWindowSize.height - mainWidgetSize.height) / 2;
mMainWidget->setPosition(absPos);
MyGUI::IntCoord messageWidgetCoord;
messageWidgetCoord.left = (mainWidgetSize.width - textSize.width) / 2;
messageWidgetCoord.top = textPadding;
messageWidgetCoord.width = textSize.width;
messageWidgetCoord.height = textSize.height;
mMessageWidget->setCoord(messageWidgetCoord);
}
setVisible(true);
}
MyGUI::Widget* InteractiveMessageBox::getDefaultKeyFocus()
{
if (mDefaultFocus >= 0 && mDefaultFocus < static_cast<int>(mButtons.size()))
return mButtons[mDefaultFocus];
auto& languageManager = MyGUI::LanguageManager::getInstance();
std::vector<MyGUI::UString> keywords{ languageManager.replaceTags("#{sOk}"),
languageManager.replaceTags("#{sYes}") };
for (MyGUI::Button* button : mButtons)
{
for (const MyGUI::UString& keyword : keywords)
{
if (Misc::StringUtils::ciEqual(keyword, button->getCaption()))
{
return button;
}
}
}
return nullptr;
}
void InteractiveMessageBox::mousePressed(MyGUI::Widget* pressed)
{
buttonActivated(pressed);
}
void InteractiveMessageBox::buttonActivated(MyGUI::Widget* pressed)
{
mMarkedToDelete = true;
int index = 0;
for (const MyGUI::Button* button : mButtons)
{
if (button == pressed)
{
mButtonPressed = index;
mMessageBoxManager.onButtonPressed(mButtonPressed);
if (!mImmediate)
return;
mMessageBoxManager.setLastButtonPressed(mButtonPressed);
MWBase::Environment::get().getInputManager()->changeInputMode(
MWBase::Environment::get().getWindowManager()->isGuiMode());
return;
}
index++;
}
}
int InteractiveMessageBox::readPressedButton()
{
return mButtonPressed;
}
}
| 14,310
|
C++
|
.cpp
| 353
| 30.311615
| 119
| 0.615523
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,491
|
countdialog.cpp
|
OpenMW_openmw/apps/openmw/mwgui/countdialog.cpp
|
#include "countdialog.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_RenderManager.h>
#include <MyGUI_ScrollBar.h>
#include <components/widgets/numericeditbox.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
namespace MWGui
{
CountDialog::CountDialog()
: WindowModal("openmw_count_window.layout")
{
getWidget(mSlider, "CountSlider");
getWidget(mItemEdit, "ItemEdit");
getWidget(mItemText, "ItemText");
getWidget(mLabelText, "LabelText");
getWidget(mOkButton, "OkButton");
getWidget(mCancelButton, "CancelButton");
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &CountDialog::onCancelButtonClicked);
mOkButton->eventMouseButtonClick += MyGUI::newDelegate(this, &CountDialog::onOkButtonClicked);
mItemEdit->eventValueChanged += MyGUI::newDelegate(this, &CountDialog::onEditValueChanged);
mSlider->eventScrollChangePosition += MyGUI::newDelegate(this, &CountDialog::onSliderMoved);
// make sure we read the enter key being pressed to accept multiple items
mItemEdit->eventEditSelectAccept += MyGUI::newDelegate(this, &CountDialog::onEnterKeyPressed);
}
void CountDialog::openCountDialog(const std::string& item, const std::string& message, const int maxCount)
{
setVisible(true);
mLabelText->setCaptionWithReplacing(message);
MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize();
mSlider->setScrollRange(maxCount);
mItemText->setCaption(item);
int width = std::max(mItemText->getTextSize().width + 160, 320);
setCoord(viewSize.width / 2 - width / 2, viewSize.height / 2 - mMainWidget->getHeight() / 2, width,
mMainWidget->getHeight());
// by default, the text edit field has the focus of the keyboard
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mItemEdit);
mSlider->setScrollPosition(maxCount - 1);
mItemEdit->setMinValue(1);
mItemEdit->setMaxValue(maxCount);
mItemEdit->setValue(maxCount);
}
void CountDialog::onCancelButtonClicked(MyGUI::Widget* _sender)
{
setVisible(false);
}
void CountDialog::onOkButtonClicked(MyGUI::Widget* _sender)
{
eventOkClicked(nullptr, mSlider->getScrollPosition() + 1);
setVisible(false);
}
// essentially duplicating what the OK button does if user presses
// Enter key
void CountDialog::onEnterKeyPressed(MyGUI::EditBox* _sender)
{
eventOkClicked(nullptr, mSlider->getScrollPosition() + 1);
setVisible(false);
// To do not spam onEnterKeyPressed() again and again
MWBase::Environment::get().getWindowManager()->injectKeyRelease(MyGUI::KeyCode::None);
}
void CountDialog::onEditValueChanged(int value)
{
mSlider->setScrollPosition(value - 1);
}
void CountDialog::onSliderMoved(MyGUI::ScrollBar* _sender, size_t _position)
{
mItemEdit->setValue(_position + 1);
}
}
| 3,091
|
C++
|
.cpp
| 69
| 37.942029
| 110
| 0.697535
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,492
|
keyboardnavigation.cpp
|
OpenMW_openmw/apps/openmw/mwgui/keyboardnavigation.cpp
|
#include "keyboardnavigation.hpp"
#include <MyGUI_Gui.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_WidgetManager.h>
#include <MyGUI_Window.h>
#include <components/debug/debuglog.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
namespace MWGui
{
bool shouldAcceptKeyFocus(MyGUI::Widget* w)
{
return w && !w->castType<MyGUI::Window>(false) && w->getInheritedEnabled() && w->getInheritedVisible()
&& w->getVisible() && w->getEnabled();
}
/// Recursively get all child widgets that accept keyboard input
void getKeyFocusWidgets(MyGUI::Widget* parent, std::vector<MyGUI::Widget*>& results)
{
assert(parent != nullptr);
if (!parent->getVisible() || !parent->getEnabled())
return;
MyGUI::EnumeratorWidgetPtr enumerator = parent->getEnumerator();
while (enumerator.next())
{
MyGUI::Widget* w = enumerator.current();
if (!w->getVisible() || !w->getEnabled())
continue;
if (w->getNeedKeyFocus() && shouldAcceptKeyFocus(w))
results.push_back(w);
else
getKeyFocusWidgets(w, results);
}
}
KeyboardNavigation::KeyboardNavigation()
: mCurrentFocus(nullptr)
, mModalWindow(nullptr)
, mEnabled(true)
{
MyGUI::WidgetManager::getInstance().registerUnlinker(this);
}
KeyboardNavigation::~KeyboardNavigation()
{
try
{
MyGUI::WidgetManager::getInstance().unregisterUnlinker(this);
}
catch (const MyGUI::Exception& e)
{
Log(Debug::Error) << "Error in the destructor: " << e.what();
}
}
void KeyboardNavigation::saveFocus(int mode)
{
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
if (shouldAcceptKeyFocus(focus))
{
mKeyFocus[mode] = focus;
}
else if (shouldAcceptKeyFocus(mCurrentFocus))
{
mKeyFocus[mode] = mCurrentFocus;
}
}
void KeyboardNavigation::restoreFocus(int mode)
{
std::map<int, MyGUI::Widget*>::const_iterator found = mKeyFocus.find(mode);
if (found != mKeyFocus.end())
{
MyGUI::Widget* w = found->second;
if (w && w->getVisible() && w->getEnabled() && w->getInheritedVisible() && w->getInheritedEnabled())
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(found->second);
}
}
void KeyboardNavigation::_unlinkWidget(MyGUI::Widget* widget)
{
for (std::pair<const int, MyGUI::Widget*>& w : mKeyFocus)
if (w.second == widget)
w.second = nullptr;
if (widget == mCurrentFocus)
mCurrentFocus = nullptr;
}
bool isRootParent(MyGUI::Widget* widget, MyGUI::Widget* root)
{
while (widget && widget->getParent())
widget = widget->getParent();
return widget == root;
}
void KeyboardNavigation::onFrame()
{
if (!mEnabled)
return;
if (!MWBase::Environment::get().getWindowManager()->isGuiMode())
{
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(nullptr);
return;
}
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
if (focus == mCurrentFocus)
{
return;
}
// workaround incorrect key focus resets (fix in MyGUI TBD)
if (!shouldAcceptKeyFocus(focus) && shouldAcceptKeyFocus(mCurrentFocus)
&& (!mModalWindow || isRootParent(mCurrentFocus, mModalWindow)))
{
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mCurrentFocus);
focus = mCurrentFocus;
}
if (focus != mCurrentFocus)
{
mCurrentFocus = focus;
}
}
void KeyboardNavigation::setDefaultFocus(MyGUI::Widget* window, MyGUI::Widget* defaultFocus)
{
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
if (!focus || !shouldAcceptKeyFocus(focus))
{
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(defaultFocus);
}
else
{
if (!isRootParent(focus, window))
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(defaultFocus);
}
}
void KeyboardNavigation::setModalWindow(MyGUI::Widget* window)
{
mModalWindow = window;
}
void KeyboardNavigation::setEnabled(bool enabled)
{
mEnabled = enabled;
}
enum Direction
{
D_Left,
D_Up,
D_Right,
D_Down,
D_Next,
D_Prev
};
bool KeyboardNavigation::injectKeyPress(MyGUI::KeyCode key, unsigned int text, bool repeat)
{
if (!mEnabled)
return false;
switch (key.getValue())
{
case MyGUI::KeyCode::ArrowLeft:
return switchFocus(D_Left, false);
case MyGUI::KeyCode::ArrowRight:
return switchFocus(D_Right, false);
case MyGUI::KeyCode::ArrowUp:
return switchFocus(D_Up, false);
case MyGUI::KeyCode::ArrowDown:
return switchFocus(D_Down, false);
case MyGUI::KeyCode::Tab:
return switchFocus(MyGUI::InputManager::getInstance().isShiftPressed() ? D_Prev : D_Next, true);
case MyGUI::KeyCode::Period:
return switchFocus(D_Prev, true);
case MyGUI::KeyCode::Slash:
return switchFocus(D_Next, true);
case MyGUI::KeyCode::Return:
case MyGUI::KeyCode::NumpadEnter:
case MyGUI::KeyCode::Space:
{
// We should disable repeating for activation keys
MyGUI::InputManager::getInstance().injectKeyRelease(MyGUI::KeyCode::None);
if (repeat)
return true;
return accept();
}
default:
return false;
}
}
bool KeyboardNavigation::switchFocus(int direction, bool wrap)
{
if (!MWBase::Environment::get().getWindowManager()->isGuiMode())
return false;
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
bool isCycle = (direction == D_Prev || direction == D_Next);
if ((focus && focus->getTypeName().find("Button") == std::string::npos) && !isCycle)
return false;
if (focus && isCycle && focus->getUserString("AcceptTab") == "true")
return false;
if ((!focus || !focus->getNeedKeyFocus()) && isCycle)
{
// if nothing is selected, select the first widget
return selectFirstWidget();
}
if (!focus)
return false;
MyGUI::Widget* window = focus;
while (window && window->getParent())
window = window->getParent();
MyGUI::VectorWidgetPtr keyFocusList;
getKeyFocusWidgets(window, keyFocusList);
if (keyFocusList.empty())
return false;
MyGUI::VectorWidgetPtr::iterator found = std::find(keyFocusList.begin(), keyFocusList.end(), focus);
if (found == keyFocusList.end())
{
if (isCycle)
return selectFirstWidget();
else
return false;
}
bool forward = (direction == D_Next || direction == D_Right || direction == D_Down);
std::ptrdiff_t index{ found - keyFocusList.begin() };
index = forward ? (index + 1) : (index - 1);
if (wrap)
index = (index + keyFocusList.size()) % keyFocusList.size();
else
index = std::clamp<std::ptrdiff_t>(index, 0, keyFocusList.size() - 1);
MyGUI::Widget* next = keyFocusList[index];
int vertdiff = next->getTop() - focus->getTop();
int horizdiff = next->getLeft() - focus->getLeft();
bool isVertical = std::abs(vertdiff) > std::abs(horizdiff);
if (direction == D_Right && (horizdiff <= 0 || isVertical))
return false;
else if (direction == D_Left && (horizdiff >= 0 || isVertical))
return false;
else if (direction == D_Down && (vertdiff <= 0 || !isVertical))
return false;
else if (direction == D_Up && (vertdiff >= 0 || !isVertical))
return false;
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(keyFocusList[index]);
return true;
}
bool KeyboardNavigation::selectFirstWidget()
{
MyGUI::VectorWidgetPtr keyFocusList;
MyGUI::EnumeratorWidgetPtr enumerator = MyGUI::Gui::getInstance().getEnumerator();
if (mModalWindow)
enumerator = mModalWindow->getEnumerator();
while (enumerator.next())
getKeyFocusWidgets(enumerator.current(), keyFocusList);
if (!keyFocusList.empty())
{
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(keyFocusList[0]);
return true;
}
return false;
}
bool KeyboardNavigation::accept()
{
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
if (!focus)
return false;
// MyGUI::Button* button = focus->castType<MyGUI::Button>(false);
// if (button && button->getEnabled())
if (focus->getTypeName().find("Button") != std::string::npos && focus->getEnabled())
{
focus->eventMouseButtonClick(focus);
return true;
}
return false;
}
}
| 9,835
|
C++
|
.cpp
| 261
| 28.038314
| 112
| 0.583526
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,493
|
controllers.cpp
|
OpenMW_openmw/apps/openmw/mwgui/controllers.cpp
|
#include "controllers.hpp"
#include <MyGUI_InputManager.h>
#include <MyGUI_Widget.h>
namespace MWGui
{
namespace Controllers
{
void ControllerFollowMouse::prepareItem(MyGUI::Widget* _widget) {}
bool ControllerFollowMouse::addTime(MyGUI::Widget* _widget, float _time)
{
_widget->setPosition(MyGUI::InputManager::getInstance().getMousePosition());
return true;
}
}
}
| 437
|
C++
|
.cpp
| 15
| 23.333333
| 88
| 0.672249
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,494
|
soulgemdialog.cpp
|
OpenMW_openmw/apps/openmw/mwgui/soulgemdialog.cpp
|
#include "soulgemdialog.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "messagebox.hpp"
namespace MWGui
{
void SoulgemDialog::show(const MWWorld::Ptr& soulgem)
{
mSoulgem = soulgem;
std::vector<std::string> buttons;
buttons.emplace_back("#{sRechargeEnchantment}");
buttons.emplace_back("#{sMake Enchantment}");
mManager->createInteractiveMessageBox("#{sDoYouWantTo}", buttons);
mManager->eventButtonPressed += MyGUI::newDelegate(this, &SoulgemDialog::onButtonPressed);
}
void SoulgemDialog::onButtonPressed(int button)
{
if (button == 0)
{
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Recharge, mSoulgem);
}
else
{
MWBase::Environment::get().getWindowManager()->pushGuiMode(GM_Enchanting, mSoulgem);
}
}
}
| 916
|
C++
|
.cpp
| 27
| 27.37037
| 98
| 0.659117
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,495
|
spellicons.cpp
|
OpenMW_openmw/apps/openmw/mwgui/spellicons.cpp
|
#include "spellicons.hpp"
#include <iomanip>
#include <sstream>
#include <MyGUI_ImageBox.h>
#include <components/esm3/loadmgef.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "tooltips.hpp"
namespace MWGui
{
void SpellIcons::updateWidgets(MyGUI::Widget* parent, bool adjustSize)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
const MWMechanics::CreatureStats& stats = player.getClass().getCreatureStats(player);
std::map<int, std::vector<MagicEffectInfo>> effects;
for (const auto& params : stats.getActiveSpells())
{
for (const auto& effect : params.getEffects())
{
if (!(effect.mFlags & ESM::ActiveEffect::Flag_Applied))
continue;
MagicEffectInfo newEffectSource;
newEffectSource.mKey = MWMechanics::EffectKey(effect.mEffectId, effect.getSkillOrAttribute());
newEffectSource.mMagnitude = static_cast<int>(effect.mMagnitude);
newEffectSource.mPermanent = effect.mDuration == -1.f;
newEffectSource.mRemainingTime = effect.mTimeLeft;
newEffectSource.mSource = params.getDisplayName();
newEffectSource.mTotalTime = effect.mDuration;
effects[effect.mEffectId].push_back(newEffectSource);
}
}
int w = 2;
const auto& store = MWBase::Environment::get().getESMStore();
for (const auto& [effectId, effectInfos] : effects)
{
const ESM::MagicEffect* effect = store->get<ESM::MagicEffect>().find(effectId);
float remainingDuration = 0;
float totalDuration = 0;
std::string sourcesDescription;
static const float fadeTime
= store->get<ESM::GameSetting>().find("fMagicStartIconBlink")->mValue.getFloat();
bool addNewLine = false;
for (const MagicEffectInfo& effectInfo : effectInfos)
{
if (addNewLine)
sourcesDescription += '\n';
// if at least one of the effect sources is permanent, the effect will never wear off
if (effectInfo.mPermanent)
{
remainingDuration = fadeTime;
totalDuration = fadeTime;
}
else
{
remainingDuration = std::max(remainingDuration, effectInfo.mRemainingTime);
totalDuration = std::max(totalDuration, effectInfo.mTotalTime);
}
sourcesDescription += effectInfo.mSource;
if (effect->mData.mFlags & ESM::MagicEffect::TargetSkill)
{
const ESM::Skill* skill = store->get<ESM::Skill>().find(effectInfo.mKey.mArg);
sourcesDescription += " (" + skill->mName + ')';
}
if (effect->mData.mFlags & ESM::MagicEffect::TargetAttribute)
{
const ESM::Attribute* attribute = store->get<ESM::Attribute>().find(effectInfo.mKey.mArg);
sourcesDescription += " (" + attribute->mName + ')';
}
ESM::MagicEffect::MagnitudeDisplayType displayType = effect->getMagnitudeDisplayType();
if (displayType == ESM::MagicEffect::MDT_TimesInt)
{
std::string_view timesInt
= MWBase::Environment::get().getWindowManager()->getGameSettingString("sXTimesINT", {});
std::stringstream formatter;
formatter << std::fixed << std::setprecision(1) << " " << (effectInfo.mMagnitude / 10.0f)
<< timesInt;
sourcesDescription += formatter.str();
}
else if (displayType != ESM::MagicEffect::MDT_None)
{
sourcesDescription += ": " + MyGUI::utility::toString(effectInfo.mMagnitude);
if (displayType == ESM::MagicEffect::MDT_Percentage)
sourcesDescription
+= MWBase::Environment::get().getWindowManager()->getGameSettingString("spercent", {});
else if (displayType == ESM::MagicEffect::MDT_Feet)
{
sourcesDescription += ' ';
sourcesDescription
+= MWBase::Environment::get().getWindowManager()->getGameSettingString("sfeet", {});
}
else if (displayType == ESM::MagicEffect::MDT_Level)
{
sourcesDescription += ' ';
if (effectInfo.mMagnitude > 1)
sourcesDescription
+= MWBase::Environment::get().getWindowManager()->getGameSettingString("sLevels", {});
else
sourcesDescription
+= MWBase::Environment::get().getWindowManager()->getGameSettingString("sLevel", {});
}
else // ESM::MagicEffect::MDT_Points
{
sourcesDescription += ' ';
if (effectInfo.mMagnitude > 1)
sourcesDescription
+= MWBase::Environment::get().getWindowManager()->getGameSettingString("spoints", {});
else
sourcesDescription
+= MWBase::Environment::get().getWindowManager()->getGameSettingString("spoint", {});
}
}
if (effectInfo.mRemainingTime > -1 && Settings::game().mShowEffectDuration)
sourcesDescription
+= MWGui::ToolTips::getDurationString(effectInfo.mRemainingTime, " #{sDuration}");
addNewLine = true;
}
if (remainingDuration > 0.f)
{
MyGUI::ImageBox* image;
if (mWidgetMap.find(effectId) == mWidgetMap.end())
{
image = parent->createWidget<MyGUI::ImageBox>(
"ImageBox", MyGUI::IntCoord(w, 2, 16, 16), MyGUI::Align::Default);
mWidgetMap[effectId] = image;
image->setImageTexture(Misc::ResourceHelpers::correctIconPath(
effect->mIcon, MWBase::Environment::get().getResourceSystem()->getVFS()));
const std::string& name = ESM::MagicEffect::indexToGmstString(effectId);
ToolTipInfo tooltipInfo;
tooltipInfo.caption = "#{" + name + "}";
tooltipInfo.icon = effect->mIcon;
tooltipInfo.imageSize = 16;
tooltipInfo.wordWrap = false;
image->setUserData(tooltipInfo);
image->setUserString("ToolTipType", "ToolTipInfo");
}
else
image = mWidgetMap[effectId];
image->setPosition(w, 2);
image->setVisible(true);
w += 16;
ToolTipInfo* tooltipInfo = image->getUserData<ToolTipInfo>();
tooltipInfo->text = std::move(sourcesDescription);
// Fade out
if (totalDuration >= fadeTime && fadeTime > 0.f)
image->setAlpha(std::min(remainingDuration / fadeTime, 1.f));
}
else if (mWidgetMap.find(effectId) != mWidgetMap.end())
{
MyGUI::ImageBox* image = mWidgetMap[effectId];
image->setVisible(false);
image->setAlpha(1.f);
}
}
if (adjustSize)
{
int s = w + 2;
if (effects.empty())
s = 0;
int diff = parent->getWidth() - s;
parent->setSize(s, parent->getHeight());
parent->setPosition(parent->getLeft() + diff, parent->getTop());
}
// hide inactive effects
for (auto& widgetPair : mWidgetMap)
{
if (effects.find(widgetPair.first) == effects.end())
widgetPair.second->setVisible(false);
}
}
}
| 8,741
|
C++
|
.cpp
| 177
| 33.084746
| 118
| 0.527654
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,496
|
journalviewmodel.cpp
|
OpenMW_openmw/apps/openmw/mwgui/journalviewmodel.cpp
|
#include "journalviewmodel.hpp"
#include <map>
#include <MyGUI_LanguageManager.h>
#include <components/misc/strings/algorithm.hpp>
#include <components/translation/translation.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/journal.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwdialogue/keywordsearch.hpp"
#include "../mwworld/datetimemanager.hpp"
namespace MWGui
{
struct JournalViewModelImpl;
struct JournalViewModelImpl : JournalViewModel
{
typedef MWDialogue::KeywordSearch<intptr_t> KeywordSearchT;
mutable bool mKeywordSearchLoaded;
mutable KeywordSearchT mKeywordSearch;
JournalViewModelImpl() { mKeywordSearchLoaded = false; }
virtual ~JournalViewModelImpl() {}
/// \todo replace this nasty BS
static Utf8Span toUtf8Span(std::string_view str)
{
if (str.size() == 0)
return Utf8Span(Utf8Point(nullptr), Utf8Point(nullptr));
Utf8Point point = reinterpret_cast<Utf8Point>(str.data());
return Utf8Span(point, point + str.size());
}
void load() override {}
void unload() override
{
mKeywordSearch.clear();
mKeywordSearchLoaded = false;
}
void ensureKeyWordSearchLoaded() const
{
if (!mKeywordSearchLoaded)
{
MWBase::Journal* journal = MWBase::Environment::get().getJournal();
for (MWBase::Journal::TTopicIter i = journal->topicBegin(); i != journal->topicEnd(); ++i)
mKeywordSearch.seed(i->second.getName(), intptr_t(&i->second));
mKeywordSearchLoaded = true;
}
}
bool isEmpty() const override
{
MWBase::Journal* journal = MWBase::Environment::get().getJournal();
return journal->begin() == journal->end();
}
template <typename t_iterator, typename Interface>
struct BaseEntry : Interface
{
typedef t_iterator iterator_t;
iterator_t itr;
JournalViewModelImpl const* mModel;
BaseEntry(JournalViewModelImpl const* model, iterator_t itr)
: itr(itr)
, mModel(model)
, loaded(false)
{
}
virtual ~BaseEntry() {}
mutable bool loaded;
mutable std::string utf8text;
typedef std::pair<size_t, size_t> Range;
// hyperlinks in @link# notation
mutable std::map<Range, intptr_t> mHyperLinks;
virtual std::string getText() const = 0;
void ensureLoaded() const
{
if (!loaded)
{
mModel->ensureKeyWordSearchLoaded();
utf8text = getText();
size_t pos_end = 0;
for (;;)
{
size_t pos_begin = utf8text.find('@');
if (pos_begin != std::string::npos)
pos_end = utf8text.find('#', pos_begin);
if (pos_begin != std::string::npos && pos_end != std::string::npos)
{
std::string link = utf8text.substr(pos_begin + 1, pos_end - pos_begin - 1);
const char specialPseudoAsteriskCharacter = 127;
std::replace(link.begin(), link.end(), specialPseudoAsteriskCharacter, '*');
std::string_view topicName = MWBase::Environment::get()
.getWindowManager()
->getTranslationDataStorage()
.topicStandardForm(link);
std::string displayName = link;
while (displayName[displayName.size() - 1] == '*')
displayName.erase(displayName.size() - 1, 1);
utf8text.replace(pos_begin, pos_end + 1 - pos_begin, displayName);
intptr_t value = 0;
if (mModel->mKeywordSearch.containsKeyword(topicName, value))
mHyperLinks[std::make_pair(pos_begin, pos_begin + displayName.size())] = value;
}
else
break;
}
loaded = true;
}
}
Utf8Span body() const override
{
ensureLoaded();
return toUtf8Span(utf8text);
}
void visitSpans(std::function<void(TopicId, size_t, size_t)> visitor) const override
{
ensureLoaded();
mModel->ensureKeyWordSearchLoaded();
if (mHyperLinks.size()
&& MWBase::Environment::get().getWindowManager()->getTranslationDataStorage().hasTranslation())
{
size_t formatted = 0; // points to the first character that is not laid out yet
for (std::map<Range, intptr_t>::const_iterator it = mHyperLinks.begin(); it != mHyperLinks.end();
++it)
{
intptr_t topicId = it->second;
if (formatted < it->first.first)
visitor(0, formatted, it->first.first);
visitor(topicId, it->first.first, it->first.second);
formatted = it->first.second;
}
if (formatted < utf8text.size())
visitor(0, formatted, utf8text.size());
}
else
{
std::vector<KeywordSearchT::Match> matches;
mModel->mKeywordSearch.highlightKeywords(utf8text.begin(), utf8text.end(), matches);
std::string::const_iterator i = utf8text.begin();
for (std::vector<KeywordSearchT::Match>::const_iterator it = matches.begin(); it != matches.end();
++it)
{
const KeywordSearchT::Match& match = *it;
if (i != match.mBeg)
visitor(0, i - utf8text.begin(), match.mBeg - utf8text.begin());
visitor(match.mValue, match.mBeg - utf8text.begin(), match.mEnd - utf8text.begin());
i = match.mEnd;
}
if (i != utf8text.end())
visitor(0, i - utf8text.begin(), utf8text.size());
}
}
};
void visitQuestNames(bool active_only, std::function<void(std::string_view, bool)> visitor) const override
{
MWBase::Journal* journal = MWBase::Environment::get().getJournal();
std::set<std::string, std::less<>> visitedQuests;
// Note that for purposes of the journal GUI, quests are identified by the name, not the ID, so several
// different quest IDs can end up in the same quest log. A quest log should be considered finished
// when any quest ID in that log is finished.
for (MWBase::Journal::TQuestIter i = journal->questBegin(); i != journal->questEnd(); ++i)
{
const MWDialogue::Quest& quest = i->second;
bool isFinished = false;
for (MWBase::Journal::TQuestIter j = journal->questBegin(); j != journal->questEnd(); ++j)
{
if (quest.getName() == j->second.getName() && j->second.isFinished())
isFinished = true;
}
if (active_only && isFinished)
continue;
// Unfortunately Morrowind.esm has no quest names, since the quest book was added with tribunal.
// Note that even with Tribunal, some quests still don't have quest names. I'm assuming those are not
// supposed to appear in the quest book.
if (!quest.getName().empty())
{
// Don't list the same quest name twice
if (visitedQuests.find(quest.getName()) != visitedQuests.end())
continue;
visitor(quest.getName(), isFinished);
visitedQuests.emplace(quest.getName());
}
}
}
template <typename iterator_t>
struct JournalEntryImpl : BaseEntry<iterator_t, JournalEntry>
{
using BaseEntry<iterator_t, JournalEntry>::itr;
mutable std::string timestamp_buffer;
JournalEntryImpl(JournalViewModelImpl const* model, iterator_t itr)
: BaseEntry<iterator_t, JournalEntry>(model, itr)
{
}
std::string getText() const override { return itr->getText(); }
Utf8Span timestamp() const override
{
if (timestamp_buffer.empty())
{
std::string dayStr = MyGUI::LanguageManager::getInstance().replaceTags("#{sDay}");
std::ostringstream os;
os << itr->mDayOfMonth << ' '
<< MWBase::Environment::get().getWorld()->getTimeManager()->getMonthName(itr->mMonth) << " ("
<< dayStr << " " << (itr->mDay) << ')';
timestamp_buffer = os.str();
}
return toUtf8Span(timestamp_buffer);
}
};
void visitJournalEntries(
std::string_view questName, std::function<void(JournalEntry const&)> visitor) const override
{
MWBase::Journal* journal = MWBase::Environment::get().getJournal();
if (!questName.empty())
{
std::vector<MWDialogue::Quest const*> quests;
for (MWBase::Journal::TQuestIter questIt = journal->questBegin(); questIt != journal->questEnd();
++questIt)
{
if (Misc::StringUtils::ciEqual(questIt->second.getName(), questName))
quests.push_back(&questIt->second);
}
for (MWBase::Journal::TEntryIter i = journal->begin(); i != journal->end(); ++i)
{
for (std::vector<MWDialogue::Quest const*>::iterator questIt = quests.begin();
questIt != quests.end(); ++questIt)
{
MWDialogue::Quest const* quest = *questIt;
for (MWDialogue::Topic::TEntryIter j = quest->begin(); j != quest->end(); ++j)
{
if (i->mInfoId == j->mInfoId)
visitor(JournalEntryImpl<MWBase::Journal::TEntryIter>(this, i));
}
}
}
}
else
{
for (MWBase::Journal::TEntryIter i = journal->begin(); i != journal->end(); ++i)
visitor(JournalEntryImpl<MWBase::Journal::TEntryIter>(this, i));
}
}
void visitTopicName(TopicId topicId, std::function<void(Utf8Span)> visitor) const override
{
MWDialogue::Topic const& topic = *reinterpret_cast<MWDialogue::Topic const*>(topicId);
visitor(toUtf8Span(topic.getName()));
}
void visitTopicNamesStartingWith(
Utf8Stream::UnicodeChar character, std::function<void(std::string_view)> visitor) const override
{
MWBase::Journal* journal = MWBase::Environment::get().getJournal();
for (MWBase::Journal::TTopicIter i = journal->topicBegin(); i != journal->topicEnd(); ++i)
{
Utf8Stream stream(i->second.getName());
Utf8Stream::UnicodeChar first = Utf8Stream::toLowerUtf8(stream.peek());
if (first != Utf8Stream::toLowerUtf8(character))
continue;
visitor(i->second.getName());
}
}
struct TopicEntryImpl : BaseEntry<MWDialogue::Topic::TEntryIter, TopicEntry>
{
MWDialogue::Topic const& mTopic;
TopicEntryImpl(JournalViewModelImpl const* model, MWDialogue::Topic const& topic, iterator_t itr)
: BaseEntry(model, itr)
, mTopic(topic)
{
}
std::string getText() const override { return itr->getText(); }
Utf8Span source() const override { return toUtf8Span(itr->mActorName); }
};
void visitTopicEntries(TopicId topicId, std::function<void(TopicEntry const&)> visitor) const override
{
typedef MWDialogue::Topic::TEntryIter iterator_t;
MWDialogue::Topic const& topic = *reinterpret_cast<MWDialogue::Topic const*>(topicId);
for (iterator_t i = topic.begin(); i != topic.end(); ++i)
visitor(TopicEntryImpl(this, topic, i));
}
};
JournalViewModel::Ptr JournalViewModel::create()
{
return std::make_shared<JournalViewModelImpl>();
}
}
| 13,553
|
C++
|
.cpp
| 278
| 32.323741
| 118
| 0.513528
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,497
|
spellwindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/spellwindow.cpp
|
#include "spellwindow.hpp"
#include <MyGUI_EditBox.h>
#include <MyGUI_InputManager.h>
#include <components/esm3/loadbsgn.hpp>
#include <components/esm3/loadrace.hpp>
#include <components/misc/strings/format.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/datetimemanager.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/player.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/spells.hpp"
#include "../mwmechanics/spellutil.hpp"
#include "confirmationdialog.hpp"
#include "spellicons.hpp"
#include "spellview.hpp"
namespace MWGui
{
SpellWindow::SpellWindow(DragAndDrop* drag)
: WindowPinnableBase("openmw_spell_window.layout")
, NoDrop(drag, mMainWidget)
, mSpellView(nullptr)
, mUpdateTimer(0.0f)
{
mSpellIcons = std::make_unique<SpellIcons>();
MyGUI::Widget* deleteButton;
getWidget(deleteButton, "DeleteSpellButton");
getWidget(mSpellView, "SpellView");
getWidget(mEffectBox, "EffectsBox");
getWidget(mFilterEdit, "FilterEdit");
mSpellView->eventSpellClicked += MyGUI::newDelegate(this, &SpellWindow::onModelIndexSelected);
mFilterEdit->eventEditTextChange += MyGUI::newDelegate(this, &SpellWindow::onFilterChanged);
deleteButton->eventMouseButtonClick += MyGUI::newDelegate(this, &SpellWindow::onDeleteClicked);
setCoord(498, 300, 302, 300);
// Adjust the spell filtering widget size because of MyGUI limitations.
int filterWidth = mSpellView->getSize().width - deleteButton->getSize().width - 3;
mFilterEdit->setSize(filterWidth, mFilterEdit->getSize().height);
}
void SpellWindow::onPinToggled()
{
Settings::windows().mSpellsPin.set(mPinned);
MWBase::Environment::get().getWindowManager()->setSpellVisibility(!mPinned);
}
void SpellWindow::onTitleDoubleClicked()
{
if (MyGUI::InputManager::getInstance().isShiftPressed())
MWBase::Environment::get().getWindowManager()->toggleMaximized(this);
else if (!mPinned)
MWBase::Environment::get().getWindowManager()->toggleVisible(GW_Magic);
}
void SpellWindow::onOpen()
{
// Reset the filter focus when opening the window
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
if (focus == mFilterEdit)
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(nullptr);
updateSpells();
}
void SpellWindow::onFrame(float dt)
{
NoDrop::onFrame(dt);
mUpdateTimer += dt;
if (0.5f < mUpdateTimer)
{
mUpdateTimer = 0;
mSpellView->incrementalUpdate();
}
// Update effects if the time is unpaused for any reason (e.g. the window is pinned)
if (!MWBase::Environment::get().getWorld()->getTimeManager()->isPaused())
mSpellIcons->updateWidgets(mEffectBox, false);
}
void SpellWindow::updateSpells()
{
mSpellIcons->updateWidgets(mEffectBox, false);
mSpellView->setModel(new SpellModel(MWMechanics::getPlayer(), mFilterEdit->getCaption()));
}
void SpellWindow::onEnchantedItemSelected(MWWorld::Ptr item, bool alreadyEquipped)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
MWWorld::InventoryStore& store = player.getClass().getInventoryStore(player);
// retrieve ContainerStoreIterator to the item
MWWorld::ContainerStoreIterator it = store.begin();
for (; it != store.end(); ++it)
{
if (*it == item)
{
break;
}
}
if (it == store.end())
throw std::runtime_error("can't find selected item");
// equip, if it can be equipped and is not already equipped
if (!alreadyEquipped && !item.getClass().getEquipmentSlots(item).first.empty())
{
MWBase::Environment::get().getWindowManager()->useItem(item);
// make sure that item was successfully equipped
if (!store.isEquipped(item))
return;
}
store.setSelectedEnchantItem(it);
// to reset WindowManager::mSelectedSpell immediately
MWBase::Environment::get().getWindowManager()->setSelectedEnchantItem(*it);
updateSpells();
}
void SpellWindow::askDeleteSpell(const ESM::RefId& spellId)
{
// delete spell, if allowed
const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().find(spellId);
MWWorld::Ptr player = MWMechanics::getPlayer();
const ESM::RefId& raceId = player.get<ESM::NPC>()->mBase->mRace;
const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(raceId);
// can't delete racial spells, birthsign spells or powers
bool isInherent = race->mPowers.exists(spell->mId) || spell->mData.mType == ESM::Spell::ST_Power;
const ESM::RefId& signId = MWBase::Environment::get().getWorld()->getPlayer().getBirthSign();
if (!isInherent && !signId.empty())
{
const ESM::BirthSign* sign = MWBase::Environment::get().getESMStore()->get<ESM::BirthSign>().find(signId);
isInherent = sign->mPowers.exists(spell->mId);
}
const auto windowManager = MWBase::Environment::get().getWindowManager();
if (isInherent)
{
windowManager->messageBox("#{sDeleteSpellError}");
}
else
{
// ask for confirmation
mSpellToDelete = spellId;
ConfirmationDialog* dialog = windowManager->getConfirmationDialog();
std::string question{ windowManager->getGameSettingString("sQuestionDeleteSpell", "Delete %s?") };
question = Misc::StringUtils::format(question, spell->mName);
dialog->askForConfirmation(question);
dialog->eventOkClicked.clear();
dialog->eventOkClicked += MyGUI::newDelegate(this, &SpellWindow::onDeleteSpellAccept);
dialog->eventCancelClicked.clear();
}
}
void SpellWindow::onModelIndexSelected(SpellModel::ModelIndex index)
{
const Spell& spell = mSpellView->getModel()->getItem(index);
if (spell.mType == Spell::Type_EnchantedItem)
{
onEnchantedItemSelected(spell.mItem, spell.mActive);
}
else
{
if (MyGUI::InputManager::getInstance().isShiftPressed())
askDeleteSpell(spell.mId);
else
onSpellSelected(spell.mId);
}
}
void SpellWindow::onFilterChanged(MyGUI::EditBox* sender)
{
mSpellView->setModel(new SpellModel(MWMechanics::getPlayer(), sender->getCaption()));
}
void SpellWindow::onDeleteClicked(MyGUI::Widget* widget)
{
SpellModel::ModelIndex selected = mSpellView->getModel()->getSelectedIndex();
if (selected < 0)
return;
const Spell& spell = mSpellView->getModel()->getItem(selected);
if (spell.mType != Spell::Type_EnchantedItem)
askDeleteSpell(spell.mId);
}
void SpellWindow::onSpellSelected(const ESM::RefId& spellId)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
MWWorld::InventoryStore& store = player.getClass().getInventoryStore(player);
store.setSelectedEnchantItem(store.end());
MWBase::Environment::get().getWindowManager()->setSelectedSpell(
spellId, int(MWMechanics::getSpellSuccessChance(spellId, player)));
updateSpells();
}
void SpellWindow::onDeleteSpellAccept()
{
MWWorld::Ptr player = MWMechanics::getPlayer();
MWMechanics::CreatureStats& stats = player.getClass().getCreatureStats(player);
MWMechanics::Spells& spells = stats.getSpells();
if (MWBase::Environment::get().getWindowManager()->getSelectedSpell() == mSpellToDelete)
MWBase::Environment::get().getWindowManager()->unsetSelectedSpell();
spells.remove(mSpellToDelete);
updateSpells();
}
void SpellWindow::cycle(bool next)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
if (MWBase::Environment::get().getMechanicsManager()->isAttackingOrSpell(player))
return;
const MWMechanics::CreatureStats& stats = player.getClass().getCreatureStats(player);
if (stats.isParalyzed() || stats.getKnockedDown() || stats.isDead() || stats.getHitRecovery())
return;
mSpellView->setModel(new SpellModel(MWMechanics::getPlayer()));
SpellModel::ModelIndex selected = mSpellView->getModel()->getSelectedIndex();
if (selected < 0)
selected = 0;
selected += next ? 1 : -1;
int itemcount = mSpellView->getModel()->getItemCount();
if (itemcount == 0)
return;
selected = (selected + itemcount) % itemcount;
const Spell& spell = mSpellView->getModel()->getItem(selected);
if (spell.mType == Spell::Type_EnchantedItem)
onEnchantedItemSelected(spell.mItem, spell.mActive);
else
onSpellSelected(spell.mId);
}
}
| 9,520
|
C++
|
.cpp
| 215
| 35.953488
| 118
| 0.653489
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,498
|
savegamedialog.cpp
|
OpenMW_openmw/apps/openmw/mwgui/savegamedialog.cpp
|
#include "savegamedialog.hpp"
#include <iomanip>
#include <sstream>
#include <MyGUI_ComboBox.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_LanguageManager.h>
#include <MyGUI_UString.h>
#include <osg/Texture2D>
#include <osgDB/ReadFile>
#include <components/debug/debuglog.hpp>
#include <components/esm3/loadclas.hpp>
#include <components/files/conversion.hpp>
#include <components/files/memorystream.hpp>
#include <components/l10n/manager.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/misc/timeconvert.hpp>
#include <components/myguiplatform/myguitexture.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/statemanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/datetimemanager.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwstate/character.hpp"
#include "confirmationdialog.hpp"
namespace MWGui
{
SaveGameDialog::SaveGameDialog()
: WindowModal("openmw_savegame_dialog.layout")
, mSaving(true)
, mCurrentCharacter(nullptr)
, mCurrentSlot(nullptr)
{
getWidget(mScreenshot, "Screenshot");
getWidget(mCharacterSelection, "SelectCharacter");
getWidget(mInfoText, "InfoText");
getWidget(mOkButton, "OkButton");
getWidget(mCancelButton, "CancelButton");
getWidget(mDeleteButton, "DeleteButton");
getWidget(mSaveList, "SaveList");
getWidget(mSaveNameEdit, "SaveNameEdit");
mOkButton->eventMouseButtonClick += MyGUI::newDelegate(this, &SaveGameDialog::onOkButtonClicked);
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &SaveGameDialog::onCancelButtonClicked);
mDeleteButton->eventMouseButtonClick += MyGUI::newDelegate(this, &SaveGameDialog::onDeleteButtonClicked);
mCharacterSelection->eventComboChangePosition += MyGUI::newDelegate(this, &SaveGameDialog::onCharacterSelected);
mCharacterSelection->eventComboAccept += MyGUI::newDelegate(this, &SaveGameDialog::onCharacterAccept);
mSaveList->eventListChangePosition += MyGUI::newDelegate(this, &SaveGameDialog::onSlotSelected);
mSaveList->eventListMouseItemActivate += MyGUI::newDelegate(this, &SaveGameDialog::onSlotMouseClick);
mSaveList->eventListSelectAccept += MyGUI::newDelegate(this, &SaveGameDialog::onSlotActivated);
mSaveList->eventKeyButtonPressed += MyGUI::newDelegate(this, &SaveGameDialog::onKeyButtonPressed);
mSaveNameEdit->eventEditSelectAccept += MyGUI::newDelegate(this, &SaveGameDialog::onEditSelectAccept);
mSaveNameEdit->eventEditTextChange += MyGUI::newDelegate(this, &SaveGameDialog::onSaveNameChanged);
// To avoid accidental deletions
mDeleteButton->setNeedKeyFocus(false);
}
void SaveGameDialog::onSlotActivated(MyGUI::ListBox* sender, size_t pos)
{
onSlotSelected(sender, pos);
accept();
}
void SaveGameDialog::onSlotMouseClick(MyGUI::ListBox* sender, size_t pos)
{
onSlotSelected(sender, pos);
if (pos != MyGUI::ITEM_NONE && MyGUI::InputManager::getInstance().isShiftPressed())
confirmDeleteSave();
}
void SaveGameDialog::confirmDeleteSave()
{
ConfirmationDialog* dialog = MWBase::Environment::get().getWindowManager()->getConfirmationDialog();
dialog->askForConfirmation("#{OMWEngine:DeleteGameConfirmation}");
dialog->eventOkClicked.clear();
dialog->eventOkClicked += MyGUI::newDelegate(this, &SaveGameDialog::onDeleteSlotConfirmed);
dialog->eventCancelClicked.clear();
dialog->eventCancelClicked += MyGUI::newDelegate(this, &SaveGameDialog::onDeleteSlotCancel);
}
void SaveGameDialog::onDeleteSlotConfirmed()
{
MWBase::Environment::get().getStateManager()->deleteGame(mCurrentCharacter, mCurrentSlot);
mSaveList->removeItemAt(mSaveList->getIndexSelected());
onSlotSelected(mSaveList, mSaveList->getIndexSelected());
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mSaveList);
if (mSaveList->getItemCount() == 0)
{
size_t previousIndex = mCharacterSelection->getIndexSelected();
mCurrentCharacter = nullptr;
mCharacterSelection->removeItemAt(previousIndex);
if (mCharacterSelection->getItemCount())
{
size_t nextCharacter = std::min(previousIndex, mCharacterSelection->getItemCount() - 1);
mCharacterSelection->setIndexSelected(nextCharacter);
onCharacterSelected(mCharacterSelection, nextCharacter);
}
else
mCharacterSelection->setIndexSelected(MyGUI::ITEM_NONE);
}
}
void SaveGameDialog::onDeleteSlotCancel()
{
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mSaveList);
}
void SaveGameDialog::onSaveNameChanged(MyGUI::EditBox* sender)
{
// This might have previously been a save slot from the list. If so, that is no longer the case
mSaveList->setIndexSelected(MyGUI::ITEM_NONE);
onSlotSelected(mSaveList, MyGUI::ITEM_NONE);
}
void SaveGameDialog::onEditSelectAccept(MyGUI::EditBox* sender)
{
accept();
// To do not spam onEditSelectAccept() again and again
MWBase::Environment::get().getWindowManager()->injectKeyRelease(MyGUI::KeyCode::None);
}
void SaveGameDialog::onClose()
{
mSaveList->setIndexSelected(MyGUI::ITEM_NONE);
WindowModal::onClose();
}
void SaveGameDialog::onOpen()
{
WindowModal::onOpen();
mSaveNameEdit->setCaption({});
if (mSaving)
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mSaveNameEdit);
else
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mSaveList);
center();
mCharacterSelection->setCaption({});
mCharacterSelection->removeAllItems();
mCurrentCharacter = nullptr;
mCurrentSlot = nullptr;
mSaveList->removeAllItems();
onSlotSelected(mSaveList, MyGUI::ITEM_NONE);
MWBase::StateManager* mgr = MWBase::Environment::get().getStateManager();
if (mgr->characterBegin() == mgr->characterEnd())
return;
mCurrentCharacter = mgr->getCurrentCharacter();
const std::string& directory = Settings::saves().mCharacter;
size_t selectedIndex = MyGUI::ITEM_NONE;
for (MWBase::StateManager::CharacterIterator it = mgr->characterBegin(); it != mgr->characterEnd(); ++it)
{
if (it->begin() != it->end())
{
const ESM::SavedGame& signature = it->getSignature();
std::stringstream title;
title << signature.mPlayerName;
// For a custom class, we will not find it in the store (unless we loaded the savegame first).
// Fall back to name stored in savegame header in that case.
std::string_view className;
if (signature.mPlayerClassId.empty())
className = signature.mPlayerClassName;
else
{
// Find the localised name for this class from the store
const ESM::Class* class_
= MWBase::Environment::get().getESMStore()->get<ESM::Class>().search(signature.mPlayerClassId);
if (class_)
className = class_->mName;
else
className = "?"; // From an older savegame format that did not support custom classes properly.
}
title << " (#{OMWEngine:Level} " << signature.mPlayerLevel << " "
<< MyGUI::TextIterator::toTagsString(MyGUI::UString(className)) << ")";
mCharacterSelection->addItem(MyGUI::LanguageManager::getInstance().replaceTags(title.str()));
if (mCurrentCharacter == &*it
|| (!mCurrentCharacter && !mSaving
&& Misc::StringUtils::ciEqual(
directory, Files::pathToUnicodeString(it->begin()->mPath.parent_path().filename()))))
{
mCurrentCharacter = &*it;
selectedIndex = mCharacterSelection->getItemCount() - 1;
}
}
}
mCharacterSelection->setIndexSelected(selectedIndex);
if (selectedIndex == MyGUI::ITEM_NONE)
mCharacterSelection->setCaptionWithReplacing("#{OMWEngine:SelectCharacter}");
fillSaveList();
}
void SaveGameDialog::setLoadOrSave(bool load)
{
mSaving = !load;
mSaveNameEdit->setVisible(!load);
mCharacterSelection->setUserString("Hidden", load ? "false" : "true");
mCharacterSelection->setVisible(load);
mDeleteButton->setUserString("Hidden", load ? "false" : "true");
mDeleteButton->setVisible(load);
if (!load)
{
mCurrentCharacter = MWBase::Environment::get().getStateManager()->getCurrentCharacter();
}
center();
}
void SaveGameDialog::onCancelButtonClicked(MyGUI::Widget* sender)
{
setVisible(false);
}
void SaveGameDialog::onDeleteButtonClicked(MyGUI::Widget* sender)
{
if (mCurrentSlot)
confirmDeleteSave();
}
void SaveGameDialog::onConfirmationGiven()
{
accept(true);
}
void SaveGameDialog::onConfirmationCancel()
{
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mSaveList);
}
void SaveGameDialog::accept(bool reallySure)
{
if (mSaving)
{
// If overwriting an existing slot, ask for confirmation first
if (mCurrentSlot != nullptr && !reallySure)
{
ConfirmationDialog* dialog = MWBase::Environment::get().getWindowManager()->getConfirmationDialog();
dialog->askForConfirmation("#{OMWEngine:OverwriteGameConfirmation}");
dialog->eventOkClicked.clear();
dialog->eventOkClicked += MyGUI::newDelegate(this, &SaveGameDialog::onConfirmationGiven);
dialog->eventCancelClicked.clear();
dialog->eventCancelClicked += MyGUI::newDelegate(this, &SaveGameDialog::onConfirmationCancel);
return;
}
if (mSaveNameEdit->getCaption().empty())
{
MWBase::Environment::get().getWindowManager()->messageBox("#{OMWEngine:EmptySaveNameError}");
return;
}
}
else
{
MWBase::StateManager::State state = MWBase::Environment::get().getStateManager()->getState();
// If game is running, ask for confirmation first
if (state == MWBase::StateManager::State_Running && !reallySure)
{
ConfirmationDialog* dialog = MWBase::Environment::get().getWindowManager()->getConfirmationDialog();
dialog->askForConfirmation("#{OMWEngine:LoadGameConfirmation}");
dialog->eventOkClicked.clear();
dialog->eventOkClicked += MyGUI::newDelegate(this, &SaveGameDialog::onConfirmationGiven);
dialog->eventCancelClicked.clear();
dialog->eventCancelClicked += MyGUI::newDelegate(this, &SaveGameDialog::onConfirmationCancel);
return;
}
}
setVisible(false);
MWBase::Environment::get().getWindowManager()->removeGuiMode(MWGui::GM_MainMenu);
if (mSaving)
{
MWBase::Environment::get().getStateManager()->saveGame(mSaveNameEdit->getCaption(), mCurrentSlot);
}
else
{
assert(mCurrentCharacter && mCurrentSlot);
MWBase::Environment::get().getStateManager()->loadGame(mCurrentCharacter, mCurrentSlot->mPath);
}
}
void SaveGameDialog::onKeyButtonPressed(MyGUI::Widget* _sender, MyGUI::KeyCode key, MyGUI::Char character)
{
if (key == MyGUI::KeyCode::Delete && mCurrentSlot)
confirmDeleteSave();
}
void SaveGameDialog::onOkButtonClicked(MyGUI::Widget* sender)
{
accept();
}
void SaveGameDialog::onCharacterSelected(MyGUI::ComboBox* sender, size_t pos)
{
MWBase::StateManager* mgr = MWBase::Environment::get().getStateManager();
unsigned int i = 0;
const MWState::Character* character = nullptr;
for (MWBase::StateManager::CharacterIterator it = mgr->characterBegin(); it != mgr->characterEnd(); ++it, ++i)
{
if (i == pos)
character = &*it;
}
assert(character && "Can't find selected character");
mCurrentCharacter = character;
mCurrentSlot = nullptr;
fillSaveList();
}
void SaveGameDialog::onCharacterAccept(MyGUI::ComboBox* sender, size_t pos)
{
// Give key focus to save list so we can confirm the selection with Enter
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mSaveList);
}
void SaveGameDialog::fillSaveList()
{
mSaveList->removeAllItems();
if (!mCurrentCharacter)
return;
for (MWState::Character::SlotIterator it = mCurrentCharacter->begin(); it != mCurrentCharacter->end(); ++it)
{
mSaveList->addItem(it->mProfile.mDescription);
}
// When loading, Auto-select the first save, if there is one
if (mSaveList->getItemCount() && !mSaving)
{
mSaveList->setIndexSelected(0);
onSlotSelected(mSaveList, 0);
}
else
onSlotSelected(mSaveList, MyGUI::ITEM_NONE);
}
std::string formatTimeplayed(const double timeInSeconds)
{
auto l10n = MWBase::Environment::get().getL10nManager()->getContext("Interface");
int duration = static_cast<int>(timeInSeconds);
if (duration <= 0)
return l10n->formatMessage("DurationSecond", { "seconds" }, { 0 });
std::string result;
int hours = duration / 3600;
int minutes = (duration / 60) % 60;
int seconds = duration % 60;
if (hours)
result += l10n->formatMessage("DurationHour", { "hours" }, { hours });
if (minutes)
result += l10n->formatMessage("DurationMinute", { "minutes" }, { minutes });
if (seconds)
result += l10n->formatMessage("DurationSecond", { "seconds" }, { seconds });
return result;
}
void SaveGameDialog::onSlotSelected(MyGUI::ListBox* sender, size_t pos)
{
mOkButton->setEnabled(pos != MyGUI::ITEM_NONE || mSaving);
mDeleteButton->setEnabled(pos != MyGUI::ITEM_NONE);
if (pos == MyGUI::ITEM_NONE || !mCurrentCharacter)
{
mCurrentSlot = nullptr;
mInfoText->setCaption({});
mScreenshot->setImageTexture({});
return;
}
if (mSaving)
mSaveNameEdit->setCaption(sender->getItemNameAt(pos));
mCurrentSlot = nullptr;
unsigned int i = 0;
for (MWState::Character::SlotIterator it = mCurrentCharacter->begin(); it != mCurrentCharacter->end();
++it, ++i)
{
if (i == pos)
mCurrentSlot = &*it;
}
if (!mCurrentSlot)
throw std::runtime_error("Can't find selected slot");
std::stringstream text;
text << Misc::fileTimeToString(mCurrentSlot->mTimeStamp, "%Y.%m.%d %T") << "\n";
if (mCurrentSlot->mProfile.mMaximumHealth > 0)
text << "#{OMWEngine:Health} " << static_cast<int>(mCurrentSlot->mProfile.mCurrentHealth) << "/"
<< static_cast<int>(mCurrentSlot->mProfile.mMaximumHealth) << "\n";
text << "#{OMWEngine:Level} " << mCurrentSlot->mProfile.mPlayerLevel << "\n";
text << "#{sCell=" << mCurrentSlot->mProfile.mPlayerCellName << "}\n";
int hour = int(mCurrentSlot->mProfile.mInGameTime.mGameHour);
bool pm = hour >= 12;
if (hour >= 13)
hour -= 12;
if (hour == 0)
hour = 12;
if (mCurrentSlot->mProfile.mCurrentDay > 0)
text << "#{Calendar:day} " << mCurrentSlot->mProfile.mCurrentDay << "\n";
text << mCurrentSlot->mProfile.mInGameTime.mDay << " "
<< MWBase::Environment::get().getWorld()->getTimeManager()->getMonthName(
mCurrentSlot->mProfile.mInGameTime.mMonth)
<< " " << hour << " " << (pm ? "#{Calendar:pm}" : "#{Calendar:am}");
if (mCurrentSlot->mProfile.mTimePlayed > 0)
{
text << "\n"
<< "#{OMWEngine:TimePlayed}: " << formatTimeplayed(mCurrentSlot->mProfile.mTimePlayed);
}
mInfoText->setCaptionWithReplacing(text.str());
// Reset the image for the case we're unable to recover a screenshot
mScreenshotTexture.reset();
mScreenshot->setRenderItemTexture(nullptr);
mScreenshot->getSubWidgetMain()->_setUVSet(MyGUI::FloatRect(0.f, 0.f, 1.f, 1.f));
// Decode screenshot
const std::vector<char>& data = mCurrentSlot->mProfile.mScreenshot;
if (!data.size())
{
Log(Debug::Warning) << "Selected save file '" << Files::pathToUnicodeString(mCurrentSlot->mPath.filename())
<< "' has no savegame screenshot";
return;
}
Files::IMemStream instream(data.data(), data.size());
osgDB::ReaderWriter* readerwriter = osgDB::Registry::instance()->getReaderWriterForExtension("jpg");
if (!readerwriter)
{
Log(Debug::Error) << "Can't open savegame screenshot, no jpg readerwriter found";
return;
}
osgDB::ReaderWriter::ReadResult result = readerwriter->readImage(instream);
if (!result.success())
{
Log(Debug::Error) << "Failed to read savegame screenshot: " << result.message() << " code "
<< result.status();
return;
}
osg::ref_ptr<osg::Texture2D> texture(new osg::Texture2D);
texture->setImage(result.getImage());
texture->setInternalFormat(GL_RGB);
texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
texture->setResizeNonPowerOfTwoHint(false);
texture->setUnRefImageDataAfterApply(true);
mScreenshotTexture = std::make_unique<osgMyGUI::OSGTexture>(texture);
mScreenshot->setRenderItemTexture(mScreenshotTexture.get());
}
}
| 19,069
|
C++
|
.cpp
| 411
| 36.452555
| 120
| 0.630066
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,499
|
birth.cpp
|
OpenMW_openmw/apps/openmw/mwgui/birth.cpp
|
#include "birth.hpp"
#include <MyGUI_Gui.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_ListBox.h>
#include <MyGUI_ScrollView.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadbsgn.hpp>
#include <components/esm3/loadspel.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/player.hpp"
#include "widgets.hpp"
namespace
{
bool sortBirthSigns(const std::pair<ESM::RefId, const ESM::BirthSign*>& left,
const std::pair<ESM::RefId, const ESM::BirthSign*>& right)
{
return left.second->mName.compare(right.second->mName) < 0;
}
}
namespace MWGui
{
BirthDialog::BirthDialog()
: WindowModal("openmw_chargen_birth.layout")
{
// Centre dialog
center();
getWidget(mSpellArea, "SpellArea");
getWidget(mBirthImage, "BirthsignImage");
getWidget(mBirthList, "BirthsignList");
mBirthList->setScrollVisible(true);
mBirthList->eventListSelectAccept += MyGUI::newDelegate(this, &BirthDialog::onAccept);
mBirthList->eventListChangePosition += MyGUI::newDelegate(this, &BirthDialog::onSelectBirth);
MyGUI::Button* backButton;
getWidget(backButton, "BackButton");
backButton->eventMouseButtonClick += MyGUI::newDelegate(this, &BirthDialog::onBackClicked);
MyGUI::Button* okButton;
getWidget(okButton, "OKButton");
okButton->setCaption(
MyGUI::UString(MWBase::Environment::get().getWindowManager()->getGameSettingString("sOK", {})));
okButton->eventMouseButtonClick += MyGUI::newDelegate(this, &BirthDialog::onOkClicked);
updateBirths();
updateSpells();
}
void BirthDialog::setNextButtonShow(bool shown)
{
MyGUI::Button* okButton;
getWidget(okButton, "OKButton");
if (shown)
okButton->setCaption(
MyGUI::UString(MWBase::Environment::get().getWindowManager()->getGameSettingString("sNext", {})));
else
okButton->setCaption(
MyGUI::UString(MWBase::Environment::get().getWindowManager()->getGameSettingString("sOK", {})));
}
void BirthDialog::onOpen()
{
WindowModal::onOpen();
updateBirths();
updateSpells();
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mBirthList);
// Show the current birthsign by default
const auto& signId = MWBase::Environment::get().getWorld()->getPlayer().getBirthSign();
if (!signId.empty())
setBirthId(signId);
}
void BirthDialog::setBirthId(const ESM::RefId& birthId)
{
mCurrentBirthId = birthId;
mBirthList->setIndexSelected(MyGUI::ITEM_NONE);
size_t count = mBirthList->getItemCount();
for (size_t i = 0; i < count; ++i)
{
if (*mBirthList->getItemDataAt<ESM::RefId>(i) == birthId)
{
mBirthList->setIndexSelected(i);
break;
}
}
updateSpells();
}
// widget controls
void BirthDialog::onOkClicked(MyGUI::Widget* _sender)
{
if (mBirthList->getIndexSelected() == MyGUI::ITEM_NONE)
return;
eventDone(this);
}
void BirthDialog::onAccept(MyGUI::ListBox* _sender, size_t _index)
{
onSelectBirth(_sender, _index);
if (mBirthList->getIndexSelected() == MyGUI::ITEM_NONE)
return;
eventDone(this);
}
void BirthDialog::onBackClicked(MyGUI::Widget* _sender)
{
eventBack();
}
void BirthDialog::onSelectBirth(MyGUI::ListBox* _sender, size_t _index)
{
if (_index == MyGUI::ITEM_NONE)
return;
const ESM::RefId& birthId = *mBirthList->getItemDataAt<ESM::RefId>(_index);
if (mCurrentBirthId == birthId)
return;
mCurrentBirthId = birthId;
updateSpells();
}
// update widget content
void BirthDialog::updateBirths()
{
mBirthList->removeAllItems();
const MWWorld::Store<ESM::BirthSign>& signs = MWBase::Environment::get().getESMStore()->get<ESM::BirthSign>();
// sort by name
std::vector<std::pair<ESM::RefId, const ESM::BirthSign*>> birthSigns;
for (const ESM::BirthSign& sign : signs)
{
birthSigns.emplace_back(sign.mId, &sign);
}
std::sort(birthSigns.begin(), birthSigns.end(), sortBirthSigns);
int index = 0;
for (auto& birthsignPair : birthSigns)
{
mBirthList->addItem(birthsignPair.second->mName, birthsignPair.first);
if (mCurrentBirthId.empty())
{
mBirthList->setIndexSelected(index);
mCurrentBirthId = birthsignPair.first;
}
else if (birthsignPair.first == mCurrentBirthId)
{
mBirthList->setIndexSelected(index);
}
index++;
}
}
void BirthDialog::updateSpells()
{
for (MyGUI::Widget* widget : mSpellItems)
{
MyGUI::Gui::getInstance().destroyWidget(widget);
}
mSpellItems.clear();
if (mCurrentBirthId.empty())
return;
Widgets::MWSpellPtr spellWidget;
const int lineHeight = Settings::gui().mFontSize + 2;
MyGUI::IntCoord coord(0, 0, mSpellArea->getWidth(), lineHeight);
const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore();
const ESM::BirthSign* birth = store.get<ESM::BirthSign>().find(mCurrentBirthId);
mBirthImage->setImageTexture(Misc::ResourceHelpers::correctTexturePath(
birth->mTexture, MWBase::Environment::get().getResourceSystem()->getVFS()));
std::vector<ESM::RefId> abilities, powers, spells;
std::vector<ESM::RefId>::const_iterator it = birth->mPowers.mList.begin();
std::vector<ESM::RefId>::const_iterator end = birth->mPowers.mList.end();
for (; it != end; ++it)
{
const ESM::RefId& spellId = *it;
const ESM::Spell* spell = store.get<ESM::Spell>().search(spellId);
if (!spell)
continue; // Skip spells which cannot be found
ESM::Spell::SpellType type = static_cast<ESM::Spell::SpellType>(spell->mData.mType);
if (type != ESM::Spell::ST_Spell && type != ESM::Spell::ST_Ability && type != ESM::Spell::ST_Power)
continue; // We only want spell, ability and powers.
if (type == ESM::Spell::ST_Ability)
abilities.push_back(spellId);
else if (type == ESM::Spell::ST_Power)
powers.push_back(spellId);
else if (type == ESM::Spell::ST_Spell)
spells.push_back(spellId);
}
int i = 0;
struct
{
const std::vector<ESM::RefId>& spells;
std::string_view label;
} categories[3] = { { abilities, "sBirthsignmenu1" }, { powers, "sPowers" }, { spells, "sBirthsignmenu2" } };
for (size_t category = 0; category < 3; ++category)
{
if (!categories[category].spells.empty())
{
MyGUI::TextBox* label
= mSpellArea->createWidget<MyGUI::TextBox>("SandBrightText", coord, MyGUI::Align::Default, "Label");
label->setCaption(MyGUI::UString(MWBase::Environment::get().getWindowManager()->getGameSettingString(
categories[category].label, {})));
mSpellItems.push_back(label);
coord.top += lineHeight;
end = categories[category].spells.end();
for (it = categories[category].spells.begin(); it != end; ++it)
{
const ESM::RefId& spellId = *it;
spellWidget = mSpellArea->createWidget<Widgets::MWSpell>(
"MW_StatName", coord, MyGUI::Align::Default, "Spell" + MyGUI::utility::toString(i));
spellWidget->setSpellId(spellId);
mSpellItems.push_back(spellWidget);
coord.top += lineHeight;
MyGUI::IntCoord spellCoord = coord;
spellCoord.height = 24; // TODO: This should be fetched from the skin somehow, or perhaps a widget
// in the layout as a template?
spellWidget->createEffectWidgets(
mSpellItems, mSpellArea, spellCoord, (category == 0) ? Widgets::MWEffectList::EF_Constant : 0);
coord.top = spellCoord.top;
++i;
}
}
}
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
// scrollbar is hidden
mSpellArea->setVisibleVScroll(false);
mSpellArea->setCanvasSize(MyGUI::IntSize(mSpellArea->getWidth(), std::max(mSpellArea->getHeight(), coord.top)));
mSpellArea->setVisibleVScroll(true);
mSpellArea->setViewOffset(MyGUI::IntPoint(0, 0));
}
}
| 9,370
|
C++
|
.cpp
| 220
| 32.472727
| 120
| 0.600594
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,500
|
inventorywindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/inventorywindow.cpp
|
#include "inventorywindow.hpp"
#include <cmath>
#include <stdexcept>
#include <MyGUI_Button.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_RenderManager.h>
#include <MyGUI_Window.h>
#include <osg/Texture2D>
#include <components/misc/strings/algorithm.hpp>
#include <components/myguiplatform/myguitexture.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/luamanager.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/action.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "countdialog.hpp"
#include "draganddrop.hpp"
#include "inventoryitemmodel.hpp"
#include "itemview.hpp"
#include "settings.hpp"
#include "sortfilteritemmodel.hpp"
#include "tooltips.hpp"
#include "tradeitemmodel.hpp"
#include "tradewindow.hpp"
namespace
{
bool isRightHandWeapon(const MWWorld::Ptr& item)
{
if (item.getClass().getType() != ESM::Weapon::sRecordId)
return false;
std::vector<int> equipmentSlots = item.getClass().getEquipmentSlots(item).first;
return (!equipmentSlots.empty() && equipmentSlots.front() == MWWorld::InventoryStore::Slot_CarriedRight);
}
}
namespace MWGui
{
namespace
{
WindowSettingValues getModeSettings(GuiMode mode)
{
switch (mode)
{
case GM_Container:
return makeInventoryContainerWindowSettingValues();
case GM_Companion:
return makeInventoryCompanionWindowSettingValues();
case GM_Barter:
return makeInventoryBarterWindowSettingValues();
default:
return makeInventoryWindowSettingValues();
}
}
}
InventoryWindow::InventoryWindow(
DragAndDrop* dragAndDrop, osg::Group* parent, Resource::ResourceSystem* resourceSystem)
: WindowPinnableBase("openmw_inventory_window.layout")
, mDragAndDrop(dragAndDrop)
, mSelectedItem(-1)
, mSortModel(nullptr)
, mTradeModel(nullptr)
, mGuiMode(GM_Inventory)
, mLastXSize(0)
, mLastYSize(0)
, mPreview(std::make_unique<MWRender::InventoryPreview>(parent, resourceSystem, MWMechanics::getPlayer()))
, mTrading(false)
, mUpdateTimer(0.f)
{
mPreviewTexture
= std::make_unique<osgMyGUI::OSGTexture>(mPreview->getTexture(), mPreview->getTextureStateSet());
mPreview->rebuild();
mMainWidget->castType<MyGUI::Window>()->eventWindowChangeCoord
+= MyGUI::newDelegate(this, &InventoryWindow::onWindowResize);
getWidget(mAvatar, "Avatar");
getWidget(mAvatarImage, "AvatarImage");
getWidget(mEncumbranceBar, "EncumbranceBar");
getWidget(mFilterAll, "AllButton");
getWidget(mFilterWeapon, "WeaponButton");
getWidget(mFilterApparel, "ApparelButton");
getWidget(mFilterMagic, "MagicButton");
getWidget(mFilterMisc, "MiscButton");
getWidget(mLeftPane, "LeftPane");
getWidget(mRightPane, "RightPane");
getWidget(mArmorRating, "ArmorRating");
getWidget(mFilterEdit, "FilterEdit");
mAvatarImage->eventMouseButtonClick += MyGUI::newDelegate(this, &InventoryWindow::onAvatarClicked);
mAvatarImage->setRenderItemTexture(mPreviewTexture.get());
mAvatarImage->getSubWidgetMain()->_setUVSet(MyGUI::FloatRect(0.f, 0.f, 1.f, 1.f));
getWidget(mItemView, "ItemView");
mItemView->eventItemClicked += MyGUI::newDelegate(this, &InventoryWindow::onItemSelected);
mItemView->eventBackgroundClicked += MyGUI::newDelegate(this, &InventoryWindow::onBackgroundSelected);
mFilterAll->eventMouseButtonClick += MyGUI::newDelegate(this, &InventoryWindow::onFilterChanged);
mFilterWeapon->eventMouseButtonClick += MyGUI::newDelegate(this, &InventoryWindow::onFilterChanged);
mFilterApparel->eventMouseButtonClick += MyGUI::newDelegate(this, &InventoryWindow::onFilterChanged);
mFilterMagic->eventMouseButtonClick += MyGUI::newDelegate(this, &InventoryWindow::onFilterChanged);
mFilterMisc->eventMouseButtonClick += MyGUI::newDelegate(this, &InventoryWindow::onFilterChanged);
mFilterEdit->eventEditTextChange += MyGUI::newDelegate(this, &InventoryWindow::onNameFilterChanged);
mFilterAll->setStateSelected(true);
setGuiMode(mGuiMode);
adjustPanes();
}
void InventoryWindow::adjustPanes()
{
const float aspect = 0.5; // fixed aspect ratio for the avatar image
int leftPaneWidth = static_cast<int>((mMainWidget->getSize().height - 44 - mArmorRating->getHeight()) * aspect);
mLeftPane->setSize(leftPaneWidth, mMainWidget->getSize().height - 44);
mRightPane->setCoord(mLeftPane->getPosition().left + leftPaneWidth + 4, mRightPane->getPosition().top,
mMainWidget->getSize().width - 12 - leftPaneWidth - 15, mMainWidget->getSize().height - 44);
}
void InventoryWindow::updatePlayer()
{
mPtr = MWBase::Environment::get().getWorld()->getPlayerPtr();
auto tradeModel = std::make_unique<TradeItemModel>(std::make_unique<InventoryItemModel>(mPtr), MWWorld::Ptr());
mTradeModel = tradeModel.get();
if (mSortModel) // reuse existing SortModel when possible to keep previous category/filter settings
mSortModel->setSourceModel(std::move(tradeModel));
else
{
auto sortModel = std::make_unique<SortFilterItemModel>(std::move(tradeModel));
mSortModel = sortModel.get();
mItemView->setModel(std::move(sortModel));
}
mSortModel->setNameFilter(mFilterEdit->getCaption());
mFilterAll->setStateSelected(true);
mFilterWeapon->setStateSelected(false);
mFilterApparel->setStateSelected(false);
mFilterMagic->setStateSelected(false);
mFilterMisc->setStateSelected(false);
mPreview->updatePtr(mPtr);
mPreview->rebuild();
mPreview->update();
dirtyPreview();
updatePreviewSize();
updateEncumbranceBar();
mItemView->update();
notifyContentChanged();
}
void InventoryWindow::clear()
{
mPtr = MWWorld::Ptr();
mTradeModel = nullptr;
mSortModel = nullptr;
mItemView->setModel(nullptr);
}
void InventoryWindow::toggleMaximized()
{
const WindowSettingValues settings = getModeSettings(mGuiMode);
const WindowRectSettingValues& rect = settings.mIsMaximized ? settings.mRegular : settings.mMaximized;
MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize();
const float x = rect.mX * viewSize.width;
const float y = rect.mY * viewSize.height;
const float w = rect.mW * viewSize.width;
const float h = rect.mH * viewSize.height;
MyGUI::Window* window = mMainWidget->castType<MyGUI::Window>();
window->setCoord(x, y, w, h);
settings.mIsMaximized.set(!settings.mIsMaximized);
adjustPanes();
updatePreviewSize();
}
void InventoryWindow::setGuiMode(GuiMode mode)
{
mGuiMode = mode;
const WindowSettingValues settings = getModeSettings(mGuiMode);
setPinButtonVisible(mode == GM_Inventory);
const WindowRectSettingValues& rect = settings.mIsMaximized ? settings.mMaximized : settings.mRegular;
MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize();
MyGUI::IntPoint pos(static_cast<int>(rect.mX * viewSize.width), static_cast<int>(rect.mY * viewSize.height));
MyGUI::IntSize size(static_cast<int>(rect.mW * viewSize.width), static_cast<int>(rect.mH * viewSize.height));
bool needUpdate = (size.width != mMainWidget->getWidth() || size.height != mMainWidget->getHeight());
mMainWidget->setPosition(pos);
mMainWidget->setSize(size);
adjustPanes();
if (needUpdate)
updatePreviewSize();
}
SortFilterItemModel* InventoryWindow::getSortFilterModel()
{
return mSortModel;
}
TradeItemModel* InventoryWindow::getTradeModel()
{
return mTradeModel;
}
ItemModel* InventoryWindow::getModel()
{
return mTradeModel;
}
void InventoryWindow::onBackgroundSelected()
{
if (mDragAndDrop->mIsOnDragAndDrop)
mDragAndDrop->drop(mTradeModel, mItemView);
}
void InventoryWindow::onItemSelected(int index)
{
onItemSelectedFromSourceModel(mSortModel->mapToSource(index));
}
void InventoryWindow::onItemSelectedFromSourceModel(int index)
{
if (mDragAndDrop->mIsOnDragAndDrop)
{
mDragAndDrop->drop(mTradeModel, mItemView);
return;
}
const ItemStack& item = mTradeModel->getItem(index);
const ESM::RefId& sound = item.mBase.getClass().getDownSoundId(item.mBase);
MWWorld::Ptr object = item.mBase;
int count = item.mCount;
bool shift = MyGUI::InputManager::getInstance().isShiftPressed();
if (MyGUI::InputManager::getInstance().isControlPressed())
count = 1;
if (mTrading)
{
// Can't give conjured items to a merchant
if (item.mFlags & ItemStack::Flag_Bound)
{
MWBase::Environment::get().getWindowManager()->playSound(sound);
MWBase::Environment::get().getWindowManager()->messageBox("#{sBarterDialog9}");
return;
}
// check if merchant accepts item
int services = MWBase::Environment::get().getWindowManager()->getTradeWindow()->getMerchantServices();
if (!object.getClass().canSell(object, services))
{
MWBase::Environment::get().getWindowManager()->playSound(sound);
MWBase::Environment::get().getWindowManager()->messageBox("#{sBarterDialog4}");
return;
}
}
// If we unequip weapon during attack, it can lead to unexpected behaviour
if (MWBase::Environment::get().getMechanicsManager()->isAttackingOrSpell(mPtr))
{
bool isWeapon = item.mBase.getType() == ESM::Weapon::sRecordId;
MWWorld::InventoryStore& invStore = mPtr.getClass().getInventoryStore(mPtr);
if (isWeapon && invStore.isEquipped(item.mBase))
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sCantEquipWeapWarning}");
return;
}
}
if (count > 1 && !shift)
{
CountDialog* dialog = MWBase::Environment::get().getWindowManager()->getCountDialog();
std::string message = mTrading ? "#{sQuanityMenuMessage01}" : "#{sTake}";
std::string name{ object.getClass().getName(object) };
name += MWGui::ToolTips::getSoulString(object.getCellRef());
dialog->openCountDialog(name, message, count);
dialog->eventOkClicked.clear();
if (mTrading)
dialog->eventOkClicked += MyGUI::newDelegate(this, &InventoryWindow::sellItem);
else
dialog->eventOkClicked += MyGUI::newDelegate(this, &InventoryWindow::dragItem);
mSelectedItem = index;
}
else
{
mSelectedItem = index;
if (mTrading)
sellItem(nullptr, count);
else
dragItem(nullptr, count);
}
}
void InventoryWindow::ensureSelectedItemUnequipped(int count)
{
const ItemStack& item = mTradeModel->getItem(mSelectedItem);
if (item.mType == ItemStack::Type_Equipped)
{
MWWorld::InventoryStore& invStore = mPtr.getClass().getInventoryStore(mPtr);
MWWorld::Ptr newStack = *invStore.unequipItemQuantity(item.mBase, count);
// The unequipped item was re-stacked. We have to update the index
// since the item pointed does not exist anymore.
if (item.mBase != newStack)
{
updateItemView(); // Unequipping can produce a new stack, not yet in the window...
// newIndex will store the index of the ItemStack the item was stacked on
int newIndex = -1;
for (size_t i = 0; i < mTradeModel->getItemCount(); ++i)
{
if (mTradeModel->getItem(i).mBase == newStack)
{
newIndex = i;
break;
}
}
if (newIndex == -1)
throw std::runtime_error("Can't find restacked item");
mSelectedItem = newIndex;
}
}
}
void InventoryWindow::dragItem(MyGUI::Widget* sender, int count)
{
ensureSelectedItemUnequipped(count);
mDragAndDrop->startDrag(mSelectedItem, mSortModel, mTradeModel, mItemView, count);
notifyContentChanged();
}
void InventoryWindow::sellItem(MyGUI::Widget* sender, int count)
{
ensureSelectedItemUnequipped(count);
const ItemStack& item = mTradeModel->getItem(mSelectedItem);
const ESM::RefId& sound = item.mBase.getClass().getUpSoundId(item.mBase);
MWBase::Environment::get().getWindowManager()->playSound(sound);
if (item.mType == ItemStack::Type_Barter)
{
// this was an item borrowed to us by the merchant
mTradeModel->returnItemBorrowedToUs(mSelectedItem, count);
MWBase::Environment::get().getWindowManager()->getTradeWindow()->returnItem(mSelectedItem, count);
}
else
{
// borrow item to the merchant
mTradeModel->borrowItemFromUs(mSelectedItem, count);
MWBase::Environment::get().getWindowManager()->getTradeWindow()->borrowItem(mSelectedItem, count);
}
mItemView->update();
notifyContentChanged();
}
void InventoryWindow::updateItemView()
{
MWBase::Environment::get().getWindowManager()->updateSpellWindow();
mItemView->update();
dirtyPreview();
}
void InventoryWindow::onOpen()
{
// Reset the filter focus when opening the window
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
if (focus == mFilterEdit)
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(nullptr);
if (!mPtr.isEmpty())
{
updateEncumbranceBar();
mItemView->update();
notifyContentChanged();
}
adjustPanes();
}
void InventoryWindow::onWindowResize(MyGUI::Window* _sender)
{
WindowBase::clampWindowCoordinates(_sender);
adjustPanes();
const WindowSettingValues settings = getModeSettings(mGuiMode);
MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize();
settings.mRegular.mX.set(_sender->getPosition().left / static_cast<float>(viewSize.width));
settings.mRegular.mY.set(_sender->getPosition().top / static_cast<float>(viewSize.height));
settings.mRegular.mW.set(_sender->getSize().width / static_cast<float>(viewSize.width));
settings.mRegular.mH.set(_sender->getSize().height / static_cast<float>(viewSize.height));
settings.mIsMaximized.set(false);
if (mMainWidget->getSize().width != mLastXSize || mMainWidget->getSize().height != mLastYSize)
{
mLastXSize = mMainWidget->getSize().width;
mLastYSize = mMainWidget->getSize().height;
updatePreviewSize();
updateArmorRating();
}
}
void InventoryWindow::updateArmorRating()
{
if (mPtr.isEmpty())
return;
mArmorRating->setCaptionWithReplacing(
"#{sArmor}: " + MyGUI::utility::toString(static_cast<int>(mPtr.getClass().getArmorRating(mPtr))));
if (mArmorRating->getTextSize().width > mArmorRating->getSize().width)
mArmorRating->setCaptionWithReplacing(
MyGUI::utility::toString(static_cast<int>(mPtr.getClass().getArmorRating(mPtr))));
}
void InventoryWindow::updatePreviewSize()
{
const MyGUI::IntSize viewport = getPreviewViewportSize();
mPreview->setViewport(viewport.width, viewport.height);
mAvatarImage->getSubWidgetMain()->_setUVSet(
MyGUI::FloatRect(0.f, 0.f, viewport.width / float(mPreview->getTextureWidth()),
viewport.height / float(mPreview->getTextureHeight())));
}
void InventoryWindow::onNameFilterChanged(MyGUI::EditBox* _sender)
{
mSortModel->setNameFilter(_sender->getCaption());
mItemView->update();
}
void InventoryWindow::onFilterChanged(MyGUI::Widget* _sender)
{
if (_sender == mFilterAll)
mSortModel->setCategory(SortFilterItemModel::Category_All);
else if (_sender == mFilterWeapon)
mSortModel->setCategory(SortFilterItemModel::Category_Weapon);
else if (_sender == mFilterApparel)
mSortModel->setCategory(SortFilterItemModel::Category_Apparel);
else if (_sender == mFilterMagic)
mSortModel->setCategory(SortFilterItemModel::Category_Magic);
else if (_sender == mFilterMisc)
mSortModel->setCategory(SortFilterItemModel::Category_Misc);
mFilterAll->setStateSelected(false);
mFilterWeapon->setStateSelected(false);
mFilterApparel->setStateSelected(false);
mFilterMagic->setStateSelected(false);
mFilterMisc->setStateSelected(false);
mItemView->update();
_sender->castType<MyGUI::Button>()->setStateSelected(true);
}
void InventoryWindow::onPinToggled()
{
Settings::windows().mInventoryPin.set(mPinned);
MWBase::Environment::get().getWindowManager()->setWeaponVisibility(!mPinned);
}
void InventoryWindow::onTitleDoubleClicked()
{
if (MyGUI::InputManager::getInstance().isShiftPressed())
toggleMaximized();
else if (!mPinned)
MWBase::Environment::get().getWindowManager()->toggleVisible(GW_Inventory);
}
void InventoryWindow::useItem(const MWWorld::Ptr& ptr, bool force)
{
const ESM::RefId& script = ptr.getClass().getScript(ptr);
if (!script.empty())
{
// Don't try to equip the item if PCSkipEquip is set to 1
if (ptr.getRefData().getLocals().getIntVar(script, "pcskipequip") == 1)
{
ptr.getRefData().getLocals().setVarByInt(script, "onpcequip", 1);
return;
}
ptr.getRefData().getLocals().setVarByInt(script, "onpcequip", 0);
}
MWWorld::Ptr player = MWMechanics::getPlayer();
// early-out for items that need to be equipped, but can't be equipped: we don't want to set OnPcEquip in that
// case
if (!ptr.getClass().getEquipmentSlots(ptr).first.empty())
{
if (ptr.getClass().hasItemHealth(ptr) && ptr.getCellRef().getCharge() == 0)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sInventoryMessage1}");
updateItemView();
return;
}
if (!force)
{
auto canEquip = ptr.getClass().canBeEquipped(ptr, player);
if (canEquip.first == 0)
{
MWBase::Environment::get().getWindowManager()->messageBox(canEquip.second);
updateItemView();
return;
}
}
}
// If the item has a script, set OnPCEquip or PCSkipEquip to 1
if (!script.empty())
{
// Ingredients, books and repair hammers must not have OnPCEquip set to 1 here
auto type = ptr.getType();
bool isBook = type == ESM::Book::sRecordId;
if (!isBook && type != ESM::Ingredient::sRecordId && type != ESM::Repair::sRecordId)
ptr.getRefData().getLocals().setVarByInt(script, "onpcequip", 1);
// Books must have PCSkipEquip set to 1 instead
else if (isBook)
ptr.getRefData().getLocals().setVarByInt(script, "pcskipequip", 1);
}
std::unique_ptr<MWWorld::Action> action = ptr.getClass().use(ptr, force);
action->execute(player);
// Handles partial equipping (final part)
if (mEquippedStackableCount.has_value())
{
// the count to unequip
int count = ptr.getCellRef().getCount() - mDragAndDrop->mDraggedCount - mEquippedStackableCount.value();
if (count > 0)
{
MWWorld::InventoryStore& invStore = mPtr.getClass().getInventoryStore(mPtr);
invStore.unequipItemQuantity(ptr, count);
updateItemView();
}
mEquippedStackableCount.reset();
}
if (isVisible())
{
mItemView->update();
notifyContentChanged();
}
// else: will be updated in open()
}
void InventoryWindow::onAvatarClicked(MyGUI::Widget* _sender)
{
if (mDragAndDrop->mIsOnDragAndDrop)
{
MWWorld::Ptr ptr = mDragAndDrop->mItem.mBase;
mDragAndDrop->finish();
if (mDragAndDrop->mSourceModel != mTradeModel)
{
// Move item to the player's inventory
ptr = mDragAndDrop->mSourceModel->moveItem(
mDragAndDrop->mItem, mDragAndDrop->mDraggedCount, mTradeModel);
}
// Handles partial equipping
mEquippedStackableCount.reset();
const auto slots = ptr.getClass().getEquipmentSlots(ptr);
if (!slots.first.empty() && slots.second)
{
MWWorld::InventoryStore& invStore = mPtr.getClass().getInventoryStore(mPtr);
MWWorld::ConstContainerStoreIterator slotIt = invStore.getSlot(slots.first.front());
// Save the currently equipped count before useItem()
if (slotIt != invStore.end() && slotIt->getCellRef().getRefId() == ptr.getCellRef().getRefId())
mEquippedStackableCount = slotIt->getCellRef().getCount();
else
mEquippedStackableCount = 0;
}
MWBase::Environment::get().getLuaManager()->useItem(ptr, MWMechanics::getPlayer(), false);
// If item is ingredient or potion don't stop drag and drop to simplify action of taking more than one 1
// item
if ((ptr.getType() == ESM::Potion::sRecordId || ptr.getType() == ESM::Ingredient::sRecordId)
&& mDragAndDrop->mDraggedCount > 1)
{
// Item can be provided from other window for example container.
// But after DragAndDrop::startDrag item automaticly always gets to player inventory.
mSelectedItem = getModel()->getIndex(mDragAndDrop->mItem);
dragItem(nullptr, mDragAndDrop->mDraggedCount - 1);
}
}
else
{
MyGUI::IntPoint mousePos
= MyGUI::InputManager::getInstance().getLastPressedPosition(MyGUI::MouseButton::Left);
MyGUI::IntPoint relPos = mousePos - mAvatarImage->getAbsolutePosition();
MWWorld::Ptr itemSelected = getAvatarSelectedItem(relPos.left, relPos.top);
if (itemSelected.isEmpty())
return;
for (size_t i = 0; i < mTradeModel->getItemCount(); ++i)
{
if (mTradeModel->getItem(i).mBase == itemSelected)
{
onItemSelectedFromSourceModel(i);
return;
}
}
throw std::runtime_error("Can't find clicked item");
}
}
MWWorld::Ptr InventoryWindow::getAvatarSelectedItem(int x, int y)
{
const osg::Vec2f viewport_coords = mapPreviewWindowToViewport(x, y);
int slot = mPreview->getSlotSelected(viewport_coords.x(), viewport_coords.y());
if (slot == -1)
return MWWorld::Ptr();
MWWorld::InventoryStore& invStore = mPtr.getClass().getInventoryStore(mPtr);
if (invStore.getSlot(slot) != invStore.end())
{
MWWorld::Ptr item = *invStore.getSlot(slot);
if (!item.getClass().showsInInventory(item))
return MWWorld::Ptr();
return item;
}
return MWWorld::Ptr();
}
void InventoryWindow::updateEncumbranceBar()
{
MWWorld::Ptr player = MWMechanics::getPlayer();
float capacity = player.getClass().getCapacity(player);
float encumbrance = player.getClass().getEncumbrance(player);
mTradeModel->adjustEncumbrance(encumbrance);
mEncumbranceBar->setValue(std::ceil(encumbrance), static_cast<int>(capacity));
}
void InventoryWindow::onFrame(float dt)
{
updateEncumbranceBar();
if (mPinned)
{
mUpdateTimer += dt;
if (0.1f < mUpdateTimer)
{
mUpdateTimer = 0;
// Update pinned inventory in-game
if (!MWBase::Environment::get().getWindowManager()->isGuiMode())
{
mItemView->update();
notifyContentChanged();
}
}
}
}
void InventoryWindow::setTrading(bool trading)
{
mTrading = trading;
}
void InventoryWindow::dirtyPreview()
{
mPreview->update();
updateArmorRating();
}
void InventoryWindow::notifyContentChanged()
{
// update the spell window just in case new enchanted items were added to inventory
MWBase::Environment::get().getWindowManager()->updateSpellWindow();
MWBase::Environment::get().getMechanicsManager()->updateMagicEffects(MWMechanics::getPlayer());
dirtyPreview();
}
void InventoryWindow::pickUpObject(MWWorld::Ptr object)
{
// If the inventory is not yet enabled, don't pick anything up
if (!MWBase::Environment::get().getWindowManager()->isAllowed(GW_Inventory))
return;
// make sure the object is of a type that can be picked up
auto type = object.getType();
if ((type != ESM::Apparatus::sRecordId) && (type != ESM::Armor::sRecordId) && (type != ESM::Book::sRecordId)
&& (type != ESM::Clothing::sRecordId) && (type != ESM::Ingredient::sRecordId)
&& (type != ESM::Light::sRecordId) && (type != ESM::Miscellaneous::sRecordId)
&& (type != ESM::Lockpick::sRecordId) && (type != ESM::Probe::sRecordId) && (type != ESM::Repair::sRecordId)
&& (type != ESM::Weapon::sRecordId) && (type != ESM::Potion::sRecordId))
return;
// An object that can be picked up must have a tooltip.
if (!object.getClass().hasToolTip(object))
return;
int count = object.getCellRef().getCount();
if (object.getClass().isGold(object))
count *= object.getClass().getValue(object);
MWWorld::Ptr player = MWMechanics::getPlayer();
MWBase::Environment::get().getWorld()->breakInvisibility(player);
if (!object.getRefData().activate())
return;
// Player must not be paralyzed, knocked down, or dead to pick up an item.
const MWMechanics::NpcStats& playerStats = player.getClass().getNpcStats(player);
if (playerStats.isParalyzed() || playerStats.getKnockedDown() || playerStats.isDead())
return;
MWBase::Environment::get().getMechanicsManager()->itemTaken(player, object, MWWorld::Ptr(), count);
// add to player inventory
// can't use ActionTake here because we need an MWWorld::Ptr to the newly inserted object
MWWorld::Ptr newObject = *player.getClass().getContainerStore(player).add(object, count);
// remove from world
MWBase::Environment::get().getWorld()->deleteObject(object);
// get ModelIndex to the item
mTradeModel->update();
size_t i = 0;
for (; i < mTradeModel->getItemCount(); ++i)
{
if (mTradeModel->getItem(i).mBase == newObject)
break;
}
if (i == mTradeModel->getItemCount())
throw std::runtime_error("Added item not found");
if (mDragAndDrop->mIsOnDragAndDrop)
mDragAndDrop->finish();
mDragAndDrop->startDrag(i, mSortModel, mTradeModel, mItemView, count);
MWBase::Environment::get().getWindowManager()->updateSpellWindow();
}
void InventoryWindow::cycle(bool next)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
if (MWBase::Environment::get().getMechanicsManager()->isAttackingOrSpell(player))
return;
const MWMechanics::CreatureStats& stats = player.getClass().getCreatureStats(player);
if (stats.isParalyzed() || stats.getKnockedDown() || stats.isDead() || stats.getHitRecovery())
return;
ItemModel::ModelIndex selected = -1;
// not using mSortFilterModel as we only need sorting, not filtering
SortFilterItemModel model(std::make_unique<InventoryItemModel>(player));
model.setSortByType(false);
model.update();
if (model.getItemCount() == 0)
return;
for (ItemModel::ModelIndex i = 0; i < int(model.getItemCount()); ++i)
{
MWWorld::Ptr item = model.getItem(i).mBase;
if (model.getItem(i).mType & ItemStack::Type_Equipped && isRightHandWeapon(item))
selected = i;
}
int incr = next ? 1 : -1;
bool found = false;
ESM::RefId lastId;
if (selected != -1)
lastId = model.getItem(selected).mBase.getCellRef().getRefId();
ItemModel::ModelIndex cycled = selected;
for (size_t i = 0; i < model.getItemCount(); ++i)
{
cycled += incr;
cycled = (cycled + model.getItemCount()) % model.getItemCount();
MWWorld::Ptr item = model.getItem(cycled).mBase;
// skip different stacks of the same item, or we will get stuck as stacking/unstacking them may change their
// relative ordering
if (lastId == item.getCellRef().getRefId())
continue;
lastId = item.getCellRef().getRefId();
if (item.getClass().getType() == ESM::Weapon::sRecordId && isRightHandWeapon(item)
&& item.getClass().canBeEquipped(item, player).first)
{
found = true;
break;
}
}
if (!found || selected == cycled)
return;
useItem(model.getItem(cycled).mBase);
}
void InventoryWindow::rebuildAvatar()
{
mPreview->rebuild();
}
MyGUI::IntSize InventoryWindow::getPreviewViewportSize() const
{
const MyGUI::IntSize previewWindowSize = mAvatarImage->getSize();
const float scale = MWBase::Environment::get().getWindowManager()->getScalingFactor();
return MyGUI::IntSize(std::min<int>(mPreview->getTextureWidth(), previewWindowSize.width * scale),
std::min<int>(mPreview->getTextureHeight(), previewWindowSize.height * scale));
}
osg::Vec2f InventoryWindow::mapPreviewWindowToViewport(int x, int y) const
{
const MyGUI::IntSize previewWindowSize = mAvatarImage->getSize();
const float normalisedX = x / std::max<float>(1.0f, previewWindowSize.width);
const float normalisedY = y / std::max<float>(1.0f, previewWindowSize.height);
const MyGUI::IntSize viewport = getPreviewViewportSize();
return osg::Vec2f(normalisedX * float(viewport.width - 1), (1.0 - normalisedY) * float(viewport.height - 1));
}
}
| 32,495
|
C++
|
.cpp
| 717
| 35.160391
| 120
| 0.624012
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,501
|
settingswindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/settingswindow.cpp
|
#include "settingswindow.hpp"
#include <array>
#include <iomanip>
#include <regex>
#include <unicode/locid.h>
#include <MyGUI_ComboBox.h>
#include <MyGUI_Gui.h>
#include <MyGUI_LanguageManager.h>
#include <MyGUI_ScrollBar.h>
#include <MyGUI_ScrollView.h>
#include <MyGUI_TabControl.h>
#include <MyGUI_UString.h>
#include <MyGUI_Window.h>
#include <SDL_video.h>
#include <components/debug/debuglog.hpp>
#include <components/lua_ui/scriptsettings.hpp>
#include <components/misc/constants.hpp>
#include <components/misc/display.hpp>
#include <components/misc/pathhelpers.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/format.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/resource/scenemanager.hpp>
#include <components/sceneutil/lightmanager.hpp>
#include <components/settings/values.hpp>
#include <components/vfs/manager.hpp>
#include <components/vfs/recursivedirectoryiterator.hpp>
#include <components/widgets/sharedstatebutton.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/inputmanager.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "confirmationdialog.hpp"
namespace
{
std::string textureFilteringToStr(const std::string& mipFilter, const std::string& magFilter)
{
if (mipFilter == "none")
return "#{OMWEngine:TextureFilteringDisabled}";
if (magFilter == "linear")
{
if (mipFilter == "linear")
return "#{OMWEngine:TextureFilteringTrilinear}";
if (mipFilter == "nearest")
return "#{OMWEngine:TextureFilteringBilinear}";
}
else if (magFilter == "nearest")
return "#{OMWEngine:TextureFilteringNearest}";
Log(Debug::Warning) << "Warning: Invalid texture filtering options: " << mipFilter << ", " << magFilter;
return "#{OMWEngine:TextureFilteringOther}";
}
std::string lightingMethodToStr(SceneUtil::LightingMethod method)
{
std::string result;
switch (method)
{
case SceneUtil::LightingMethod::FFP:
result = "#{OMWEngine:LightingMethodLegacy}";
break;
case SceneUtil::LightingMethod::PerObjectUniform:
result = "#{OMWEngine:LightingMethodShadersCompatibility}";
break;
case SceneUtil::LightingMethod::SingleUBO:
default:
result = "#{OMWEngine:LightingMethodShaders}";
break;
}
return MyGUI::LanguageManager::getInstance().replaceTags(result);
}
void parseResolution(int& x, int& y, const std::string& str)
{
std::vector<std::string> split;
Misc::StringUtils::split(str, split, "@(x");
assert(split.size() >= 2);
Misc::StringUtils::trim(split[0]);
Misc::StringUtils::trim(split[1]);
x = MyGUI::utility::parseInt(split[0]);
y = MyGUI::utility::parseInt(split[1]);
}
bool sortResolutions(std::pair<int, int> left, std::pair<int, int> right)
{
if (left.first == right.first)
return left.second > right.second;
return left.first > right.first;
}
const std::string_view checkButtonType = "CheckButton";
const std::string_view sliderType = "Slider";
std::string_view getSettingType(MyGUI::Widget* widget)
{
return widget->getUserString("SettingType");
}
std::string_view getSettingName(MyGUI::Widget* widget)
{
return widget->getUserString("SettingName");
}
std::string_view getSettingCategory(MyGUI::Widget* widget)
{
return widget->getUserString("SettingCategory");
}
std::string_view getSettingValueType(MyGUI::Widget* widget)
{
return widget->getUserString("SettingValueType");
}
void getSettingMinMax(MyGUI::Widget* widget, float& min, float& max)
{
const char* settingMin = "SettingMin";
const char* settingMax = "SettingMax";
min = 0.f;
max = 1.f;
if (!widget->getUserString(settingMin).empty())
min = MyGUI::utility::parseFloat(widget->getUserString(settingMin));
if (!widget->getUserString(settingMax).empty())
max = MyGUI::utility::parseFloat(widget->getUserString(settingMax));
}
void updateMaxLightsComboBox(MyGUI::ComboBox* box)
{
constexpr int min = 8;
constexpr int max = 64;
constexpr int increment = 8;
const int maxLights = Settings::shaders().mMaxLights;
// show increments of 8 in dropdown
if (maxLights >= min && maxLights <= max && !(maxLights % increment))
box->setIndexSelected((maxLights / increment) - 1);
else
box->setIndexSelected(MyGUI::ITEM_NONE);
}
}
namespace MWGui
{
void SettingsWindow::configureWidgets(MyGUI::Widget* widget, bool init)
{
MyGUI::EnumeratorWidgetPtr widgets = widget->getEnumerator();
while (widgets.next())
{
MyGUI::Widget* current = widgets.current();
std::string_view type = getSettingType(current);
if (type == checkButtonType)
{
std::string_view initialValue
= Settings::get<bool>(getSettingCategory(current), getSettingName(current)) ? "#{Interface:On}"
: "#{Interface:Off}";
current->castType<MyGUI::Button>()->setCaptionWithReplacing(initialValue);
if (init)
current->eventMouseButtonClick += MyGUI::newDelegate(this, &SettingsWindow::onButtonToggled);
}
if (type == sliderType)
{
MyGUI::ScrollBar* scroll = current->castType<MyGUI::ScrollBar>();
std::string valueStr;
std::string_view valueType = getSettingValueType(current);
if (valueType == "Float" || valueType == "Integer" || valueType == "Cell")
{
// TODO: ScrollBar isn't meant for this. should probably use a dedicated FloatSlider widget
float min, max;
getSettingMinMax(scroll, min, max);
float value;
if (valueType == "Cell")
{
value = Settings::get<float>(getSettingCategory(current), getSettingName(current));
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << value / Constants::CellSizeInUnits;
valueStr = ss.str();
}
else if (valueType == "Float")
{
value = Settings::get<float>(getSettingCategory(current), getSettingName(current));
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << value;
valueStr = ss.str();
}
else
{
const int intValue = Settings::get<int>(getSettingCategory(current), getSettingName(current));
valueStr = MyGUI::utility::toString(intValue);
value = static_cast<float>(intValue);
}
value = std::clamp(value, min, max);
value = (value - min) / (max - min);
scroll->setScrollPosition(static_cast<size_t>(value * (scroll->getScrollRange() - 1)));
}
else
{
const int value = Settings::get<int>(getSettingCategory(current), getSettingName(current));
valueStr = MyGUI::utility::toString(value);
scroll->setScrollPosition(value);
}
if (init)
scroll->eventScrollChangePosition
+= MyGUI::newDelegate(this, &SettingsWindow::onSliderChangePosition);
if (scroll->getVisible())
updateSliderLabel(scroll, valueStr);
}
configureWidgets(current, init);
}
}
void SettingsWindow::onFrame(float duration)
{
if (mScriptView->getVisible())
{
const auto scriptsSize = mScriptAdapter->getSize();
if (mScriptView->getCanvasSize() != scriptsSize)
mScriptView->setCanvasSize(scriptsSize);
}
}
void SettingsWindow::updateSliderLabel(MyGUI::ScrollBar* scroller, const std::string& value)
{
auto labelWidgetName = scroller->getUserString("SettingLabelWidget");
if (!labelWidgetName.empty())
{
MyGUI::TextBox* textBox;
getWidget(textBox, labelWidgetName);
std::string labelCaption{ scroller->getUserString("SettingLabelCaption") };
labelCaption = Misc::StringUtils::format(labelCaption, value);
textBox->setCaptionWithReplacing(labelCaption);
}
}
SettingsWindow::SettingsWindow()
: WindowBase("openmw_settings_window.layout")
, mKeyboardMode(true)
, mCurrentPage(-1)
{
const bool terrain = Settings::terrain().mDistantTerrain;
const std::string_view widgetName = terrain ? "RenderingDistanceSlider" : "LargeRenderingDistanceSlider";
MyGUI::Widget* unusedSlider;
getWidget(unusedSlider, widgetName);
unusedSlider->setVisible(false);
configureWidgets(mMainWidget, true);
setTitle("#{OMWEngine:SettingsWindow}");
getWidget(mSettingsTab, "SettingsTab");
getWidget(mOkButton, "OkButton");
getWidget(mResolutionList, "ResolutionList");
getWidget(mWindowModeList, "WindowModeList");
getWidget(mVSyncModeList, "VSyncModeList");
getWidget(mWindowBorderButton, "WindowBorderButton");
getWidget(mTextureFilteringButton, "TextureFilteringButton");
getWidget(mControlsBox, "ControlsBox");
getWidget(mResetControlsButton, "ResetControlsButton");
getWidget(mKeyboardSwitch, "KeyboardButton");
getWidget(mControllerSwitch, "ControllerButton");
getWidget(mWaterRefractionButton, "WaterRefractionButton");
getWidget(mSunlightScatteringButton, "SunlightScatteringButton");
getWidget(mWobblyShoresButton, "WobblyShoresButton");
getWidget(mWaterTextureSize, "WaterTextureSize");
getWidget(mWaterReflectionDetail, "WaterReflectionDetail");
getWidget(mWaterRainRippleDetail, "WaterRainRippleDetail");
getWidget(mPrimaryLanguage, "PrimaryLanguage");
getWidget(mSecondaryLanguage, "SecondaryLanguage");
getWidget(mGmstOverridesL10n, "GmstOverridesL10nButton");
getWidget(mWindowModeHint, "WindowModeHint");
getWidget(mLightingMethodButton, "LightingMethodButton");
getWidget(mLightsResetButton, "LightsResetButton");
getWidget(mMaxLights, "MaxLights");
getWidget(mScriptFilter, "ScriptFilter");
getWidget(mScriptList, "ScriptList");
getWidget(mScriptBox, "ScriptBox");
getWidget(mScriptView, "ScriptView");
getWidget(mScriptAdapter, "ScriptAdapter");
getWidget(mScriptDisabled, "ScriptDisabled");
#ifndef WIN32
// hide gamma controls since it currently does not work under Linux
MyGUI::ScrollBar* gammaSlider;
getWidget(gammaSlider, "GammaSlider");
gammaSlider->setVisible(false);
MyGUI::TextBox* textBox;
getWidget(textBox, "GammaText");
textBox->setVisible(false);
getWidget(textBox, "GammaTextDark");
textBox->setVisible(false);
getWidget(textBox, "GammaTextLight");
textBox->setVisible(false);
#endif
mMainWidget->castType<MyGUI::Window>()->eventWindowChangeCoord
+= MyGUI::newDelegate(this, &SettingsWindow::onWindowResize);
mSettingsTab->eventTabChangeSelect += MyGUI::newDelegate(this, &SettingsWindow::onTabChanged);
mOkButton->eventMouseButtonClick += MyGUI::newDelegate(this, &SettingsWindow::onOkButtonClicked);
mTextureFilteringButton->eventComboChangePosition
+= MyGUI::newDelegate(this, &SettingsWindow::onTextureFilteringChanged);
mResolutionList->eventListChangePosition += MyGUI::newDelegate(this, &SettingsWindow::onResolutionSelected);
mWaterRefractionButton->eventMouseButtonClick
+= MyGUI::newDelegate(this, &SettingsWindow::onRefractionButtonClicked);
mWaterTextureSize->eventComboChangePosition
+= MyGUI::newDelegate(this, &SettingsWindow::onWaterTextureSizeChanged);
mWaterReflectionDetail->eventComboChangePosition
+= MyGUI::newDelegate(this, &SettingsWindow::onWaterReflectionDetailChanged);
mWaterRainRippleDetail->eventComboChangePosition
+= MyGUI::newDelegate(this, &SettingsWindow::onWaterRainRippleDetailChanged);
mLightingMethodButton->eventComboChangePosition
+= MyGUI::newDelegate(this, &SettingsWindow::onLightingMethodButtonChanged);
mLightsResetButton->eventMouseButtonClick
+= MyGUI::newDelegate(this, &SettingsWindow::onLightsResetButtonClicked);
mMaxLights->eventComboChangePosition += MyGUI::newDelegate(this, &SettingsWindow::onMaxLightsChanged);
mWindowModeList->eventComboChangePosition += MyGUI::newDelegate(this, &SettingsWindow::onWindowModeChanged);
mVSyncModeList->eventComboChangePosition += MyGUI::newDelegate(this, &SettingsWindow::onVSyncModeChanged);
mKeyboardSwitch->eventMouseButtonClick += MyGUI::newDelegate(this, &SettingsWindow::onKeyboardSwitchClicked);
mControllerSwitch->eventMouseButtonClick
+= MyGUI::newDelegate(this, &SettingsWindow::onControllerSwitchClicked);
mPrimaryLanguage->eventComboChangePosition
+= MyGUI::newDelegate(this, &SettingsWindow::onPrimaryLanguageChanged);
mSecondaryLanguage->eventComboChangePosition
+= MyGUI::newDelegate(this, &SettingsWindow::onSecondaryLanguageChanged);
mGmstOverridesL10n->eventMouseButtonClick
+= MyGUI::newDelegate(this, &SettingsWindow::onGmstOverridesL10nChanged);
computeMinimumWindowSize();
center();
mResetControlsButton->eventMouseButtonClick
+= MyGUI::newDelegate(this, &SettingsWindow::onResetDefaultBindings);
// fill resolution list
const int screen = Settings::video().mScreen;
int numDisplayModes = SDL_GetNumDisplayModes(screen);
std::vector<std::pair<int, int>> resolutions;
for (int i = 0; i < numDisplayModes; i++)
{
SDL_DisplayMode mode;
SDL_GetDisplayMode(screen, i, &mode);
resolutions.emplace_back(mode.w, mode.h);
}
std::sort(resolutions.begin(), resolutions.end(), sortResolutions);
for (std::pair<int, int>& resolution : resolutions)
{
std::string str = Misc::getResolutionText(resolution.first, resolution.second, "%i x %i (%i:%i)");
if (mResolutionList->findItemIndexWith(str) == MyGUI::ITEM_NONE)
mResolutionList->addItem(str);
}
highlightCurrentResolution();
mTextureFilteringButton->setCaptionWithReplacing(
textureFilteringToStr(Settings::general().mTextureMipmap, Settings::general().mTextureMinFilter));
int waterTextureSize = Settings::water().mRttSize;
if (waterTextureSize >= 512)
mWaterTextureSize->setIndexSelected(0);
if (waterTextureSize >= 1024)
mWaterTextureSize->setIndexSelected(1);
if (waterTextureSize >= 2048)
mWaterTextureSize->setIndexSelected(2);
const int waterReflectionDetail = Settings::water().mReflectionDetail;
mWaterReflectionDetail->setIndexSelected(waterReflectionDetail);
const int waterRainRippleDetail = Settings::water().mRainRippleDetail;
mWaterRainRippleDetail->setIndexSelected(waterRainRippleDetail);
const bool waterRefraction = Settings::water().mRefraction;
mSunlightScatteringButton->setEnabled(waterRefraction);
mWobblyShoresButton->setEnabled(waterRefraction);
updateMaxLightsComboBox(mMaxLights);
const Settings::WindowMode windowMode = Settings::video().mWindowMode;
mWindowBorderButton->setEnabled(
windowMode != Settings::WindowMode::Fullscreen && windowMode != Settings::WindowMode::WindowedFullscreen);
mWindowModeHint->setVisible(windowMode == Settings::WindowMode::WindowedFullscreen);
mKeyboardSwitch->setStateSelected(true);
mControllerSwitch->setStateSelected(false);
mScriptFilter->eventEditTextChange += MyGUI::newDelegate(this, &SettingsWindow::onScriptFilterChange);
mScriptList->eventListMouseItemActivate += MyGUI::newDelegate(this, &SettingsWindow::onScriptListSelection);
std::vector<std::string> availableLanguages;
const VFS::Manager* vfs = MWBase::Environment::get().getResourceSystem()->getVFS();
constexpr VFS::Path::NormalizedView l10n("l10n/");
for (const auto& path : vfs->getRecursiveDirectoryIterator(l10n))
{
if (Misc::getFileExtension(path) == "yaml")
{
std::string localeName(Misc::stemFile(path));
if (localeName == "gmst")
continue; // fake locale to get gmst strings from content files
if (std::find(availableLanguages.begin(), availableLanguages.end(), localeName)
== availableLanguages.end())
availableLanguages.push_back(localeName);
}
}
std::sort(availableLanguages.begin(), availableLanguages.end());
std::vector<std::string> currentLocales = Settings::general().mPreferredLocales;
if (currentLocales.empty())
currentLocales.push_back("en");
icu::Locale primaryLocale(currentLocales[0].c_str());
mPrimaryLanguage->removeAllItems();
mPrimaryLanguage->setIndexSelected(MyGUI::ITEM_NONE);
mSecondaryLanguage->removeAllItems();
mSecondaryLanguage->addItem(
MyGUI::LanguageManager::getInstance().replaceTags("#{Interface:None}"), std::string());
mSecondaryLanguage->setIndexSelected(0);
size_t i = 0;
for (const auto& language : availableLanguages)
{
icu::Locale locale(language.c_str());
icu::UnicodeString str(language.c_str());
locale.getDisplayName(primaryLocale, str);
std::string localeString;
str.toUTF8String(localeString);
mPrimaryLanguage->addItem(localeString, language);
mSecondaryLanguage->addItem(localeString, language);
if (language == currentLocales[0])
mPrimaryLanguage->setIndexSelected(i);
if (currentLocales.size() > 1 && language == currentLocales[1])
mSecondaryLanguage->setIndexSelected(i + 1);
i++;
}
}
void SettingsWindow::onTabChanged(MyGUI::TabControl* /*_sender*/, size_t /*index*/)
{
resetScrollbars();
}
void SettingsWindow::onOkButtonClicked(MyGUI::Widget* _sender)
{
setVisible(false);
}
void SettingsWindow::onResolutionSelected(MyGUI::ListBox* _sender, size_t index)
{
if (index == MyGUI::ITEM_NONE)
return;
ConfirmationDialog* dialog = MWBase::Environment::get().getWindowManager()->getConfirmationDialog();
dialog->askForConfirmation("#{OMWEngine:ConfirmResolution}");
dialog->eventOkClicked.clear();
dialog->eventOkClicked += MyGUI::newDelegate(this, &SettingsWindow::onResolutionAccept);
dialog->eventCancelClicked.clear();
dialog->eventCancelClicked += MyGUI::newDelegate(this, &SettingsWindow::onResolutionCancel);
}
void SettingsWindow::onResolutionAccept()
{
const std::string& resStr = mResolutionList->getItemNameAt(mResolutionList->getIndexSelected());
int resX, resY;
parseResolution(resX, resY, resStr);
Settings::video().mResolutionX.set(resX);
Settings::video().mResolutionY.set(resY);
apply();
}
void SettingsWindow::onResolutionCancel()
{
highlightCurrentResolution();
}
void SettingsWindow::highlightCurrentResolution()
{
mResolutionList->setIndexSelected(MyGUI::ITEM_NONE);
const int currentX = Settings::video().mResolutionX;
const int currentY = Settings::video().mResolutionY;
for (size_t i = 0; i < mResolutionList->getItemCount(); ++i)
{
int resX, resY;
parseResolution(resX, resY, mResolutionList->getItemNameAt(i));
if (resX == currentX && resY == currentY)
{
mResolutionList->setIndexSelected(i);
break;
}
}
}
void SettingsWindow::onRefractionButtonClicked(MyGUI::Widget* _sender)
{
const bool refractionEnabled = Settings::water().mRefraction;
mSunlightScatteringButton->setEnabled(refractionEnabled);
mWobblyShoresButton->setEnabled(refractionEnabled);
}
void SettingsWindow::onWaterTextureSizeChanged(MyGUI::ComboBox* _sender, size_t pos)
{
int size = 0;
if (pos == 0)
size = 512;
else if (pos == 1)
size = 1024;
else if (pos == 2)
size = 2048;
Settings::water().mRttSize.set(size);
apply();
}
void SettingsWindow::onWaterReflectionDetailChanged(MyGUI::ComboBox* _sender, size_t pos)
{
Settings::water().mReflectionDetail.set(static_cast<int>(pos));
apply();
}
void SettingsWindow::onWaterRainRippleDetailChanged(MyGUI::ComboBox* _sender, size_t pos)
{
Settings::water().mRainRippleDetail.set(static_cast<int>(pos));
apply();
}
void SettingsWindow::onLightingMethodButtonChanged(MyGUI::ComboBox* _sender, size_t pos)
{
if (pos == MyGUI::ITEM_NONE)
return;
_sender->setCaptionWithReplacing(_sender->getItemNameAt(_sender->getIndexSelected()));
MWBase::Environment::get().getWindowManager()->interactiveMessageBox(
"#{OMWEngine:ChangeRequiresRestart}", { "#{Interface:OK}" }, true);
Settings::shaders().mLightingMethod.set(
Settings::parseLightingMethod(*_sender->getItemDataAt<std::string>(pos)));
apply();
}
void SettingsWindow::onLanguageChanged(size_t langPriority, MyGUI::ComboBox* _sender, size_t pos)
{
if (pos == MyGUI::ITEM_NONE)
return;
_sender->setCaptionWithReplacing(_sender->getItemNameAt(_sender->getIndexSelected()));
MWBase::Environment::get().getWindowManager()->interactiveMessageBox(
"#{OMWEngine:ChangeRequiresRestart}", { "#{Interface:OK}" }, true);
std::vector<std::string> currentLocales = Settings::general().mPreferredLocales;
if (currentLocales.size() <= langPriority)
currentLocales.resize(langPriority + 1, "en");
const auto& languageCode = *_sender->getItemDataAt<std::string>(pos);
if (!languageCode.empty())
currentLocales[langPriority] = languageCode;
else
currentLocales.resize(1);
Settings::general().mPreferredLocales.set(currentLocales);
}
void SettingsWindow::onGmstOverridesL10nChanged(MyGUI::Widget*)
{
MWBase::Environment::get().getWindowManager()->interactiveMessageBox(
"#{OMWEngine:ChangeRequiresRestart}", { "#{Interface:OK}" }, true);
}
void SettingsWindow::onVSyncModeChanged(MyGUI::ComboBox* sender, size_t pos)
{
if (pos == MyGUI::ITEM_NONE)
return;
Settings::video().mVsyncMode.set(static_cast<SDLUtil::VSyncMode>(sender->getIndexSelected()));
apply();
}
void SettingsWindow::onWindowModeChanged(MyGUI::ComboBox* sender, size_t pos)
{
if (pos == MyGUI::ITEM_NONE)
return;
const Settings::WindowMode windowMode = static_cast<Settings::WindowMode>(sender->getIndexSelected());
if (windowMode == Settings::WindowMode::WindowedFullscreen)
{
mResolutionList->setEnabled(false);
mWindowModeHint->setVisible(true);
}
else
{
mResolutionList->setEnabled(true);
mWindowModeHint->setVisible(false);
}
if (windowMode == Settings::WindowMode::Windowed)
mWindowBorderButton->setEnabled(true);
else
mWindowBorderButton->setEnabled(false);
Settings::video().mWindowMode.set(windowMode);
apply();
}
void SettingsWindow::onMaxLightsChanged(MyGUI::ComboBox* _sender, size_t pos)
{
Settings::shaders().mMaxLights.set(8 * (pos + 1));
apply();
configureWidgets(mMainWidget, false);
}
void SettingsWindow::onLightsResetButtonClicked(MyGUI::Widget* _sender)
{
std::vector<std::string> buttons = { "#{Interface:Yes}", "#{Interface:No}" };
MWBase::Environment::get().getWindowManager()->interactiveMessageBox(
"#{OMWEngine:LightingResetToDefaults}", buttons, true);
int selectedButton = MWBase::Environment::get().getWindowManager()->readPressedButton();
if (selectedButton == 1 || selectedButton == -1)
return;
Settings::shaders().mForcePerPixelLighting.reset();
Settings::shaders().mClassicFalloff.reset();
Settings::shaders().mLightBoundsMultiplier.reset();
Settings::shaders().mMaximumLightDistance.reset();
Settings::shaders().mLightFadeStart.reset();
Settings::shaders().mMinimumInteriorBrightness.reset();
Settings::shaders().mMaxLights.reset();
Settings::shaders().mLightingMethod.reset();
const SceneUtil::LightingMethod lightingMethod = Settings::shaders().mLightingMethod;
const std::size_t lightIndex = mLightingMethodButton->findItemIndexWith(lightingMethodToStr(lightingMethod));
mLightingMethodButton->setIndexSelected(lightIndex);
updateMaxLightsComboBox(mMaxLights);
apply();
configureWidgets(mMainWidget, false);
}
void SettingsWindow::onButtonToggled(MyGUI::Widget* _sender)
{
std::string_view on = MWBase::Environment::get().getWindowManager()->getGameSettingString("sOn", "On");
bool newState;
if (_sender->castType<MyGUI::Button>()->getCaption() == on)
{
_sender->castType<MyGUI::Button>()->setCaption(
MyGUI::UString(MWBase::Environment::get().getWindowManager()->getGameSettingString("sOff", "Off")));
newState = false;
}
else
{
_sender->castType<MyGUI::Button>()->setCaption(MyGUI::UString(on));
newState = true;
}
if (getSettingType(_sender) == checkButtonType)
{
Settings::get<bool>(getSettingCategory(_sender), getSettingName(_sender)).set(newState);
apply();
return;
}
}
void SettingsWindow::onTextureFilteringChanged(MyGUI::ComboBox* _sender, size_t pos)
{
auto& generalSettings = Settings::general();
switch (pos)
{
case 0: // Bilinear with mips
generalSettings.mTextureMipmap.set("nearest");
generalSettings.mTextureMagFilter.set("linear");
generalSettings.mTextureMinFilter.set("linear");
break;
case 1: // Trilinear with mips
generalSettings.mTextureMipmap.set("linear");
generalSettings.mTextureMagFilter.set("linear");
generalSettings.mTextureMinFilter.set("linear");
break;
default:
Log(Debug::Warning) << "Unexpected texture filtering option pos " << pos;
break;
}
apply();
}
void SettingsWindow::onResChange(int width, int height)
{
center();
highlightCurrentResolution();
}
void SettingsWindow::onSliderChangePosition(MyGUI::ScrollBar* scroller, size_t pos)
{
if (getSettingType(scroller) == "Slider")
{
std::string valueStr;
std::string_view valueType = getSettingValueType(scroller);
if (valueType == "Float" || valueType == "Integer" || valueType == "Cell")
{
float value = pos / float(scroller->getScrollRange() - 1);
float min, max;
getSettingMinMax(scroller, min, max);
value = min + (max - min) * value;
if (valueType == "Cell")
{
Settings::get<float>(getSettingCategory(scroller), getSettingName(scroller)).set(value);
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << value / Constants::CellSizeInUnits;
valueStr = ss.str();
}
else if (valueType == "Float")
{
Settings::get<float>(getSettingCategory(scroller), getSettingName(scroller)).set(value);
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << value;
valueStr = ss.str();
}
else
{
Settings::get<int>(getSettingCategory(scroller), getSettingName(scroller))
.set(static_cast<int>(value));
valueStr = MyGUI::utility::toString(int(value));
}
}
else
{
Settings::get<int>(getSettingCategory(scroller), getSettingName(scroller)).set(pos);
valueStr = MyGUI::utility::toString(pos);
}
updateSliderLabel(scroller, valueStr);
apply();
}
}
void SettingsWindow::apply()
{
const Settings::CategorySettingVector changed = Settings::Manager::getPendingChanges();
MWBase::Environment::get().getWorld()->processChangedSettings(changed);
MWBase::Environment::get().getSoundManager()->processChangedSettings(changed);
MWBase::Environment::get().getWindowManager()->processChangedSettings(changed);
MWBase::Environment::get().getInputManager()->processChangedSettings(changed);
MWBase::Environment::get().getMechanicsManager()->processChangedSettings(changed);
Settings::Manager::resetPendingChanges();
}
void SettingsWindow::onKeyboardSwitchClicked(MyGUI::Widget* _sender)
{
if (mKeyboardMode)
return;
mKeyboardMode = true;
mKeyboardSwitch->setStateSelected(true);
mControllerSwitch->setStateSelected(false);
updateControlsBox();
resetScrollbars();
}
void SettingsWindow::onControllerSwitchClicked(MyGUI::Widget* _sender)
{
if (!mKeyboardMode)
return;
mKeyboardMode = false;
mKeyboardSwitch->setStateSelected(false);
mControllerSwitch->setStateSelected(true);
updateControlsBox();
resetScrollbars();
}
void SettingsWindow::updateControlsBox()
{
while (mControlsBox->getChildCount())
MyGUI::Gui::getInstance().destroyWidget(mControlsBox->getChildAt(0));
MWBase::Environment::get().getWindowManager()->removeStaticMessageBox();
const auto inputManager = MWBase::Environment::get().getInputManager();
const auto& actions
= mKeyboardMode ? inputManager->getActionKeySorting() : inputManager->getActionControllerSorting();
for (const int& action : actions)
{
std::string desc{ inputManager->getActionDescription(action) };
if (desc.empty())
continue;
std::string binding;
if (mKeyboardMode)
binding = inputManager->getActionKeyBindingName(action);
else
binding = inputManager->getActionControllerBindingName(action);
Gui::SharedStateButton* leftText = mControlsBox->createWidget<Gui::SharedStateButton>(
"SandTextButton", MyGUI::IntCoord(), MyGUI::Align::Default);
leftText->setCaptionWithReplacing(desc);
Gui::SharedStateButton* rightText = mControlsBox->createWidget<Gui::SharedStateButton>(
"SandTextButton", MyGUI::IntCoord(), MyGUI::Align::Default);
rightText->setCaptionWithReplacing(binding);
rightText->setTextAlign(MyGUI::Align::Right);
rightText->setUserData(action); // save the action id for callbacks
rightText->eventMouseButtonClick += MyGUI::newDelegate(this, &SettingsWindow::onRebindAction);
rightText->eventMouseWheel += MyGUI::newDelegate(this, &SettingsWindow::onInputTabMouseWheel);
Gui::ButtonGroup group;
group.push_back(leftText);
group.push_back(rightText);
Gui::SharedStateButton::createButtonGroup(group);
}
layoutControlsBox();
}
void SettingsWindow::updateLightSettings()
{
auto lightingMethod = MWBase::Environment::get().getResourceSystem()->getSceneManager()->getLightingMethod();
std::string lightingMethodStr = lightingMethodToStr(lightingMethod);
mLightingMethodButton->removeAllItems();
std::array<SceneUtil::LightingMethod, 3> methods = {
SceneUtil::LightingMethod::FFP,
SceneUtil::LightingMethod::PerObjectUniform,
SceneUtil::LightingMethod::SingleUBO,
};
for (const auto& method : methods)
{
if (!MWBase::Environment::get().getResourceSystem()->getSceneManager()->isSupportedLightingMethod(method))
continue;
mLightingMethodButton->addItem(
lightingMethodToStr(method), SceneUtil::LightManager::getLightingMethodString(method));
}
mLightingMethodButton->setIndexSelected(mLightingMethodButton->findItemIndexWith(lightingMethodStr));
}
void SettingsWindow::updateWindowModeSettings()
{
const Settings::WindowMode windowMode = Settings::video().mWindowMode;
const std::size_t windowModeIndex = static_cast<std::size_t>(windowMode);
mWindowModeList->setIndexSelected(windowModeIndex);
if (windowMode != Settings::WindowMode::Windowed && windowModeIndex != MyGUI::ITEM_NONE)
{
// check if this resolution is supported in fullscreen
if (mResolutionList->getIndexSelected() != MyGUI::ITEM_NONE)
{
const std::string& resStr = mResolutionList->getItemNameAt(mResolutionList->getIndexSelected());
int resX, resY;
parseResolution(resX, resY, resStr);
Settings::video().mResolutionX.set(resX);
Settings::video().mResolutionY.set(resY);
}
bool supported = false;
int fallbackX = 0, fallbackY = 0;
for (size_t i = 0; i < mResolutionList->getItemCount(); ++i)
{
const std::string& resStr = mResolutionList->getItemNameAt(i);
int resX, resY;
parseResolution(resX, resY, resStr);
if (i == 0)
{
fallbackX = resX;
fallbackY = resY;
}
if (resX == Settings::video().mResolutionX && resY == Settings::video().mResolutionY)
supported = true;
}
if (!supported && mResolutionList->getItemCount())
{
if (fallbackX != 0 && fallbackY != 0)
{
Settings::video().mResolutionX.set(fallbackX);
Settings::video().mResolutionY.set(fallbackY);
}
}
mWindowBorderButton->setEnabled(false);
}
if (windowMode == Settings::WindowMode::WindowedFullscreen)
mResolutionList->setEnabled(false);
}
void SettingsWindow::updateVSyncModeSettings()
{
mVSyncModeList->setIndexSelected(static_cast<size_t>(Settings::video().mVsyncMode));
}
void SettingsWindow::layoutControlsBox()
{
const int h = Settings::gui().mFontSize + 2;
const int w = mControlsBox->getWidth() - 28;
const int noWidgetsInRow = 2;
const int totalH = mControlsBox->getChildCount() / noWidgetsInRow * h;
for (size_t i = 0; i < mControlsBox->getChildCount(); i++)
{
MyGUI::Widget* widget = mControlsBox->getChildAt(i);
widget->setCoord(0, i / noWidgetsInRow * h, w, h);
}
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
// scrollbar is hidden
mControlsBox->setVisibleVScroll(false);
mControlsBox->setCanvasSize(mControlsBox->getWidth(), std::max(totalH, mControlsBox->getHeight()));
mControlsBox->setVisibleVScroll(true);
}
namespace
{
std::string escapeRegex(const std::string& str)
{
static const std::regex specialChars(R"r([\^\.\[\$\(\)\|\*\+\?\{])r", std::regex_constants::extended);
return std::regex_replace(str, specialChars, R"(\$&)");
}
std::regex wordSearch(const std::string& query)
{
static const std::regex wordsRegex(R"([^[:space:]]+)", std::regex_constants::extended);
auto wordsBegin = std::sregex_iterator(query.begin(), query.end(), wordsRegex);
auto wordsEnd = std::sregex_iterator();
std::string searchRegex("(");
for (auto it = wordsBegin; it != wordsEnd; ++it)
{
if (it != wordsBegin)
searchRegex += '|';
searchRegex += escapeRegex(query.substr(it->position(), it->length()));
}
searchRegex += ')';
// query had only whitespace characters
if (searchRegex == "()")
searchRegex = "^(.*)$";
return std::regex(searchRegex, std::regex_constants::extended | std::regex_constants::icase);
}
double weightedSearch(const std::regex& regex, const std::string& text)
{
std::smatch matches;
std::regex_search(text, matches, regex);
// need a signed value, so cast to double (not an integer type to guarantee no overflow)
return static_cast<double>(matches.size());
}
}
void SettingsWindow::renderScriptSettings()
{
mScriptAdapter->detach();
mScriptList->removeAllItems();
mScriptView->setCanvasSize({ 0, 0 });
struct WeightedPage
{
size_t mIndex;
std::string mName;
double mNameWeight;
double mHintWeight;
constexpr auto tie() const { return std::tie(mNameWeight, mHintWeight, mName); }
constexpr bool operator<(const WeightedPage& rhs) const { return tie() < rhs.tie(); }
};
std::regex searchRegex = wordSearch(mScriptFilter->getCaption());
std::vector<WeightedPage> weightedPages;
weightedPages.reserve(LuaUi::scriptSettingsPageCount());
for (size_t i = 0; i < LuaUi::scriptSettingsPageCount(); ++i)
{
LuaUi::ScriptSettingsPage page = LuaUi::scriptSettingsPageAt(i);
double nameWeight = weightedSearch(searchRegex, page.mName);
double hintWeight = weightedSearch(searchRegex, page.mSearchHints);
if ((nameWeight + hintWeight) > 0)
weightedPages.push_back({ i, page.mName, -nameWeight, -hintWeight });
}
std::sort(weightedPages.begin(), weightedPages.end());
for (const WeightedPage& weightedPage : weightedPages)
mScriptList->addItem(weightedPage.mName, weightedPage.mIndex);
// Hide script settings when the game world isn't loaded
bool disabled = LuaUi::scriptSettingsPageCount() == 0;
mScriptFilter->setVisible(!disabled);
mScriptList->setVisible(!disabled);
mScriptBox->setVisible(!disabled);
mScriptDisabled->setVisible(disabled);
LuaUi::attachPageAt(mCurrentPage, mScriptAdapter);
}
void SettingsWindow::onScriptFilterChange(MyGUI::EditBox*)
{
renderScriptSettings();
}
void SettingsWindow::onScriptListSelection(MyGUI::ListBox*, size_t index)
{
mScriptAdapter->detach();
mCurrentPage = -1;
if (index < mScriptList->getItemCount())
{
mCurrentPage = *mScriptList->getItemDataAt<size_t>(index);
LuaUi::attachPageAt(mCurrentPage, mScriptAdapter);
}
}
void SettingsWindow::onRebindAction(MyGUI::Widget* _sender)
{
int actionId = *_sender->getUserData<int>();
_sender->castType<MyGUI::Button>()->setCaptionWithReplacing("#{Interface:None}");
MWBase::Environment::get().getWindowManager()->staticMessageBox("#{OMWEngine:RebindAction}");
MWBase::Environment::get().getWindowManager()->disallowMouse();
MWBase::Environment::get().getInputManager()->enableDetectingBindingMode(actionId, mKeyboardMode);
}
void SettingsWindow::onInputTabMouseWheel(MyGUI::Widget* _sender, int _rel)
{
if (mControlsBox->getViewOffset().top + _rel * 0.3f > 0)
mControlsBox->setViewOffset(MyGUI::IntPoint(0, 0));
else
mControlsBox->setViewOffset(
MyGUI::IntPoint(0, static_cast<int>(mControlsBox->getViewOffset().top + _rel * 0.3f)));
}
void SettingsWindow::onResetDefaultBindings(MyGUI::Widget* _sender)
{
ConfirmationDialog* dialog = MWBase::Environment::get().getWindowManager()->getConfirmationDialog();
dialog->askForConfirmation("#{OMWEngine:ConfirmResetBindings}");
dialog->eventOkClicked.clear();
dialog->eventOkClicked += MyGUI::newDelegate(this, &SettingsWindow::onResetDefaultBindingsAccept);
dialog->eventCancelClicked.clear();
}
void SettingsWindow::onResetDefaultBindingsAccept()
{
if (mKeyboardMode)
MWBase::Environment::get().getInputManager()->resetToDefaultKeyBindings();
else
MWBase::Environment::get().getInputManager()->resetToDefaultControllerBindings();
updateControlsBox();
}
void SettingsWindow::onOpen()
{
highlightCurrentResolution();
updateControlsBox();
updateLightSettings();
updateWindowModeSettings();
updateVSyncModeSettings();
resetScrollbars();
renderScriptSettings();
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mOkButton);
}
void SettingsWindow::onWindowResize(MyGUI::Window* _sender)
{
layoutControlsBox();
}
void SettingsWindow::computeMinimumWindowSize()
{
auto* window = mMainWidget->castType<MyGUI::Window>();
auto minSize = window->getMinSize();
// Window should be at minimum wide enough to show all tabs.
int tabBarWidth = 0;
for (uint32_t i = 0; i < mSettingsTab->getItemCount(); i++)
{
tabBarWidth += mSettingsTab->getButtonWidthAt(i);
}
// Need to include window margins
int margins = mMainWidget->getWidth() - mSettingsTab->getWidth();
int minimumWindowWidth = tabBarWidth + margins;
if (minimumWindowWidth > minSize.width)
{
minSize.width = minimumWindowWidth;
window->setMinSize(minSize);
// Make a dummy call to setSize so MyGUI can apply any resize resulting from the change in MinSize
mMainWidget->setSize(mMainWidget->getSize());
}
}
void SettingsWindow::resetScrollbars()
{
mResolutionList->setScrollPosition(0);
mControlsBox->setViewOffset(MyGUI::IntPoint(0, 0));
}
}
| 44,561
|
C++
|
.cpp
| 957
| 36.083595
| 118
| 0.633565
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,502
|
itemwidget.cpp
|
OpenMW_openmw/apps/openmw/mwgui/itemwidget.cpp
|
#include "itemwidget.hpp"
#include <MyGUI_FactoryManager.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_RenderManager.h>
#include <MyGUI_TextBox.h>
#include <components/debug/debuglog.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/settings/values.hpp>
#include <components/vfs/manager.hpp>
#include "../mwbase/environment.hpp"
#include "../mwworld/class.hpp"
namespace
{
std::string getCountString(int count)
{
if (count == 1)
return {};
// With small text size we can use up to 4 characters, while with large ones - only up to 3.
if (Settings::gui().mFontSize > 16)
{
if (count > 999999999)
return MyGUI::utility::toString(count / 1000000000) + "b";
else if (count > 99999999)
return ">9m";
else if (count > 999999)
return MyGUI::utility::toString(count / 1000000) + "m";
else if (count > 99999)
return ">9k";
else if (count > 999)
return MyGUI::utility::toString(count / 1000) + "k";
else
return MyGUI::utility::toString(count);
}
if (count > 999999999)
return MyGUI::utility::toString(count / 1000000000) + "b";
else if (count > 999999)
return MyGUI::utility::toString(count / 1000000) + "m";
else if (count > 9999)
return MyGUI::utility::toString(count / 1000) + "k";
else
return MyGUI::utility::toString(count);
}
}
namespace MWGui
{
std::map<std::string, float> ItemWidget::mScales;
ItemWidget::ItemWidget()
: mItem(nullptr)
, mItemShadow(nullptr)
, mFrame(nullptr)
, mText(nullptr)
{
}
void ItemWidget::registerComponents()
{
MyGUI::FactoryManager::getInstance().registerFactory<ItemWidget>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<SpellWidget>("Widget");
}
void ItemWidget::initialiseOverride()
{
assignWidget(mItem, "Item");
if (mItem)
mItem->setNeedMouseFocus(false);
assignWidget(mItemShadow, "ItemShadow");
if (mItemShadow)
mItemShadow->setNeedMouseFocus(false);
assignWidget(mFrame, "Frame");
if (mFrame)
mFrame->setNeedMouseFocus(false);
assignWidget(mText, "Text");
if (mText)
mText->setNeedMouseFocus(false);
Base::initialiseOverride();
}
void ItemWidget::setCount(int count)
{
if (!mText)
return;
mText->setCaption(getCountString(count));
}
void ItemWidget::setIcon(const std::string& icon)
{
if (mCurrentIcon != icon)
{
mCurrentIcon = icon;
if (mItemShadow)
mItemShadow->setImageTexture(icon);
if (mItem)
mItem->setImageTexture(icon);
}
}
void ItemWidget::setFrame(const std::string& frame, const MyGUI::IntCoord& coord)
{
if (mFrame)
{
mFrame->setImageTile(MyGUI::IntSize(coord.width, coord.height)); // Why is this needed? MyGUI bug?
mFrame->setImageCoord(coord);
}
if (mCurrentFrame != frame)
{
mCurrentFrame = frame;
mFrame->setImageTexture(frame);
}
}
void ItemWidget::setIcon(const MWWorld::Ptr& ptr)
{
std::string_view icon = ptr.getClass().getInventoryIcon(ptr);
if (icon.empty())
icon = "default icon.tga";
const VFS::Manager* const vfs = MWBase::Environment::get().getResourceSystem()->getVFS();
std::string invIcon = Misc::ResourceHelpers::correctIconPath(icon, vfs);
if (!vfs->exists(invIcon))
{
Log(Debug::Error) << "Failed to open image: '" << invIcon
<< "' not found, falling back to 'default-icon.tga'";
invIcon = Misc::ResourceHelpers::correctIconPath("default icon.tga", vfs);
}
setIcon(invIcon);
}
void ItemWidget::setItem(const MWWorld::Ptr& ptr, ItemState state)
{
if (!mItem)
return;
if (ptr.isEmpty())
{
if (mFrame)
mFrame->setImageTexture({});
if (mItemShadow)
mItemShadow->setImageTexture({});
mItem->setImageTexture({});
mText->setCaption({});
mCurrentIcon.clear();
mCurrentFrame.clear();
return;
}
bool isMagic = !ptr.getClass().getEnchantment(ptr).empty();
std::string backgroundTex = "textures\\menu_icon";
if (isMagic)
backgroundTex += "_magic";
if (state == None)
{
if (!isMagic)
backgroundTex.clear();
}
else if (state == Equip)
{
backgroundTex += "_equip";
}
else if (state == Barter)
backgroundTex += "_barter";
if (!backgroundTex.empty())
backgroundTex += ".dds";
float scale = 1.f;
if (!backgroundTex.empty())
{
auto found = mScales.find(backgroundTex);
if (found == mScales.end())
{
// By default, background icons are supposed to use the 42x42 part of 64x64 image.
// If the image has a different size, we should use a different chunk size
// Cache result to do not retrieve background texture every frame.
MyGUI::ITexture* texture = MyGUI::RenderManager::getInstance().getTexture(backgroundTex);
if (texture)
scale = texture->getHeight() / 64.f;
mScales[backgroundTex] = scale;
}
else
scale = found->second;
}
if (state == Barter && !isMagic)
setFrame(backgroundTex, MyGUI::IntCoord(2 * scale, 2 * scale, 44 * scale, 44 * scale));
else
setFrame(backgroundTex, MyGUI::IntCoord(0, 0, 44 * scale, 44 * scale));
setIcon(ptr);
}
void SpellWidget::setSpellIcon(std::string_view icon)
{
if (mFrame && !mCurrentFrame.empty())
{
mCurrentFrame.clear();
mFrame->setImageTexture({});
}
if (mCurrentIcon != icon)
{
mCurrentIcon = icon;
if (mItemShadow)
mItemShadow->setImageTexture(icon);
if (mItem)
mItem->setImageTexture(icon);
}
}
}
| 6,682
|
C++
|
.cpp
| 193
| 24.797927
| 110
| 0.560217
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,503
|
cursor.cpp
|
OpenMW_openmw/apps/openmw/mwgui/cursor.cpp
|
#include "cursor.hpp"
#include <MyGUI_Gui.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_PointerManager.h>
#include <MyGUI_RotatingSkin.h>
namespace MWGui
{
ResourceImageSetPointerFix::ResourceImageSetPointerFix()
: mImageSet(nullptr)
, mRotation(0)
{
}
ResourceImageSetPointerFix::~ResourceImageSetPointerFix() {}
void ResourceImageSetPointerFix::deserialization(MyGUI::xml::ElementPtr _node, MyGUI::Version _version)
{
Base::deserialization(_node, _version);
MyGUI::xml::ElementEnumerator info = _node->getElementEnumerator();
while (info.next("Property"))
{
auto key = info->findAttribute("key");
auto value = info->findAttribute("value");
if (key == "Point")
mPoint = MyGUI::IntPoint::parse(value);
else if (key == "Size")
mSize = MyGUI::IntSize::parse(value);
else if (key == "Rotation")
mRotation = MyGUI::utility::parseInt(value);
else if (key == "Resource")
mImageSet = MyGUI::ResourceManager::getInstance().getByName(value)->castType<MyGUI::ResourceImageSet>();
}
}
int ResourceImageSetPointerFix::getRotation()
{
return mRotation;
}
void ResourceImageSetPointerFix::setImage(MyGUI::ImageBox* _image)
{
if (mImageSet != nullptr)
_image->setItemResourceInfo(mImageSet->getIndexInfo(0, 0));
}
void ResourceImageSetPointerFix::setPosition(MyGUI::ImageBox* _image, const MyGUI::IntPoint& _point)
{
_image->setCoord(_point.left - mPoint.left, _point.top - mPoint.top, mSize.width, mSize.height);
}
MyGUI::ResourceImageSetPtr ResourceImageSetPointerFix::getImageSet()
{
return mImageSet;
}
MyGUI::IntPoint ResourceImageSetPointerFix::getHotSpot()
{
return mPoint;
}
MyGUI::IntSize ResourceImageSetPointerFix::getSize()
{
return mSize;
}
}
| 2,012
|
C++
|
.cpp
| 57
| 27.877193
| 120
| 0.645028
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,505
|
itemchargeview.cpp
|
OpenMW_openmw/apps/openmw/mwgui/itemchargeview.cpp
|
#include "itemchargeview.hpp"
#include <set>
#include <MyGUI_FactoryManager.h>
#include <MyGUI_Gui.h>
#include <MyGUI_ScrollView.h>
#include <MyGUI_TextBox.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadench.hpp>
#include "../mwbase/environment.hpp"
#include "../mwmechanics/spellutil.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "itemmodel.hpp"
#include "itemwidget.hpp"
namespace MWGui
{
ItemChargeView::ItemChargeView()
: mScrollView(nullptr)
, mDisplayMode(DisplayMode_Health)
{
}
void ItemChargeView::registerComponents()
{
MyGUI::FactoryManager::getInstance().registerFactory<ItemChargeView>("Widget");
}
void ItemChargeView::initialiseOverride()
{
Base::initialiseOverride();
assignWidget(mScrollView, "ScrollView");
if (mScrollView == nullptr)
throw std::runtime_error("Item charge view needs a scroll view");
mScrollView->setCanvasAlign(MyGUI::Align::Left | MyGUI::Align::Top);
}
void ItemChargeView::setModel(ItemModel* model)
{
mModel.reset(model);
}
void ItemChargeView::setDisplayMode(ItemChargeView::DisplayMode type)
{
mDisplayMode = type;
update();
}
void ItemChargeView::update()
{
if (!mModel.get())
{
layoutWidgets();
return;
}
mModel->update();
Lines lines;
std::set<Lines::const_iterator> visitedLines;
for (size_t i = 0; i < mModel->getItemCount(); ++i)
{
ItemStack stack = mModel->getItem(static_cast<ItemModel::ModelIndex>(i));
bool found = false;
for (Lines::const_iterator iter = mLines.begin(); iter != mLines.end(); ++iter)
{
if (iter->mItemPtr == stack.mBase)
{
found = true;
visitedLines.insert(iter);
// update line widgets
updateLine(*iter);
lines.push_back(*iter);
break;
}
}
if (!found)
{
// add line widgets
Line line;
line.mItemPtr = stack.mBase;
line.mText
= mScrollView->createWidget<MyGUI::TextBox>("SandText", MyGUI::IntCoord(), MyGUI::Align::Default);
line.mText->setNeedMouseFocus(false);
line.mIcon = mScrollView->createWidget<ItemWidget>(
"MW_ItemIconSmall", MyGUI::IntCoord(), MyGUI::Align::Default);
line.mIcon->setItem(line.mItemPtr);
line.mIcon->setUserString("ToolTipType", "ItemPtr");
line.mIcon->setUserData(MWWorld::Ptr(line.mItemPtr));
line.mIcon->eventMouseButtonClick += MyGUI::newDelegate(this, &ItemChargeView::onIconClicked);
line.mIcon->eventMouseWheel += MyGUI::newDelegate(this, &ItemChargeView::onMouseWheelMoved);
line.mCharge = mScrollView->createWidget<Widgets::MWDynamicStat>(
"MW_ChargeBar", MyGUI::IntCoord(), MyGUI::Align::Default);
line.mCharge->setNeedMouseFocus(false);
updateLine(line);
lines.push_back(line);
}
}
for (Lines::iterator iter = mLines.begin(); iter != mLines.end(); ++iter)
{
if (visitedLines.count(iter))
continue;
// remove line widgets
MyGUI::Gui::getInstance().destroyWidget(iter->mText);
MyGUI::Gui::getInstance().destroyWidget(iter->mIcon);
MyGUI::Gui::getInstance().destroyWidget(iter->mCharge);
}
mLines.swap(lines);
std::stable_sort(mLines.begin(), mLines.end(),
[](const MWGui::ItemChargeView::Line& a, const MWGui::ItemChargeView::Line& b) {
return Misc::StringUtils::ciLess(a.mText->getCaption(), b.mText->getCaption());
});
layoutWidgets();
}
void ItemChargeView::layoutWidgets()
{
int currentY = 0;
for (Line& line : mLines)
{
line.mText->setCoord(8, currentY, mScrollView->getWidth() - 8, 18);
currentY += 19;
line.mIcon->setCoord(16, currentY, 32, 32);
line.mCharge->setCoord(72, currentY + 2, std::max(199, mScrollView->getWidth() - 72 - 38), 20);
currentY += 32 + 4;
}
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
// scrollbar is hidden
mScrollView->setVisibleVScroll(false);
mScrollView->setCanvasSize(
MyGUI::IntSize(mScrollView->getWidth(), std::max(mScrollView->getHeight(), currentY)));
mScrollView->setVisibleVScroll(true);
}
void ItemChargeView::resetScrollbars()
{
mScrollView->setViewOffset(MyGUI::IntPoint(0, 0));
}
void ItemChargeView::setSize(const MyGUI::IntSize& value)
{
bool changed = (value.width != getWidth() || value.height != getHeight());
Base::setSize(value);
if (changed)
layoutWidgets();
}
void ItemChargeView::setCoord(const MyGUI::IntCoord& value)
{
bool changed = (value.width != getWidth() || value.height != getHeight());
Base::setCoord(value);
if (changed)
layoutWidgets();
}
void ItemChargeView::updateLine(const ItemChargeView::Line& line)
{
std::string_view name = line.mItemPtr.getClass().getName(line.mItemPtr);
line.mText->setCaption(MyGUI::UString(name));
line.mCharge->setVisible(false);
switch (mDisplayMode)
{
case DisplayMode_Health:
if (!line.mItemPtr.getClass().hasItemHealth(line.mItemPtr))
break;
line.mCharge->setVisible(true);
line.mCharge->setValue(line.mItemPtr.getClass().getItemHealth(line.mItemPtr),
line.mItemPtr.getClass().getItemMaxHealth(line.mItemPtr));
break;
case DisplayMode_EnchantmentCharge:
const ESM::RefId& enchId = line.mItemPtr.getClass().getEnchantment(line.mItemPtr);
if (enchId.empty())
break;
const ESM::Enchantment* ench
= MWBase::Environment::get().getESMStore()->get<ESM::Enchantment>().search(enchId);
if (!ench)
break;
line.mCharge->setVisible(true);
line.mCharge->setValue(static_cast<int>(line.mItemPtr.getCellRef().getEnchantmentCharge()),
MWMechanics::getEnchantmentCharge(*ench));
break;
}
}
void ItemChargeView::onIconClicked(MyGUI::Widget* sender)
{
eventItemClicked(this, *sender->getUserData<MWWorld::Ptr>());
}
void ItemChargeView::onMouseWheelMoved(MyGUI::Widget* /*sender*/, int rel)
{
if (mScrollView->getViewOffset().top + rel * 0.3f > 0)
mScrollView->setViewOffset(MyGUI::IntPoint(0, 0));
else
mScrollView->setViewOffset(
MyGUI::IntPoint(0, static_cast<int>(mScrollView->getViewOffset().top + rel * 0.3f)));
}
}
| 7,395
|
C++
|
.cpp
| 183
| 29.726776
| 118
| 0.585658
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,506
|
screenfader.cpp
|
OpenMW_openmw/apps/openmw/mwgui/screenfader.cpp
|
#include "screenfader.hpp"
#include <MyGUI_Gui.h>
#include <MyGUI_ImageBox.h>
namespace MWGui
{
FadeOp::FadeOp(ScreenFader* fader, float time, float targetAlpha, float delay)
: mFader(fader)
, mRemainingTime(time + delay)
, mTargetTime(time)
, mTargetAlpha(targetAlpha)
, mStartAlpha(0.f)
, mDelay(delay)
, mRunning(false)
{
}
bool FadeOp::isRunning()
{
return mRunning;
}
void FadeOp::start()
{
if (mRunning)
return;
mRemainingTime = mTargetTime + mDelay;
mStartAlpha = mFader->getCurrentAlpha();
mRunning = true;
}
void FadeOp::update(float dt)
{
if (!mRunning)
return;
if (mStartAlpha == mTargetAlpha)
{
finish();
return;
}
if (mRemainingTime <= 0)
{
// Make sure the target alpha is applied
mFader->notifyAlphaChanged(mTargetAlpha);
finish();
return;
}
if (mRemainingTime > mTargetTime)
{
mRemainingTime -= dt;
return;
}
float currentAlpha = mFader->getCurrentAlpha();
if (mStartAlpha > mTargetAlpha)
{
currentAlpha -= dt / mTargetTime * (mStartAlpha - mTargetAlpha);
if (currentAlpha < mTargetAlpha)
currentAlpha = mTargetAlpha;
}
else
{
currentAlpha += dt / mTargetTime * (mTargetAlpha - mStartAlpha);
if (currentAlpha > mTargetAlpha)
currentAlpha = mTargetAlpha;
}
mFader->notifyAlphaChanged(currentAlpha);
mRemainingTime -= dt;
}
void FadeOp::finish()
{
mRunning = false;
mFader->notifyOperationFinished();
}
ScreenFader::ScreenFader(
const std::string& texturePath, const std::string& layout, const MyGUI::FloatCoord& texCoordOverride)
: WindowBase(layout)
, mCurrentAlpha(0.f)
, mFactor(1.f)
, mRepeat(false)
{
MyGUI::Gui::getInstance().eventFrameStart += MyGUI::newDelegate(this, &ScreenFader::onFrameStart);
MyGUI::ImageBox* imageBox = mMainWidget->castType<MyGUI::ImageBox>(false);
if (imageBox)
{
imageBox->setImageTexture(texturePath);
const MyGUI::IntSize imageSize = imageBox->getImageSize();
imageBox->setImageCoord(MyGUI::IntCoord(static_cast<int>(texCoordOverride.left * imageSize.width),
static_cast<int>(texCoordOverride.top * imageSize.height),
static_cast<int>(texCoordOverride.width * imageSize.width),
static_cast<int>(texCoordOverride.height * imageSize.height)));
}
}
ScreenFader::~ScreenFader()
{
try
{
MyGUI::Gui::getInstance().eventFrameStart -= MyGUI::newDelegate(this, &ScreenFader::onFrameStart);
}
catch (const MyGUI::Exception& e)
{
Log(Debug::Error) << "Error in the destructor: " << e.what();
}
}
void ScreenFader::onFrameStart(float dt)
{
if (!mQueue.empty())
{
if (!mQueue.front()->isRunning())
mQueue.front()->start();
mQueue.front()->update(dt);
}
}
void ScreenFader::applyAlpha()
{
setVisible(true);
mMainWidget->setAlpha(1.f - ((1.f - mCurrentAlpha) * mFactor));
}
void ScreenFader::fadeIn(float time, float delay)
{
queue(time, 1.f, delay);
}
void ScreenFader::fadeOut(const float time, float delay)
{
queue(time, 0.f, delay);
}
void ScreenFader::fadeTo(const int percent, const float time, float delay)
{
queue(time, percent / 100.f, delay);
}
void ScreenFader::clear()
{
clearQueue();
notifyAlphaChanged(0.f);
}
void ScreenFader::setFactor(float factor)
{
mFactor = factor;
applyAlpha();
}
void ScreenFader::setRepeat(bool repeat)
{
mRepeat = repeat;
}
void ScreenFader::queue(float time, float targetAlpha, float delay)
{
if (time < 0.f)
return;
if (time == 0.f && delay == 0.f)
{
mCurrentAlpha = targetAlpha;
applyAlpha();
return;
}
mQueue.push_back(FadeOp::Ptr(new FadeOp(this, time, targetAlpha, delay)));
}
bool ScreenFader::isEmpty()
{
return mQueue.empty();
}
void ScreenFader::clearQueue()
{
mQueue.clear();
}
void ScreenFader::notifyAlphaChanged(float alpha)
{
if (mCurrentAlpha == alpha)
return;
mCurrentAlpha = alpha;
if (1.f - ((1.f - mCurrentAlpha) * mFactor) == 0.f)
mMainWidget->setVisible(false);
else
applyAlpha();
}
void ScreenFader::notifyOperationFinished()
{
FadeOp::Ptr op = mQueue.front();
mQueue.pop_front();
if (mRepeat)
mQueue.push_back(op);
}
float ScreenFader::getCurrentAlpha()
{
return mCurrentAlpha;
}
}
| 5,230
|
C++
|
.cpp
| 181
| 20.447514
| 110
| 0.568721
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
35,507
|
container.cpp
|
OpenMW_openmw/apps/openmw/mwgui/container.cpp
|
#include "container.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_InputManager.h>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/scriptmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwmechanics/aipackage.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/summoning.hpp"
#include "../mwscript/interpretercontext.hpp"
#include "countdialog.hpp"
#include "inventorywindow.hpp"
#include "containeritemmodel.hpp"
#include "draganddrop.hpp"
#include "inventoryitemmodel.hpp"
#include "itemview.hpp"
#include "pickpocketitemmodel.hpp"
#include "sortfilteritemmodel.hpp"
#include "tooltips.hpp"
namespace MWGui
{
ContainerWindow::ContainerWindow(DragAndDrop* dragAndDrop)
: WindowBase("openmw_container_window.layout")
, mDragAndDrop(dragAndDrop)
, mSortModel(nullptr)
, mModel(nullptr)
, mSelectedItem(-1)
, mTreatNextOpenAsLoot(false)
{
getWidget(mDisposeCorpseButton, "DisposeCorpseButton");
getWidget(mTakeButton, "TakeButton");
getWidget(mCloseButton, "CloseButton");
getWidget(mItemView, "ItemView");
mItemView->eventBackgroundClicked += MyGUI::newDelegate(this, &ContainerWindow::onBackgroundSelected);
mItemView->eventItemClicked += MyGUI::newDelegate(this, &ContainerWindow::onItemSelected);
mDisposeCorpseButton->eventMouseButtonClick
+= MyGUI::newDelegate(this, &ContainerWindow::onDisposeCorpseButtonClicked);
mCloseButton->eventMouseButtonClick += MyGUI::newDelegate(this, &ContainerWindow::onCloseButtonClicked);
mTakeButton->eventMouseButtonClick += MyGUI::newDelegate(this, &ContainerWindow::onTakeAllButtonClicked);
setCoord(200, 0, 600, 300);
}
void ContainerWindow::onItemSelected(int index)
{
if (mDragAndDrop->mIsOnDragAndDrop)
{
dropItem();
return;
}
const ItemStack& item = mSortModel->getItem(index);
// We can't take a conjured item from a container (some NPC we're pickpocketing, a box, etc)
if (item.mFlags & ItemStack::Flag_Bound)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sContentsMessage1}");
return;
}
MWWorld::Ptr object = item.mBase;
int count = item.mCount;
bool shift = MyGUI::InputManager::getInstance().isShiftPressed();
if (MyGUI::InputManager::getInstance().isControlPressed())
count = 1;
mSelectedItem = mSortModel->mapToSource(index);
if (count > 1 && !shift)
{
CountDialog* dialog = MWBase::Environment::get().getWindowManager()->getCountDialog();
std::string name{ object.getClass().getName(object) };
name += MWGui::ToolTips::getSoulString(object.getCellRef());
dialog->openCountDialog(name, "#{sTake}", count);
dialog->eventOkClicked.clear();
dialog->eventOkClicked += MyGUI::newDelegate(this, &ContainerWindow::dragItem);
}
else
dragItem(nullptr, count);
}
void ContainerWindow::dragItem(MyGUI::Widget* sender, int count)
{
if (!mModel)
return;
if (!onTakeItem(mModel->getItem(mSelectedItem), count))
return;
mDragAndDrop->startDrag(mSelectedItem, mSortModel, mModel, mItemView, count);
}
void ContainerWindow::dropItem()
{
if (!mModel)
return;
bool success = mModel->onDropItem(mDragAndDrop->mItem.mBase, mDragAndDrop->mDraggedCount);
if (success)
mDragAndDrop->drop(mModel, mItemView);
}
void ContainerWindow::onBackgroundSelected()
{
if (mDragAndDrop->mIsOnDragAndDrop)
dropItem();
}
void ContainerWindow::setPtr(const MWWorld::Ptr& container)
{
if (container.isEmpty() || (container.getType() != ESM::REC_CONT && !container.getClass().isActor()))
throw std::runtime_error("Invalid argument in ContainerWindow::setPtr");
bool lootAnyway = mTreatNextOpenAsLoot;
mTreatNextOpenAsLoot = false;
mPtr = container;
bool loot = mPtr.getClass().isActor() && mPtr.getClass().getCreatureStats(mPtr).isDead();
std::unique_ptr<ItemModel> model;
if (mPtr.getClass().hasInventoryStore(mPtr))
{
if (mPtr.getClass().isNpc() && !loot && !lootAnyway)
{
// we are stealing stuff
model = std::make_unique<PickpocketItemModel>(mPtr, std::make_unique<InventoryItemModel>(container),
!mPtr.getClass().getCreatureStats(mPtr).getKnockedDown());
}
else
model = std::make_unique<InventoryItemModel>(container);
}
else
{
model = std::make_unique<ContainerItemModel>(container);
}
mDisposeCorpseButton->setVisible(loot);
mModel = model.get();
auto sortModel = std::make_unique<SortFilterItemModel>(std::move(model));
mSortModel = sortModel.get();
mItemView->setModel(std::move(sortModel));
mItemView->resetScrollBars();
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mCloseButton);
setTitle(container.getClass().getName(container));
}
void ContainerWindow::resetReference()
{
ReferenceInterface::resetReference();
mItemView->setModel(nullptr);
mModel = nullptr;
mSortModel = nullptr;
}
void ContainerWindow::onClose()
{
WindowBase::onClose();
// Make sure the window was actually closed and not temporarily hidden.
if (MWBase::Environment::get().getWindowManager()->containsMode(GM_Container))
return;
if (mModel)
mModel->onClose();
if (!mPtr.isEmpty())
MWBase::Environment::get().getMechanicsManager()->onClose(mPtr);
resetReference();
}
void ContainerWindow::onCloseButtonClicked(MyGUI::Widget* _sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Container);
}
void ContainerWindow::onTakeAllButtonClicked(MyGUI::Widget* _sender)
{
if (!mModel)
return;
if (mDragAndDrop != nullptr && mDragAndDrop->mIsOnDragAndDrop)
return;
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mCloseButton);
// transfer everything into the player's inventory
ItemModel* playerModel = MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getModel();
assert(mModel);
mModel->update();
// unequip all items to avoid unequipping/reequipping
if (mPtr.getClass().hasInventoryStore(mPtr))
{
MWWorld::InventoryStore& invStore = mPtr.getClass().getInventoryStore(mPtr);
for (size_t i = 0; i < mModel->getItemCount(); ++i)
{
const ItemStack& item = mModel->getItem(i);
if (invStore.isEquipped(item.mBase) == false)
continue;
invStore.unequipItem(item.mBase);
}
}
mModel->update();
for (size_t i = 0; i < mModel->getItemCount(); ++i)
{
if (i == 0)
{
// play the sound of the first object
MWWorld::Ptr item = mModel->getItem(i).mBase;
const ESM::RefId& sound = item.getClass().getUpSoundId(item);
MWBase::Environment::get().getWindowManager()->playSound(sound);
}
const ItemStack& item = mModel->getItem(i);
if (!onTakeItem(item, item.mCount))
break;
mModel->moveItem(item, item.mCount, playerModel);
}
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Container);
}
void ContainerWindow::onDisposeCorpseButtonClicked(MyGUI::Widget* sender)
{
if (mDragAndDrop == nullptr || !mDragAndDrop->mIsOnDragAndDrop)
{
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mCloseButton);
// Copy mPtr because onTakeAllButtonClicked closes the window which resets the reference
MWWorld::Ptr ptr = mPtr;
onTakeAllButtonClicked(mTakeButton);
if (ptr.getClass().isPersistent(ptr))
MWBase::Environment::get().getWindowManager()->messageBox("#{sDisposeCorpseFail}");
else
{
MWMechanics::CreatureStats& creatureStats = ptr.getClass().getCreatureStats(ptr);
// If we dispose corpse before end of death animation, we should update death counter counter manually.
// Also we should run actor's script - it may react on actor's death.
if (creatureStats.isDead() && !creatureStats.isDeathAnimationFinished())
{
creatureStats.setDeathAnimationFinished(true);
MWBase::Environment::get().getMechanicsManager()->notifyDied(ptr);
const ESM::RefId& script = ptr.getClass().getScript(ptr);
if (!script.empty() && MWBase::Environment::get().getWorld()->getScriptsEnabled())
{
MWScript::InterpreterContext interpreterContext(&ptr.getRefData().getLocals(), ptr);
MWBase::Environment::get().getScriptManager()->run(script, interpreterContext);
}
// Clean up summoned creatures as well
auto& creatureMap = creatureStats.getSummonedCreatureMap();
for (const auto& creature : creatureMap)
MWBase::Environment::get().getMechanicsManager()->cleanupSummonedCreature(ptr, creature.second);
creatureMap.clear();
// Check if we are a summon and inform our master we've bit the dust
for (const auto& package : creatureStats.getAiSequence())
{
if (package->followTargetThroughDoors() && !package->getTarget().isEmpty())
{
const auto& summoner = package->getTarget();
auto& summons = summoner.getClass().getCreatureStats(summoner).getSummonedCreatureMap();
auto it = std::find_if(summons.begin(), summons.end(),
[&](const auto& entry) { return entry.second == creatureStats.getActorId(); });
if (it != summons.end())
{
auto summon = *it;
summons.erase(it);
MWMechanics::purgeSummonEffect(summoner, summon);
break;
}
}
}
}
MWBase::Environment::get().getWorld()->deleteObject(ptr);
}
mPtr = MWWorld::Ptr();
}
}
void ContainerWindow::onReferenceUnavailable()
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Container);
}
bool ContainerWindow::onTakeItem(const ItemStack& item, int count)
{
return mModel->onTakeItem(item.mBase, count);
}
void ContainerWindow::onDeleteCustomData(const MWWorld::Ptr& ptr)
{
if (mModel && mModel->usesContainer(ptr))
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Container);
}
}
| 11,854
|
C++
|
.cpp
| 262
| 34.103053
| 120
| 0.609401
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,508
|
itemmodel.cpp
|
OpenMW_openmw/apps/openmw/mwgui/itemmodel.cpp
|
#include "itemmodel.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
namespace MWGui
{
ItemStack::ItemStack(const MWWorld::Ptr& base, ItemModel* creator, size_t count)
: mType(Type_Normal)
, mFlags(0)
, mCreator(creator)
, mCount(count)
, mBase(base)
{
if (!base.getClass().getEnchantment(base).empty())
mFlags |= Flag_Enchanted;
if (MWBase::Environment::get().getMechanicsManager()->isBoundItem(base))
mFlags |= Flag_Bound;
}
ItemStack::ItemStack()
: mType(Type_Normal)
, mFlags(0)
, mCreator(nullptr)
, mCount(0)
{
}
bool operator==(const ItemStack& left, const ItemStack& right)
{
if (left.mType != right.mType)
return false;
if (left.mBase == right.mBase)
return true;
// If one of the items is in an inventory and currently equipped, we need to check stacking both ways to be sure
if (left.mBase.getContainerStore() && right.mBase.getContainerStore())
return left.mBase.getContainerStore()->stacks(left.mBase, right.mBase)
&& right.mBase.getContainerStore()->stacks(left.mBase, right.mBase);
if (left.mBase.getContainerStore())
return left.mBase.getContainerStore()->stacks(left.mBase, right.mBase);
if (right.mBase.getContainerStore())
return right.mBase.getContainerStore()->stacks(left.mBase, right.mBase);
MWWorld::ContainerStore store;
return store.stacks(left.mBase, right.mBase);
}
ItemModel::ItemModel() {}
MWWorld::Ptr ItemModel::moveItem(const ItemStack& item, size_t count, ItemModel* otherModel, bool allowAutoEquip)
{
MWWorld::Ptr ret = MWWorld::Ptr();
if (static_cast<size_t>(item.mBase.getCellRef().getCount()) <= count)
{
// We are moving the full stack
ret = otherModel->addItem(item, count, allowAutoEquip);
removeItem(item, count);
}
else
{
// We are moving only part of the stack, so create a copy in the other model
// and then remove count from this model.
ret = otherModel->copyItem(item, count, allowAutoEquip);
removeItem(item, count);
}
return ret;
}
bool ItemModel::allowedToUseItems() const
{
return true;
}
bool ItemModel::onDropItem(const MWWorld::Ptr& item, int count)
{
return true;
}
bool ItemModel::onTakeItem(const MWWorld::Ptr& item, int count)
{
return true;
}
bool ProxyItemModel::allowedToUseItems() const
{
return mSourceModel->allowedToUseItems();
}
MWWorld::Ptr ProxyItemModel::copyItem(const ItemStack& item, size_t count, bool allowAutoEquip)
{
return mSourceModel->copyItem(item, count, allowAutoEquip);
}
void ProxyItemModel::removeItem(const ItemStack& item, size_t count)
{
mSourceModel->removeItem(item, count);
}
ItemModel::ModelIndex ProxyItemModel::mapToSource(ModelIndex index)
{
const ItemStack& itemToSearch = getItem(index);
for (size_t i = 0; i < mSourceModel->getItemCount(); ++i)
{
const ItemStack& item = mSourceModel->getItem(i);
if (item.mBase == itemToSearch.mBase)
return i;
}
return -1;
}
ItemModel::ModelIndex ProxyItemModel::mapFromSource(ModelIndex index)
{
const ItemStack& itemToSearch = mSourceModel->getItem(index);
for (size_t i = 0; i < getItemCount(); ++i)
{
const ItemStack& item = getItem(i);
if (item.mBase == itemToSearch.mBase)
return i;
}
return -1;
}
ItemModel::ModelIndex ProxyItemModel::getIndex(const ItemStack& item)
{
return mSourceModel->getIndex(item);
}
void ProxyItemModel::setSourceModel(std::unique_ptr<ItemModel> sourceModel)
{
mSourceModel = std::move(sourceModel);
}
void ProxyItemModel::onClose()
{
mSourceModel->onClose();
}
bool ProxyItemModel::onDropItem(const MWWorld::Ptr& item, int count)
{
return mSourceModel->onDropItem(item, count);
}
bool ProxyItemModel::onTakeItem(const MWWorld::Ptr& item, int count)
{
return mSourceModel->onTakeItem(item, count);
}
MWWorld::Ptr ProxyItemModel::addItem(const ItemStack& item, size_t count, bool allowAutoEquip)
{
return mSourceModel->addItem(item, count, allowAutoEquip);
}
bool ProxyItemModel::usesContainer(const MWWorld::Ptr& container)
{
return mSourceModel->usesContainer(container);
}
}
| 4,875
|
C++
|
.cpp
| 137
| 27.839416
| 120
| 0.633333
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,509
|
quickkeysmenu.cpp
|
OpenMW_openmw/apps/openmw/mwgui/quickkeysmenu.cpp
|
#include "quickkeysmenu.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_Gui.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_RenderManager.h>
#include <components/esm3/esmwriter.hpp>
#include <components/esm3/loadmgef.hpp>
#include <components/esm3/quickkeys.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/resource/resourcesystem.hpp>
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/player.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/spellutil.hpp"
#include "itemselection.hpp"
#include "itemwidget.hpp"
#include "sortfilteritemmodel.hpp"
#include "spellview.hpp"
namespace MWGui
{
QuickKeysMenu::QuickKeysMenu()
: WindowBase("openmw_quickkeys_menu.layout")
, mKey(std::vector<keyData>(10))
, mSelected(nullptr)
, mActivated(nullptr)
{
getWidget(mOkButton, "OKButton");
getWidget(mInstructionLabel, "InstructionLabel");
mMainWidget->setSize(mMainWidget->getWidth(),
mMainWidget->getHeight() + (mInstructionLabel->getTextSize().height - mInstructionLabel->getHeight()));
mOkButton->eventMouseButtonClick += MyGUI::newDelegate(this, &QuickKeysMenu::onOkButtonClicked);
center();
for (int i = 0; i < 10; ++i)
{
mKey[i].index = i + 1;
getWidget(mKey[i].button, "QuickKey" + MyGUI::utility::toString(i + 1));
mKey[i].button->eventMouseButtonClick += MyGUI::newDelegate(this, &QuickKeysMenu::onQuickKeyButtonClicked);
unassign(&mKey[i]);
}
}
void QuickKeysMenu::clear()
{
mActivated = nullptr;
for (int i = 0; i < 10; ++i)
{
unassign(&mKey[i]);
}
}
inline void QuickKeysMenu::validate(int index)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
MWWorld::InventoryStore& store = player.getClass().getInventoryStore(player);
switch (mKey[index].type)
{
case ESM::QuickKeys::Type::Unassigned:
case ESM::QuickKeys::Type::HandToHand:
case ESM::QuickKeys::Type::Magic:
break;
case ESM::QuickKeys::Type::Item:
case ESM::QuickKeys::Type::MagicItem:
{
MWWorld::Ptr item = *mKey[index].button->getUserData<MWWorld::Ptr>();
// Make sure the item is available and is not broken
if (item.isEmpty() || item.getCellRef().getCount() < 1
|| (item.getClass().hasItemHealth(item) && item.getClass().getItemHealth(item) <= 0))
{
// Try searching for a compatible replacement
item = store.findReplacement(mKey[index].id);
if (!item.isEmpty())
mKey[index].button->setUserData(MWWorld::Ptr(item));
break;
}
}
}
}
void QuickKeysMenu::onOpen()
{
WindowBase::onOpen();
// Quick key index
for (int index = 0; index < 10; ++index)
{
validate(index);
}
}
void QuickKeysMenu::onClose()
{
WindowBase::onClose();
if (mAssignDialog)
mAssignDialog->setVisible(false);
if (mItemSelectionDialog)
mItemSelectionDialog->setVisible(false);
if (mMagicSelectionDialog)
mMagicSelectionDialog->setVisible(false);
}
void QuickKeysMenu::unassign(keyData* key)
{
key->button->clearUserStrings();
key->button->setItem(MWWorld::Ptr());
while (key->button->getChildCount()) // Destroy number label
MyGUI::Gui::getInstance().destroyWidget(key->button->getChildAt(0));
if (key->index == 10)
{
key->type = ESM::QuickKeys::Type::HandToHand;
MyGUI::ImageBox* image = key->button->createWidget<MyGUI::ImageBox>(
"ImageBox", MyGUI::IntCoord(14, 13, 32, 32), MyGUI::Align::Default);
image->setImageTexture("icons\\k\\stealth_handtohand.dds");
image->setNeedMouseFocus(false);
}
else
{
key->type = ESM::QuickKeys::Type::Unassigned;
key->id = ESM::RefId();
key->name.clear();
MyGUI::TextBox* textBox = key->button->createWidgetReal<MyGUI::TextBox>(
"SandText", MyGUI::FloatCoord(0, 0, 1, 1), MyGUI::Align::Default);
textBox->setTextAlign(MyGUI::Align::Center);
textBox->setCaption(MyGUI::utility::toString(key->index));
textBox->setNeedMouseFocus(false);
}
}
void QuickKeysMenu::onQuickKeyButtonClicked(MyGUI::Widget* sender)
{
int index = -1;
for (int i = 0; i < 10; ++i)
{
if (sender == mKey[i].button || sender->getParent() == mKey[i].button)
{
index = i;
break;
}
}
assert(index != -1);
if (index < 0)
{
mSelected = nullptr;
return;
}
mSelected = &mKey[index];
// prevent reallocation of zero key from ESM::QuickKeys::Type::HandToHand
if (mSelected->index == 10)
return;
// open assign dialog
if (!mAssignDialog)
mAssignDialog = std::make_unique<QuickKeysMenuAssign>(this);
mAssignDialog->setVisible(true);
}
void QuickKeysMenu::onOkButtonClicked(MyGUI::Widget* sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_QuickKeysMenu);
}
void QuickKeysMenu::onItemButtonClicked(MyGUI::Widget* sender)
{
if (!mItemSelectionDialog)
{
mItemSelectionDialog = std::make_unique<ItemSelectionDialog>("#{sQuickMenu6}");
mItemSelectionDialog->eventItemSelected += MyGUI::newDelegate(this, &QuickKeysMenu::onAssignItem);
mItemSelectionDialog->eventDialogCanceled += MyGUI::newDelegate(this, &QuickKeysMenu::onAssignItemCancel);
}
mItemSelectionDialog->setVisible(true);
mItemSelectionDialog->openContainer(MWMechanics::getPlayer());
mItemSelectionDialog->setFilter(SortFilterItemModel::Filter_OnlyUsableItems);
mAssignDialog->setVisible(false);
}
void QuickKeysMenu::onMagicButtonClicked(MyGUI::Widget* sender)
{
if (!mMagicSelectionDialog)
{
mMagicSelectionDialog = std::make_unique<MagicSelectionDialog>(this);
}
mMagicSelectionDialog->setVisible(true);
mAssignDialog->setVisible(false);
}
void QuickKeysMenu::onUnassignButtonClicked(MyGUI::Widget* sender)
{
unassign(mSelected);
mAssignDialog->setVisible(false);
}
void QuickKeysMenu::onCancelButtonClicked(MyGUI::Widget* sender)
{
mAssignDialog->setVisible(false);
}
void QuickKeysMenu::onAssignItem(MWWorld::Ptr item)
{
assert(mSelected);
while (mSelected->button->getChildCount()) // Destroy number label
MyGUI::Gui::getInstance().destroyWidget(mSelected->button->getChildAt(0));
mSelected->type = ESM::QuickKeys::Type::Item;
mSelected->id = item.getCellRef().getRefId();
mSelected->name = item.getClass().getName(item);
mSelected->button->setItem(item, ItemWidget::Barter);
mSelected->button->setUserString("ToolTipType", "ItemPtr");
mSelected->button->setUserData(item);
if (mItemSelectionDialog)
mItemSelectionDialog->setVisible(false);
}
void QuickKeysMenu::onAssignItemCancel()
{
mItemSelectionDialog->setVisible(false);
}
void QuickKeysMenu::onAssignMagicItem(MWWorld::Ptr item)
{
assert(mSelected);
while (mSelected->button->getChildCount()) // Destroy number label
MyGUI::Gui::getInstance().destroyWidget(mSelected->button->getChildAt(0));
mSelected->type = ESM::QuickKeys::Type::MagicItem;
mSelected->id = item.getCellRef().getRefId();
mSelected->name = item.getClass().getName(item);
float scale = 1.f;
MyGUI::ITexture* texture
= MyGUI::RenderManager::getInstance().getTexture("textures\\menu_icon_select_magic_magic.dds");
if (texture)
scale = texture->getHeight() / 64.f;
mSelected->button->setFrame(
"textures\\menu_icon_select_magic_magic.dds", MyGUI::IntCoord(0, 0, 44 * scale, 44 * scale));
mSelected->button->setIcon(item);
mSelected->button->setUserString("ToolTipType", "ItemPtr");
mSelected->button->setUserData(MWWorld::Ptr(item));
if (mMagicSelectionDialog)
mMagicSelectionDialog->setVisible(false);
}
void QuickKeysMenu::onAssignMagic(const ESM::RefId& spellId)
{
assert(mSelected);
while (mSelected->button->getChildCount()) // Destroy number label
MyGUI::Gui::getInstance().destroyWidget(mSelected->button->getChildAt(0));
const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore();
const ESM::Spell* spell = esmStore.get<ESM::Spell>().find(spellId);
mSelected->type = ESM::QuickKeys::Type::Magic;
mSelected->id = spellId;
mSelected->name = spell->mName;
mSelected->button->setItem(MWWorld::Ptr());
mSelected->button->setUserString("ToolTipType", "Spell");
mSelected->button->setUserString("Spell", spellId.serialize());
// use the icon of the first effect
const ESM::MagicEffect* effect
= esmStore.get<ESM::MagicEffect>().find(spell->mEffects.mList.front().mData.mEffectID);
std::string path = effect->mIcon;
std::replace(path.begin(), path.end(), '/', '\\');
int slashPos = path.rfind('\\');
path.insert(slashPos + 1, "b_");
path = Misc::ResourceHelpers::correctIconPath(path, MWBase::Environment::get().getResourceSystem()->getVFS());
float scale = 1.f;
MyGUI::ITexture* texture
= MyGUI::RenderManager::getInstance().getTexture("textures\\menu_icon_select_magic.dds");
if (texture)
scale = texture->getHeight() / 64.f;
mSelected->button->setFrame(
"textures\\menu_icon_select_magic.dds", MyGUI::IntCoord(0, 0, 44 * scale, 44 * scale));
mSelected->button->setIcon(path);
if (mMagicSelectionDialog)
mMagicSelectionDialog->setVisible(false);
}
void QuickKeysMenu::onAssignMagicCancel()
{
mMagicSelectionDialog->setVisible(false);
}
void QuickKeysMenu::updateActivatedQuickKey()
{
// there is no delayed action, nothing to do.
if (!mActivated)
return;
activateQuickKey(mActivated->index);
}
void QuickKeysMenu::activateQuickKey(int index)
{
assert(index >= 1 && index <= 10);
keyData* key = &mKey[index - 1];
MWWorld::Ptr player = MWMechanics::getPlayer();
MWWorld::InventoryStore& store = player.getClass().getInventoryStore(player);
const MWMechanics::CreatureStats& playerStats = player.getClass().getCreatureStats(player);
validate(index - 1);
// Delay action executing,
// if player is busy for now (casting a spell, attacking someone, etc.)
bool isDelayNeeded = MWBase::Environment::get().getMechanicsManager()->isAttackingOrSpell(player)
|| playerStats.getKnockedDown() || playerStats.getHitRecovery();
bool isReturnNeeded = playerStats.isParalyzed() || playerStats.isDead();
if (isReturnNeeded)
{
return;
}
else if (isDelayNeeded)
{
mActivated = key;
return;
}
else
{
mActivated = nullptr;
}
if (key->type == ESM::QuickKeys::Type::Item || key->type == ESM::QuickKeys::Type::MagicItem)
{
MWWorld::Ptr item = *key->button->getUserData<MWWorld::Ptr>();
MWWorld::ContainerStoreIterator it = store.begin();
for (; it != store.end(); ++it)
{
if (*it == item)
break;
}
if (it == store.end())
item = nullptr;
// check the item is available and not broken
if (item.isEmpty() || item.getCellRef().getCount() < 1
|| (item.getClass().hasItemHealth(item) && item.getClass().getItemHealth(item) <= 0))
{
item = store.findReplacement(key->id);
if (item.isEmpty() || item.getCellRef().getCount() < 1)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sQuickMenu5} " + key->name);
return;
}
}
if (key->type == ESM::QuickKeys::Type::Item)
{
if (!store.isEquipped(item))
MWBase::Environment::get().getWindowManager()->useItem(item);
MWWorld::ConstContainerStoreIterator rightHand
= store.getSlot(MWWorld::InventoryStore::Slot_CarriedRight);
// change draw state only if the item is in player's right hand
if (rightHand != store.end() && item == *rightHand)
{
MWBase::Environment::get().getWorld()->getPlayer().setDrawState(MWMechanics::DrawState::Weapon);
}
}
else if (key->type == ESM::QuickKeys::Type::MagicItem)
{
// equip, if it can be equipped and isn't yet equipped
if (!item.getClass().getEquipmentSlots(item).first.empty() && !store.isEquipped(item))
{
MWBase::Environment::get().getWindowManager()->useItem(item);
// make sure that item was successfully equipped
if (!store.isEquipped(item))
return;
}
store.setSelectedEnchantItem(it);
MWBase::Environment::get().getWorld()->getPlayer().setDrawState(MWMechanics::DrawState::Spell);
}
}
else if (key->type == ESM::QuickKeys::Type::Magic)
{
const ESM::RefId& spellId = key->id;
// Make sure the player still has this spell
MWMechanics::CreatureStats& stats = player.getClass().getCreatureStats(player);
MWMechanics::Spells& spells = stats.getSpells();
if (!spells.hasSpell(spellId))
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sQuickMenu5} " + key->name);
return;
}
store.setSelectedEnchantItem(store.end());
MWBase::Environment::get().getWindowManager()->setSelectedSpell(
spellId, int(MWMechanics::getSpellSuccessChance(spellId, player)));
MWBase::Environment::get().getWorld()->getPlayer().setDrawState(MWMechanics::DrawState::Spell);
}
else if (key->type == ESM::QuickKeys::Type::HandToHand)
{
store.unequipSlot(MWWorld::InventoryStore::Slot_CarriedRight);
MWBase::Environment::get().getWorld()->getPlayer().setDrawState(MWMechanics::DrawState::Weapon);
}
}
// ---------------------------------------------------------------------------------------------------------
QuickKeysMenuAssign::QuickKeysMenuAssign(QuickKeysMenu* parent)
: WindowModal("openmw_quickkeys_menu_assign.layout")
, mParent(parent)
{
getWidget(mLabel, "Label");
getWidget(mItemButton, "ItemButton");
getWidget(mMagicButton, "MagicButton");
getWidget(mUnassignButton, "UnassignButton");
getWidget(mCancelButton, "CancelButton");
mItemButton->eventMouseButtonClick += MyGUI::newDelegate(mParent, &QuickKeysMenu::onItemButtonClicked);
mMagicButton->eventMouseButtonClick += MyGUI::newDelegate(mParent, &QuickKeysMenu::onMagicButtonClicked);
mUnassignButton->eventMouseButtonClick += MyGUI::newDelegate(mParent, &QuickKeysMenu::onUnassignButtonClicked);
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(mParent, &QuickKeysMenu::onCancelButtonClicked);
int maxWidth = mLabel->getTextSize().width + 24;
maxWidth = std::max(maxWidth, mItemButton->getTextSize().width + 24);
maxWidth = std::max(maxWidth, mMagicButton->getTextSize().width + 24);
maxWidth = std::max(maxWidth, mUnassignButton->getTextSize().width + 24);
maxWidth = std::max(maxWidth, mCancelButton->getTextSize().width + 24);
mMainWidget->setSize(maxWidth + 24, mMainWidget->getHeight());
mLabel->setSize(maxWidth, mLabel->getHeight());
mItemButton->setCoord((maxWidth - mItemButton->getTextSize().width - 24) / 2 + 8, mItemButton->getTop(),
mItemButton->getTextSize().width + 24, mItemButton->getHeight());
mMagicButton->setCoord((maxWidth - mMagicButton->getTextSize().width - 24) / 2 + 8, mMagicButton->getTop(),
mMagicButton->getTextSize().width + 24, mMagicButton->getHeight());
mUnassignButton->setCoord((maxWidth - mUnassignButton->getTextSize().width - 24) / 2 + 8,
mUnassignButton->getTop(), mUnassignButton->getTextSize().width + 24, mUnassignButton->getHeight());
mCancelButton->setCoord((maxWidth - mCancelButton->getTextSize().width - 24) / 2 + 8, mCancelButton->getTop(),
mCancelButton->getTextSize().width + 24, mCancelButton->getHeight());
center();
}
void QuickKeysMenu::write(ESM::ESMWriter& writer)
{
writer.startRecord(ESM::REC_KEYS);
ESM::QuickKeys keys;
// NB: The quick key with index 9 always has Hand-to-Hand type and must not be saved
for (int i = 0; i < 9; ++i)
{
ItemWidget* button = mKey[i].button;
const ESM::QuickKeys::Type type = mKey[i].type;
ESM::QuickKeys::QuickKey key;
key.mType = type;
switch (type)
{
case ESM::QuickKeys::Type::Unassigned:
case ESM::QuickKeys::Type::HandToHand:
break;
case ESM::QuickKeys::Type::Item:
case ESM::QuickKeys::Type::MagicItem:
{
MWWorld::Ptr item = *button->getUserData<MWWorld::Ptr>();
key.mId = item.getCellRef().getRefId();
break;
}
case ESM::QuickKeys::Type::Magic:
key.mId = ESM::RefId::deserialize(button->getUserString("Spell"));
break;
}
keys.mKeys.push_back(key);
}
keys.save(writer);
writer.endRecord(ESM::REC_KEYS);
}
void QuickKeysMenu::readRecord(ESM::ESMReader& reader, uint32_t type)
{
if (type != ESM::REC_KEYS)
return;
ESM::QuickKeys keys;
keys.load(reader);
MWWorld::Ptr player = MWMechanics::getPlayer();
MWWorld::InventoryStore& store = player.getClass().getInventoryStore(player);
int i = 0;
for (ESM::QuickKeys::QuickKey& quickKey : keys.mKeys)
{
// NB: The quick key with index 9 always has Hand-to-Hand type and must not be loaded
if (i >= 9)
return;
mSelected = &mKey[i];
switch (quickKey.mType)
{
case ESM::QuickKeys::Type::Magic:
if (MWBase::Environment::get().getESMStore()->get<ESM::Spell>().search(quickKey.mId))
onAssignMagic(quickKey.mId);
break;
case ESM::QuickKeys::Type::Item:
case ESM::QuickKeys::Type::MagicItem:
{
// Find the item by id
MWWorld::Ptr item = store.findReplacement(quickKey.mId);
if (item.isEmpty())
unassign(mSelected);
else
{
if (quickKey.mType == ESM::QuickKeys::Type::Item)
onAssignItem(item);
else // if (quickKey.mType == ESM::QuickKeys::Type::MagicItem)
onAssignMagicItem(item);
}
break;
}
case ESM::QuickKeys::Type::Unassigned:
case ESM::QuickKeys::Type::HandToHand:
unassign(mSelected);
break;
}
++i;
}
}
// ---------------------------------------------------------------------------------------------------------
MagicSelectionDialog::MagicSelectionDialog(QuickKeysMenu* parent)
: WindowModal("openmw_magicselection_dialog.layout")
, mParent(parent)
{
getWidget(mCancelButton, "CancelButton");
getWidget(mMagicList, "MagicList");
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &MagicSelectionDialog::onCancelButtonClicked);
mMagicList->setShowCostColumn(false);
mMagicList->setHighlightSelected(false);
mMagicList->eventSpellClicked += MyGUI::newDelegate(this, &MagicSelectionDialog::onModelIndexSelected);
center();
}
void MagicSelectionDialog::onCancelButtonClicked(MyGUI::Widget* sender)
{
exit();
}
bool MagicSelectionDialog::exit()
{
mParent->onAssignMagicCancel();
return true;
}
void MagicSelectionDialog::onOpen()
{
WindowModal::onOpen();
mMagicList->setModel(new SpellModel(MWMechanics::getPlayer()));
mMagicList->resetScrollbars();
}
void MagicSelectionDialog::onModelIndexSelected(SpellModel::ModelIndex index)
{
const Spell& spell = mMagicList->getModel()->getItem(index);
if (spell.mType == Spell::Type_EnchantedItem)
mParent->onAssignMagicItem(spell.mItem);
else
mParent->onAssignMagic(spell.mId);
}
}
| 22,551
|
C++
|
.cpp
| 512
| 33.335938
| 119
| 0.593157
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,510
|
statswatcher.cpp
|
OpenMW_openmw/apps/openmw/mwgui/statswatcher.cpp
|
#include "statswatcher.hpp"
#include <components/esm3/loadclas.hpp>
#include <components/esm3/loadrace.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include <string>
namespace MWGui
{
// mWatchedTimeToStartDrowning = -1 for correct drowning state check,
// if stats.getTimeToStartDrowning() == 0 already on game start
StatsWatcher::StatsWatcher()
: mWatchedLevel(-1)
, mWatchedTimeToStartDrowning(-1)
, mWatchedStatsEmpty(true)
{
}
void StatsWatcher::watchActor(const MWWorld::Ptr& ptr)
{
mWatched = ptr;
}
void StatsWatcher::update()
{
if (mWatched.isEmpty())
return;
const auto& store = MWBase::Environment::get().getESMStore();
MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager();
const MWMechanics::NpcStats& stats = mWatched.getClass().getNpcStats(mWatched);
for (const ESM::Attribute& attribute : store->get<ESM::Attribute>())
{
const auto& value = stats.getAttribute(attribute.mId);
if (value != mWatchedAttributes[attribute.mId] || mWatchedStatsEmpty)
{
mWatchedAttributes[attribute.mId] = value;
setAttribute(attribute.mId, value);
}
}
if (stats.getHealth() != mWatchedHealth || mWatchedStatsEmpty)
{
mWatchedHealth = stats.getHealth();
setValue("HBar", stats.getHealth());
}
if (stats.getMagicka() != mWatchedMagicka || mWatchedStatsEmpty)
{
mWatchedMagicka = stats.getMagicka();
setValue("MBar", stats.getMagicka());
}
if (stats.getFatigue() != mWatchedFatigue || mWatchedStatsEmpty)
{
mWatchedFatigue = stats.getFatigue();
setValue("FBar", stats.getFatigue());
}
float timeToDrown = stats.getTimeToStartDrowning();
if (timeToDrown != mWatchedTimeToStartDrowning)
{
static const float fHoldBreathTime = MWBase::Environment::get()
.getESMStore()
->get<ESM::GameSetting>()
.find("fHoldBreathTime")
->mValue.getFloat();
mWatchedTimeToStartDrowning = timeToDrown;
if (timeToDrown >= fHoldBreathTime || timeToDrown == -1.0) // -1.0 is a special value during initialization
winMgr->setDrowningBarVisibility(false);
else
{
winMgr->setDrowningBarVisibility(true);
winMgr->setDrowningTimeLeft(stats.getTimeToStartDrowning(), fHoldBreathTime);
}
}
for (const ESM::Skill& skill : store->get<ESM::Skill>())
{
const auto& value = stats.getSkill(skill.mId);
if (value != mWatchedSkills[skill.mId] || mWatchedStatsEmpty)
{
mWatchedSkills[skill.mId] = value;
setValue(skill.mId, value);
}
}
if (stats.getLevel() != mWatchedLevel || mWatchedStatsEmpty)
{
mWatchedLevel = stats.getLevel();
setValue("level", mWatchedLevel);
}
if (mWatched.getClass().isNpc())
{
const ESM::NPC* watchedRecord = mWatched.get<ESM::NPC>()->mBase;
if (watchedRecord->mName != mWatchedName || mWatchedStatsEmpty)
{
mWatchedName = watchedRecord->mName;
setValue("name", watchedRecord->mName);
}
if (watchedRecord->mRace != mWatchedRace || mWatchedStatsEmpty)
{
mWatchedRace = watchedRecord->mRace;
const ESM::Race* race = store->get<ESM::Race>().find(watchedRecord->mRace);
setValue("race", race->mName);
}
if (watchedRecord->mClass != mWatchedClass || mWatchedStatsEmpty)
{
mWatchedClass = watchedRecord->mClass;
const ESM::Class* cls = store->get<ESM::Class>().find(watchedRecord->mClass);
setValue("class", cls->mName);
size_t size = cls->mData.mSkills.size();
std::vector<ESM::RefId> majorSkills(size);
std::vector<ESM::RefId> minorSkills(size);
for (size_t i = 0; i < size; ++i)
{
minorSkills[i] = ESM::Skill::indexToRefId(cls->mData.mSkills[i][0]);
majorSkills[i] = ESM::Skill::indexToRefId(cls->mData.mSkills[i][1]);
}
configureSkills(majorSkills, minorSkills);
}
}
mWatchedStatsEmpty = false;
}
void StatsWatcher::addListener(StatsListener* listener)
{
mListeners.insert(listener);
}
void StatsWatcher::removeListener(StatsListener* listener)
{
mListeners.erase(listener);
}
void StatsWatcher::setAttribute(ESM::RefId id, const MWMechanics::AttributeValue& value)
{
for (StatsListener* listener : mListeners)
listener->setAttribute(id, value);
}
void StatsWatcher::setValue(ESM::RefId id, const MWMechanics::SkillValue& value)
{
for (StatsListener* listener : mListeners)
listener->setValue(id, value);
}
void StatsWatcher::setValue(std::string_view id, const MWMechanics::DynamicStat<float>& value)
{
for (StatsListener* listener : mListeners)
listener->setValue(id, value);
}
void StatsWatcher::setValue(std::string_view id, const std::string& value)
{
for (StatsListener* listener : mListeners)
listener->setValue(id, value);
}
void StatsWatcher::setValue(std::string_view id, int value)
{
for (StatsListener* listener : mListeners)
listener->setValue(id, value);
}
void StatsWatcher::configureSkills(const std::vector<ESM::RefId>& major, const std::vector<ESM::RefId>& minor)
{
for (StatsListener* listener : mListeners)
listener->configureSkills(major, minor);
}
}
| 6,395
|
C++
|
.cpp
| 156
| 29.865385
| 119
| 0.582407
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,511
|
mainmenu.cpp
|
OpenMW_openmw/apps/openmw/mwgui/mainmenu.cpp
|
#include "mainmenu.hpp"
#include <MyGUI_Gui.h>
#include <MyGUI_RenderManager.h>
#include <MyGUI_TextBox.h>
#include <components/misc/frameratelimiter.hpp>
#include <components/settings/values.hpp>
#include <components/vfs/manager.hpp>
#include <components/vfs/pathutil.hpp>
#include <components/widgets/imagebutton.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/statemanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/globals.hpp"
#include "backgroundimage.hpp"
#include "confirmationdialog.hpp"
#include "savegamedialog.hpp"
#include "settingswindow.hpp"
#include "videowidget.hpp"
namespace MWGui
{
void MenuVideo::run()
{
Misc::FrameRateLimiter frameRateLimiter
= Misc::makeFrameRateLimiter(MWBase::Environment::get().getFrameRateLimit());
while (mRunning)
{
// If finished playing, start again
if (!mVideo->update())
mVideo->playVideo("video\\menu_background.bik");
frameRateLimiter.limit();
}
}
MenuVideo::MenuVideo(const VFS::Manager* vfs)
: mRunning(true)
{
// Use black background to correct aspect ratio
mVideoBackground = MyGUI::Gui::getInstance().createWidgetReal<MyGUI::ImageBox>(
"ImageBox", 0, 0, 1, 1, MyGUI::Align::Default, "MainMenuBackground");
mVideoBackground->setImageTexture("black");
mVideo = mVideoBackground->createWidget<VideoWidget>(
"ImageBox", 0, 0, 1, 1, MyGUI::Align::Stretch, "MainMenuBackground");
mVideo->setVFS(vfs);
mVideo->playVideo("video\\menu_background.bik");
mThread = std::thread([this] { run(); });
}
void MenuVideo::resize(int screenWidth, int screenHeight)
{
const bool stretch = Settings::gui().mStretchMenuBackground;
mVideoBackground->setSize(screenWidth, screenHeight);
mVideo->autoResize(stretch);
mVideo->setVisible(true);
}
MenuVideo::~MenuVideo()
{
mRunning = false;
mThread.join();
try
{
MyGUI::Gui::getInstance().destroyWidget(mVideoBackground);
}
catch (const MyGUI::Exception& e)
{
Log(Debug::Error) << "Error in the destructor: " << e.what();
}
}
MainMenu::MainMenu(int w, int h, const VFS::Manager* vfs, const std::string& versionDescription)
: WindowBase("openmw_mainmenu.layout")
, mWidth(w)
, mHeight(h)
, mVFS(vfs)
, mButtonBox(nullptr)
, mBackground(nullptr)
{
getWidget(mVersionText, "VersionText");
mVersionText->setCaption(versionDescription);
constexpr VFS::Path::NormalizedView menuBackgroundVideo("video/menu_background.bik");
mHasAnimatedMenu = mVFS->exists(menuBackgroundVideo);
updateMenu();
}
void MainMenu::onResChange(int w, int h)
{
mWidth = w;
mHeight = h;
updateMenu();
if (mVideo)
mVideo->resize(w, h);
}
void MainMenu::setVisible(bool visible)
{
if (visible)
updateMenu();
bool isMainMenu = MWBase::Environment::get().getWindowManager()->containsMode(MWGui::GM_MainMenu)
&& MWBase::Environment::get().getStateManager()->getState() == MWBase::StateManager::State_NoGame;
showBackground(isMainMenu);
if (visible)
{
if (isMainMenu)
{
if (mButtons["loadgame"]->getVisible())
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mButtons["loadgame"]);
else
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mButtons["newgame"]);
}
else
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mButtons["return"]);
}
Layout::setVisible(visible);
}
void MainMenu::onNewGameConfirmed()
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(MWGui::GM_MainMenu);
MWBase::Environment::get().getStateManager()->newGame();
}
void MainMenu::onExitConfirmed()
{
MWBase::Environment::get().getStateManager()->requestQuit();
}
void MainMenu::onButtonClicked(MyGUI::Widget* sender)
{
MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager();
const std::string& name = *sender->getUserData<std::string>();
winMgr->playSound(ESM::RefId::stringRefId("Menu Click"));
if (name == "return")
{
winMgr->removeGuiMode(GM_MainMenu);
}
else if (name == "credits")
winMgr->playVideo("mw_credits.bik", true);
else if (name == "exitgame")
{
if (MWBase::Environment::get().getStateManager()->getState() == MWBase::StateManager::State_NoGame)
onExitConfirmed();
else
{
ConfirmationDialog* dialog = winMgr->getConfirmationDialog();
dialog->askForConfirmation("#{OMWEngine:QuitGameConfirmation}");
dialog->eventOkClicked.clear();
dialog->eventOkClicked += MyGUI::newDelegate(this, &MainMenu::onExitConfirmed);
dialog->eventCancelClicked.clear();
}
}
else if (name == "newgame")
{
if (MWBase::Environment::get().getStateManager()->getState() == MWBase::StateManager::State_NoGame)
onNewGameConfirmed();
else
{
ConfirmationDialog* dialog = winMgr->getConfirmationDialog();
dialog->askForConfirmation("#{OMWEngine:NewGameConfirmation}");
dialog->eventOkClicked.clear();
dialog->eventOkClicked += MyGUI::newDelegate(this, &MainMenu::onNewGameConfirmed);
dialog->eventCancelClicked.clear();
}
}
else if (name == "loadgame" || name == "savegame")
{
if (!mSaveGameDialog)
mSaveGameDialog = std::make_unique<SaveGameDialog>();
mSaveGameDialog->setLoadOrSave(name == "loadgame");
mSaveGameDialog->setVisible(true);
}
if (winMgr->isSettingsWindowVisible() || name == "options")
{
winMgr->toggleSettingsWindow();
}
}
void MainMenu::showBackground(bool show)
{
if (mVideo && !show)
{
mVideo.reset();
}
if (mBackground && !show)
{
MyGUI::Gui::getInstance().destroyWidget(mBackground);
mBackground = nullptr;
}
if (!show)
return;
const bool stretch = Settings::gui().mStretchMenuBackground;
if (mHasAnimatedMenu)
{
if (!mVideo)
mVideo.emplace(mVFS);
const auto& viewSize = MyGUI::RenderManager::getInstance().getViewSize();
int screenWidth = viewSize.width;
int screenHeight = viewSize.height;
mVideo->resize(screenWidth, screenHeight);
}
else
{
if (!mBackground)
{
mBackground = MyGUI::Gui::getInstance().createWidgetReal<BackgroundImage>(
"ImageBox", 0, 0, 1, 1, MyGUI::Align::Stretch, "MainMenuBackground");
mBackground->setBackgroundImage("textures\\menu_morrowind.dds", true, stretch);
}
mBackground->setVisible(true);
}
}
bool MainMenu::exit()
{
if (MWBase::Environment::get().getWindowManager()->isSettingsWindowVisible())
{
MWBase::Environment::get().getWindowManager()->toggleSettingsWindow();
return false;
}
return MWBase::Environment::get().getStateManager()->getState() == MWBase::StateManager::State_Running;
}
void MainMenu::updateMenu()
{
setCoord(0, 0, mWidth, mHeight);
if (!mButtonBox)
mButtonBox
= mMainWidget->createWidget<MyGUI::Widget>({}, MyGUI::IntCoord(0, 0, 0, 0), MyGUI::Align::Default);
int curH = 0;
MWBase::StateManager::State state = MWBase::Environment::get().getStateManager()->getState();
mVersionText->setVisible(state == MWBase::StateManager::State_NoGame);
std::vector<std::string> buttons;
if (state == MWBase::StateManager::State_Running)
buttons.emplace_back("return");
buttons.emplace_back("newgame");
if (state == MWBase::StateManager::State_Running
&& MWBase::Environment::get().getWorld()->getGlobalInt(MWWorld::Globals::sCharGenState) == -1
&& MWBase::Environment::get().getWindowManager()->isSavingAllowed())
buttons.emplace_back("savegame");
if (MWBase::Environment::get().getStateManager()->characterBegin()
!= MWBase::Environment::get().getStateManager()->characterEnd())
buttons.emplace_back("loadgame");
buttons.emplace_back("options");
if (state == MWBase::StateManager::State_NoGame)
buttons.emplace_back("credits");
buttons.emplace_back("exitgame");
// Create new buttons if needed
for (std::string_view id : { "return", "newgame", "savegame", "loadgame", "options", "credits", "exitgame" })
{
if (mButtons.find(id) == mButtons.end())
{
Gui::ImageButton* button = mButtonBox->createWidget<Gui::ImageButton>(
"ImageBox", MyGUI::IntCoord(0, curH, 0, 0), MyGUI::Align::Default);
const std::string& buttonId = mButtons.emplace(id, button).first->first;
button->setProperty("ImageHighlighted", "textures\\menu_" + buttonId + "_over.dds");
button->setProperty("ImageNormal", "textures\\menu_" + buttonId + ".dds");
button->setProperty("ImagePushed", "textures\\menu_" + buttonId + "_pressed.dds");
button->eventMouseButtonClick += MyGUI::newDelegate(this, &MainMenu::onButtonClicked);
button->setUserData(buttonId);
}
}
// Start by hiding all buttons
int maxwidth = 0;
for (const auto& buttonPair : mButtons)
{
buttonPair.second->setVisible(false);
MyGUI::IntSize requested = buttonPair.second->getRequestedSize();
if (requested.width > maxwidth)
maxwidth = requested.width;
}
// Now show and position the ones we want
for (const std::string& buttonId : buttons)
{
auto it = mButtons.find(buttonId);
assert(it != mButtons.end());
Gui::ImageButton* button = it->second;
button->setVisible(true);
// By default, assume that all menu buttons textures should have 64 height.
// If they have a different resolution, scale them.
MyGUI::IntSize requested = button->getRequestedSize();
float scale = requested.height / 64.f;
button->setImageCoord(MyGUI::IntCoord(0, 0, requested.width, requested.height));
// Trim off some of the excessive padding
// TODO: perhaps do this within ImageButton?
int height = requested.height;
button->setImageTile(MyGUI::IntSize(requested.width, requested.height - 16 * scale));
button->setCoord(
(maxwidth - requested.width / scale) / 2, curH, requested.width / scale, height / scale - 16);
curH += height / scale - 16;
}
if (state == MWBase::StateManager::State_NoGame)
{
// Align with the background image
int bottomPadding = 24;
mButtonBox->setCoord(mWidth / 2 - maxwidth / 2, mHeight - curH - bottomPadding, maxwidth, curH);
}
else
mButtonBox->setCoord(mWidth / 2 - maxwidth / 2, mHeight / 2 - curH / 2, maxwidth, curH);
}
}
| 12,088
|
C++
|
.cpp
| 288
| 31.871528
| 117
| 0.59811
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,512
|
alchemywindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/alchemywindow.cpp
|
#include "alchemywindow.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_ComboBox.h>
#include <MyGUI_ControllerManager.h>
#include <MyGUI_ControllerRepeatClick.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_Gui.h>
#include <MyGUI_UString.h>
#include <components/esm3/loadappa.hpp>
#include <components/esm3/loadingr.hpp>
#include <components/esm3/loadmgef.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/alchemy.hpp"
#include "../mwmechanics/magiceffects.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include <MyGUI_Macros.h>
#include "inventoryitemmodel.hpp"
#include "itemview.hpp"
#include "itemwidget.hpp"
#include "sortfilteritemmodel.hpp"
#include "widgets.hpp"
namespace MWGui
{
AlchemyWindow::AlchemyWindow()
: WindowBase("openmw_alchemy_window.layout")
, mCurrentFilter(FilterType::ByName)
, mModel(nullptr)
, mSortModel(nullptr)
, mAlchemy(std::make_unique<MWMechanics::Alchemy>())
, mApparatus(4)
, mIngredients(4)
{
getWidget(mCreateButton, "CreateButton");
getWidget(mCancelButton, "CancelButton");
getWidget(mIngredients[0], "Ingredient1");
getWidget(mIngredients[1], "Ingredient2");
getWidget(mIngredients[2], "Ingredient3");
getWidget(mIngredients[3], "Ingredient4");
getWidget(mApparatus[0], "Apparatus1");
getWidget(mApparatus[1], "Apparatus2");
getWidget(mApparatus[2], "Apparatus3");
getWidget(mApparatus[3], "Apparatus4");
getWidget(mEffectsBox, "CreatedEffects");
getWidget(mBrewCountEdit, "BrewCount");
getWidget(mIncreaseButton, "IncreaseButton");
getWidget(mDecreaseButton, "DecreaseButton");
getWidget(mNameEdit, "NameEdit");
getWidget(mItemView, "ItemView");
getWidget(mFilterValue, "FilterValue");
getWidget(mFilterType, "FilterType");
mBrewCountEdit->eventValueChanged += MyGUI::newDelegate(this, &AlchemyWindow::onCountValueChanged);
mBrewCountEdit->eventEditSelectAccept += MyGUI::newDelegate(this, &AlchemyWindow::onAccept);
mBrewCountEdit->setMinValue(1);
mBrewCountEdit->setValue(1);
mIncreaseButton->eventMouseButtonPressed += MyGUI::newDelegate(this, &AlchemyWindow::onIncreaseButtonPressed);
mIncreaseButton->eventMouseButtonReleased += MyGUI::newDelegate(this, &AlchemyWindow::onCountButtonReleased);
mDecreaseButton->eventMouseButtonPressed += MyGUI::newDelegate(this, &AlchemyWindow::onDecreaseButtonPressed);
mDecreaseButton->eventMouseButtonReleased += MyGUI::newDelegate(this, &AlchemyWindow::onCountButtonReleased);
mItemView->eventItemClicked += MyGUI::newDelegate(this, &AlchemyWindow::onSelectedItem);
mIngredients[0]->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onIngredientSelected);
mIngredients[1]->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onIngredientSelected);
mIngredients[2]->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onIngredientSelected);
mIngredients[3]->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onIngredientSelected);
mApparatus[0]->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onApparatusSelected);
mApparatus[1]->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onApparatusSelected);
mApparatus[2]->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onApparatusSelected);
mApparatus[3]->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onApparatusSelected);
mCreateButton->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onCreateButtonClicked);
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onCancelButtonClicked);
mNameEdit->eventEditSelectAccept += MyGUI::newDelegate(this, &AlchemyWindow::onAccept);
mFilterValue->eventComboChangePosition += MyGUI::newDelegate(this, &AlchemyWindow::onFilterChanged);
mFilterValue->eventEditTextChange += MyGUI::newDelegate(this, &AlchemyWindow::onFilterEdited);
mFilterType->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::switchFilterType);
center();
}
void AlchemyWindow::onAccept(MyGUI::EditBox* sender)
{
onCreateButtonClicked(sender);
// To do not spam onAccept() again and again
MWBase::Environment::get().getWindowManager()->injectKeyRelease(MyGUI::KeyCode::None);
}
void AlchemyWindow::onCancelButtonClicked(MyGUI::Widget* _sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Alchemy);
}
void AlchemyWindow::onCreateButtonClicked(MyGUI::Widget* _sender)
{
mAlchemy->setPotionName(mNameEdit->getCaption());
int count = mAlchemy->countPotionsToBrew();
count = std::min(count, mBrewCountEdit->getValue());
createPotions(count);
}
void AlchemyWindow::createPotions(int count)
{
MWMechanics::Alchemy::Result result = mAlchemy->create(mNameEdit->getCaption(), count);
MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager();
switch (result)
{
case MWMechanics::Alchemy::Result_NoName:
winMgr->messageBox("#{sNotifyMessage37}");
break;
case MWMechanics::Alchemy::Result_NoMortarAndPestle:
winMgr->messageBox("#{sNotifyMessage45}");
break;
case MWMechanics::Alchemy::Result_LessThanTwoIngredients:
winMgr->messageBox("#{sNotifyMessage6a}");
break;
case MWMechanics::Alchemy::Result_Success:
winMgr->playSound(ESM::RefId::stringRefId("potion success"));
if (count == 1)
winMgr->messageBox("#{sPotionSuccess}");
else
winMgr->messageBox(
"#{sPotionSuccess} " + mNameEdit->getCaption().asUTF8() + " (" + std::to_string(count) + ")");
break;
case MWMechanics::Alchemy::Result_NoEffects:
case MWMechanics::Alchemy::Result_RandomFailure:
winMgr->messageBox("#{sNotifyMessage8}");
winMgr->playSound(ESM::RefId::stringRefId("potion fail"));
break;
}
// remove ingredient slots that have been fully used up
for (size_t i = 0; i < mIngredients.size(); ++i)
if (mIngredients[i]->isUserString("ToolTipType"))
{
MWWorld::Ptr ingred = *mIngredients[i]->getUserData<MWWorld::Ptr>();
if (ingred.getCellRef().getCount() == 0)
mAlchemy->removeIngredient(i);
}
updateFilters();
update();
}
void AlchemyWindow::initFilter()
{
auto const& wm = MWBase::Environment::get().getWindowManager();
std::string_view ingredient = wm->getGameSettingString("sIngredients", "Ingredients");
if (mFilterType->getCaption() == ingredient)
mCurrentFilter = FilterType::ByName;
else
mCurrentFilter = FilterType::ByEffect;
updateFilters();
mFilterValue->clearIndexSelected();
updateFilters();
}
void AlchemyWindow::switchFilterType(MyGUI::Widget* _sender)
{
auto const& wm = MWBase::Environment::get().getWindowManager();
std::string_view ingredient = wm->getGameSettingString("sIngredients", "Ingredients");
auto* button = _sender->castType<MyGUI::Button>();
if (button->getCaption() == ingredient)
{
button->setCaption(MyGUI::UString(wm->getGameSettingString("sMagicEffects", "Magic Effects")));
mCurrentFilter = FilterType::ByEffect;
}
else
{
button->setCaption(MyGUI::UString(ingredient));
mCurrentFilter = FilterType::ByName;
}
mSortModel->setNameFilter({});
mSortModel->setEffectFilter({});
mFilterValue->clearIndexSelected();
updateFilters();
mItemView->update();
}
void AlchemyWindow::updateFilters()
{
std::set<std::string> itemNames, itemEffects;
for (size_t i = 0; i < mModel->getItemCount(); ++i)
{
MWWorld::Ptr item = mModel->getItem(i).mBase;
if (item.getType() != ESM::Ingredient::sRecordId)
continue;
itemNames.emplace(item.getClass().getName(item));
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
auto const alchemySkill = player.getClass().getSkill(player, ESM::Skill::Alchemy);
auto const effects = MWMechanics::Alchemy::effectsDescription(item, alchemySkill);
itemEffects.insert(effects.begin(), effects.end());
}
mFilterValue->removeAllItems();
auto const addItems = [&](auto const& container) {
for (auto const& item : container)
mFilterValue->addItem(item);
};
switch (mCurrentFilter)
{
case FilterType::ByName:
addItems(itemNames);
break;
case FilterType::ByEffect:
addItems(itemEffects);
break;
}
}
void AlchemyWindow::applyFilter(const std::string& filter)
{
switch (mCurrentFilter)
{
case FilterType::ByName:
mSortModel->setNameFilter(filter);
break;
case FilterType::ByEffect:
mSortModel->setEffectFilter(filter);
break;
}
mItemView->update();
}
void AlchemyWindow::onFilterChanged(MyGUI::ComboBox* _sender, size_t _index)
{
// ignore spurious event fired when one edit the content after selection.
// onFilterEdited will handle it.
if (_index != MyGUI::ITEM_NONE)
applyFilter(_sender->getItemNameAt(_index));
}
void AlchemyWindow::onFilterEdited(MyGUI::EditBox* _sender)
{
applyFilter(_sender->getCaption());
}
void AlchemyWindow::onOpen()
{
mAlchemy->clear();
mAlchemy->setAlchemist(MWMechanics::getPlayer());
auto model = std::make_unique<InventoryItemModel>(MWMechanics::getPlayer());
mModel = model.get();
auto sortModel = std::make_unique<SortFilterItemModel>(std::move(model));
mSortModel = sortModel.get();
mSortModel->setFilter(SortFilterItemModel::Filter_OnlyIngredients);
mItemView->setModel(std::move(sortModel));
mItemView->resetScrollBars();
mNameEdit->setCaption({});
mBrewCountEdit->setValue(1);
size_t index = 0;
for (auto iter = mAlchemy->beginTools(); iter != mAlchemy->endTools() && index < mApparatus.size();
++iter, ++index)
{
const auto& widget = mApparatus[index];
widget->setItem(*iter);
widget->clearUserStrings();
if (!iter->isEmpty())
{
widget->setUserString("ToolTipType", "ItemPtr");
widget->setUserData(MWWorld::Ptr(*iter));
}
}
update();
initFilter();
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mNameEdit);
}
void AlchemyWindow::onIngredientSelected(MyGUI::Widget* _sender)
{
size_t i = std::distance(mIngredients.begin(), std::find(mIngredients.begin(), mIngredients.end(), _sender));
mAlchemy->removeIngredient(i);
update();
}
void AlchemyWindow::onItemSelected(MWWorld::Ptr item)
{
mItemSelectionDialog->setVisible(false);
int32_t index = item.get<ESM::Apparatus>()->mBase->mData.mType;
const auto& widget = mApparatus[index];
widget->setItem(item);
if (item.isEmpty())
{
widget->clearUserStrings();
return;
}
mAlchemy->addApparatus(item);
widget->setUserString("ToolTipType", "ItemPtr");
widget->setUserData(MWWorld::Ptr(item));
MWBase::Environment::get().getWindowManager()->playSound(item.getClass().getDownSoundId(item));
update();
}
void AlchemyWindow::onItemCancel()
{
mItemSelectionDialog->setVisible(false);
}
void AlchemyWindow::onApparatusSelected(MyGUI::Widget* _sender)
{
size_t i = std::distance(mApparatus.begin(), std::find(mApparatus.begin(), mApparatus.end(), _sender));
if (_sender->getUserData<MWWorld::Ptr>()->isEmpty()) // if this apparatus slot is empty
{
std::string title;
switch (i)
{
case ESM::Apparatus::AppaType::MortarPestle:
title = "#{sMortar}";
break;
case ESM::Apparatus::AppaType::Alembic:
title = "#{sAlembic}";
break;
case ESM::Apparatus::AppaType::Calcinator:
title = "#{sCalcinator}";
break;
case ESM::Apparatus::AppaType::Retort:
title = "#{sRetort}";
break;
default:
title = "#{sApparatus}";
}
mItemSelectionDialog = std::make_unique<ItemSelectionDialog>(title);
mItemSelectionDialog->eventItemSelected += MyGUI::newDelegate(this, &AlchemyWindow::onItemSelected);
mItemSelectionDialog->eventDialogCanceled += MyGUI::newDelegate(this, &AlchemyWindow::onItemCancel);
mItemSelectionDialog->setVisible(true);
mItemSelectionDialog->openContainer(MWMechanics::getPlayer());
mItemSelectionDialog->getSortModel()->setApparatusTypeFilter(i);
mItemSelectionDialog->setFilter(SortFilterItemModel::Filter_OnlyAlchemyTools);
}
else
{
const auto& widget = mApparatus[i];
mAlchemy->removeApparatus(i);
if (widget->getChildCount())
MyGUI::Gui::getInstance().destroyWidget(widget->getChildAt(0));
widget->clearUserStrings();
widget->setItem(MWWorld::Ptr());
widget->setUserData(MWWorld::Ptr());
}
update();
}
void AlchemyWindow::onSelectedItem(int index)
{
MWWorld::Ptr item = mSortModel->getItem(index).mBase;
int res = mAlchemy->addIngredient(item);
if (res != -1)
{
update();
const ESM::RefId& sound = item.getClass().getUpSoundId(item);
MWBase::Environment::get().getWindowManager()->playSound(sound);
}
}
void AlchemyWindow::update()
{
std::string suggestedName = mAlchemy->suggestPotionName();
if (suggestedName != mSuggestedPotionName)
{
mNameEdit->setCaptionWithReplacing(suggestedName);
mSuggestedPotionName = std::move(suggestedName);
}
mSortModel->clearDragItems();
MWMechanics::Alchemy::TIngredientsIterator it = mAlchemy->beginIngredients();
for (int i = 0; i < 4; ++i)
{
ItemWidget* ingredient = mIngredients[i];
MWWorld::Ptr item;
if (it != mAlchemy->endIngredients())
{
item = *it;
++it;
}
if (!item.isEmpty())
mSortModel->addDragItem(item, item.getCellRef().getCount());
if (ingredient->getChildCount())
MyGUI::Gui::getInstance().destroyWidget(ingredient->getChildAt(0));
ingredient->clearUserStrings();
ingredient->setItem(item);
if (item.isEmpty())
continue;
ingredient->setUserString("ToolTipType", "ItemPtr");
ingredient->setUserData(MWWorld::Ptr(item));
ingredient->setCount(item.getCellRef().getCount());
}
mItemView->update();
std::vector<MWMechanics::EffectKey> effectIds = mAlchemy->listEffects();
Widgets::SpellEffectList list;
unsigned int effectIndex = 0;
for (const MWMechanics::EffectKey& effectKey : effectIds)
{
Widgets::SpellEffectParams params;
params.mEffectID = effectKey.mId;
const ESM::MagicEffect* magicEffect
= MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>().find(effectKey.mId);
if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetSkill)
params.mSkill = effectKey.mArg;
else if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetAttribute)
params.mAttribute = effectKey.mArg;
params.mIsConstant = true;
params.mNoTarget = true;
params.mNoMagnitude = true;
params.mKnown = mAlchemy->knownEffect(effectIndex, MWBase::Environment::get().getWorld()->getPlayerPtr());
list.push_back(params);
++effectIndex;
}
while (mEffectsBox->getChildCount())
MyGUI::Gui::getInstance().destroyWidget(mEffectsBox->getChildAt(0));
MyGUI::IntCoord coord(0, 0, mEffectsBox->getWidth(), 24);
Widgets::MWEffectListPtr effectsWidget = mEffectsBox->createWidget<Widgets::MWEffectList>(
"MW_StatName", coord, MyGUI::Align::Left | MyGUI::Align::Top);
effectsWidget->setEffectList(list);
std::vector<MyGUI::Widget*> effectItems;
effectsWidget->createEffectWidgets(effectItems, mEffectsBox, coord, false, 0);
effectsWidget->setCoord(coord);
}
void AlchemyWindow::addRepeatController(MyGUI::Widget* widget)
{
MyGUI::ControllerItem* item
= MyGUI::ControllerManager::getInstance().createItem(MyGUI::ControllerRepeatClick::getClassTypeName());
MyGUI::ControllerRepeatClick* controller = static_cast<MyGUI::ControllerRepeatClick*>(item);
controller->eventRepeatClick += newDelegate(this, &AlchemyWindow::onRepeatClick);
MyGUI::ControllerManager::getInstance().addItem(widget, controller);
}
void AlchemyWindow::onIncreaseButtonPressed(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
{
addRepeatController(_sender);
onIncreaseButtonTriggered();
}
void AlchemyWindow::onDecreaseButtonPressed(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
{
addRepeatController(_sender);
onDecreaseButtonTriggered();
}
void AlchemyWindow::onRepeatClick(MyGUI::Widget* widget, MyGUI::ControllerItem* controller)
{
if (widget == mIncreaseButton)
onIncreaseButtonTriggered();
else if (widget == mDecreaseButton)
onDecreaseButtonTriggered();
}
void AlchemyWindow::onCountButtonReleased(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
{
MyGUI::ControllerManager::getInstance().removeItem(_sender);
}
void AlchemyWindow::onCountValueChanged(int value)
{
mBrewCountEdit->setValue(std::abs(value));
}
void AlchemyWindow::onIncreaseButtonTriggered()
{
int currentCount = mBrewCountEdit->getValue();
// prevent overflows
if (currentCount == std::numeric_limits<int>::max())
return;
mBrewCountEdit->setValue(currentCount + 1);
}
void AlchemyWindow::onDecreaseButtonTriggered()
{
int currentCount = mBrewCountEdit->getValue();
if (currentCount > 1)
mBrewCountEdit->setValue(currentCount - 1);
}
}
| 19,934
|
C++
|
.cpp
| 443
| 35.092551
| 118
| 0.63485
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,513
|
sortfilteritemmodel.cpp
|
OpenMW_openmw/apps/openmw/mwgui/sortfilteritemmodel.cpp
|
#include "sortfilteritemmodel.hpp"
#include <components/debug/debuglog.hpp>
#include <components/esm3/loadalch.hpp>
#include <components/esm3/loadappa.hpp>
#include <components/esm3/loadarmo.hpp>
#include <components/esm3/loadbook.hpp>
#include <components/esm3/loadclot.hpp>
#include <components/esm3/loadcrea.hpp>
#include <components/esm3/loadench.hpp>
#include <components/esm3/loadingr.hpp>
#include <components/esm3/loadligh.hpp>
#include <components/esm3/loadlock.hpp>
#include <components/esm3/loadmisc.hpp>
#include <components/esm3/loadprob.hpp>
#include <components/esm3/loadrepa.hpp>
#include <components/esm3/loadweap.hpp>
#include <components/misc/utf8stream.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/action.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwmechanics/alchemy.hpp"
#include "../mwmechanics/spellutil.hpp"
namespace
{
unsigned int getTypeOrder(unsigned int type)
{
switch (type)
{
case ESM::Weapon::sRecordId:
return 0;
case ESM::Armor::sRecordId:
return 1;
case ESM::Clothing::sRecordId:
return 2;
case ESM::Potion::sRecordId:
return 3;
case ESM::Ingredient::sRecordId:
return 4;
case ESM::Apparatus::sRecordId:
return 5;
case ESM::Book::sRecordId:
return 6;
case ESM::Light::sRecordId:
return 7;
case ESM::Miscellaneous::sRecordId:
return 8;
case ESM::Lockpick::sRecordId:
return 9;
case ESM::Repair::sRecordId:
return 10;
case ESM::Probe::sRecordId:
return 11;
}
assert(false && "Invalid type value");
return std::numeric_limits<unsigned int>::max();
}
bool compareType(unsigned int type1, unsigned int type2)
{
return getTypeOrder(type1) < getTypeOrder(type2);
}
struct Compare
{
bool mSortByType;
Compare()
: mSortByType(true)
{
}
bool operator()(const MWGui::ItemStack& left, const MWGui::ItemStack& right)
{
if (mSortByType && left.mType != right.mType)
return left.mType < right.mType;
float result = 0;
// compare items by type
auto leftType = left.mBase.getType();
auto rightType = right.mBase.getType();
if (leftType != rightType)
return compareType(leftType, rightType);
// compare items by name
std::string leftName = Utf8Stream::lowerCaseUtf8(left.mBase.getClass().getName(left.mBase));
std::string rightName = Utf8Stream::lowerCaseUtf8(right.mBase.getClass().getName(right.mBase));
result = leftName.compare(rightName);
if (result != 0)
return result < 0;
// compare items by enchantment:
// 1. enchanted items showed before non-enchanted
// 2. item with lesser charge percent comes after items with more charge percent
// 3. item with constant effect comes before items with non-constant effects
int leftChargePercent = -1;
int rightChargePercent = -1;
const ESM::RefId& leftNameEnch = left.mBase.getClass().getEnchantment(left.mBase);
const ESM::RefId& rightNameEnch = right.mBase.getClass().getEnchantment(right.mBase);
if (!leftNameEnch.empty())
{
const ESM::Enchantment* ench
= MWBase::Environment::get().getESMStore()->get<ESM::Enchantment>().search(leftNameEnch);
if (ench)
{
if (ench->mData.mType == ESM::Enchantment::ConstantEffect)
leftChargePercent = 101;
else
leftChargePercent
= static_cast<int>(left.mBase.getCellRef().getNormalizedEnchantmentCharge(*ench) * 100);
}
}
if (!rightNameEnch.empty())
{
const ESM::Enchantment* ench
= MWBase::Environment::get().getESMStore()->get<ESM::Enchantment>().search(rightNameEnch);
if (ench)
{
if (ench->mData.mType == ESM::Enchantment::ConstantEffect)
rightChargePercent = 101;
else
rightChargePercent
= static_cast<int>(right.mBase.getCellRef().getNormalizedEnchantmentCharge(*ench) * 100);
}
}
result = leftChargePercent - rightChargePercent;
if (result != 0)
return result > 0;
// compare items by condition
if (left.mBase.getClass().hasItemHealth(left.mBase) && right.mBase.getClass().hasItemHealth(right.mBase))
{
result = left.mBase.getClass().getItemHealth(left.mBase)
- right.mBase.getClass().getItemHealth(right.mBase);
if (result != 0)
return result > 0;
}
// compare items by remaining usage time
result = left.mBase.getClass().getRemainingUsageTime(left.mBase)
- right.mBase.getClass().getRemainingUsageTime(right.mBase);
if (result != 0)
return result > 0;
// compare items by value
result = left.mBase.getClass().getValue(left.mBase) - right.mBase.getClass().getValue(right.mBase);
if (result != 0)
return result > 0;
// compare items by weight
result = left.mBase.getClass().getWeight(left.mBase) - right.mBase.getClass().getWeight(right.mBase);
if (result != 0)
return result > 0;
return left.mBase.getCellRef().getRefId() < right.mBase.getCellRef().getRefId();
}
};
}
namespace MWGui
{
SortFilterItemModel::SortFilterItemModel(std::unique_ptr<ItemModel> sourceModel)
: mCategory(Category_All)
, mFilter(0)
, mSortByType(true)
, mApparatusTypeFilter(-1)
{
mSourceModel = std::move(sourceModel);
}
bool SortFilterItemModel::allowedToUseItems() const
{
return mSourceModel->allowedToUseItems();
}
void SortFilterItemModel::addDragItem(const MWWorld::Ptr& dragItem, size_t count)
{
mDragItems.emplace_back(dragItem, count);
}
void SortFilterItemModel::clearDragItems()
{
mDragItems.clear();
}
bool SortFilterItemModel::filterAccepts(const ItemStack& item)
{
MWWorld::Ptr base = item.mBase;
int category = 0;
switch (base.getType())
{
case ESM::Armor::sRecordId:
case ESM::Clothing::sRecordId:
category = Category_Apparel;
break;
case ESM::Weapon::sRecordId:
category = Category_Weapon;
break;
case ESM::Ingredient::sRecordId:
case ESM::Potion::sRecordId:
category = Category_Magic;
break;
case ESM::Miscellaneous::sRecordId:
case ESM::Repair::sRecordId:
case ESM::Lockpick::sRecordId:
case ESM::Light::sRecordId:
case ESM::Apparatus::sRecordId:
case ESM::Book::sRecordId:
case ESM::Probe::sRecordId:
category = Category_Misc;
break;
}
if (item.mFlags & ItemStack::Flag_Enchanted)
category |= Category_Magic;
if (!(category & mCategory))
return false;
if (mFilter & Filter_OnlyIngredients)
{
if (base.getType() != ESM::Ingredient::sRecordId)
return false;
if (!mNameFilter.empty() && !mEffectFilter.empty())
throw std::logic_error("name and magic effect filter are mutually exclusive");
if (!mNameFilter.empty())
{
const auto itemName = Utf8Stream::lowerCaseUtf8(base.getClass().getName(base));
return itemName.find(mNameFilter) != std::string::npos;
}
if (!mEffectFilter.empty())
{
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
const auto alchemySkill = player.getClass().getSkill(player, ESM::Skill::Alchemy);
const auto effects = MWMechanics::Alchemy::effectsDescription(base, alchemySkill);
for (const auto& effect : effects)
{
const auto ciEffect = Utf8Stream::lowerCaseUtf8(effect);
if (ciEffect.find(mEffectFilter) != std::string::npos)
return true;
}
return false;
}
return true;
}
if ((mFilter & Filter_OnlyEnchanted) && !(item.mFlags & ItemStack::Flag_Enchanted))
return false;
if ((mFilter & Filter_OnlyChargedSoulstones)
&& (base.getType() != ESM::Miscellaneous::sRecordId || base.getCellRef().getSoul().empty()
|| !MWBase::Environment::get().getESMStore()->get<ESM::Creature>().search(base.getCellRef().getSoul())))
return false;
if ((mFilter & Filter_OnlyRepairTools) && (base.getType() != ESM::Repair::sRecordId))
return false;
if ((mFilter & Filter_OnlyEnchantable)
&& (item.mFlags & ItemStack::Flag_Enchanted
|| (base.getType() != ESM::Armor::sRecordId && base.getType() != ESM::Clothing::sRecordId
&& base.getType() != ESM::Weapon::sRecordId && base.getType() != ESM::Book::sRecordId)))
return false;
if ((mFilter & Filter_OnlyEnchantable) && base.getType() == ESM::Book::sRecordId
&& !base.get<ESM::Book>()->mBase->mData.mIsScroll)
return false;
if ((mFilter & Filter_OnlyUsableItems) && base.getClass().getScript(base).empty())
{
std::unique_ptr<MWWorld::Action> actionOnUse = base.getClass().use(base);
if (!actionOnUse || actionOnUse->isNullAction())
return false;
}
if ((mFilter & Filter_OnlyRepairable)
&& (!base.getClass().hasItemHealth(base)
|| (base.getClass().getItemHealth(base) >= base.getClass().getItemMaxHealth(base))
|| (base.getType() != ESM::Weapon::sRecordId && base.getType() != ESM::Armor::sRecordId)))
return false;
if (mFilter & Filter_OnlyRechargable)
{
if (!(item.mFlags & ItemStack::Flag_Enchanted))
return false;
const ESM::RefId& enchId = base.getClass().getEnchantment(base);
const ESM::Enchantment* ench
= MWBase::Environment::get().getESMStore()->get<ESM::Enchantment>().search(enchId);
if (!ench)
{
Log(Debug::Warning) << "Warning: Can't find enchantment '" << enchId << "' on item "
<< base.getCellRef().getRefId();
return false;
}
if (base.getCellRef().getEnchantmentCharge() == -1
|| base.getCellRef().getEnchantmentCharge() >= MWMechanics::getEnchantmentCharge(*ench))
return false;
}
if ((mFilter & Filter_OnlyAlchemyTools))
{
if (base.getType() != ESM::Apparatus::sRecordId)
return false;
int32_t apparatusType = base.get<ESM::Apparatus>()->mBase->mData.mType;
if (mApparatusTypeFilter >= 0 && apparatusType != mApparatusTypeFilter)
return false;
}
std::string compare = Utf8Stream::lowerCaseUtf8(item.mBase.getClass().getName(item.mBase));
if (compare.find(mNameFilter) == std::string::npos)
return false;
return true;
}
ItemStack SortFilterItemModel::getItem(ModelIndex index)
{
if (index < 0)
throw std::runtime_error("Invalid index supplied");
if (mItems.size() <= static_cast<size_t>(index))
throw std::runtime_error("Item index out of range");
return mItems[index];
}
size_t SortFilterItemModel::getItemCount()
{
return mItems.size();
}
void SortFilterItemModel::setCategory(int category)
{
mCategory = category;
}
void SortFilterItemModel::setFilter(int filter)
{
mFilter = filter;
}
void SortFilterItemModel::setNameFilter(const std::string& filter)
{
mNameFilter = Utf8Stream::lowerCaseUtf8(filter);
}
void SortFilterItemModel::setEffectFilter(const std::string& filter)
{
mEffectFilter = Utf8Stream::lowerCaseUtf8(filter);
}
void SortFilterItemModel::setApparatusTypeFilter(const int32_t type)
{
mApparatusTypeFilter = type;
}
void SortFilterItemModel::update()
{
mSourceModel->update();
size_t count = mSourceModel->getItemCount();
mItems.clear();
for (size_t i = 0; i < count; ++i)
{
ItemStack item = mSourceModel->getItem(i);
for (std::vector<std::pair<MWWorld::Ptr, size_t>>::iterator it = mDragItems.begin(); it != mDragItems.end();
++it)
{
if (item.mBase == it->first)
{
if (item.mCount < it->second)
throw std::runtime_error("Dragging more than present in the model");
item.mCount -= it->second;
}
}
if (item.mCount > 0 && filterAccepts(item))
mItems.push_back(item);
}
Compare cmp;
cmp.mSortByType = mSortByType;
std::sort(mItems.begin(), mItems.end(), cmp);
}
void SortFilterItemModel::onClose()
{
mSourceModel->onClose();
}
bool SortFilterItemModel::onDropItem(const MWWorld::Ptr& item, int count)
{
return mSourceModel->onDropItem(item, count);
}
bool SortFilterItemModel::onTakeItem(const MWWorld::Ptr& item, int count)
{
return mSourceModel->onTakeItem(item, count);
}
}
| 14,582
|
C++
|
.cpp
| 353
| 29.815864
| 120
| 0.572003
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,514
|
textcolours.cpp
|
OpenMW_openmw/apps/openmw/mwgui/textcolours.cpp
|
#include "textcolours.hpp"
#include <MyGUI_LanguageManager.h>
#include <string>
namespace MWGui
{
MyGUI::Colour getTextColour(const std::string& type)
{
return MyGUI::Colour::parse(MyGUI::LanguageManager::getInstance().replaceTags("#{fontcolour=" + type + "}"));
}
void TextColours::loadColours()
{
header = getTextColour("header");
normal = getTextColour("normal");
notify = getTextColour("notify");
link = getTextColour("link");
linkOver = getTextColour("link_over");
linkPressed = getTextColour("link_pressed");
answer = getTextColour("answer");
answerOver = getTextColour("answer_over");
answerPressed = getTextColour("answer_pressed");
journalLink = getTextColour("journal_link");
journalLinkOver = getTextColour("journal_link_over");
journalLinkPressed = getTextColour("journal_link_pressed");
journalTopic = getTextColour("journal_topic");
journalTopicOver = getTextColour("journal_topic_over");
journalTopicPressed = getTextColour("journal_topic_pressed");
}
}
| 1,129
|
C++
|
.cpp
| 28
| 33.607143
| 117
| 0.676121
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,515
|
windowpinnablebase.cpp
|
OpenMW_openmw/apps/openmw/mwgui/windowpinnablebase.cpp
|
#include "windowpinnablebase.hpp"
#include "exposedwindow.hpp"
namespace MWGui
{
WindowPinnableBase::WindowPinnableBase(const std::string& parLayout)
: WindowBase(parLayout)
, mPinned(false)
{
Window* window = mMainWidget->castType<Window>();
mPinButton = window->getSkinWidget("Button");
mPinButton->eventMouseButtonPressed += MyGUI::newDelegate(this, &WindowPinnableBase::onPinButtonPressed);
}
void WindowPinnableBase::onPinButtonPressed(MyGUI::Widget* _sender, int left, int top, MyGUI::MouseButton id)
{
if (id != MyGUI::MouseButton::Left)
return;
mPinned = !mPinned;
if (mPinned)
mPinButton->changeWidgetSkin("PinDown");
else
mPinButton->changeWidgetSkin("PinUp");
onPinToggled();
}
void WindowPinnableBase::setPinned(bool pinned)
{
if (pinned != mPinned)
onPinButtonPressed(mPinButton, 0, 0, MyGUI::MouseButton::Left);
}
void WindowPinnableBase::setPinButtonVisible(bool visible)
{
mPinButton->setVisible(visible);
}
}
| 1,127
|
C++
|
.cpp
| 33
| 27.060606
| 113
| 0.665438
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,516
|
pickpocketitemmodel.cpp
|
OpenMW_openmw/apps/openmw/mwgui/pickpocketitemmodel.cpp
|
#include "pickpocketitemmodel.hpp"
#include <components/esm3/loadskil.hpp>
#include <components/misc/rng.hpp>
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/pickpocket.hpp"
#include "../mwworld/class.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
namespace MWGui
{
PickpocketItemModel::PickpocketItemModel(
const MWWorld::Ptr& actor, std::unique_ptr<ItemModel> sourceModel, bool hideItems)
: mActor(actor)
, mPickpocketDetected(false)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
mSourceModel = std::move(sourceModel);
float chance = player.getClass().getSkill(player, ESM::Skill::Sneak);
mSourceModel->update();
// build list of items that player is unable to find when attempts to pickpocket.
if (hideItems)
{
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
for (size_t i = 0; i < mSourceModel->getItemCount(); ++i)
{
if (Misc::Rng::roll0to99(prng) > chance)
mHiddenItems.push_back(mSourceModel->getItem(i));
}
}
}
bool PickpocketItemModel::allowedToUseItems() const
{
return false;
}
ItemStack PickpocketItemModel::getItem(ModelIndex index)
{
if (index < 0)
throw std::runtime_error("Invalid index supplied");
if (mItems.size() <= static_cast<size_t>(index))
throw std::runtime_error("Item index out of range");
return mItems[index];
}
size_t PickpocketItemModel::getItemCount()
{
return mItems.size();
}
void PickpocketItemModel::update()
{
mSourceModel->update();
mItems.clear();
for (size_t i = 0; i < mSourceModel->getItemCount(); ++i)
{
const ItemStack& item = mSourceModel->getItem(i);
// Bound items may not be stolen
if (item.mFlags & ItemStack::Flag_Bound)
continue;
if (std::find(mHiddenItems.begin(), mHiddenItems.end(), item) == mHiddenItems.end()
&& item.mType != ItemStack::Type_Equipped)
mItems.push_back(item);
}
}
void PickpocketItemModel::removeItem(const ItemStack& item, size_t count)
{
ProxyItemModel::removeItem(item, count);
}
bool PickpocketItemModel::onDropItem(const MWWorld::Ptr& item, int count)
{
// don't allow "reverse pickpocket" (it will be handled by scripts after 1.0)
return false;
}
void PickpocketItemModel::onClose()
{
// Make sure we were actually closed, rather than just temporarily hidden (e.g. console or main menu opened)
if (MWBase::Environment::get().getWindowManager()->containsMode(GM_Container)
// If it was already detected while taking an item, no need to check now
|| mPickpocketDetected)
return;
MWWorld::Ptr player = MWMechanics::getPlayer();
MWMechanics::Pickpocket pickpocket(player, mActor);
if (pickpocket.finish())
{
MWBase::Environment::get().getMechanicsManager()->commitCrime(
player, mActor, MWBase::MechanicsManager::OT_Pickpocket, ESM::RefId(), 0, true);
MWBase::Environment::get().getWindowManager()->removeGuiMode(MWGui::GM_Container);
mPickpocketDetected = true;
}
}
bool PickpocketItemModel::onTakeItem(const MWWorld::Ptr& item, int count)
{
if (mActor.getClass().getCreatureStats(mActor).getKnockedDown())
return mSourceModel->onTakeItem(item, count);
bool success = stealItem(item, count);
if (success)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
MWBase::Environment::get().getMechanicsManager()->itemTaken(player, item, mActor, count, false);
}
return success;
}
bool PickpocketItemModel::stealItem(const MWWorld::Ptr& item, int count)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
MWMechanics::Pickpocket pickpocket(player, mActor);
if (pickpocket.pick(item, count))
{
MWBase::Environment::get().getMechanicsManager()->commitCrime(
player, mActor, MWBase::MechanicsManager::OT_Pickpocket, ESM::RefId(), 0, true);
MWBase::Environment::get().getWindowManager()->removeGuiMode(MWGui::GM_Container);
mPickpocketDetected = true;
return false;
}
else
player.getClass().skillUsageSucceeded(player, ESM::Skill::Sneak, ESM::Skill::Sneak_PickPocket);
return true;
}
}
| 4,832
|
C++
|
.cpp
| 119
| 32.058824
| 116
| 0.631209
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,517
|
recharge.cpp
|
OpenMW_openmw/apps/openmw/mwgui/recharge.cpp
|
#include "recharge.hpp"
#include <MyGUI_ScrollView.h>
#include <components/widgets/box.hpp>
#include <components/esm3/loadcrea.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/recharge.hpp"
#include "inventoryitemmodel.hpp"
#include "itemchargeview.hpp"
#include "itemselection.hpp"
#include "itemwidget.hpp"
#include "sortfilteritemmodel.hpp"
namespace MWGui
{
Recharge::Recharge()
: WindowBase("openmw_recharge_dialog.layout")
{
getWidget(mBox, "Box");
getWidget(mGemBox, "GemBox");
getWidget(mGemIcon, "GemIcon");
getWidget(mChargeLabel, "ChargeLabel");
getWidget(mCancelButton, "CancelButton");
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &Recharge::onCancel);
mBox->eventItemClicked += MyGUI::newDelegate(this, &Recharge::onItemClicked);
mBox->setDisplayMode(ItemChargeView::DisplayMode_EnchantmentCharge);
mGemIcon->eventMouseButtonClick += MyGUI::newDelegate(this, &Recharge::onSelectItem);
}
void Recharge::onOpen()
{
center();
SortFilterItemModel* model
= new SortFilterItemModel(std::make_unique<InventoryItemModel>(MWMechanics::getPlayer()));
model->setFilter(SortFilterItemModel::Filter_OnlyRechargable);
mBox->setModel(model);
// Reset scrollbars
mBox->resetScrollbars();
}
void Recharge::setPtr(const MWWorld::Ptr& item)
{
if (item.isEmpty() || !item.getClass().isItem(item))
throw std::runtime_error("Invalid argument in Recharge::setPtr");
mGemIcon->setItem(item);
mGemIcon->setUserString("ToolTipType", "ItemPtr");
mGemIcon->setUserData(MWWorld::Ptr(item));
updateView();
}
void Recharge::updateView()
{
MWWorld::Ptr gem = *mGemIcon->getUserData<MWWorld::Ptr>();
const ESM::RefId& soul = gem.getCellRef().getSoul();
const ESM::Creature* creature = MWBase::Environment::get().getESMStore()->get<ESM::Creature>().find(soul);
mChargeLabel->setCaptionWithReplacing("#{sCharges} " + MyGUI::utility::toString(creature->mData.mSoul));
bool toolBoxVisible = gem.getCellRef().getCount() != 0;
mGemBox->setVisible(toolBoxVisible);
mGemBox->setUserString("Hidden", toolBoxVisible ? "false" : "true");
if (!toolBoxVisible)
{
mGemIcon->setItem(MWWorld::Ptr());
mGemIcon->clearUserStrings();
}
mBox->update();
Gui::Box* box = dynamic_cast<Gui::Box*>(mMainWidget);
if (box == nullptr)
throw std::runtime_error("main widget must be a box");
box->notifyChildrenSizeChanged();
center();
}
void Recharge::onCancel(MyGUI::Widget* sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Recharge);
}
void Recharge::onSelectItem(MyGUI::Widget* sender)
{
mItemSelectionDialog = std::make_unique<ItemSelectionDialog>("#{sSoulGemsWithSouls}");
mItemSelectionDialog->eventItemSelected += MyGUI::newDelegate(this, &Recharge::onItemSelected);
mItemSelectionDialog->eventDialogCanceled += MyGUI::newDelegate(this, &Recharge::onItemCancel);
mItemSelectionDialog->setVisible(true);
mItemSelectionDialog->openContainer(MWMechanics::getPlayer());
mItemSelectionDialog->setFilter(SortFilterItemModel::Filter_OnlyChargedSoulstones);
}
void Recharge::onItemSelected(MWWorld::Ptr item)
{
mItemSelectionDialog->setVisible(false);
mGemIcon->setItem(item);
mGemIcon->setUserString("ToolTipType", "ItemPtr");
mGemIcon->setUserData(item);
MWBase::Environment::get().getWindowManager()->playSound(item.getClass().getDownSoundId(item));
updateView();
}
void Recharge::onItemCancel()
{
mItemSelectionDialog->setVisible(false);
}
void Recharge::onItemClicked(MyGUI::Widget* sender, const MWWorld::Ptr& item)
{
MWWorld::Ptr gem = *mGemIcon->getUserData<MWWorld::Ptr>();
if (!MWMechanics::rechargeItem(item, gem))
return;
updateView();
}
}
| 4,351
|
C++
|
.cpp
| 104
| 34.692308
| 114
| 0.676163
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,518
|
exposedwindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/exposedwindow.cpp
|
#include "exposedwindow.hpp"
namespace MWGui
{
MyGUI::VectorWidgetPtr Window::getSkinWidgetsByName(const std::string& name)
{
return MyGUI::Widget::getSkinWidgetsByName(name);
}
MyGUI::Widget* Window::getSkinWidget(const std::string& _name, bool _throw)
{
MyGUI::VectorWidgetPtr widgets = getSkinWidgetsByName(_name);
if (widgets.empty())
{
MYGUI_ASSERT(!_throw, "widget name '" << _name << "' not found in skin of layout '" << getName() << "'");
return nullptr;
}
else
{
return widgets[0];
}
}
}
| 624
|
C++
|
.cpp
| 21
| 22.666667
| 117
| 0.59
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,519
|
formatting.cpp
|
OpenMW_openmw/apps/openmw/mwgui/formatting.cpp
|
#include "formatting.hpp"
#include <charconv>
#include <system_error>
#include <MyGUI_EditBox.h>
#include <MyGUI_EditText.h>
#include <MyGUI_Gui.h>
#include <MyGUI_ImageBox.h>
#include <components/debug/debuglog.hpp>
#include <components/fontloader/fontloader.hpp>
#include <components/interpreter/defines.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/settings/values.hpp>
#include <components/vfs/manager.hpp>
#include "../mwbase/environment.hpp"
#include "../mwscript/interpretercontext.hpp"
namespace MWGui::Formatting
{
/* BookTextParser */
BookTextParser::BookTextParser(const std::string& text, bool shrinkTextAtLastTag)
: mIndex(0)
, mText(text)
, mIgnoreNewlineTags(true)
, mIgnoreLineEndings(true)
, mClosingTag(false)
{
MWScript::InterpreterContext interpreterContext(
nullptr, MWWorld::Ptr()); // empty arguments, because there is no locals or actor
mText = Interpreter::fixDefinesBook(mText, interpreterContext);
Misc::StringUtils::replaceAll(mText, "\r", {});
if (shrinkTextAtLastTag)
{
// vanilla game does not show any text after the last EOL tag.
const std::string lowerText = Misc::StringUtils::lowerCase(mText);
size_t brIndex = lowerText.rfind("<br>");
size_t pIndex = lowerText.rfind("<p>");
mPlainTextEnd = 0;
if (brIndex != pIndex)
{
if (brIndex != std::string::npos && pIndex != std::string::npos)
mPlainTextEnd = std::max(brIndex, pIndex);
else if (brIndex != std::string::npos)
mPlainTextEnd = brIndex;
else
mPlainTextEnd = pIndex;
}
}
else
mPlainTextEnd = mText.size();
registerTag("br", Event_BrTag);
registerTag("p", Event_PTag);
registerTag("img", Event_ImgTag);
registerTag("div", Event_DivTag);
registerTag("font", Event_FontTag);
}
void BookTextParser::registerTag(const std::string& tag, BookTextParser::Events type)
{
mTagTypes[tag] = type;
}
std::string BookTextParser::getReadyText() const
{
return mReadyText;
}
BookTextParser::Events BookTextParser::next()
{
while (mIndex < mText.size())
{
char ch = mText[mIndex];
if (ch == '[')
{
constexpr std::string_view pageBreakTag = "[pagebreak]\n";
if (std::string_view(mText.data() + mIndex, mText.size() - mIndex).starts_with(pageBreakTag))
{
mIndex += pageBreakTag.size();
flushBuffer();
mIgnoreNewlineTags = false;
return Event_PageBreak;
}
}
if (ch == '<')
{
const size_t tagStart = mIndex + 1;
const size_t tagEnd = mText.find('>', tagStart);
if (tagEnd == std::string::npos)
throw std::runtime_error("BookTextParser Error: Tag is not terminated");
parseTag(mText.substr(tagStart, tagEnd - tagStart));
mIndex = tagEnd;
if (auto it = mTagTypes.find(mTag); it != mTagTypes.end())
{
Events type = it->second;
if (type == Event_BrTag || type == Event_PTag)
{
if (!mIgnoreNewlineTags)
{
if (type == Event_BrTag)
mBuffer.push_back('\n');
else
{
mBuffer.append("\n\n");
}
}
mIgnoreLineEndings = true;
if (type == Event_PTag && !mAttributes.empty())
flushBuffer();
}
else
flushBuffer();
if (type == Event_ImgTag)
{
mIgnoreNewlineTags = false;
}
++mIndex;
return type;
}
}
else
{
if (!mIgnoreLineEndings || ch != '\n')
{
if (mIndex < mPlainTextEnd)
mBuffer.push_back(ch);
mIgnoreLineEndings = false;
mIgnoreNewlineTags = false;
}
}
++mIndex;
}
flushBuffer();
return Event_EOF;
}
void BookTextParser::flushBuffer()
{
mReadyText = mBuffer;
mBuffer.clear();
}
const BookTextParser::Attributes& BookTextParser::getAttributes() const
{
return mAttributes;
}
bool BookTextParser::isClosingTag() const
{
return mClosingTag;
}
void BookTextParser::parseTag(std::string tag)
{
size_t tagNameEndPos = tag.find(' ');
mAttributes.clear();
mTag = tag.substr(0, tagNameEndPos);
Misc::StringUtils::lowerCaseInPlace(mTag);
if (mTag.empty())
return;
mClosingTag = (mTag[0] == '/');
if (mClosingTag)
{
mTag.erase(mTag.begin());
return;
}
if (tagNameEndPos == std::string::npos)
return;
tag.erase(0, tagNameEndPos + 1);
while (!tag.empty())
{
size_t sepPos = tag.find('=');
if (sepPos == std::string::npos)
return;
std::string key = tag.substr(0, sepPos);
Misc::StringUtils::lowerCaseInPlace(key);
tag.erase(0, sepPos + 1);
std::string value;
if (tag.empty())
return;
if (tag[0] == '"' || tag[0] == '\'')
{
size_t quoteEndPos = tag.find(tag[0], 1);
if (quoteEndPos == std::string::npos)
throw std::runtime_error("BookTextParser Error: Missing end quote in tag");
value = tag.substr(1, quoteEndPos - 1);
tag.erase(0, quoteEndPos + 2);
}
else
{
size_t valEndPos = tag.find(' ');
if (valEndPos == std::string::npos)
{
value = tag;
tag.erase();
}
else
{
value = tag.substr(0, valEndPos);
tag.erase(0, valEndPos + 1);
}
}
mAttributes[key] = std::move(value);
}
}
/* BookFormatter */
Paginator::Pages BookFormatter::markupToWidget(MyGUI::Widget* parent, const std::string& markup,
const int pageWidth, const int pageHeight, bool shrinkTextAtLastTag)
{
Paginator pag(pageWidth, pageHeight);
while (parent->getChildCount())
{
MyGUI::Gui::getInstance().destroyWidget(parent->getChildAt(0));
}
mTextStyle = TextStyle();
mBlockStyle = BlockStyle();
MyGUI::Widget* paper = parent->createWidget<MyGUI::Widget>("Widget",
MyGUI::IntCoord(0, 0, pag.getPageWidth(), pag.getPageHeight()), MyGUI::Align::Left | MyGUI::Align::Top);
paper->setNeedMouseFocus(false);
BookTextParser parser(markup, shrinkTextAtLastTag);
bool brBeforeLastTag = false;
bool isPrevImg = false;
bool inlineImageInserted = false;
for (;;)
{
BookTextParser::Events event = parser.next();
if (event == BookTextParser::Event_BrTag
|| (event == BookTextParser::Event_PTag && parser.getAttributes().empty()))
continue;
std::string plainText = parser.getReadyText();
// for cases when linebreaks are used to cause a shift to the next page
// if the split text block ends in an empty line, proceeding text block(s) should have leading empty lines
// removed
if (pag.getIgnoreLeadingEmptyLines())
{
while (!plainText.empty())
{
if (plainText[0] == '\n')
plainText.erase(plainText.begin());
else
{
pag.setIgnoreLeadingEmptyLines(false);
break;
}
}
}
if (plainText.empty())
brBeforeLastTag = true;
else
{
// Each block of text (between two tags / boundary and tag) will be displayed in a separate editbox
// widget, which means an additional linebreak will be created between them. ^ This is not what vanilla
// MW assumes, so we must deal with line breaks around tags appropriately.
bool brAtStart = (plainText[0] == '\n');
bool brAtEnd = (plainText[plainText.size() - 1] == '\n');
if (brAtStart && !brBeforeLastTag && !isPrevImg)
plainText.erase(plainText.begin());
if (plainText.size() && brAtEnd)
plainText.erase(plainText.end() - 1);
if (!plainText.empty() || brBeforeLastTag || isPrevImg)
{
if (inlineImageInserted)
{
pag.setCurrentTop(pag.getCurrentTop() - mTextStyle.mTextSize);
plainText = " " + plainText;
inlineImageInserted = false;
}
TextElement elem(paper, pag, mBlockStyle, mTextStyle, plainText);
elem.paginate();
}
brBeforeLastTag = brAtEnd;
}
if (event == BookTextParser::Event_EOF)
break;
isPrevImg = (event == BookTextParser::Event_ImgTag);
switch (event)
{
case BookTextParser::Event_PageBreak:
pag << Paginator::Page(pag.getStartTop(), pag.getCurrentTop());
pag.setStartTop(pag.getCurrentTop());
break;
case BookTextParser::Event_ImgTag:
{
const BookTextParser::Attributes& attr = parser.getAttributes();
auto srcIt = attr.find("src");
if (srcIt == attr.end())
continue;
int width = 0;
if (auto widthIt = attr.find("width"); widthIt != attr.end())
width = MyGUI::utility::parseInt(widthIt->second);
int height = 0;
if (auto heightIt = attr.find("height"); heightIt != attr.end())
height = MyGUI::utility::parseInt(heightIt->second);
const std::string& src = srcIt->second;
auto vfs = MWBase::Environment::get().getResourceSystem()->getVFS();
std::string correctedSrc;
constexpr std::string_view imgPrefix = "img://";
if (src.starts_with(imgPrefix))
{
correctedSrc = src.substr(imgPrefix.size(), src.size() - imgPrefix.size());
if (width == 0)
{
width = 50;
inlineImageInserted = true;
}
if (height == 0)
height = 50;
}
else
{
if (width == 0 || height == 0)
continue;
correctedSrc = Misc::ResourceHelpers::correctBookartPath(src, width, height, vfs);
}
if (!vfs->exists(correctedSrc))
{
Log(Debug::Warning) << "Warning: Could not find \"" << src << "\" referenced by an <img> tag.";
break;
}
pag.setIgnoreLeadingEmptyLines(false);
ImageElement elem(paper, pag, mBlockStyle, correctedSrc, width, height);
elem.paginate();
break;
}
case BookTextParser::Event_FontTag:
if (parser.isClosingTag())
resetFontProperties();
else
handleFont(parser.getAttributes());
break;
case BookTextParser::Event_PTag:
case BookTextParser::Event_DivTag:
handleDiv(parser.getAttributes());
break;
default:
break;
}
}
// insert last page
if (pag.getStartTop() != pag.getCurrentTop())
pag << Paginator::Page(pag.getStartTop(), pag.getStartTop() + pag.getPageHeight());
paper->setSize(paper->getWidth(), pag.getCurrentTop());
return pag.getPages();
}
Paginator::Pages BookFormatter::markupToWidget(
MyGUI::Widget* parent, const std::string& markup, bool shrinkTextAtLastTag)
{
return markupToWidget(parent, markup, parent->getWidth(), parent->getHeight(), shrinkTextAtLastTag);
}
void BookFormatter::resetFontProperties()
{
mTextStyle = TextStyle();
}
void BookFormatter::handleDiv(const BookTextParser::Attributes& attr)
{
auto it = attr.find("align");
if (it == attr.end())
return;
const std::string& align = it->second;
if (Misc::StringUtils::ciEqual(align, "center"))
mBlockStyle.mAlign = MyGUI::Align::HCenter;
else if (Misc::StringUtils::ciEqual(align, "left"))
mBlockStyle.mAlign = MyGUI::Align::Left;
else if (Misc::StringUtils::ciEqual(align, "right"))
mBlockStyle.mAlign = MyGUI::Align::Right;
}
void BookFormatter::handleFont(const BookTextParser::Attributes& attr)
{
auto it = attr.find("color");
if (it != attr.end())
{
const auto& colorString = it->second;
unsigned int color = 0;
std::from_chars(colorString.data(), colorString.data() + colorString.size(), color, 16);
mTextStyle.mColour
= MyGUI::Colour((color >> 16 & 0xFF) / 255.f, (color >> 8 & 0xFF) / 255.f, (color & 0xFF) / 255.f);
}
it = attr.find("face");
if (it != attr.end())
{
const std::string& face = it->second;
std::string name{ Gui::FontLoader::getFontForFace(face) };
mTextStyle.mFont = "Journalbook " + name;
}
if (attr.find("size") != attr.end())
{
/// \todo
}
}
/* GraphicElement */
GraphicElement::GraphicElement(MyGUI::Widget* parent, Paginator& pag, const BlockStyle& blockStyle)
: mParent(parent)
, mPaginator(pag)
, mBlockStyle(blockStyle)
{
}
void GraphicElement::paginate()
{
int newTop = mPaginator.getCurrentTop() + getHeight();
while (newTop - mPaginator.getStartTop() > mPaginator.getPageHeight())
{
int newStartTop = pageSplit();
mPaginator << Paginator::Page(mPaginator.getStartTop(), newStartTop);
mPaginator.setStartTop(newStartTop);
}
mPaginator.setCurrentTop(newTop);
}
int GraphicElement::pageSplit()
{
return mPaginator.getStartTop() + mPaginator.getPageHeight();
}
/* TextElement */
TextElement::TextElement(MyGUI::Widget* parent, Paginator& pag, const BlockStyle& blockStyle,
const TextStyle& textStyle, const std::string& text)
: GraphicElement(parent, pag, blockStyle)
, mTextStyle(textStyle)
{
Gui::EditBox* box = parent->createWidget<Gui::EditBox>("NormalText",
MyGUI::IntCoord(0, pag.getCurrentTop(), pag.getPageWidth(), 0), MyGUI::Align::Left | MyGUI::Align::Top,
parent->getName() + MyGUI::utility::toString(parent->getChildCount()));
box->setEditStatic(true);
box->setEditMultiLine(true);
box->setEditWordWrap(true);
box->setNeedMouseFocus(false);
box->setNeedKeyFocus(false);
box->setMaxTextLength(text.size());
box->setTextAlign(mBlockStyle.mAlign);
box->setTextColour(mTextStyle.mColour);
box->setFontName(mTextStyle.mFont);
box->setCaption(MyGUI::TextIterator::toTagsString(text));
box->setSize(box->getSize().width, box->getTextSize().height);
mEditBox = box;
}
int TextElement::getHeight()
{
return mEditBox->getTextSize().height;
}
int TextElement::pageSplit()
{
// split lines
const int lineHeight = Settings::gui().mFontSize;
unsigned int lastLine = (mPaginator.getStartTop() + mPaginator.getPageHeight() - mPaginator.getCurrentTop());
if (lineHeight > 0)
lastLine /= lineHeight;
int ret = mPaginator.getCurrentTop() + lastLine * lineHeight;
// first empty lines that would go to the next page should be ignored
mPaginator.setIgnoreLeadingEmptyLines(true);
const MyGUI::VectorLineInfo& lines = mEditBox->getSubWidgetText()->castType<MyGUI::EditText>()->getLineInfo();
for (size_t i = lastLine; i < lines.size(); ++i)
{
if (lines[i].width == 0)
ret += lineHeight;
else
{
mPaginator.setIgnoreLeadingEmptyLines(false);
break;
}
}
return ret;
}
/* ImageElement */
ImageElement::ImageElement(MyGUI::Widget* parent, Paginator& pag, const BlockStyle& blockStyle,
const std::string& src, int width, int height)
: GraphicElement(parent, pag, blockStyle)
, mImageHeight(height)
{
int left = 0;
if (mBlockStyle.mAlign.isHCenter())
left += (pag.getPageWidth() - width) / 2;
else if (mBlockStyle.mAlign.isLeft())
left = 0;
else if (mBlockStyle.mAlign.isRight())
left += pag.getPageWidth() - width;
mImageBox = parent->createWidget<MyGUI::ImageBox>("ImageBox",
MyGUI::IntCoord(left, pag.getCurrentTop(), width, mImageHeight), MyGUI::Align::Left | MyGUI::Align::Top,
parent->getName() + MyGUI::utility::toString(parent->getChildCount()));
mImageBox->setImageTexture(src);
mImageBox->setProperty("NeedMouse", "false");
}
int ImageElement::getHeight()
{
return mImageHeight;
}
int ImageElement::pageSplit()
{
// if the image is larger than the page, fall back to the default pageSplit implementation
if (mImageHeight > mPaginator.getPageHeight())
return GraphicElement::pageSplit();
return mPaginator.getCurrentTop();
}
}
| 19,513
|
C++
|
.cpp
| 483
| 27.281573
| 119
| 0.524772
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,520
|
travelwindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/travelwindow.cpp
|
#include "travelwindow.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_Gui.h>
#include <MyGUI_ScrollView.h>
#include <components/esm3/loadcrea.hpp>
#include <components/esm3/loadgmst.hpp>
#include <components/misc/strings/conversion.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/actionteleport.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/store.hpp"
#include "../mwworld/worldmodel.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
namespace MWGui
{
TravelWindow::TravelWindow()
: WindowBase("openmw_travel_window.layout")
, mCurrentY(0)
{
getWidget(mCancelButton, "CancelButton");
getWidget(mPlayerGold, "PlayerGold");
getWidget(mSelect, "Select");
getWidget(mDestinations, "Travel");
getWidget(mDestinationsView, "DestinationsView");
mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &TravelWindow::onCancelButtonClicked);
mDestinations->setCoord(450 / 2 - mDestinations->getTextSize().width / 2, mDestinations->getTop(),
mDestinations->getTextSize().width, mDestinations->getHeight());
mSelect->setCoord(8, mSelect->getTop(), mSelect->getTextSize().width, mSelect->getHeight());
}
void TravelWindow::addDestination(const ESM::RefId& name, const ESM::Position& pos, bool interior)
{
int price;
const MWWorld::Store<ESM::GameSetting>& gmst
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
int playerGold = player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId);
if (!mPtr.getCell()->isExterior())
{
price = gmst.find("fMagesGuildTravel")->mValue.getInteger();
}
else
{
ESM::Position PlayerPos = player.getRefData().getPosition();
float d = sqrt(pow(pos.pos[0] - PlayerPos.pos[0], 2) + pow(pos.pos[1] - PlayerPos.pos[1], 2)
+ pow(pos.pos[2] - PlayerPos.pos[2], 2));
float fTravelMult = gmst.find("fTravelMult")->mValue.getFloat();
if (fTravelMult != 0)
price = static_cast<int>(d / fTravelMult);
else
price = static_cast<int>(d);
}
price = std::max(1, price);
price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr, price, true);
// Add price for the travelling followers
std::set<MWWorld::Ptr> followers;
MWWorld::ActionTeleport::getFollowers(player, followers, !interior);
// Apply followers cost, unlike vanilla the first follower doesn't travel for free
price *= 1 + static_cast<int>(followers.size());
const int lineHeight = Settings::gui().mFontSize + 2;
MyGUI::Button* toAdd = mDestinationsView->createWidget<MyGUI::Button>(
"SandTextButton", 0, mCurrentY, 200, lineHeight, MyGUI::Align::Default);
toAdd->setEnabled(price <= playerGold);
mCurrentY += lineHeight;
if (interior)
toAdd->setUserString("interior", "y");
else
toAdd->setUserString("interior", "n");
const std::string& nameString = name.getRefIdString();
toAdd->setUserString("price", std::to_string(price));
toAdd->setCaptionWithReplacing(
"#{sCell=" + nameString + "} - " + MyGUI::utility::toString(price) + "#{sgp}");
toAdd->setSize(mDestinationsView->getWidth(), lineHeight);
toAdd->eventMouseWheel += MyGUI::newDelegate(this, &TravelWindow::onMouseWheel);
toAdd->setUserString("Destination", nameString);
toAdd->setUserData(pos);
toAdd->eventMouseButtonClick += MyGUI::newDelegate(this, &TravelWindow::onTravelButtonClick);
}
void TravelWindow::clearDestinations()
{
mDestinationsView->setViewOffset(MyGUI::IntPoint(0, 0));
mCurrentY = 0;
while (mDestinationsView->getChildCount())
MyGUI::Gui::getInstance().destroyWidget(mDestinationsView->getChildAt(0));
}
void TravelWindow::setPtr(const MWWorld::Ptr& actor)
{
if (actor.isEmpty() || !actor.getClass().isActor())
throw std::runtime_error("Invalid argument in TravelWindow::setPtr");
center();
mPtr = actor;
clearDestinations();
std::vector<ESM::Transport::Dest> transport;
if (mPtr.getClass().isNpc())
transport = mPtr.get<ESM::NPC>()->mBase->getTransport();
else if (mPtr.getType() == ESM::Creature::sRecordId)
transport = mPtr.get<ESM::Creature>()->mBase->getTransport();
for (const auto& dest : transport)
{
std::string_view cellname = dest.mCellName;
bool interior = true;
const ESM::ExteriorCellLocation cellIndex
= ESM::positionToExteriorCellLocation(dest.mPos.pos[0], dest.mPos.pos[1]);
if (cellname.empty())
{
MWWorld::CellStore& cell = MWBase::Environment::get().getWorldModel()->getExterior(cellIndex);
cellname = MWBase::Environment::get().getWorld()->getCellName(&cell);
interior = false;
}
addDestination(ESM::RefId::stringRefId(cellname), dest.mPos, interior);
}
updateLabels();
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
// scrollbar is hidden
mDestinationsView->setVisibleVScroll(false);
mDestinationsView->setCanvasSize(
MyGUI::IntSize(mDestinationsView->getWidth(), std::max(mDestinationsView->getHeight(), mCurrentY)));
mDestinationsView->setVisibleVScroll(true);
}
void TravelWindow::onTravelButtonClick(MyGUI::Widget* _sender)
{
const int price = Misc::StringUtils::toNumeric<int>(_sender->getUserString("price"), 0);
MWWorld::Ptr player = MWMechanics::getPlayer();
int playerGold = player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId);
if (playerGold < price)
return;
// Set "traveling" flag, so GetPCTraveling can detect teleportation.
// We will reset this flag during next world update.
MWBase::Environment::get().getWorld()->setPlayerTraveling(true);
if (!mPtr.getCell()->isExterior())
// Interior cell -> mages guild transport
MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("mysticism cast"));
player.getClass().getContainerStore(player).remove(MWWorld::ContainerStore::sGoldId, price);
// add gold to NPC trading gold pool
MWMechanics::CreatureStats& npcStats = mPtr.getClass().getCreatureStats(mPtr);
npcStats.setGoldPool(npcStats.getGoldPool() + price);
MWBase::Environment::get().getWindowManager()->fadeScreenOut(1);
ESM::Position pos = *_sender->getUserData<ESM::Position>();
std::string_view cellname = _sender->getUserString("Destination");
bool interior = _sender->getUserString("interior") == "y";
if (mPtr.getCell()->isExterior())
{
ESM::Position playerPos = player.getRefData().getPosition();
float d
= (osg::Vec3f(pos.pos[0], pos.pos[1], 0) - osg::Vec3f(playerPos.pos[0], playerPos.pos[1], 0)).length();
int hours = static_cast<int>(d
/ MWBase::Environment::get()
.getESMStore()
->get<ESM::GameSetting>()
.find("fTravelTimeMult")
->mValue.getFloat());
MWBase::Environment::get().getMechanicsManager()->rest(hours, true);
MWBase::Environment::get().getWorld()->advanceTime(hours);
}
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Travel);
MWBase::Environment::get().getWindowManager()->exitCurrentGuiMode();
MWBase::Environment::get().getWindowManager()->fadeScreenOut(1);
const ESM::ExteriorCellLocation posCell = ESM::positionToExteriorCellLocation(pos.pos[0], pos.pos[1]);
ESM::RefId cellId = ESM::Cell::generateIdForCell(!interior, cellname, posCell.mX, posCell.mY);
// Teleports any followers, too.
MWWorld::ActionTeleport action(cellId, pos, true);
action.execute(player);
MWBase::Environment::get().getWindowManager()->fadeScreenOut(0);
MWBase::Environment::get().getWindowManager()->fadeScreenIn(1);
}
void TravelWindow::onCancelButtonClicked(MyGUI::Widget* _sender)
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Travel);
}
void TravelWindow::updateLabels()
{
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
int playerGold = player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId);
mPlayerGold->setCaptionWithReplacing("#{sGold}: " + MyGUI::utility::toString(playerGold));
mPlayerGold->setCoord(8, mPlayerGold->getTop(), mPlayerGold->getTextSize().width, mPlayerGold->getHeight());
}
void TravelWindow::onReferenceUnavailable()
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(GM_Travel);
MWBase::Environment::get().getWindowManager()->exitCurrentGuiMode();
}
void TravelWindow::onMouseWheel(MyGUI::Widget* _sender, int _rel)
{
if (mDestinationsView->getViewOffset().top + _rel * 0.3f > 0)
mDestinationsView->setViewOffset(MyGUI::IntPoint(0, 0));
else
mDestinationsView->setViewOffset(
MyGUI::IntPoint(0, static_cast<int>(mDestinationsView->getViewOffset().top + _rel * 0.3f)));
}
}
| 10,186
|
C++
|
.cpp
| 197
| 42.639594
| 119
| 0.649879
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,521
|
layout.cpp
|
OpenMW_openmw/apps/openmw/mwgui/layout.cpp
|
#include "layout.hpp"
#include <MyGUI_Gui.h>
#include <MyGUI_LayoutManager.h>
#include <MyGUI_TextBox.h>
#include <MyGUI_UString.h>
#include <MyGUI_Widget.h>
#include <MyGUI_Window.h>
namespace MWGui
{
void Layout::initialise(std::string_view _layout)
{
const auto MAIN_WINDOW = "_Main";
mLayoutName = _layout;
mPrefix = MyGUI::utility::toString(this, "_");
mListWindowRoot = MyGUI::LayoutManager::getInstance().loadLayout(mLayoutName, mPrefix);
const std::string main_name = mPrefix + MAIN_WINDOW;
for (MyGUI::Widget* widget : mListWindowRoot)
{
if (widget->getName() == main_name)
mMainWidget = widget;
// Force the alignment to update immediately
widget->_setAlign(widget->getSize(), widget->getParentSize());
}
MYGUI_ASSERT(
mMainWidget, "root widget name '" << MAIN_WINDOW << "' in layout '" << mLayoutName << "' not found.");
}
void Layout::shutdown()
{
setVisible(false);
MyGUI::Gui::getInstance().destroyWidget(mMainWidget);
mListWindowRoot.clear();
}
void Layout::setCoord(int x, int y, int w, int h)
{
mMainWidget->setCoord(x, y, w, h);
}
void Layout::setVisible(bool b)
{
mMainWidget->setVisible(b);
}
void Layout::setText(std::string_view name, std::string_view caption)
{
MyGUI::Widget* pt;
getWidget(pt, name);
static_cast<MyGUI::TextBox*>(pt)->setCaption(MyGUI::UString(caption));
}
void Layout::setTitle(std::string_view title)
{
MyGUI::Window* window = static_cast<MyGUI::Window*>(mMainWidget);
if (window->getCaption() != title)
window->setCaptionWithReplacing(MyGUI::UString(title));
}
MyGUI::Widget* Layout::getWidget(std::string_view _name)
{
std::string target = mPrefix;
target += _name;
for (MyGUI::Widget* widget : mListWindowRoot)
{
MyGUI::Widget* find = widget->findWidget(target);
if (nullptr != find)
{
return find;
}
}
MYGUI_EXCEPT("widget name '" << _name << "' in layout '" << mLayoutName << "' not found.");
}
}
| 2,282
|
C++
|
.cpp
| 67
| 26.537313
| 114
| 0.595822
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,522
|
inventoryitemmodel.cpp
|
OpenMW_openmw/apps/openmw/mwgui/inventoryitemmodel.cpp
|
#include "inventoryitemmodel.hpp"
#include <sstream>
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/manualref.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
namespace MWGui
{
InventoryItemModel::InventoryItemModel(const MWWorld::Ptr& actor)
: mActor(actor)
{
}
ItemStack InventoryItemModel::getItem(ModelIndex index)
{
if (index < 0)
throw std::runtime_error("Invalid index supplied");
if (mItems.size() <= static_cast<size_t>(index))
throw std::runtime_error("Item index out of range");
return mItems[index];
}
size_t InventoryItemModel::getItemCount()
{
return mItems.size();
}
ItemModel::ModelIndex InventoryItemModel::getIndex(const ItemStack& item)
{
size_t i = 0;
for (ItemStack& itemStack : mItems)
{
if (itemStack == item)
return i;
++i;
}
return -1;
}
MWWorld::Ptr InventoryItemModel::addItem(const ItemStack& item, size_t count, bool allowAutoEquip)
{
if (item.mBase.getContainerStore() == &mActor.getClass().getContainerStore(mActor))
throw std::runtime_error("Item to add needs to be from a different container!");
return *mActor.getClass().getContainerStore(mActor).add(item.mBase, count, allowAutoEquip);
}
MWWorld::Ptr InventoryItemModel::copyItem(const ItemStack& item, size_t count, bool allowAutoEquip)
{
if (item.mBase.getContainerStore() == &mActor.getClass().getContainerStore(mActor))
throw std::runtime_error("Item to copy needs to be from a different container!");
MWWorld::ManualRef newRef(*MWBase::Environment::get().getESMStore(), item.mBase, count);
return *mActor.getClass().getContainerStore(mActor).add(newRef.getPtr(), count, allowAutoEquip);
}
void InventoryItemModel::removeItem(const ItemStack& item, size_t count)
{
int removed = 0;
// Re-equipping makes sense only if a target has inventory
if (mActor.getClass().hasInventoryStore(mActor))
{
MWWorld::InventoryStore& store = mActor.getClass().getInventoryStore(mActor);
removed = store.remove(item.mBase, count, true);
}
else
{
MWWorld::ContainerStore& store = mActor.getClass().getContainerStore(mActor);
removed = store.remove(item.mBase, count);
}
std::stringstream error;
if (removed == 0)
{
error << "Item '" << item.mBase.getCellRef().getRefId() << "' was not found in container store to remove";
throw std::runtime_error(error.str());
}
else if (removed < static_cast<int>(count))
{
error << "Not enough items '" << item.mBase.getCellRef().getRefId() << "' in the stack to remove ("
<< static_cast<int>(count) << " requested, " << removed << " found)";
throw std::runtime_error(error.str());
}
}
MWWorld::Ptr InventoryItemModel::moveItem(
const ItemStack& item, size_t count, ItemModel* otherModel, bool allowAutoEquip)
{
// Can't move conjured items: This is a general fix that also takes care of issues with taking conjured items
// via the 'Take All' button.
if (item.mFlags & ItemStack::Flag_Bound)
return MWWorld::Ptr();
return ItemModel::moveItem(item, count, otherModel, allowAutoEquip);
}
void InventoryItemModel::update()
{
MWWorld::ContainerStore& store = mActor.getClass().getContainerStore(mActor);
mItems.clear();
for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it)
{
MWWorld::Ptr item = *it;
if (!item.getClass().showsInInventory(item))
continue;
ItemStack newItem(item, this, item.getCellRef().getCount());
if (mActor.getClass().hasInventoryStore(mActor))
{
MWWorld::InventoryStore& invStore = mActor.getClass().getInventoryStore(mActor);
if (invStore.isEquipped(newItem.mBase))
newItem.mType = ItemStack::Type_Equipped;
}
mItems.push_back(newItem);
}
}
bool InventoryItemModel::onTakeItem(const MWWorld::Ptr& item, int count)
{
// Looting a dead corpse is considered OK
if (mActor.getClass().isActor() && mActor.getClass().getCreatureStats(mActor).isDead())
return true;
MWWorld::Ptr player = MWMechanics::getPlayer();
MWBase::Environment::get().getMechanicsManager()->itemTaken(player, item, mActor, count);
return true;
}
bool InventoryItemModel::usesContainer(const MWWorld::Ptr& container)
{
return mActor == container;
}
}
| 5,084
|
C++
|
.cpp
| 121
| 33.520661
| 118
| 0.632347
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,523
|
jailscreen.cpp
|
OpenMW_openmw/apps/openmw/mwgui/jailscreen.cpp
|
#include <MyGUI_ScrollBar.h>
#include <components/misc/rng.hpp>
#include <components/misc/strings/format.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/store.hpp"
#include "jailscreen.hpp"
namespace MWGui
{
JailScreen::JailScreen()
: WindowBase("openmw_jail_screen.layout")
, mDays(1)
, mFadeTimeRemaining(0)
, mTimeAdvancer(0.01f)
{
getWidget(mProgressBar, "ProgressBar");
mTimeAdvancer.eventProgressChanged += MyGUI::newDelegate(this, &JailScreen::onJailProgressChanged);
mTimeAdvancer.eventFinished += MyGUI::newDelegate(this, &JailScreen::onJailFinished);
center();
}
void JailScreen::goToJail(int days)
{
mDays = days;
MWBase::Environment::get().getWindowManager()->fadeScreenOut(0.5);
mFadeTimeRemaining = 0.5;
setVisible(false);
mProgressBar->setScrollRange(100 + 1);
mProgressBar->setScrollPosition(0);
mProgressBar->setTrackSize(0);
}
void JailScreen::onFrame(float dt)
{
mTimeAdvancer.onFrame(dt);
if (mFadeTimeRemaining <= 0)
return;
mFadeTimeRemaining -= dt;
if (mFadeTimeRemaining <= 0)
{
MWWorld::Ptr player = MWMechanics::getPlayer();
MWBase::Environment::get().getWorld()->teleportToClosestMarker(
player, ESM::RefId::stringRefId("prisonmarker"));
MWBase::Environment::get().getWindowManager()->fadeScreenOut(
0.f); // override fade-in caused by cell transition
setVisible(true);
mTimeAdvancer.run(100);
}
}
void JailScreen::onJailProgressChanged(int cur, int /*total*/)
{
mProgressBar->setScrollPosition(0);
mProgressBar->setTrackSize(
static_cast<int>(cur / (float)(mProgressBar->getScrollRange()) * mProgressBar->getLineSize()));
}
void JailScreen::onJailFinished()
{
MWBase::Environment::get().getWindowManager()->removeGuiMode(MWGui::GM_Jail);
MWBase::Environment::get().getWindowManager()->fadeScreenIn(0.5);
MWWorld::Ptr player = MWMechanics::getPlayer();
MWBase::Environment::get().getMechanicsManager()->rest(mDays * 24, true);
MWBase::Environment::get().getWorld()->advanceTime(mDays * 24);
// We should not worsen corprus when in prison
player.getClass().getCreatureStats(player).getActiveSpells().skipWorsenings(mDays * 24);
const auto& skillStore = MWBase::Environment::get().getESMStore()->get<ESM::Skill>();
std::set<const ESM::Skill*> skills;
for (int day = 0; day < mDays; ++day)
{
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
const ESM::Skill* skill = skillStore.searchRandom({}, prng);
skills.insert(skill);
MWMechanics::SkillValue& value = player.getClass().getNpcStats(player).getSkill(skill->mId);
if (skill->mId == ESM::Skill::Security || skill->mId == ESM::Skill::Sneak)
value.setBase(std::min(100.f, value.getBase() + 1));
else
value.setBase(std::max(0.f, value.getBase() - 1));
}
const MWWorld::Store<ESM::GameSetting>& gmst
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
std::string message;
if (mDays == 1)
message = gmst.find("sNotifyMessage42")->mValue.getString();
else
message = gmst.find("sNotifyMessage43")->mValue.getString();
message = Misc::StringUtils::format(message, mDays);
for (const ESM::Skill* skill : skills)
{
int skillValue = player.getClass().getNpcStats(player).getSkill(skill->mId).getBase();
std::string skillMsg = gmst.find("sNotifyMessage44")->mValue.getString();
if (skill->mId == ESM::Skill::Sneak || skill->mId == ESM::Skill::Security)
skillMsg = gmst.find("sNotifyMessage39")->mValue.getString();
skillMsg = Misc::StringUtils::format(skillMsg, skill->mName, skillValue);
message += "\n" + skillMsg;
}
std::vector<std::string> buttons;
buttons.emplace_back("#{Interface:OK}");
MWBase::Environment::get().getWindowManager()->interactiveMessageBox(message, buttons);
}
}
| 4,644
|
C++
|
.cpp
| 103
| 36.427184
| 107
| 0.6332
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,524
|
backgroundimage.cpp
|
OpenMW_openmw/apps/openmw/mwgui/backgroundimage.cpp
|
#include "backgroundimage.hpp"
#include <MyGUI_Gui.h>
namespace MWGui
{
void BackgroundImage::setBackgroundImage(const std::string& image, bool fixedRatio, bool stretch)
{
if (mChild)
{
MyGUI::Gui::getInstance().destroyWidget(mChild);
mChild = nullptr;
}
if (!stretch)
{
setImageTexture("black");
if (fixedRatio)
mAspect = 4.0 / 3.0;
else
mAspect = 0; // TODO
mChild
= createWidgetReal<MyGUI::ImageBox>("ImageBox", MyGUI::FloatCoord(0, 0, 1, 1), MyGUI::Align::Default);
mChild->setImageTexture(image);
adjustSize();
}
else
{
mAspect = 0;
setImageTexture(image);
}
}
void BackgroundImage::adjustSize()
{
if (mAspect == 0)
return;
MyGUI::IntSize screenSize = getSize();
int leftPadding = std::max(0, static_cast<int>(screenSize.width - screenSize.height * mAspect) / 2);
int topPadding = std::max(0, static_cast<int>(screenSize.height - screenSize.width / mAspect) / 2);
mChild->setCoord(
leftPadding, topPadding, screenSize.width - leftPadding * 2, screenSize.height - topPadding * 2);
}
void BackgroundImage::setSize(const MyGUI::IntSize& _value)
{
MyGUI::Widget::setSize(_value);
adjustSize();
}
void BackgroundImage::setCoord(const MyGUI::IntCoord& _value)
{
MyGUI::Widget::setCoord(_value);
adjustSize();
}
}
| 1,609
|
C++
|
.cpp
| 50
| 23.24
| 118
| 0.571151
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,525
|
windowbase.cpp
|
OpenMW_openmw/apps/openmw/mwgui/windowbase.cpp
|
#include "windowbase.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_InputManager.h>
#include <MyGUI_RenderManager.h>
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include <components/widgets/imagebutton.hpp>
#include "draganddrop.hpp"
#include "exposedwindow.hpp"
using namespace MWGui;
WindowBase::WindowBase(std::string_view parLayout)
: Layout(parLayout)
{
mMainWidget->setVisible(false);
Window* window = mMainWidget->castType<Window>(false);
if (!window)
return;
MyGUI::Button* button = nullptr;
MyGUI::VectorWidgetPtr widgets = window->getSkinWidgetsByName("Action");
for (MyGUI::Widget* widget : widgets)
{
if (widget->isUserString("SupportDoubleClick"))
button = widget->castType<MyGUI::Button>();
}
if (button)
button->eventMouseButtonDoubleClick += MyGUI::newDelegate(this, &WindowBase::onDoubleClick);
}
void WindowBase::onTitleDoubleClicked()
{
if (MyGUI::InputManager::getInstance().isShiftPressed())
MWBase::Environment::get().getWindowManager()->toggleMaximized(this);
}
void WindowBase::onDoubleClick(MyGUI::Widget* _sender)
{
onTitleDoubleClicked();
}
void WindowBase::setVisible(bool visible)
{
visible = visible && !mDisabledByLua;
bool wasVisible = mMainWidget->getVisible();
mMainWidget->setVisible(visible);
if (visible)
onOpen();
else if (wasVisible)
onClose();
}
bool WindowBase::isVisible() const
{
return mMainWidget->getVisible();
}
void WindowBase::center()
{
// Centre dialog
MyGUI::IntSize layerSize = MyGUI::RenderManager::getInstance().getViewSize();
if (mMainWidget->getLayer())
layerSize = mMainWidget->getLayer()->getSize();
MyGUI::IntCoord coord = mMainWidget->getCoord();
coord.left = (layerSize.width - coord.width) / 2;
coord.top = (layerSize.height - coord.height) / 2;
mMainWidget->setCoord(coord);
}
void WindowBase::clampWindowCoordinates(MyGUI::Window* window)
{
MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize();
if (window->getLayer())
viewSize = window->getLayer()->getSize();
// Window's minimum size is larger than the screen size, can not clamp coordinates
auto minSize = window->getMinSize();
if (minSize.width > viewSize.width || minSize.height > viewSize.height)
return;
int left = std::max(0, window->getPosition().left);
int top = std::max(0, window->getPosition().top);
int width = std::clamp(window->getSize().width, 0, viewSize.width);
int height = std::clamp(window->getSize().height, 0, viewSize.height);
if (left + width > viewSize.width)
left = viewSize.width - width;
if (top + height > viewSize.height)
top = viewSize.height - height;
if (window->getSize().width != width || window->getSize().height != height)
window->setSize(width, height);
if (window->getPosition().left != left || window->getPosition().top != top)
window->setPosition(left, top);
}
WindowModal::WindowModal(const std::string& parLayout)
: WindowBase(parLayout)
{
}
void WindowModal::onOpen()
{
MWBase::Environment::get().getWindowManager()->addCurrentModal(this); // Set so we can escape it if needed
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getKeyFocusWidget();
MyGUI::InputManager::getInstance().addWidgetModal(mMainWidget);
MyGUI::InputManager::getInstance().setKeyFocusWidget(focus);
}
void WindowModal::onClose()
{
MWBase::Environment::get().getWindowManager()->removeCurrentModal(this);
MyGUI::InputManager::getInstance().removeWidgetModal(mMainWidget);
}
NoDrop::NoDrop(DragAndDrop* drag, MyGUI::Widget* widget)
: mWidget(widget)
, mDrag(drag)
, mTransparent(false)
{
}
void NoDrop::onFrame(float dt)
{
if (!mWidget)
return;
MyGUI::IntPoint mousePos = MyGUI::InputManager::getInstance().getMousePosition();
if (mDrag->mIsOnDragAndDrop)
{
MyGUI::Widget* focus = MyGUI::InputManager::getInstance().getMouseFocusWidget();
while (focus && focus != mWidget)
focus = focus->getParent();
if (focus == mWidget)
mTransparent = true;
}
if (!mWidget->getAbsoluteCoord().inside(mousePos))
mTransparent = false;
if (mTransparent)
{
mWidget->setNeedMouseFocus(false); // Allow click-through
setAlpha(std::max(0.13f, mWidget->getAlpha() - dt * 5));
}
else
{
mWidget->setNeedMouseFocus(true);
setAlpha(std::min(1.0f, mWidget->getAlpha() + dt * 5));
}
}
void NoDrop::setAlpha(float alpha)
{
if (mWidget)
mWidget->setAlpha(alpha);
}
BookWindowBase::BookWindowBase(std::string_view parLayout)
: WindowBase(parLayout)
{
}
float BookWindowBase::adjustButton(std::string_view name)
{
Gui::ImageButton* button;
WindowBase::getWidget(button, name);
MyGUI::IntSize requested = button->getRequestedSize();
float scale = float(requested.height) / button->getSize().height;
MyGUI::IntSize newSize = requested;
newSize.width /= scale;
newSize.height /= scale;
button->setSize(newSize);
if (button->getAlign().isRight())
{
MyGUI::IntSize diff = (button->getSize() - requested);
diff.width /= scale;
diff.height /= scale;
button->setPosition(button->getPosition() + MyGUI::IntPoint(diff.width, 0));
}
return scale;
}
| 5,489
|
C++
|
.cpp
| 159
| 29.830189
| 110
| 0.689473
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,526
|
itemselection.cpp
|
OpenMW_openmw/apps/openmw/mwgui/itemselection.cpp
|
#include "itemselection.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_TextBox.h>
#include "inventoryitemmodel.hpp"
#include "itemview.hpp"
#include "sortfilteritemmodel.hpp"
namespace MWGui
{
ItemSelectionDialog::ItemSelectionDialog(const std::string& label)
: WindowModal("openmw_itemselection_dialog.layout")
, mSortModel(nullptr)
{
getWidget(mItemView, "ItemView");
mItemView->eventItemClicked += MyGUI::newDelegate(this, &ItemSelectionDialog::onSelectedItem);
MyGUI::TextBox* l;
getWidget(l, "Label");
l->setCaptionWithReplacing(label);
MyGUI::Button* cancelButton;
getWidget(cancelButton, "CancelButton");
cancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &ItemSelectionDialog::onCancelButtonClicked);
center();
}
bool ItemSelectionDialog::exit()
{
eventDialogCanceled();
return true;
}
void ItemSelectionDialog::openContainer(const MWWorld::Ptr& container)
{
auto sortModel = std::make_unique<SortFilterItemModel>(std::make_unique<InventoryItemModel>(container));
mSortModel = sortModel.get();
mItemView->setModel(std::move(sortModel));
mItemView->resetScrollBars();
}
void ItemSelectionDialog::setCategory(int category)
{
mSortModel->setCategory(category);
mItemView->update();
}
void ItemSelectionDialog::setFilter(int filter)
{
mSortModel->setFilter(filter);
mItemView->update();
}
void ItemSelectionDialog::onSelectedItem(int index)
{
ItemStack item = mSortModel->getItem(index);
eventItemSelected(item.mBase);
}
void ItemSelectionDialog::onCancelButtonClicked(MyGUI::Widget* sender)
{
exit();
}
}
| 1,813
|
C++
|
.cpp
| 54
| 27.203704
| 117
| 0.689971
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,527
|
debugwindow.cpp
|
OpenMW_openmw/apps/openmw/mwgui/debugwindow.cpp
|
#include "debugwindow.hpp"
#include <MyGUI_EditBox.h>
#include <MyGUI_TabControl.h>
#include <MyGUI_TabItem.h>
#include <LinearMath/btQuickprof.h>
#include <components/debug/debugging.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/luamanager.hpp"
#include <mutex>
#ifndef BT_NO_PROFILE
namespace
{
void bulletDumpRecursive(CProfileIterator* pit, int spacing, std::stringstream& os)
{
pit->First();
if (pit->Is_Done())
return;
float accumulated_time = 0,
parent_time
= pit->Is_Root() ? CProfileManager::Get_Time_Since_Reset() : pit->Get_Current_Parent_Total_Time();
int i, j;
int frames_since_reset = CProfileManager::Get_Frame_Count_Since_Reset();
for (i = 0; i < spacing; i++)
os << ".";
os << "----------------------------------\n";
for (i = 0; i < spacing; i++)
os << ".";
std::string s = "Profiling: " + std::string(pit->Get_Current_Parent_Name())
+ " (total running time: " + MyGUI::utility::toString(parent_time, 3) + " ms) ---\n";
os << s;
// float totalTime = 0.f;
int numChildren = 0;
for (i = 0; !pit->Is_Done(); i++, pit->Next())
{
numChildren++;
float current_total_time = pit->Get_Current_Total_Time();
accumulated_time += current_total_time;
float fraction = parent_time > SIMD_EPSILON ? (current_total_time / parent_time) * 100 : 0.f;
for (j = 0; j < spacing; j++)
os << ".";
double ms = (current_total_time / (double)frames_since_reset);
s = MyGUI::utility::toString(i) + " -- " + pit->Get_Current_Name() + " ("
+ MyGUI::utility::toString(fraction, 2) + " %) :: " + MyGUI::utility::toString(ms, 3) + " ms / frame ("
+ MyGUI::utility::toString(pit->Get_Current_Total_Calls()) + " calls)\n";
os << s;
// totalTime += current_total_time;
// recurse into children
}
if (parent_time < accumulated_time)
{
os << "what's wrong\n";
}
for (i = 0; i < spacing; i++)
os << ".";
double unaccounted = parent_time > SIMD_EPSILON ? ((parent_time - accumulated_time) / parent_time) * 100 : 0.f;
s = "Unaccounted: (" + MyGUI::utility::toString(unaccounted, 3)
+ " %) :: " + MyGUI::utility::toString(parent_time - accumulated_time, 3) + " ms\n";
os << s;
for (i = 0; i < numChildren; i++)
{
pit->Enter_Child(i);
bulletDumpRecursive(pit, spacing + 3, os);
pit->Enter_Parent();
}
}
void bulletDumpAll(std::stringstream& os)
{
CProfileIterator* profileIterator = 0;
profileIterator = CProfileManager::Get_Iterator();
bulletDumpRecursive(profileIterator, 0, os);
CProfileManager::Release_Iterator(profileIterator);
}
}
#endif // BT_NO_PROFILE
namespace MWGui
{
DebugWindow::DebugWindow()
: WindowBase("openmw_debug_window.layout")
{
getWidget(mTabControl, "TabControl");
// Ideas for other tabs:
// - Texture / compositor texture viewer
// - Material editor
// - Shader editor
MyGUI::TabItem* itemLV = mTabControl->addItem("Log Viewer");
itemLV->setCaptionWithReplacing(" #{OMWEngine:LogViewer} ");
mLogView
= itemLV->createWidgetReal<MyGUI::EditBox>("LogEdit", MyGUI::FloatCoord(0, 0, 1, 1), MyGUI::Align::Stretch);
mLogView->setEditReadOnly(true);
MyGUI::TabItem* itemLuaProfiler = mTabControl->addItem("Lua Profiler");
itemLuaProfiler->setCaptionWithReplacing(" #{OMWEngine:LuaProfiler} ");
mLuaProfiler = itemLuaProfiler->createWidgetReal<MyGUI::EditBox>(
"LogEdit", MyGUI::FloatCoord(0, 0, 1, 1), MyGUI::Align::Stretch);
mLuaProfiler->setEditReadOnly(true);
#ifndef BT_NO_PROFILE
MyGUI::TabItem* item = mTabControl->addItem("Physics Profiler");
item->setCaptionWithReplacing(" #{OMWEngine:PhysicsProfiler} ");
mBulletProfilerEdit
= item->createWidgetReal<MyGUI::EditBox>("LogEdit", MyGUI::FloatCoord(0, 0, 1, 1), MyGUI::Align::Stretch);
#else
mBulletProfilerEdit = nullptr;
#endif
}
static std::vector<char> sLogCircularBuffer;
static std::mutex sBufferMutex;
static int64_t sLogStartIndex;
static int64_t sLogEndIndex;
static bool hasPrefix = false;
void DebugWindow::startLogRecording()
{
sLogCircularBuffer.resize(Settings::general().mLogBufferSize);
Debug::setLogListener([](Debug::Level level, std::string_view prefix, std::string_view msg) {
if (sLogCircularBuffer.empty())
return; // Log viewer is disabled.
std::string_view color;
switch (level)
{
case Debug::Error:
color = "#FF0000";
break;
case Debug::Warning:
color = "#FFFF00";
break;
case Debug::Info:
color = "#FFFFFF";
break;
case Debug::Verbose:
case Debug::Debug:
color = "#666666";
break;
default:
color = "#FFFFFF";
}
bool bufferOverflow = false;
std::lock_guard lock(sBufferMutex);
const int64_t bufSize = sLogCircularBuffer.size();
auto addChar = [&](char c) {
sLogCircularBuffer[sLogEndIndex++] = c;
if (sLogEndIndex == bufSize)
sLogEndIndex = 0;
bufferOverflow = bufferOverflow || sLogEndIndex == sLogStartIndex;
};
auto addShieldedStr = [&](std::string_view s) {
for (char c : s)
{
addChar(c);
if (c == '#')
addChar(c);
if (c == '\n')
hasPrefix = false;
}
};
for (char c : color)
addChar(c);
if (!hasPrefix)
{
addShieldedStr(prefix);
hasPrefix = true;
}
addShieldedStr(msg);
if (bufferOverflow)
sLogStartIndex = (sLogEndIndex + 1) % bufSize;
});
}
void DebugWindow::updateLogView()
{
std::lock_guard lock(sBufferMutex);
if (!mLogView || sLogCircularBuffer.empty() || sLogStartIndex == sLogEndIndex)
return;
if (mLogView->isTextSelection())
return; // Don't change text while player is trying to copy something
std::string addition;
const int64_t bufSize = sLogCircularBuffer.size();
{
if (sLogStartIndex < sLogEndIndex)
addition = std::string(sLogCircularBuffer.data() + sLogStartIndex, sLogEndIndex - sLogStartIndex);
else
{
addition = std::string(sLogCircularBuffer.data() + sLogStartIndex, bufSize - sLogStartIndex);
addition.append(sLogCircularBuffer.data(), sLogEndIndex);
}
sLogStartIndex = sLogEndIndex;
}
size_t scrollPos = mLogView->getVScrollPosition();
bool scrolledToTheEnd = scrollPos + 1 >= mLogView->getVScrollRange();
int64_t newSizeEstimation = mLogView->getTextLength() + addition.size();
if (newSizeEstimation > bufSize)
mLogView->eraseText(0, newSizeEstimation - bufSize);
mLogView->addText(addition);
if (scrolledToTheEnd && mLogView->getVScrollRange() > 0)
mLogView->setVScrollPosition(mLogView->getVScrollRange() - 1);
else
mLogView->setVScrollPosition(scrollPos);
}
void DebugWindow::updateLuaProfile()
{
if (mLuaProfiler->isTextSelection())
return;
size_t previousPos = mLuaProfiler->getVScrollPosition();
mLuaProfiler->setCaption(MWBase::Environment::get().getLuaManager()->formatResourceUsageStats());
mLuaProfiler->setVScrollPosition(std::min(previousPos, mLuaProfiler->getVScrollRange() - 1));
}
void DebugWindow::updateBulletProfile()
{
#ifndef BT_NO_PROFILE
std::stringstream stream;
bulletDumpAll(stream);
if (mBulletProfilerEdit->isTextSelection()) // pause updating while user is trying to copy text
return;
size_t previousPos = mBulletProfilerEdit->getVScrollPosition();
mBulletProfilerEdit->setCaption(stream.str());
mBulletProfilerEdit->setVScrollPosition(std::min(previousPos, mBulletProfilerEdit->getVScrollRange() - 1));
#endif
}
void DebugWindow::onFrame(float dt)
{
static float timer = 0;
timer -= dt;
if (timer > 0 || !isVisible())
return;
timer = 0.25;
switch (mTabControl->getIndexSelected())
{
case 0:
updateLogView();
break;
case 1:
updateLuaProfile();
break;
case 2:
updateBulletProfile();
break;
default:;
}
}
}
| 9,486
|
C++
|
.cpp
| 237
| 29.350211
| 120
| 0.561971
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,530
|
textinput.cpp
|
OpenMW_openmw/apps/openmw/mwgui/textinput.cpp
|
#include "textinput.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"
#include <MyGUI_Button.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_UString.h>
namespace MWGui
{
TextInputDialog::TextInputDialog()
: WindowModal("openmw_text_input.layout")
{
// Centre dialog
center();
getWidget(mTextEdit, "TextEdit");
mTextEdit->eventEditSelectAccept += newDelegate(this, &TextInputDialog::onTextAccepted);
MyGUI::Button* okButton;
getWidget(okButton, "OKButton");
okButton->eventMouseButtonClick += MyGUI::newDelegate(this, &TextInputDialog::onOkClicked);
// Make sure the edit box has focus
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mTextEdit);
}
void TextInputDialog::setNextButtonShow(bool shown)
{
MyGUI::Button* okButton;
getWidget(okButton, "OKButton");
if (shown)
okButton->setCaption(
MyGUI::UString(MWBase::Environment::get().getWindowManager()->getGameSettingString("sNext", {})));
else
okButton->setCaption(
MyGUI::UString(MWBase::Environment::get().getWindowManager()->getGameSettingString("sOK", {})));
}
void TextInputDialog::setTextLabel(std::string_view label)
{
setText("LabelT", label);
}
void TextInputDialog::onOpen()
{
WindowModal::onOpen();
// Make sure the edit box has focus
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mTextEdit);
}
// widget controls
void TextInputDialog::onOkClicked(MyGUI::Widget* _sender)
{
if (mTextEdit->getCaption().empty())
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage37}");
MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mTextEdit);
}
else
eventDone(this);
}
void TextInputDialog::onTextAccepted(MyGUI::EditBox* _sender)
{
onOkClicked(_sender);
// To do not spam onTextAccepted() again and again
MWBase::Environment::get().getWindowManager()->injectKeyRelease(MyGUI::KeyCode::None);
}
std::string TextInputDialog::getTextInput() const
{
return mTextEdit->getCaption();
}
void TextInputDialog::setTextInput(const std::string& text)
{
mTextEdit->setCaption(text);
}
}
| 2,459
|
C++
|
.cpp
| 68
| 28.897059
| 114
| 0.654024
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.