diff --git a/.gitignore b/.gitignore index 26ba80e1a..9734ac35c 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ Makefile makefile data *.kdev4 +CMakeLists.txt.user diff --git a/.gitmodules b/.gitmodules index d2a4cf0d3..8b1378917 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1 @@ -[submodule "extern/shiny"] - path = extern/shiny - url = git://github.com/scrawl/shiny.git + diff --git a/CMakeLists.txt b/CMakeLists.txt index 614a840c4..78388e20f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,7 +15,7 @@ include (OpenMWMacros) # Version set (OPENMW_VERSION_MAJOR 0) -set (OPENMW_VERSION_MINOR 18) +set (OPENMW_VERSION_MINOR 19) set (OPENMW_VERSION_RELEASE 0) set (OPENMW_VERSION "${OPENMW_VERSION_MAJOR}.${OPENMW_VERSION_MINOR}.${OPENMW_VERSION_RELEASE}") @@ -306,7 +306,7 @@ endif() # Compiler settings if (CMAKE_COMPILER_IS_GNUCC) - add_definitions (-Wall -Wextra -Wno-unused-parameter -Wno-reorder) + add_definitions (-Wall -Wextra -Wno-unused-parameter -Wno-reorder -std=c++0x -pedantic) # Silence warnings in OGRE headers. Remove once OGRE got fixed! add_definitions (-Wno-ignored-qualifiers) @@ -659,7 +659,6 @@ if (NOT WIN32 AND NOT DPKG_PROGRAM AND NOT APPLE) #INSTALL(FILES "${OpenMW_BINARY_DIR}/plugins.cfg" DESTINATION "${SYSCONFDIR}" ) INSTALL(FILES "${OpenMW_BINARY_DIR}/settings-default.cfg" DESTINATION "${SYSCONFDIR}" ) INSTALL(FILES "${OpenMW_BINARY_DIR}/transparency-overrides.cfg" DESTINATION "${SYSCONFDIR}" ) - INSTALL(FILES "${OpenMW_BINARY_DIR}/launcher.cfg" DESTINATION "${SYSCONFDIR}" ) # Install resources INSTALL(DIRECTORY "${OpenMW_BINARY_DIR}/resources" DESTINATION "${DATADIR}" ) diff --git a/apps/esmtool/CMakeLists.txt b/apps/esmtool/CMakeLists.txt index f48aa41bf..5c588fb29 100644 --- a/apps/esmtool/CMakeLists.txt +++ b/apps/esmtool/CMakeLists.txt @@ -1,5 +1,7 @@ set(ESMTOOL esmtool.cpp + labels.hpp + labels.cpp record.hpp record.cpp ) diff --git a/apps/esmtool/esmtool.cpp b/apps/esmtool/esmtool.cpp index 88709f58b..4f6d9dbfc 100644 --- a/apps/esmtool/esmtool.cpp +++ b/apps/esmtool/esmtool.cpp @@ -13,7 +13,7 @@ #include "record.hpp" -#define ESMTOOL_VERSION 1.1 +#define ESMTOOL_VERSION 1.2 // Create a local alias for brevity namespace bpo = boost::program_options; @@ -57,6 +57,8 @@ struct Arguments std::string encoding; std::string filename; std::string outname; + + std::vector types; ESMData data; ESM::ESMReader reader; @@ -70,7 +72,12 @@ bool parseOptions (int argc, char** argv, Arguments &info) desc.add_options() ("help,h", "print help message.") ("version,v", "print version information and quit.") - ("raw,r", "Show an unformattet list of all records and subrecords.") + ("raw,r", "Show an unformatted list of all records and subrecords.") + // The intention is that this option would interact better + // with other modes including clone, dump, and raw. + ("type,t", bpo::value< std::vector >(), + "Show only records of this type (four character record code). May " + "be specified multiple times. Only affects dump mode.") ("quiet,q", "Supress all record information. Useful for speed tests.") ("loadcells,C", "Browse through contents of all cells.") @@ -122,6 +129,9 @@ bool parseOptions (int argc, char** argv, Arguments &info) return false; } + if (variables.count("type") > 0) + info.types = variables["type"].as< std::vector >(); + info.mode = variables["mode"].as(); if (!(info.mode == "dump" || info.mode == "clone" || info.mode == "comp")) { @@ -306,14 +316,23 @@ int load(Arguments& info) uint32_t flags; esm.getRecHeader(flags); + // Is the user interested in this record type? + bool interested = true; + if (info.types.size() > 0) + { + std::vector::iterator match; + match = std::find(info.types.begin(), info.types.end(), + n.toString()); + if (match == info.types.end()) interested = false; + } + std::string id = esm.getHNOString("NAME"); - if(!quiet) + if(!quiet && interested) std::cout << "\nRecord: " << n.toString() << " '" << id << "'\n"; - EsmTool::RecordBase *record = - EsmTool::RecordBase::create(n.val); + EsmTool::RecordBase *record = EsmTool::RecordBase::create(n); if (record == 0) { if (std::find(skipped.begin(), skipped.end(), n.val) == skipped.end()) @@ -326,18 +345,16 @@ int load(Arguments& info) if (quiet) break; std::cout << " Skipping\n"; } else { - if (record->getType() == ESM::REC_GMST) { + if (record->getType().val == ESM::REC_GMST) { // preset id for GameSetting record record->cast()->get().mId = id; } record->setId(id); record->setFlags((int) flags); record->load(esm); - if (!quiet) { - record->print(); - } + if (!quiet && interested) record->print(); - if (record->getType() == ESM::REC_CELL && loadCells) { + if (record->getType().val == ESM::REC_CELL && loadCells) { loadCell(record->cast()->get(), esm, info); } @@ -434,7 +451,7 @@ int clone(Arguments& info) { EsmTool::RecordBase *record = *it; - name.val = record->getType(); + name.val = record->getType().val; esm.startRecord(name.toString(), record->getFlags()); diff --git a/apps/esmtool/labels.cpp b/apps/esmtool/labels.cpp new file mode 100644 index 000000000..9fb233237 --- /dev/null +++ b/apps/esmtool/labels.cpp @@ -0,0 +1,881 @@ +#include "labels.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +std::string bodyPartLabel(char idx) +{ + const char *bodyPartLabels[] = { + "Head", + "Hair", + "Neck", + "Cuirass", + "Groin", + "Skirt", + "Right Hand", + "Left Hand", + "Right Wrist", + "Left Wrist", + "Shield", + "Right Forearm", + "Left Forearm", + "Right Upperarm", + "Left Upperarm", + "Right Foot", + "Left Foot", + "Right Ankle", + "Left Ankle", + "Right Knee", + "Left Knee", + "Right Leg", + "Left Leg", + "Right Shoulder", + "Left Shoulder", + "Weapon", + "Tail" + }; + + if ((int)idx >= 0 && (int)(idx) <= 26) + return bodyPartLabels[(int)(idx)]; + else + return "Invalid"; +} + +std::string meshPartLabel(char idx) +{ + const char *meshPartLabels[] = { + "Head", + "Hair", + "Neck", + "Chest", + "Groin", + "Hand", + "Wrist", + "Forearm", + "Upperarm", + "Foot", + "Ankle", + "Knee", + "Upper Leg", + "Clavicle", + "Tail" + }; + + if ((int)(idx) >= 0 && (int)(idx) <= ESM::BodyPart::MP_Tail) + return meshPartLabels[(int)(idx)]; + else + return "Invalid"; +} + +std::string meshTypeLabel(char idx) +{ + const char *meshTypeLabels[] = { + "Skin", + "Clothing", + "Armor" + }; + + if ((int)(idx) >= 0 && (int)(idx) <= ESM::BodyPart::MT_Armor) + return meshTypeLabels[(int)(idx)]; + else + return "Invalid"; +} + +std::string clothingTypeLabel(int idx) +{ + const char *clothingTypeLabels[] = { + "Pants", + "Shoes", + "Shirt", + "Belt", + "Robe", + "Right Glove", + "Left Glove", + "Skirt", + "Ring", + "Amulet" + }; + + if (idx >= 0 && idx <= 9) + return clothingTypeLabels[idx]; + else + return "Invalid"; +} + +std::string armorTypeLabel(int idx) +{ + const char *armorTypeLabels[] = { + "Helmet", + "Cuirass", + "Left Pauldron", + "Right Pauldron", + "Greaves", + "Boots", + "Left Gauntlet", + "Right Gauntlet", + "Shield", + "Left Bracer", + "Right Bracer" + }; + + if (idx >= 0 && idx <= 10) + return armorTypeLabels[idx]; + else + return "Invalid"; +} + +std::string dialogTypeLabel(int idx) +{ + const char *dialogTypeLabels[] = { + "Topic", + "Voice", + "Greeting", + "Persuasion", + "Journal" + }; + + if (idx >= 0 && idx <= 4) + return dialogTypeLabels[idx]; + else if (idx == -1) + return "Deleted"; + else + return "Invalid"; +} + +std::string questStatusLabel(int idx) +{ + const char *questStatusLabels[] = { + "None", + "Name", + "Finished", + "Restart", + "Deleted" + }; + + if (idx >= 0 && idx <= 4) + return questStatusLabels[idx]; + else + return "Invalid"; +} + +std::string creatureTypeLabel(int idx) +{ + const char *creatureTypeLabels[] = { + "Creature", + "Daedra", + "Undead", + "Humanoid", + }; + + if (idx >= 0 && idx <= 3) + return creatureTypeLabels[idx]; + else + return "Invalid"; +} + +std::string soundTypeLabel(int idx) +{ + const char *soundTypeLabels[] = { + "Left Foot", + "Right Foot", + "Swim Left", + "Swim Right", + "Moan", + "Roar", + "Scream", + "Land" + }; + + if (idx >= 0 && idx <= 7) + return soundTypeLabels[idx]; + else + return "Invalid"; +} + +std::string weaponTypeLabel(int idx) +{ + const char *weaponTypeLabels[] = { + "Short Blade One Hand", + "Long Blade One Hand", + "Long Blade Two Hand", + "Blunt One Hand", + "Blunt Two Close", + "Blunt Two Wide", + "Spear Two Wide", + "Axe One Hand", + "Axe Two Hand", + "Marksman Bow", + "Marksman Crossbow", + "Marksman Thrown", + "Arrow", + "Bolt" + }; + + if (idx >= 0 && idx <= 13) + return weaponTypeLabels[idx]; + else + return "Invalid"; +} + +std::string aiTypeLabel(int type) +{ + if (type == ESM::AI_Wander) return "Wander"; + else if (type == ESM::AI_Travel) return "Travel"; + else if (type == ESM::AI_Follow) return "Follow"; + else if (type == ESM::AI_Escort) return "Escort"; + else if (type == ESM::AI_Activate) return "Activate"; + else return "Invalid"; +} + +std::string magicEffectLabel(int idx) +{ + const char* magicEffectLabels [] = { + "Water Breathing", + "Swift Swim", + "Water Walking", + "Shield", + "Fire Shield", + "Lightning Shield", + "Frost Shield", + "Burden", + "Feather", + "Jump", + "Levitate", + "SlowFall", + "Lock", + "Open", + "Fire Damage", + "Shock Damage", + "Frost Damage", + "Drain Attribute", + "Drain Health", + "Drain Magicka", + "Drain Fatigue", + "Drain Skill", + "Damage Attribute", + "Damage Health", + "Damage Magicka", + "Damage Fatigue", + "Damage Skill", + "Poison", + "Weakness to Fire", + "Weakness to Frost", + "Weakness to Shock", + "Weakness to Magicka", + "Weakness to Common Disease", + "Weakness to Blight Disease", + "Weakness to Corprus Disease", + "Weakness to Poison", + "Weakness to Normal Weapons", + "Disintegrate Weapon", + "Disintegrate Armor", + "Invisibility", + "Chameleon", + "Light", + "Sanctuary", + "Night Eye", + "Charm", + "Paralyze", + "Silence", + "Blind", + "Sound", + "Calm Humanoid", + "Calm Creature", + "Frenzy Humanoid", + "Frenzy Creature", + "Demoralize Humanoid", + "Demoralize Creature", + "Rally Humanoid", + "Rally Creature", + "Dispel", + "Soultrap", + "Telekinesis", + "Mark", + "Recall", + "Divine Intervention", + "Almsivi Intervention", + "Detect Animal", + "Detect Enchantment", + "Detect Key", + "Spell Absorption", + "Reflect", + "Cure Common Disease", + "Cure Blight Disease", + "Cure Corprus Disease", + "Cure Poison", + "Cure Paralyzation", + "Restore Attribute", + "Restore Health", + "Restore Magicka", + "Restore Fatigue", + "Restore Skill", + "Fortify Attribute", + "Fortify Health", + "Fortify Magicka", + "Fortify Fatigue", + "Fortify Skill", + "Fortify Maximum Magicka", + "Absorb Attribute", + "Absorb Health", + "Absorb Magicka", + "Absorb Fatigue", + "Absorb Skill", + "Resist Fire", + "Resist Frost", + "Resist Shock", + "Resist Magicka", + "Resist Common Disease", + "Resist Blight Disease", + "Resist Corprus Disease", + "Resist Poison", + "Resist Normal Weapons", + "Resist Paralysis", + "Remove Curse", + "Turn Undead", + "Summon Scamp", + "Summon Clannfear", + "Summon Daedroth", + "Summon Dremora", + "Summon Ancestral Ghost", + "Summon Skeletal Minion", + "Summon Bonewalker", + "Summon Greater Bonewalker", + "Summon Bonelord", + "Summon Winged Twilight", + "Summon Hunger", + "Summon Golden Saint", + "Summon Flame Atronach", + "Summon Frost Atronach", + "Summon Storm Atronach", + "Fortify Attack", + "Command Creature", + "Command Humanoid", + "Bound Dagger", + "Bound Longsword", + "Bound Mace", + "Bound Battle Axe", + "Bound Spear", + "Bound Longbow", + "EXTRA SPELL", + "Bound Cuirass", + "Bound Helm", + "Bound Boots", + "Bound Shield", + "Bound Gloves", + "Corprus", + "Vampirism", + "Summon Centurion Sphere", + "Sun Damage", + "Stunted Magicka", + "Summon Fabricant", + "sEffectSummonCreature01", + "sEffectSummonCreature02", + "sEffectSummonCreature03", + "sEffectSummonCreature04", + "sEffectSummonCreature05" + }; + if (idx >= 0 && idx <= 143) + return magicEffectLabels[idx]; + else + return "Invalid"; +} + +std::string attributeLabel(int idx) +{ + const char* attributeLabels [] = { + "Strength", + "Intelligence", + "Willpower", + "Agility", + "Speed", + "Endurance", + "Personality", + "Luck" + }; + if (idx >= 0 && idx <= 7) + return attributeLabels[idx]; + else + return "Invalid"; +} + +std::string spellTypeLabel(int idx) +{ + const char* spellTypeLabels [] = { + "Spells", + "Abilities", + "Blight Disease", + "Disease", + "Curse", + "Powers" + }; + if (idx >= 0 && idx <= 5) + return spellTypeLabels[idx]; + else + return "Invalid"; +} + +std::string specializationLabel(int idx) +{ + const char* specializationLabels [] = { + "Combat", + "Magic", + "Stealth" + }; + if (idx >= 0 && idx <= 2) + return specializationLabels[idx]; + else + return "Invalid"; +} + +std::string skillLabel(int idx) +{ + const char* skillLabels [] = { + "Block", + "Armorer", + "Medium Armor", + "Heavy Armor", + "Blunt Weapon", + "Long Blade", + "Axe", + "Spear", + "Athletics", + "Enchant", + "Destruction", + "Alteration", + "Illusion", + "Conjuration", + "Mysticism", + "Restoration", + "Alchemy", + "Unarmored", + "Security", + "Sneak", + "Acrobatics", + "Light Armor", + "Short Blade", + "Marksman", + "Mercantile", + "Speechcraft", + "Hand-to-hand" + }; + if (idx >= 0 && idx <= 27) + return skillLabels[idx]; + else + return "Invalid"; +} + +std::string apparatusTypeLabel(int idx) +{ + const char* apparatusTypeLabels [] = { + "Mortar", + "Alembic", + "Calcinator", + "Retort", + }; + if (idx >= 0 && idx <= 3) + return apparatusTypeLabels[idx]; + else + return "Invalid"; +} + +std::string rangeTypeLabel(int idx) +{ + const char* rangeTypeLabels [] = { + "Self", + "Touch", + "Target" + }; + if (idx >= 0 && idx <= 3) + return rangeTypeLabels[idx]; + else + return "Invalid"; +} + +std::string schoolLabel(int idx) +{ + const char* schoolLabels [] = { + "Alteration", + "Conjuration", + "Destruction", + "Illusion", + "Mysticism", + "Restoration" + }; + if (idx >= 0 && idx <= 5) + return schoolLabels[idx]; + else + return "Invalid"; +} + +std::string enchantTypeLabel(int idx) +{ + const char* enchantTypeLabels [] = { + "Cast Once", + "Cast When Strikes", + "Cast When Used", + "Constant Effect" + }; + if (idx >= 0 && idx <= 3) + return enchantTypeLabels[idx]; + else + return "Invalid"; +} + +std::string ruleFunction(int idx) +{ + std::string ruleFunctions[] = { + "Reaction Low", + "Reaction High", + "Rank Requirement", + "NPC? Reputation", + "Health Percent", + "Player Reputation", + "NPC Level", + "Player Health Percent", + "Player Magicka", + "Player Fatigue", + "Player Attribute Strength", + "Player Skill Block", + "Player Skill Armorer", + "Player Skill Medium Armor", + "Player Skill Heavy Armor", + "Player Skill Blunt Weapon", + "Player Skill Long Blade", + "Player Skill Axe", + "Player Skill Spear", + "Player Skill Athletics", + "Player Skill Enchant", + "Player Skill Destruction", + "Player Skill Alteration", + "Player Skill Illusion", + "Player Skill Conjuration", + "Player Skill Mysticism", + "Player SKill Restoration", + "Player Skill Alchemy", + "Player Skill Unarmored", + "Player Skill Security", + "Player Skill Sneak", + "Player Skill Acrobatics", + "Player Skill Light Armor", + "Player Skill Short Blade", + "Player Skill Marksman", + "Player Skill Mercantile", + "Player Skill Speechcraft", + "Player Skill Hand to Hand", + "Player Gender", + "Player Expelled from Faction", + "Player Diseased (Common)", + "Player Diseased (Blight)", + "Player Clothing Modifier", + "Player Crime Level", + "Player Same Sex", + "Player Same Race", + "Player Same Faction", + "Faction Rank Difference", + "Player Detected", + "Alarmed", + "Choice Selected", + "Player Attribute Intelligence", + "Player Attribute Willpower", + "Player Attribute Agility", + "Player Attribute Speed", + "Player Attribute Endurance", + "Player Attribute Personality", + "Player Attribute Luck", + "Player Diseased (Corprus)", + "Weather", + "Player is a Vampire", + "Player Level", + "Attacked", + "NPC Talked to Player", + "Player Health", + "Creature Target", + "Friend Hit", + "Fight", + "Hello", + "Alarm", + "Flee", + "Should Attack", + //Unkown but causes NPCs to growl and roar. + "UNKNOWN 72" + }; + if (idx >= 0 && idx <= 72) + return ruleFunctions[idx]; + else + return "Invalid"; +} + +// The "unused flag bits" should probably be defined alongside the +// defined bits in the ESM component. The names of the flag bits are +// very inconsistent. + +std::string bodyPartFlags(int flags) +{ + std::string properties = ""; + if (flags == 0) properties += "[None] "; + if (flags & ESM::BodyPart::BPF_Female) properties += "Female "; + if (flags & ESM::BodyPart::BPF_Playable) properties += "Playable "; + int unused = (0xFFFFFFFF ^ + (ESM::BodyPart::BPF_Female| + ESM::BodyPart::BPF_Playable)); + if (flags & unused) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} + +std::string cellFlags(int flags) +{ + std::string properties = ""; + if (flags == 0) properties += "[None] "; + if (flags & ESM::Cell::HasWater) properties += "HasWater "; + if (flags & ESM::Cell::Interior) properties += "Interior "; + if (flags & ESM::Cell::NoSleep) properties += "NoSleep "; + if (flags & ESM::Cell::QuasiEx) properties += "QuasiEx "; + // This used value is not in the ESM component. + if (flags & 0x00000040) properties += "Unknown "; + int unused = (0xFFFFFFFF ^ + (ESM::Cell::HasWater| + ESM::Cell::Interior| + ESM::Cell::NoSleep| + ESM::Cell::QuasiEx| + 0x00000040)); + if (flags & unused) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} + +std::string containerFlags(int flags) +{ + std::string properties = ""; + if (flags == 0) properties += "[None] "; + if (flags & ESM::Container::Unknown) properties += "Unknown "; + if (flags & ESM::Container::Organic) properties += "Organic "; + if (flags & ESM::Container::Respawn) properties += "Respawn "; + int unused = (0xFFFFFFFF ^ + (ESM::Container::Unknown| + ESM::Container::Organic| + ESM::Container::Respawn)); + if (flags & unused) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} + +std::string creatureFlags(int flags) +{ + std::string properties = ""; + if (flags == 0) properties += "[None] "; + if (flags & ESM::Creature::None) properties += "All "; + if (flags & ESM::Creature::Walks) properties += "Walks "; + if (flags & ESM::Creature::Swims) properties += "Swims "; + if (flags & ESM::Creature::Flies) properties += "Flies "; + if (flags & ESM::Creature::Biped) properties += "Biped "; + if (flags & ESM::Creature::Respawn) properties += "Respawn "; + if (flags & ESM::Creature::Weapon) properties += "Weapon "; + if (flags & ESM::Creature::Skeleton) properties += "Skeleton "; + if (flags & ESM::Creature::Metal) properties += "Metal "; + if (flags & ESM::Creature::Essential) properties += "Essential "; + int unused = (0xFFFFFFFF ^ + (ESM::Creature::None| + ESM::Creature::Walks| + ESM::Creature::Swims| + ESM::Creature::Flies| + ESM::Creature::Biped| + ESM::Creature::Respawn| + ESM::Creature::Weapon| + ESM::Creature::Skeleton| + ESM::Creature::Metal| + ESM::Creature::Essential)); + if (flags & unused) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} + +std::string landFlags(int flags) +{ + std::string properties = ""; + // The ESM component says that this first four bits are used, but + // only the first three bits are used as far as I can tell. + // There's also no enumeration of the bit in the ESM component. + if (flags == 0) properties += "[None] "; + if (flags & 0x00000001) properties += "Unknown1 "; + if (flags & 0x00000004) properties += "Unknown3 "; + if (flags & 0x00000002) properties += "Unknown2 "; + if (flags & 0xFFFFFFF8) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} + +std::string leveledListFlags(int flags) +{ + std::string properties = ""; + if (flags == 0) properties += "[None] "; + if (flags & ESM::LeveledListBase::AllLevels) properties += "AllLevels "; + // This flag apparently not present on creature lists... + if (flags & ESM::LeveledListBase::Each) properties += "Each "; + int unused = (0xFFFFFFFF ^ + (ESM::LeveledListBase::AllLevels| + ESM::LeveledListBase::Each)); + if (flags & unused) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} + +std::string lightFlags(int flags) +{ + std::string properties = ""; + if (flags == 0) properties += "[None] "; + if (flags & ESM::Light::Dynamic) properties += "Dynamic "; + if (flags & ESM::Light::Fire) properties += "Fire "; + if (flags & ESM::Light::Carry) properties += "Carry "; + if (flags & ESM::Light::Flicker) properties += "Flicker "; + if (flags & ESM::Light::FlickerSlow) properties += "FlickerSlow "; + if (flags & ESM::Light::Pulse) properties += "Pulse "; + if (flags & ESM::Light::PulseSlow) properties += "PulseSlow "; + if (flags & ESM::Light::Negative) properties += "Negative "; + if (flags & ESM::Light::OffDefault) properties += "OffDefault "; + int unused = (0xFFFFFFFF ^ + (ESM::Light::Dynamic| + ESM::Light::Fire| + ESM::Light::Carry| + ESM::Light::Flicker| + ESM::Light::FlickerSlow| + ESM::Light::Pulse| + ESM::Light::PulseSlow| + ESM::Light::Negative| + ESM::Light::OffDefault)); + if (flags & unused) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} + +std::string magicEffectFlags(int flags) +{ + std::string properties = ""; + if (flags == 0) properties += "[None] "; + // Enchanting & SpellMaking occur on the same list of effects. + // "EXTRA SPELL" appears in the construction set under both the + // spell making and enchanting tabs as an allowed effect. Since + // most of the effects without this flags are defective in various + // ways, it's still very unclear what these flag bits are. + if (flags & ESM::MagicEffect::SpellMaking) properties += "SpellMaking "; + if (flags & ESM::MagicEffect::Enchanting) properties += "Enchanting "; + if (flags & 0x00000040) properties += "RangeNoSelf "; + if (flags & 0x00000080) properties += "RangeTouch "; + if (flags & 0x00000100) properties += "RangeTarget "; + if (flags & 0x00001000) properties += "Unknown2 "; + if (flags & 0x00000001) properties += "AffectSkill "; + if (flags & 0x00000002) properties += "AffectAttribute "; + if (flags & ESM::MagicEffect::NoDuration) properties += "NoDuration "; + if (flags & 0x00000008) properties += "NoMagnitude "; + if (flags & 0x00000010) properties += "Negative "; + if (flags & 0x00000020) properties += "Unknown1 "; + // ESM componet says 0x800 is negative, but none of the magic + // effects have this flags set. + if (flags & ESM::MagicEffect::Negative) properties += "Unused "; + // Since only Chameleon has this flag it could be anything + // that uniquely distinguishes Chameleon. + if (flags & 0x00002000) properties += "Chameleon "; + if (flags & 0x00004000) properties += "Bound "; + if (flags & 0x00008000) properties += "Summon "; + // Calm, Demoralize, Frenzy, Lock, Open, Rally, Soultrap, Turn Unded + if (flags & 0x00010000) properties += "Unknown3 "; + if (flags & 0x00020000) properties += "Absorb "; + if (flags & 0xFFFC0000) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} + +std::string npcFlags(int flags) +{ + std::string properties = ""; + if (flags == 0) properties += "[None] "; + // Mythicmods and the ESM component differ. Mythicmods says + // 0x8=None and 0x10=AutoCalc, while our code defines 0x8 as + // AutoCalc. The former seems to be correct. All Bethesda + // records have bit 0x8 set. A suspiciously large portion of + // females have autocalc turned off. + if (flags & ESM::NPC::Autocalc) properties += "Unknown "; + if (flags & 0x00000010) properties += "Autocalc "; + if (flags & ESM::NPC::Female) properties += "Female "; + if (flags & ESM::NPC::Respawn) properties += "Respawn "; + if (flags & ESM::NPC::Essential) properties += "Essential "; + // These two flags do not appear on any NPCs and may have been + // confused with the flags for creatures. + if (flags & ESM::NPC::Skeleton) properties += "Skeleton "; + if (flags & ESM::NPC::Metal) properties += "Metal "; + // Whether corpses persist is a bit that is unaccounted for, + // however the only unknown bit occurs on ALL records, and + // relatively few NPCs have this bit set. + int unused = (0xFFFFFFFF ^ + (ESM::NPC::Autocalc| + 0x00000010| + ESM::NPC::Female| + ESM::NPC::Respawn| + ESM::NPC::Essential| + ESM::NPC::Skeleton| + ESM::NPC::Metal)); + if (flags & unused) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} + +std::string raceFlags(int flags) +{ + std::string properties = ""; + if (flags == 0) properties += "[None] "; + // All races have the playable flag set in Bethesda files. + if (flags & ESM::Race::Playable) properties += "Playable "; + if (flags & ESM::Race::Beast) properties += "Beast "; + int unused = (0xFFFFFFFF ^ + (ESM::Race::Playable| + ESM::Race::Beast)); + if (flags & unused) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} + +std::string spellFlags(int flags) +{ + std::string properties = ""; + if (flags == 0) properties += "[None] "; + if (flags & ESM::Spell::F_Autocalc) properties += "Autocalc "; + if (flags & ESM::Spell::F_PCStart) properties += "PCStart "; + if (flags & ESM::Spell::F_Always) properties += "Always "; + int unused = (0xFFFFFFFF ^ + (ESM::Spell::F_Autocalc| + ESM::Spell::F_PCStart| + ESM::Spell::F_Always)); + if (flags & unused) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} + +std::string weaponFlags(int flags) +{ + std::string properties = ""; + if (flags == 0) properties += "[None] "; + // The interpretation of the flags are still unclear to me. + // Apparently you can't be Silver without being Magical? Many of + // the "Magical" weapons don't have enchantments of any sort. + if (flags & ESM::Weapon::Magical) properties += "Magical "; + if (flags & ESM::Weapon::Silver) properties += "Silver "; + int unused = (0xFFFFFFFF ^ + (ESM::Weapon::Magical| + ESM::Weapon::Silver)); + if (flags & unused) properties += "Invalid "; + properties += str(boost::format("(0x%08X)") % flags); + return properties; +} diff --git a/apps/esmtool/labels.hpp b/apps/esmtool/labels.hpp new file mode 100644 index 000000000..7f1ff7986 --- /dev/null +++ b/apps/esmtool/labels.hpp @@ -0,0 +1,64 @@ +#ifndef OPENMW_ESMTOOL_LABELS_H +#define OPENMW_ESMTOOL_LABELS_H + +#include + +std::string bodyPartLabel(char idx); +std::string meshPartLabel(char idx); +std::string meshTypeLabel(char idx); +std::string clothingTypeLabel(int idx); +std::string armorTypeLabel(int idx); +std::string dialogTypeLabel(int idx); +std::string questStatusLabel(int idx); +std::string creatureTypeLabel(int idx); +std::string soundTypeLabel(int idx); +std::string weaponTypeLabel(int idx); + +// This function's a bit different because the types are record types, +// not consecutive values. +std::string aiTypeLabel(int type); + +// This one's also a bit different, because it enumerates dialog +// select rule functions, not types. Structurally, it still converts +// indexes to strings for display. +std::string ruleFunction(int idx); + +// The labels below here can all be loaded from GMSTs, but are not +// currently because among other things, that requires loading the +// GMSTs before dumping any of the records. + +// If the data format supported ordered lists of GMSTs (post 1.0), the +// lists could define the valid values, their localization strings, +// and the indexes for referencing the types in other records in the +// database. Then a single label function could work for all types. + +std::string magicEffectLabel(int idx); +std::string attributeLabel(int idx); +std::string spellTypeLabel(int idx); +std::string specializationLabel(int idx); +std::string skillLabel(int idx); +std::string apparatusTypeLabel(int idx); +std::string rangeTypeLabel(int idx); +std::string schoolLabel(int idx); +std::string enchantTypeLabel(int idx); + +// The are the flag functions that convert a bitmask into a list of +// human readble strings representing the set bits. + +std::string bodyPartFlags(int flags); +std::string cellFlags(int flags); +std::string containerFlags(int flags); +std::string creatureFlags(int flags); +std::string landFlags(int flags); +std::string leveledListFlags(int flags); +std::string lightFlags(int flags); +std::string magicEffectFlags(int flags); +std::string npcFlags(int flags); +std::string raceFlags(int flags); +std::string spellFlags(int flags); +std::string weaponFlags(int flags); + +// Missing flags functions: +// aiServicesFlags, possibly more + +#endif diff --git a/apps/esmtool/record.cpp b/apps/esmtool/record.cpp index 9609e5242..b5f97e979 100644 --- a/apps/esmtool/record.cpp +++ b/apps/esmtool/record.cpp @@ -1,15 +1,161 @@ #include "record.hpp" +#include "labels.hpp" #include +#include + +void printAIPackage(ESM::AIPackage p) +{ + std::cout << " AI Type: " << aiTypeLabel(p.mType) + << " (" << boost::format("0x%08X") % p.mType << ")" << std::endl; + if (p.mType == ESM::AI_Wander) + { + std::cout << " Distance: " << p.mWander.mDistance << std::endl; + std::cout << " Duration: " << p.mWander.mDuration << std::endl; + std::cout << " Time of Day: " << (int)p.mWander.mTimeOfDay << std::endl; + if (p.mWander.mUnk != 1) + std::cout << " Unknown: " << (int)p.mWander.mUnk << std::endl; + + std::cout << " Idle: "; + for (int i = 0; i != 8; i++) + std::cout << (int)p.mWander.mIdle[i] << " "; + std::cout << std::endl; + } + else if (p.mType == ESM::AI_Travel) + { + std::cout << " Travel Coordinates: (" << p.mTravel.mX << "," + << p.mTravel.mY << "," << p.mTravel.mZ << ")" << std::endl; + std::cout << " Travel Unknown: " << (int)p.mTravel.mUnk << std::endl; + } + else if (p.mType == ESM::AI_Follow || p.mType == ESM::AI_Escort) + { + std::cout << " Follow Coordinates: (" << p.mTarget.mX << "," + << p.mTarget.mY << "," << p.mTarget.mZ << ")" << std::endl; + std::cout << " Duration: " << p.mTarget.mDuration << std::endl; + std::cout << " Target ID: " << p.mTarget.mId.toString() << std::endl; + std::cout << " Unknown: " << (int)p.mTarget.mUnk << std::endl; + } + else if (p.mType == ESM::AI_Activate) + { + std::cout << " Name: " << p.mActivate.mName.toString() << std::endl; + std::cout << " Activate Unknown: " << (int)p.mActivate.mUnk << std::endl; + } + else { + std::cout << " BadPackage: " << boost::format("0x%08x") % p.mType << std::endl; + } + + if (p.mCellName != "") + std::cout << " Cell Name: " << p.mCellName << std::endl; +} + +std::string ruleString(ESM::DialInfo::SelectStruct ss) +{ + std::string rule = ss.mSelectRule; + + if (rule.length() < 5) + return "INVALID"; + + char type = rule[1]; + char indicator = rule[2]; + + std::string type_str = "INVALID"; + std::string func_str = str(boost::format("INVALID=%s") % rule.substr(1,3)); + int func; + std::istringstream iss(rule.substr(2,2)); + iss >> func; + + switch(type) + { + case '1': + type_str = "Function"; + func_str = ruleFunction(func); + break; + case '2': + if (indicator == 's') type_str = "Global short"; + else if (indicator == 'l') type_str = "Global long"; + else if (indicator == 'f') type_str = "Global float"; + break; + case '3': + if (indicator == 's') type_str = "Local short"; + else if (indicator == 'l') type_str = "Local long"; + else if (indicator == 'f') type_str = "Local float"; + break; + case '4': if (indicator == 'J') type_str = "Journal"; break; + case '5': if (indicator == 'I') type_str = "Item type"; break; + case '6': if (indicator == 'D') type_str = "NPC Dead"; break; + case '7': if (indicator == 'X') type_str = "Not ID"; break; + case '8': if (indicator == 'F') type_str = "Not Faction"; break; + case '9': if (indicator == 'C') type_str = "Not Class"; break; + case 'A': if (indicator == 'R') type_str = "Not Race"; break; + case 'B': if (indicator == 'L') type_str = "Not Cell"; break; + case 'C': if (indicator == 's') type_str = "Not Local"; break; + } + + // Append the variable name to the function string if any. + if (type != '1') func_str = rule.substr(5); + + // In the previous switch, we assumed that the second char was X + // for all types not qual to one. If this wasn't true, go back to + // the error message. + if (type != '1' && rule[3] != 'X') + func_str = str(boost::format("INVALID=%s") % rule.substr(1,3)); + + char oper = rule[4]; + std::string oper_str = "??"; + switch (oper) + { + case '0': oper_str = "=="; break; + case '1': oper_str = "!="; break; + case '2': oper_str = "< "; break; + case '3': oper_str = "<="; break; + case '4': oper_str = "> "; break; + case '5': oper_str = ">="; break; + } + + std::string value_str = "??"; + if (ss.mType == ESM::VT_Int) + value_str = str(boost::format("%d") % ss.mI); + else if (ss.mType == ESM::VT_Float) + value_str = str(boost::format("%f") % ss.mF); + + std::string result = str(boost::format("%-12s %-32s %2s %s") + % type_str % func_str % oper_str % value_str); + return result; +} + +void printEffectList(ESM::EffectList effects) +{ + int i = 0; + std::vector::iterator eit; + for (eit = effects.mList.begin(); eit != effects.mList.end(); eit++) + { + std::cout << " Effect[" << i << "]: " << magicEffectLabel(eit->mEffectID) + << " (" << eit->mEffectID << ")" << std::endl; + if (eit->mSkill != -1) + std::cout << " Skill: " << skillLabel(eit->mSkill) + << " (" << (int)eit->mSkill << ")" << std::endl; + if (eit->mAttribute != -1) + std::cout << " Attribute: " << attributeLabel(eit->mAttribute) + << " (" << (int)eit->mAttribute << ")" << std::endl; + std::cout << " Range: " << rangeTypeLabel(eit->mRange) + << " (" << eit->mRange << ")" << std::endl; + // Area is always zero if range type is "Self" + if (eit->mRange != ESM::RT_Self) + std::cout << " Area: " << eit->mArea << std::endl; + std::cout << " Duration: " << eit->mDuration << std::endl; + std::cout << " Magnitude: " << eit->mMagnMin << "-" << eit->mMagnMax << std::endl; + i++; + } +} namespace EsmTool { RecordBase * -RecordBase::create(int type) +RecordBase::create(ESM::NAME type) { RecordBase *record = 0; - switch (type) { + switch (type.val) { case ESM::REC_ACTI: { record = new EsmTool::Record; @@ -233,7 +379,7 @@ template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; - std::cout << " Mesh: " << mData.mModel << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Script: " << mData.mScript << std::endl; } @@ -241,38 +387,92 @@ template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + std::cout << " Icon: " << mData.mIcon << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + std::cout << " Weight: " << mData.mData.mWeight << std::endl; + std::cout << " Value: " << mData.mData.mValue << std::endl; + std::cout << " AutoCalc: " << mData.mData.mAutoCalc << std::endl; + printEffectList(mData.mEffects); } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; - std::cout << " Mesh: " << mData.mModel << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; - std::cout << " Script: " << mData.mScript << std::endl; - std::cout << " Enchantment: " << mData.mEnchant << std::endl; - std::cout << " Type: " << mData.mData.mType << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + if (mData.mEnchant != "") + std::cout << " Enchantment: " << mData.mEnchant << std::endl; + std::cout << " Type: " << armorTypeLabel(mData.mData.mType) + << " (" << mData.mData.mType << ")" << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; + std::cout << " Value: " << mData.mData.mValue << std::endl; + std::cout << " Health: " << mData.mData.mHealth << std::endl; + std::cout << " Armor: " << mData.mData.mArmor << std::endl; + std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl; + std::vector::iterator pit; + for (pit = mData.mParts.mParts.begin(); pit != mData.mParts.mParts.end(); pit++) + { + std::cout << " Body Part: " << bodyPartLabel(pit->mPart) + << " (" << (int)(pit->mPart) << ")" << std::endl; + std::cout << " Male Name: " << pit->mMale << std::endl; + if (pit->mFemale != "") + std::cout << " Female Name: " << pit->mFemale << std::endl; + } } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + std::cout << " Icon: " << mData.mIcon << std::endl; + std::cout << " Script: " << mData.mScript << std::endl; + std::cout << " Type: " << apparatusTypeLabel(mData.mData.mType) + << " (" << (int)mData.mData.mType << ")" << std::endl; + std::cout << " Weight: " << mData.mData.mWeight << std::endl; + std::cout << " Value: " << mData.mData.mValue << std::endl; + std::cout << " Quality: " << mData.mData.mQuality << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; - std::cout << " Mesh: " << mData.mModel << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + std::cout << " Type: " << meshTypeLabel(mData.mData.mType) + << " (" << (int)mData.mData.mType << ")" << std::endl; + std::cout << " Flags: " << bodyPartFlags(mData.mData.mFlags) << std::endl; + std::cout << " Part: " << meshPartLabel(mData.mData.mPart) + << " (" << (int)mData.mData.mPart << ")" << std::endl; + std::cout << " Vampire: " << (int)mData.mData.mVampire << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; - std::cout << " Mesh: " << mData.mModel << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + std::cout << " Icon: " << mData.mIcon << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + if (mData.mEnchant != "") + std::cout << " Enchantment: " << mData.mEnchant << std::endl; + std::cout << " Weight: " << mData.mData.mWeight << std::endl; + std::cout << " Value: " << mData.mData.mValue << std::endl; + std::cout << " IsScroll: " << mData.mData.mIsScroll << std::endl; + std::cout << " SkillID: " << mData.mData.mSkillID << std::endl; + std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl; + std::cout << " Text: [skipped]" << std::endl; + // Skip until multi-line fields is controllable by a command line option. + // Mildly problematic because there are no parameter to print() currently. + // std::cout << "-------------------------------------------" << std::endl; + // std::cout << mData.mText << std::endl; + // std::cout << "-------------------------------------------" << std::endl; } template<> @@ -281,13 +481,38 @@ void Record::print() std::cout << " Name: " << mData.mName << std::endl; std::cout << " Texture: " << mData.mTexture << std::endl; std::cout << " Description: " << mData.mDescription << std::endl; + std::vector::iterator pit; + for (pit = mData.mPowers.mList.begin(); pit != mData.mPowers.mList.end(); pit++) + std::cout << " Power: " << *pit << std::endl; } template<> void Record::print() { - std::cout << " Name: " << mData.mName << std::endl; - std::cout << " Region: " << mData.mRegion << std::endl; + // None of the cells have names... + if (mData.mName != "") + std::cout << " Name: " << mData.mName << std::endl; + if (mData.mRegion != "") + std::cout << " Region: " << mData.mRegion << std::endl; + std::cout << " Flags: " << cellFlags(mData.mData.mFlags) << std::endl; + + std::cout << " Coordinates: " << " (" << mData.getGridX() << "," + << mData.getGridY() << ")" << std::endl; + + if (mData.mData.mFlags & ESM::Cell::Interior && + !(mData.mData.mFlags & ESM::Cell::QuasiEx)) + { + std::cout << " Ambient Light Color: " << mData.mAmbi.mAmbient << std::endl; + std::cout << " Sunlight Color: " << mData.mAmbi.mSunlight << std::endl; + std::cout << " Fog Color: " << mData.mAmbi.mFog << std::endl; + std::cout << " Fog Density: " << mData.mAmbi.mFogDensity << std::endl; + std::cout << " Water Level: " << mData.mWater << std::endl; + } + else + std::cout << " Map Color: " << boost::format("0x%08X") % mData.mMapColor << std::endl; + std::cout << " Water Level Int: " << mData.mWaterInt << std::endl; + std::cout << " NAM0: " << mData.mNAM0 << std::endl; + } template<> @@ -295,37 +520,145 @@ void Record::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Description: " << mData.mDescription << std::endl; + std::cout << " Playable: " << mData.mData.mIsPlayable << std::endl; + std::cout << " AutoCalc: " << mData.mData.mCalc << std::endl; + std::cout << " Attribute1: " << attributeLabel(mData.mData.mAttribute[0]) + << " (" << mData.mData.mAttribute[0] << ")" << std::endl; + std::cout << " Attribute2: " << attributeLabel(mData.mData.mAttribute[1]) + << " (" << mData.mData.mAttribute[1] << ")" << std::endl; + std::cout << " Specialization: " << specializationLabel(mData.mData.mSpecialization) + << " (" << mData.mData.mSpecialization << ")" << std::endl; + for (int i = 0; i != 5; i++) + std::cout << " Major Skill: " << skillLabel(mData.mData.mSkills[i][0]) + << " (" << mData.mData.mSkills[i][0] << ")" << std::endl; + for (int i = 0; i != 5; i++) + std::cout << " Minor Skill: " << skillLabel(mData.mData.mSkills[i][1]) + << " (" << mData.mData.mSkills[i][1] << ")" << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + std::cout << " Icon: " << mData.mIcon << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + if (mData.mEnchant != "") + std::cout << " Enchantment: " << mData.mEnchant << std::endl; + std::cout << " Type: " << clothingTypeLabel(mData.mData.mType) + << " (" << mData.mData.mType << ")" << std::endl; + std::cout << " Weight: " << mData.mData.mWeight << std::endl; + std::cout << " Value: " << mData.mData.mValue << std::endl; + std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl; + std::vector::iterator pit; + for (pit = mData.mParts.mParts.begin(); pit != mData.mParts.mParts.end(); pit++) + { + std::cout << " Body Part: " << bodyPartLabel(pit->mPart) + << " (" << (int)(pit->mPart) << ")" << std::endl; + std::cout << " Male Name: " << pit->mMale << std::endl; + if (pit->mFemale != "") + std::cout << " Female Name: " << pit->mFemale << std::endl; + } } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + std::cout << " Flags: " << containerFlags(mData.mFlags) << std::endl; + std::cout << " Weight: " << mData.mWeight << std::endl; + std::vector::iterator cit; + for (cit = mData.mInventory.mList.begin(); cit != mData.mInventory.mList.end(); cit++) + std::cout << " Inventory: Count: " << boost::format("%4d") % cit->mCount + << " Item: " << cit->mItem.toString() << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + std::cout << " Script: " << mData.mScript << std::endl; + std::cout << " Flags: " << creatureFlags(mData.mFlags) << std::endl; + std::cout << " Original: " << mData.mOriginal << std::endl; + std::cout << " Scale: " << mData.mScale << std::endl; + + std::cout << " Type: " << creatureTypeLabel(mData.mData.mType) + << " (" << mData.mData.mType << ")" << std::endl; + std::cout << " Level: " << mData.mData.mLevel << std::endl; + + std::cout << " Attributes:" << std::endl; + std::cout << " Strength: " << mData.mData.mStrength << std::endl; + std::cout << " Intelligence: " << mData.mData.mIntelligence << std::endl; + std::cout << " Willpower: " << mData.mData.mWillpower << std::endl; + std::cout << " Agility: " << mData.mData.mAgility << std::endl; + std::cout << " Speed: " << mData.mData.mSpeed << std::endl; + std::cout << " Endurance: " << mData.mData.mEndurance << std::endl; + std::cout << " Personality: " << mData.mData.mPersonality << std::endl; + std::cout << " Luck: " << mData.mData.mLuck << std::endl; + + std::cout << " Health: " << mData.mData.mHealth << std::endl; + std::cout << " Magicka: " << mData.mData.mMana << std::endl; + std::cout << " Fatigue: " << mData.mData.mFatigue << std::endl; + std::cout << " Soul: " << mData.mData.mSoul << std::endl; + std::cout << " Combat: " << mData.mData.mCombat << std::endl; + std::cout << " Magic: " << mData.mData.mMagic << std::endl; + std::cout << " Stealth: " << mData.mData.mStealth << std::endl; + std::cout << " Attack1: " << mData.mData.mAttack[0] + << "-" << mData.mData.mAttack[1] << std::endl; + std::cout << " Attack2: " << mData.mData.mAttack[2] + << "-" << mData.mData.mAttack[3] << std::endl; + std::cout << " Attack3: " << mData.mData.mAttack[4] + << "-" << mData.mData.mAttack[5] << std::endl; + std::cout << " Gold: " << mData.mData.mGold << std::endl; + + std::vector::iterator cit; + for (cit = mData.mInventory.mList.begin(); cit != mData.mInventory.mList.end(); cit++) + std::cout << " Inventory: Count: " << boost::format("%4d") % cit->mCount + << " Item: " << cit->mItem.toString() << std::endl; + + std::vector::iterator sit; + for (sit = mData.mSpells.mList.begin(); sit != mData.mSpells.mList.end(); sit++) + std::cout << " Spell: " << *sit << std::endl; + + std::cout << " Artifical Intelligence: " << mData.mHasAI << std::endl; + std::cout << " AI Hello:" << (int)mData.mAiData.mHello << std::endl; + std::cout << " AI Fight:" << (int)mData.mAiData.mFight << std::endl; + std::cout << " AI Flee:" << (int)mData.mAiData.mFlee << std::endl; + std::cout << " AI Alarm:" << (int)mData.mAiData.mAlarm << std::endl; + std::cout << " AI U1:" << (int)mData.mAiData.mU1 << std::endl; + std::cout << " AI U2:" << (int)mData.mAiData.mU2 << std::endl; + std::cout << " AI U3:" << (int)mData.mAiData.mU3 << std::endl; + std::cout << " AI U4:" << (int)mData.mAiData.mU4 << std::endl; + std::cout << " AI Services:" << boost::format("0x%08X") % mData.mAiData.mServices << std::endl; + + std::vector::iterator pit; + for (pit = mData.mAiPackage.mList.begin(); pit != mData.mAiPackage.mList.end(); pit++) + printAIPackage(*pit); } template<> void Record::print() { - // nothing to print + std::cout << " Type: " << dialogTypeLabel(mData.mType) + << " (" << (int)mData.mType << ")" << std::endl; + // Sadly, there are no DialInfos, because the loader dumps as it + // loads, rather than loading and then dumping. :-( Anyone mind if + // I change this? + std::vector::iterator iit; + for (iit = mData.mInfo.begin(); iit != mData.mInfo.end(); iit++) + std::cout << "INFO!" << iit->mId << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; - std::cout << " Mesh: " << mData.mModel << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Script: " << mData.mScript << std::endl; std::cout << " OpenSound: " << mData.mOpenSound << std::endl; std::cout << " CloseSound: " << mData.mCloseSound << std::endl; @@ -334,22 +667,55 @@ void Record::print() template<> void Record::print() { - // nothing to print + std::cout << " Type: " << enchantTypeLabel(mData.mData.mType) + << " (" << mData.mData.mType << ")" << std::endl; + std::cout << " Cost: " << mData.mData.mCost << std::endl; + std::cout << " Charge: " << mData.mData.mCharge << std::endl; + std::cout << " AutoCalc: " << mData.mData.mAutocalc << std::endl; + printEffectList(mData.mEffects); } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; - std::cout << " Attr1: " << mData.mData.mAttribute1 << std::endl; - std::cout << " Attr2: " << mData.mData.mAttribute2 << std::endl; std::cout << " Hidden: " << mData.mData.mIsHidden << std::endl; + if (mData.mData.mUnknown != -1) + std::cout << " Unknown: " << mData.mData.mUnknown << std::endl; + std::cout << " Attribute1: " << attributeLabel(mData.mData.mAttribute1) + << " (" << mData.mData.mAttribute1 << ")" << std::endl; + std::cout << " Attribute2: " << attributeLabel(mData.mData.mAttribute2) + << " (" << mData.mData.mAttribute2 << ")" << std::endl; + for (int i = 0; i != 6; i++) + if (mData.mData.mSkillID[i] != -1) + std::cout << " Skill: " << skillLabel(mData.mData.mSkillID[i]) + << " (" << mData.mData.mSkillID[i] << ")" << std::endl; + for (int i = 0; i != 10; i++) + if (mData.mRanks[i] != "") + { + std::cout << " Rank: " << mData.mRanks[i] << std::endl; + std::cout << " Attribute1 Requirement: " + << mData.mData.mRankData[i].mAttribute1 << std::endl; + std::cout << " Attribute2 Requirement: " + << mData.mData.mRankData[i].mAttribute2 << std::endl; + std::cout << " One Skill at Level: " + << mData.mData.mRankData[i].mSkill1 << std::endl; + std::cout << " Two Skills at Level: " + << mData.mData.mRankData[i].mSkill2 << std::endl; + std::cout << " Faction Reaction: " + << mData.mData.mRankData[i].mFactReaction << std::endl; + } + std::vector::iterator rit; + for (rit = mData.mReactions.begin(); rit != mData.mReactions.end(); rit++) + std::cout << " Reaction: " << rit->mReaction << " = " << rit->mFaction << std::endl; } template<> void Record::print() { - // nothing to print + // nothing to print (well, nothing that's correct anyway) + std::cout << " Type: " << mData.mType << std::endl; + std::cout << " Value: " << mData.mValue << std::endl; } template<> @@ -379,139 +745,511 @@ template<> void Record::print() { std::cout << " Id: " << mData.mId << std::endl; + if (mData.mPrev != "") + std::cout << " Previous ID: " << mData.mPrev << std::endl; + if (mData.mNext != "") + std::cout << " Next ID: " << mData.mNext << std::endl; std::cout << " Text: " << mData.mResponse << std::endl; + if (mData.mActor != "") + std::cout << " Actor: " << mData.mActor << std::endl; + if (mData.mRace != "") + std::cout << " Race: " << mData.mRace << std::endl; + if (mData.mClass != "") + std::cout << " Class: " << mData.mClass << std::endl; + std::cout << " Factionless: " << mData.mFactionLess << std::endl; + if (mData.mNpcFaction != "") + std::cout << " NPC Faction: " << mData.mNpcFaction << std::endl; + if (mData.mData.mRank != -1) + std::cout << " NPC Rank: " << (int)mData.mData.mRank << std::endl; + if (mData.mPcFaction != "") + std::cout << " PC Faction: " << mData.mPcFaction << std::endl; + // CHANGE? non-standard capitalization mPCrank -> mPCRank (mPcRank?) + if (mData.mData.mPCrank != -1) + std::cout << " PC Rank: " << (int)mData.mData.mPCrank << std::endl; + if (mData.mCell != "") + std::cout << " Cell: " << mData.mCell << std::endl; + if (mData.mData.mDisposition > 0) + std::cout << " Disposition: " << mData.mData.mDisposition << std::endl; + if (mData.mData.mGender != ESM::DialInfo::NA) + std::cout << " Gender: " << mData.mData.mGender << std::endl; + if (mData.mSound != "") + std::cout << " Sound File: " << mData.mSound << std::endl; + + if (mData.mResultScript != "") + { + std::cout << " Result Script: [skipped]" << std::endl; + // Skip until multi-line fields is controllable by a command line option. + // Mildly problematic because there are no parameter to print() currently. + // std::cout << "-------------------------------------------" << std::endl; + // std::cout << mData.mResultScript << std::endl; + // std::cout << "-------------------------------------------" << std::endl; + } + + std::cout << " Quest Status: " << questStatusLabel(mData.mQuestStatus) + << " (" << mData.mQuestStatus << ")" << std::endl; + std::cout << " Unknown1: " << mData.mData.mUnknown1 << std::endl; + std::cout << " Unknown2: " << (int)mData.mData.mUnknown2 << std::endl; + + std::vector::iterator sit; + for (sit = mData.mSelects.begin(); sit != mData.mSelects.end(); sit++) + std::cout << " Select Rule: " << ruleString(*sit) << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + std::cout << " Icon: " << mData.mIcon << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; + for (int i = 0; i !=4; i++) + { + // A value of -1 means no effect + if (mData.mData.mEffectID[i] == -1) continue; + std::cout << " Effect: " << magicEffectLabel(mData.mData.mEffectID[i]) + << " (" << mData.mData.mEffectID[i] << ")" << std::endl; + std::cout << " Skill: " << skillLabel(mData.mData.mSkills[i]) + << " (" << mData.mData.mSkills[i] << ")" << std::endl; + std::cout << " Attribute: " << attributeLabel(mData.mData.mAttributes[i]) + << " (" << mData.mData.mAttributes[i] << ")" << std::endl; + } } template<> void Record::print() { - std::cout << " Coords: [" << mData.mX << "," << mData.mY << "]" << std::endl; + std::cout << " Coordinates: (" << mData.mX << "," << mData.mY << ")" << std::endl; + std::cout << " Flags: " << landFlags(mData.mFlags) << std::endl; + std::cout << " HasData: " << mData.mHasData << std::endl; + std::cout << " DataTypes: " << mData.mDataTypes << std::endl; + + // Seems like this should done with reference counting in the + // loader to me. But I'm not really knowledgable about this + // record type yet. --Cory + bool wasLoaded = mData.mDataLoaded; + if (mData.mDataTypes) mData.loadData(mData.mDataTypes); + if (mData.mDataLoaded) + { + std::cout << " Height Offset: " << mData.mLandData->mHeightOffset << std::endl; + // Lots of missing members. + std::cout << " Unknown1: " << mData.mLandData->mUnk1 << std::endl; + std::cout << " Unknown2: " << mData.mLandData->mUnk2 << std::endl; + } + if (!wasLoaded) mData.unloadData(); } template<> void Record::print() { + std::cout << " Chance for None: " << (int)mData.mChanceNone << std::endl; + std::cout << " Flags: " << leveledListFlags(mData.mFlags) << std::endl; std::cout << " Number of items: " << mData.mList.size() << std::endl; + std::vector::iterator iit; + for (iit = mData.mList.begin(); iit != mData.mList.end(); iit++) + std::cout << " Creature: Level: " << iit->mLevel + << " Creature: " << iit->mId << std::endl; } template<> void Record::print() { + std::cout << " Chance for None: " << (int)mData.mChanceNone << std::endl; + std::cout << " Flags: " << leveledListFlags(mData.mFlags) << std::endl; std::cout << " Number of items: " << mData.mList.size() << std::endl; + std::vector::iterator iit; + for (iit = mData.mList.begin(); iit != mData.mList.end(); iit++) + std::cout << " Inventory: Count: " << iit->mLevel + << " Item: " << iit->mId << std::endl; } template<> void Record::print() { - std::cout << " Name: " << mData.mName << std::endl; + if (mData.mName != "") + std::cout << " Name: " << mData.mName << std::endl; + if (mData.mModel != "") + std::cout << " Model: " << mData.mModel << std::endl; + if (mData.mIcon != "") + std::cout << " Icon: " << mData.mIcon << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + std::cout << " Flags: " << lightFlags(mData.mData.mFlags) << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; + std::cout << " Sound: " << mData.mSound << std::endl; + std::cout << " Duration: " << mData.mData.mTime << std::endl; + std::cout << " Radius: " << mData.mData.mRadius << std::endl; + std::cout << " Color: " << mData.mData.mColor << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + std::cout << " Icon: " << mData.mIcon << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + std::cout << " Type: " << mData.mType << std::endl; + std::cout << " Weight: " << mData.mData.mWeight << std::endl; + std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Quality: " << mData.mData.mQuality << std::endl; + std::cout << " Uses: " << mData.mData.mUses << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + std::cout << " Icon: " << mData.mIcon << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + // BUG? No Type Label? + std::cout << " Type: " << mData.mType << std::endl; + std::cout << " Weight: " << mData.mData.mWeight << std::endl; + std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Quality: " << mData.mData.mQuality << std::endl; + std::cout << " Uses: " << mData.mData.mUses << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + std::cout << " Icon: " << mData.mIcon << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + std::cout << " Type: " << mData.mType << std::endl; + std::cout << " Weight: " << mData.mData.mWeight << std::endl; + std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Quality: " << mData.mData.mQuality << std::endl; + std::cout << " Uses: " << mData.mData.mUses << std::endl; } template<> void Record::print() { std::cout << " Id: " << mData.mId << std::endl; + std::cout << " Index: " << mData.mIndex << std::endl; std::cout << " Texture: " << mData.mTexture << std::endl; } template<> void Record::print() { - std::cout << " Index: " << mData.mIndex << std::endl; - - const char *text = "Positive"; - if (mData.mData.mFlags & ESM::MagicEffect::Negative) { - text = "Negative"; - } - std::cout << " " << text << std::endl; + std::cout << " Index: " << magicEffectLabel(mData.mIndex) + << " (" << mData.mIndex << ")" << std::endl; + std::cout << " Description: " << mData.mDescription << std::endl; + std::cout << " Icon: " << mData.mIcon << std::endl; + std::cout << " Flags: " << magicEffectFlags(mData.mData.mFlags) << std::endl; + std::cout << " Particle Texture: " << mData.mParticle << std::endl; + if (mData.mCasting != "") + std::cout << " Casting Static: " << mData.mCasting << std::endl; + if (mData.mCastSound != "") + std::cout << " Casting Sound: " << mData.mCastSound << std::endl; + if (mData.mBolt != "") + std::cout << " Bolt Static: " << mData.mBolt << std::endl; + if (mData.mBoltSound != "") + std::cout << " Bolt Sound: " << mData.mBoltSound << std::endl; + if (mData.mHit != "") + std::cout << " Hit Static: " << mData.mHit << std::endl; + if (mData.mHitSound != "") + std::cout << " Hit Sound: " << mData.mHitSound << std::endl; + if (mData.mArea != "") + std::cout << " Area Static: " << mData.mArea << std::endl; + if (mData.mAreaSound != "") + std::cout << " Area Sound: " << mData.mAreaSound << std::endl; + std::cout << " School: " << schoolLabel(mData.mData.mSchool) + << " (" << mData.mData.mSchool << ")" << std::endl; + std::cout << " Base Cost: " << mData.mData.mBaseCost << std::endl; + std::cout << " Speed: " << mData.mData.mSpeed << std::endl; + std::cout << " Size: " << mData.mData.mSize << std::endl; + std::cout << " Size Cap: " << mData.mData.mSizeCap << std::endl; + std::cout << " RGB Color: " << "(" + << mData.mData.mRed << "," + << mData.mData.mGreen << "," + << mData.mData.mGreen << ")" << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + std::cout << " Icon: " << mData.mIcon << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; + std::cout << " Is Key: " << mData.mData.mIsKey << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Animation: " << mData.mModel << std::endl; + std::cout << " Hair Model: " << mData.mHair << std::endl; + std::cout << " Head Model: " << mData.mHead << std::endl; std::cout << " Race: " << mData.mRace << std::endl; + std::cout << " Class: " << mData.mClass << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + if (mData.mFaction != "") + std::cout << " Faction: " << mData.mFaction << std::endl; + std::cout << " Flags: " << npcFlags(mData.mFlags) << std::endl; + + // Seriously? + if (mData.mNpdt52.mGold == -10) + { + std::cout << " Level: " << mData.mNpdt12.mLevel << std::endl; + std::cout << " Reputation: " << (int)mData.mNpdt12.mReputation << std::endl; + std::cout << " Disposition: " << (int)mData.mNpdt12.mDisposition << std::endl; + std::cout << " Faction: " << (int)mData.mNpdt52.mFactionID << std::endl; + std::cout << " Rank: " << (int)mData.mNpdt12.mRank << std::endl; + std::cout << " Unknown1: " + << (unsigned int)((unsigned char)mData.mNpdt12.mUnknown1) << std::endl; + std::cout << " Unknown2: " + << (unsigned int)((unsigned char)mData.mNpdt12.mUnknown2) << std::endl; + std::cout << " Unknown3: " + << (unsigned int)((unsigned char)mData.mNpdt12.mUnknown3) << std::endl; + std::cout << " Gold: " << (int)mData.mNpdt12.mGold << std::endl; + } + else { + std::cout << " Level: " << mData.mNpdt52.mLevel << std::endl; + std::cout << " Reputation: " << (int)mData.mNpdt52.mReputation << std::endl; + std::cout << " Disposition: " << (int)mData.mNpdt52.mDisposition << std::endl; + std::cout << " Rank: " << (int)mData.mNpdt52.mRank << std::endl; + + std::cout << " Attributes:" << std::endl; + std::cout << " Strength: " << (int)mData.mNpdt52.mStrength << std::endl; + std::cout << " Intelligence: " << (int)mData.mNpdt52.mIntelligence << std::endl; + std::cout << " Willpower: " << (int)mData.mNpdt52.mWillpower << std::endl; + std::cout << " Agility: " << (int)mData.mNpdt52.mAgility << std::endl; + std::cout << " Speed: " << (int)mData.mNpdt52.mSpeed << std::endl; + std::cout << " Endurance: " << (int)mData.mNpdt52.mEndurance << std::endl; + std::cout << " Personality: " << (int)mData.mNpdt52.mPersonality << std::endl; + std::cout << " Luck: " << (int)mData.mNpdt52.mLuck << std::endl; + + std::cout << " Skills:" << std::endl; + for (int i = 0; i != 27; i++) + std::cout << " " << skillLabel(i) << ": " + << (int)((unsigned char)mData.mNpdt52.mSkills[i]) << std::endl; + + std::cout << " Health: " << mData.mNpdt52.mHealth << std::endl; + std::cout << " Magicka: " << mData.mNpdt52.mMana << std::endl; + std::cout << " Fatigue: " << mData.mNpdt52.mFatigue << std::endl; + std::cout << " Unknown: " << (int)mData.mNpdt52.mUnknown << std::endl; + std::cout << " Gold: " << mData.mNpdt52.mGold << std::endl; + } + + std::vector::iterator cit; + for (cit = mData.mInventory.mList.begin(); cit != mData.mInventory.mList.end(); cit++) + std::cout << " Inventory: Count: " << boost::format("%4d") % cit->mCount + << " Item: " << cit->mItem.toString() << std::endl; + + std::vector::iterator sit; + for (sit = mData.mSpells.mList.begin(); sit != mData.mSpells.mList.end(); sit++) + std::cout << " Spell: " << *sit << std::endl; + + std::vector::iterator dit; + for (dit = mData.mTransport.begin(); dit != mData.mTransport.end(); dit++) + { + std::cout << " Destination Position: " + << boost::format("%12.3f") % dit->mPos.pos[0] << "," + << boost::format("%12.3f") % dit->mPos.pos[1] << "," + << boost::format("%12.3f") % dit->mPos.pos[2] << ")" << std::endl; + std::cout << " Destination Rotation: " + << boost::format("%9.6f") % dit->mPos.rot[0] << "," + << boost::format("%9.6f") % dit->mPos.rot[1] << "," + << boost::format("%9.6f") % dit->mPos.rot[2] << ")" << std::endl; + if (dit->mCellName != "") + std::cout << " Destination Cell: " << dit->mCellName << std::endl; + } + + std::cout << " Artifical Intelligence: " << mData.mHasAI << std::endl; + std::cout << " AI Hello:" << (int)mData.mAiData.mHello << std::endl; + std::cout << " AI Fight:" << (int)mData.mAiData.mFight << std::endl; + std::cout << " AI Flee:" << (int)mData.mAiData.mFlee << std::endl; + std::cout << " AI Alarm:" << (int)mData.mAiData.mAlarm << std::endl; + std::cout << " AI U1:" << (int)mData.mAiData.mU1 << std::endl; + std::cout << " AI U2:" << (int)mData.mAiData.mU2 << std::endl; + std::cout << " AI U3:" << (int)mData.mAiData.mU3 << std::endl; + std::cout << " AI U4:" << (int)mData.mAiData.mU4 << std::endl; + std::cout << " AI Services:" << boost::format("0x%08X") % mData.mAiData.mServices << std::endl; + + std::vector::iterator pit; + for (pit = mData.mAiPackage.mList.begin(); pit != mData.mAiPackage.mList.end(); pit++) + printAIPackage(*pit); } template<> void Record::print() { std::cout << " Cell: " << mData.mCell << std::endl; - std::cout << " Point count: " << mData.mPoints.size() << std::endl; - std::cout << " Edge count: " << mData.mEdges.size() << std::endl; + std::cout << " Coordinates: (" << mData.mData.mX << "," << mData.mData.mY << ")" << std::endl; + std::cout << " Unknown S1: " << mData.mData.mS1 << std::endl; + if ((unsigned int)mData.mData.mS2 != mData.mPoints.size()) + std::cout << " Reported Point Count: " << mData.mData.mS2 << std::endl; + std::cout << " Point Count: " << mData.mPoints.size() << std::endl; + std::cout << " Edge Count: " << mData.mEdges.size() << std::endl; + + int i = 0; + ESM::Pathgrid::PointList::iterator pit; + for (pit = mData.mPoints.begin(); pit != mData.mPoints.end(); pit++) + { + std::cout << " Point[" << i << "]:" << std::endl; + std::cout << " Coordinates: (" << pit->mX << "," + << pit->mY << "," << pit->mZ << ")" << std::endl; + std::cout << " Auto-Generated: " << (int)pit->mAutogenerated << std::endl; + std::cout << " Connections: " << (int)pit->mConnectionNum << std::endl; + std::cout << " Unknown: " << pit->mUnknown << std::endl; + i++; + } + i = 0; + ESM::Pathgrid::EdgeList::iterator eit; + for (eit = mData.mEdges.begin(); eit != mData.mEdges.end(); eit++) + { + std::cout << " Edge[" << i << "]: " << eit->mV0 << " -> " << eit->mV1 << std::endl; + if (eit->mV0 >= mData.mData.mS2 || eit->mV1 >= mData.mData.mS2) + std::cout << " BAD POINT IN EDGE!" << std::endl; + i++; + } } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; - std::cout << " Length: " << mData.mData.mHeight.mMale << "m " << mData.mData.mHeight.mFemale << "f" << std::endl; + std::cout << " Description: " << mData.mDescription << std::endl; + std::cout << " Flags: " << raceFlags(mData.mData.mFlags) << std::endl; + + std::cout << " Male:" << std::endl; + std::cout << " Strength: " + << mData.mData.mStrength.mMale << std::endl; + std::cout << " Intelligence: " + << mData.mData.mIntelligence.mMale << std::endl; + std::cout << " Willpower: " + << mData.mData.mWillpower.mMale << std::endl; + std::cout << " Agility: " + << mData.mData.mAgility.mMale << std::endl; + std::cout << " Speed: " + << mData.mData.mSpeed.mMale << std::endl; + std::cout << " Endurance: " + << mData.mData.mEndurance.mMale << std::endl; + std::cout << " Personality: " + << mData.mData.mPersonality.mMale << std::endl; + std::cout << " Luck: " + << mData.mData.mLuck.mMale << std::endl; + std::cout << " Height: " + << mData.mData.mHeight.mMale << std::endl; + std::cout << " Weight: " + << mData.mData.mWeight.mMale << std::endl; + + std::cout << " Female:" << std::endl; + std::cout << " Strength: " + << mData.mData.mStrength.mFemale << std::endl; + std::cout << " Intelligence: " + << mData.mData.mIntelligence.mFemale << std::endl; + std::cout << " Willpower: " + << mData.mData.mWillpower.mFemale << std::endl; + std::cout << " Agility: " + << mData.mData.mAgility.mFemale << std::endl; + std::cout << " Speed: " + << mData.mData.mSpeed.mFemale << std::endl; + std::cout << " Endurance: " + << mData.mData.mEndurance.mFemale << std::endl; + std::cout << " Personality: " + << mData.mData.mPersonality.mFemale << std::endl; + std::cout << " Luck: " + << mData.mData.mLuck.mFemale << std::endl; + std::cout << " Height: " + << mData.mData.mHeight.mFemale << std::endl; + std::cout << " Weight: " + << mData.mData.mWeight.mFemale << std::endl; + + for (int i = 0; i != 7; i++) + // Not all races have 7 skills. + if (mData.mData.mBonus[i].mSkill != -1) + std::cout << " Skill: " + << skillLabel(mData.mData.mBonus[i].mSkill) + << " (" << mData.mData.mBonus[i].mSkill << ") = " + << mData.mData.mBonus[i].mBonus << std::endl; + + std::vector::iterator sit; + for (sit = mData.mPowers.mList.begin(); sit != mData.mPowers.mList.end(); sit++) + std::cout << " Power: " << *sit << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + + std::cout << " Weather:" << std::endl; + std::cout << " Clear: " << (int)mData.mData.mClear << std::endl; + std::cout << " Cloudy: " << (int)mData.mData.mCloudy << std::endl; + std::cout << " Foggy: " << (int)mData.mData.mFoggy << std::endl; + std::cout << " Overcast: " << (int)mData.mData.mOvercast << std::endl; + std::cout << " Rain: " << (int)mData.mData.mOvercast << std::endl; + std::cout << " Thunder: " << (int)mData.mData.mThunder << std::endl; + std::cout << " Ash: " << (int)mData.mData.mAsh << std::endl; + std::cout << " Blight: " << (int)mData.mData.mBlight << std::endl; + std::cout << " UnknownA: " << (int)mData.mData.mA << std::endl; + std::cout << " UnknownB: " << (int)mData.mData.mB << std::endl; + std::cout << " Map Color: " << mData.mMapColor << std::endl; + if (mData.mSleepList != "") + std::cout << " Sleep List: " << mData.mSleepList << std::endl; + std::vector::iterator sit; + for (sit = mData.mSoundList.begin(); sit != mData.mSoundList.end(); sit++) + std::cout << " Sound: " << (int)sit->mChance << " = " << sit->mSound.toString() << std::endl; } template<> void Record::print() { - std::cout << " Name: " << mData.mData.mName.toString() << std::endl; + std::cout << " Name: " << mData.mId << std::endl; + + std::cout << " Num Shorts: " << mData.mData.mNumShorts << std::endl; + std::cout << " Num Longs: " << mData.mData.mNumLongs << std::endl; + std::cout << " Num Floats: " << mData.mData.mNumFloats << std::endl; + std::cout << " Script Data Size: " << mData.mData.mScriptDataSize << std::endl; + std::cout << " Table Size: " << mData.mData.mStringTableSize << std::endl; + + std::cout << " Script: [skipped]" << std::endl; + // Skip until multi-line fields is controllable by a command line option. + // Mildly problematic because there are no parameter to print() currently. + // std::cout << "-------------------------------------------" << std::endl; + // std::cout << s->scriptText << std::endl; + // std::cout << "-------------------------------------------" << std::endl; + std::vector::iterator vit; + for (vit = mData.mVarNames.begin(); vit != mData.mVarNames.end(); vit++) + std::cout << " Variable: " << *vit << std::endl; + + std::cout << " ByteCode: "; + std::vector::iterator cit; + for (cit = mData.mScriptData.begin(); cit != mData.mScriptData.end(); cit++) + std::cout << boost::format("%02X") % (int)(*cit); + std::cout << std::endl; } template<> void Record::print() { - std::cout << " ID: " << mData.mIndex << std::endl; - - const char *spec = 0; - int specId = mData.mData.mSpecialization; - if (specId == 0) { - spec = "Combat"; - } else if (specId == 1) { - spec = "Magic"; - } else { - spec = "Stealth"; - } - std::cout << " Type: " << spec << std::endl; + std::cout << " ID: " << skillLabel(mData.mIndex) + << " (" << mData.mIndex << ")" << std::endl; + std::cout << " Description: " << mData.mDescription << std::endl; + std::cout << " Governing Attribute: " << attributeLabel(mData.mData.mAttribute) + << " (" << mData.mData.mAttribute << ")" << std::endl; + std::cout << " Specialization: " << specializationLabel(mData.mData.mSpecialization) + << " (" << mData.mData.mSpecialization << ")" << std::endl; + for (int i = 0; i != 4; i++) + std::cout << " UseValue[" << i << "]:" << mData.mData.mUseValue[i] << std::endl; } template<> @@ -519,25 +1257,36 @@ void Record::print() { std::cout << " Creature: " << mData.mCreature << std::endl; std::cout << " Sound: " << mData.mSound << std::endl; + std::cout << " Type: " << soundTypeLabel(mData.mType) + << " (" << mData.mType << ")" << std::endl; } template<> void Record::print() { std::cout << " Sound: " << mData.mSound << std::endl; - std::cout << " Volume: " << mData.mData.mVolume << std::endl; + std::cout << " Volume: " << (int)mData.mData.mVolume << std::endl; + if (mData.mData.mMinRange != 0 && mData.mData.mMaxRange != 0) + std::cout << " Range: " << (int)mData.mData.mMinRange << " - " + << (int)mData.mData.mMaxRange << std::endl; } template<> void Record::print() { std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Type: " << spellTypeLabel(mData.mData.mType) + << " (" << mData.mData.mType << ")" << std::endl; + std::cout << " Flags: " << spellFlags(mData.mData.mFlags) << std::endl; + std::cout << " Cost: " << mData.mData.mCost << std::endl; + printEffectList(mData.mEffects); } template<> void Record::print() { - std::cout << "Start script: " << mData.mScript << std::endl; + std::cout << "Start Script: " << mData.mScript << std::endl; + std::cout << "Start Data: " << mData.mData << std::endl; } template<> @@ -549,20 +1298,35 @@ void Record::print() template<> void Record::print() { - std::cout << " Name: " << mData.mName << std::endl; - std::cout << " Chop: " << mData.mData.mChop[0] << "-" << mData.mData.mChop[1] << std::endl; - std::cout << " Slash: " << mData.mData.mSlash[0] << "-" << mData.mData.mSlash[1] << std::endl; - std::cout << " Thrust: " << mData.mData.mThrust[0] << "-" << mData.mData.mThrust[1] << std::endl; + // No names on VFX bolts + if (mData.mName != "") + std::cout << " Name: " << mData.mName << std::endl; + std::cout << " Model: " << mData.mModel << std::endl; + // No icons on VFX bolts or magic bolts + if (mData.mIcon != "") + std::cout << " Icon: " << mData.mIcon << std::endl; + if (mData.mScript != "") + std::cout << " Script: " << mData.mScript << std::endl; + if (mData.mEnchant != "") + std::cout << " Enchantment: " << mData.mEnchant << std::endl; + std::cout << " Type: " << weaponTypeLabel(mData.mData.mType) + << " (" << mData.mData.mType << ")" << std::endl; + std::cout << " Flags: " << weaponFlags(mData.mData.mFlags) << std::endl; + std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; -} - -template<> -void Record::print() -{ - std::cout << " Refnum: " << mData.mRefnum << std::endl; - std::cout << " ID: '" << mData.mRefID << "'\n"; - std::cout << " Owner: '" << mData.mOwner << "'\n"; - std::cout << " INTV: " << mData.mIntv << " NAM9: " << mData.mIntv << std::endl; + std::cout << " Health: " << mData.mData.mHealth << std::endl; + std::cout << " Speed: " << mData.mData.mSpeed << std::endl; + std::cout << " Reach: " << mData.mData.mReach << std::endl; + std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl; + if (mData.mData.mChop[0] != 0 && mData.mData.mChop[1] != 0) + std::cout << " Chop: " << (int)mData.mData.mChop[0] << "-" + << (int)mData.mData.mChop[1] << std::endl; + if (mData.mData.mSlash[0] != 0 && mData.mData.mSlash[1] != 0) + std::cout << " Slash: " << (int)mData.mData.mSlash[0] << "-" + << (int)mData.mData.mSlash[1] << std::endl; + if (mData.mData.mThrust[0] != 0 && mData.mData.mThrust[1] != 0) + std::cout << " Thrust: " << (int)mData.mData.mThrust[0] << "-" + << (int)mData.mData.mThrust[1] << std::endl; } } // end namespace diff --git a/apps/esmtool/record.hpp b/apps/esmtool/record.hpp index 3cd7f5b54..c3daa9d0c 100644 --- a/apps/esmtool/record.hpp +++ b/apps/esmtool/record.hpp @@ -20,7 +20,7 @@ namespace EsmTool protected: std::string mId; int mFlags; - int mType; + ESM::NAME mType; public: RecordBase () {} @@ -42,7 +42,7 @@ namespace EsmTool mFlags = flags; } - int getType() const { + ESM::NAME getType() const { return mType; } @@ -50,7 +50,7 @@ namespace EsmTool virtual void save(ESM::ESMWriter &esm) = 0; virtual void print() = 0; - static RecordBase *create(int type); + static RecordBase *create(ESM::NAME type); // just make it a bit shorter template diff --git a/apps/launcher/CMakeLists.txt b/apps/launcher/CMakeLists.txt index 2bc43db80..09beaf59d 100644 --- a/apps/launcher/CMakeLists.txt +++ b/apps/launcher/CMakeLists.txt @@ -1,42 +1,56 @@ set(LAUNCHER datafilespage.cpp graphicspage.cpp - lineedit.cpp main.cpp maindialog.cpp - naturalsort.cpp playpage.cpp - pluginsmodel.cpp - pluginsview.cpp - filedialog.cpp + + model/datafilesmodel.cpp + model/modelitem.cpp + model/esm/esmfile.cpp + + utils/filedialog.cpp + utils/naturalsort.cpp + utils/lineedit.cpp + utils/profilescombobox.cpp + utils/textinputdialog.cpp launcher.rc ) set(LAUNCHER_HEADER - combobox.hpp datafilespage.hpp graphicspage.hpp - lineedit.hpp maindialog.hpp - naturalsort.hpp playpage.hpp - pluginsmodel.hpp - pluginsview.hpp - filedialog.hpp + + model/datafilesmodel.hpp + model/modelitem.hpp + model/esm/esmfile.hpp + + utils/lineedit.hpp + utils/filedialog.hpp + utils/naturalsort.hpp + utils/profilescombobox.hpp + utils/textinputdialog.hpp + ) # Headers that must be pre-processed set(LAUNCHER_HEADER_MOC - combobox.hpp datafilespage.hpp graphicspage.hpp - lineedit.hpp maindialog.hpp playpage.hpp - pluginsmodel.hpp - pluginsview.hpp - filedialog.hpp + + model/datafilesmodel.hpp + model/modelitem.hpp + model/esm/esmfile.hpp + + utils/lineedit.hpp + utils/filedialog.hpp + utils/profilescombobox.hpp + utils/textinputdialog.hpp ) source_group(launcher FILES ${LAUNCHER} ${LAUNCHER_HEADER} ${LAUNCHER_HEADER_MOC}) @@ -75,7 +89,7 @@ add_executable(omwlauncher target_link_libraries(omwlauncher ${Boost_LIBRARIES} ${OGRE_LIBRARIES} - ${OGRE_STATIC_PLUGINS} + ${OGRE_STATIC_PLUGINS} ${QT_LIBRARIES} components ) @@ -87,8 +101,6 @@ endif() if (APPLE) configure_file(${CMAKE_SOURCE_DIR}/files/launcher.qss "${APP_BUNDLE_DIR}/../launcher.qss") - configure_file(${CMAKE_SOURCE_DIR}/files/launcher.cfg - "${APP_BUNDLE_DIR}/../launcher.cfg") else() configure_file(${CMAKE_SOURCE_DIR}/files/launcher.qss "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/resources/launcher.qss") @@ -96,9 +108,6 @@ else() # Fallback in case getGlobalDataPath does not point to resources configure_file(${CMAKE_SOURCE_DIR}/files/launcher.qss "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/launcher.qss") - - configure_file(${CMAKE_SOURCE_DIR}/files/launcher.cfg - "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/launcher.cfg") endif() if (BUILD_WITH_CODE_COVERAGE) diff --git a/apps/launcher/combobox.hpp b/apps/launcher/combobox.hpp deleted file mode 100644 index bc99575d7..000000000 --- a/apps/launcher/combobox.hpp +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef COMBOBOX_H -#define COMBOBOX_H - -#include - -class ComboBox : public QComboBox -{ - Q_OBJECT -private: - QString oldText; -public: - ComboBox(QWidget *parent=0) : QComboBox(parent), oldText() - { - connect(this,SIGNAL(editTextChanged(const QString&)), this, - SLOT(textChangedSlot(const QString&))); - connect(this,SIGNAL(currentIndexChanged(const QString&)), this, - SLOT(textChangedSlot(const QString&))); - } -private slots: - void textChangedSlot(const QString &newText) - { - emit textChanged(oldText, newText); - oldText = newText; - } -signals: - void textChanged(const QString &oldText, const QString &newText); -}; -#endif \ No newline at end of file diff --git a/apps/launcher/datafilespage.cpp b/apps/launcher/datafilespage.cpp index 8ca3c9aed..6b0539c1d 100644 --- a/apps/launcher/datafilespage.cpp +++ b/apps/launcher/datafilespage.cpp @@ -3,12 +3,16 @@ #include #include +#include "model/datafilesmodel.hpp" +#include "model/esm/esmfile.hpp" + +#include "utils/profilescombobox.hpp" +#include "utils/filedialog.hpp" +#include "utils/lineedit.hpp" +#include "utils/naturalsort.hpp" +#include "utils/textinputdialog.hpp" + #include "datafilespage.hpp" -#include "lineedit.hpp" -#include "filedialog.hpp" -#include "naturalsort.hpp" -#include "pluginsmodel.hpp" -#include "pluginsview.hpp" #include /** @@ -46,13 +50,15 @@ DataFilesPage::DataFilesPage(Files::ConfigurationManager &cfg, QWidget *parent) : QWidget(parent) , mCfgMgr(cfg) { - mDataFilesModel = new QStandardItemModel(); // Contains all plugins with masters - mPluginsModel = new PluginsModel(); // Contains selectable plugins + // Models + mMastersModel = new DataFilesModel(this); + mPluginsModel = new DataFilesModel(this); mPluginsProxyModel = new QSortFilterProxyModel(); mPluginsProxyModel->setDynamicSortFilter(true); mPluginsProxyModel->setSourceModel(mPluginsModel); + // Filter toolbar QLabel *filterLabel = new QLabel(tr("&Filter:"), this); LineEdit *filterLineEdit = new LineEdit(this); filterLabel->setBuddy(filterLineEdit); @@ -71,48 +77,74 @@ DataFilesPage::DataFilesPage(Files::ConfigurationManager &cfg, QWidget *parent) filterToolBar->addWidget(filterWidget); - mMastersWidget = new QTableWidget(this); // Contains the available masters - mMastersWidget->setObjectName("MastersWidget"); - mMastersWidget->setSelectionBehavior(QAbstractItemView::SelectRows); - mMastersWidget->setSelectionMode(QAbstractItemView::MultiSelection); - mMastersWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); - mMastersWidget->setAlternatingRowColors(true); - mMastersWidget->horizontalHeader()->setStretchLastSection(true); - mMastersWidget->horizontalHeader()->hide(); - mMastersWidget->verticalHeader()->hide(); - mMastersWidget->insertColumn(0); - - mPluginsTable = new PluginsView(this); - mPluginsTable->setModel(mPluginsProxyModel); - mPluginsTable->setVerticalScrollMode(QAbstractItemView::ScrollPerItem); - - mPluginsTable->horizontalHeader()->setStretchLastSection(true); - mPluginsTable->horizontalHeader()->hide(); - - // Set the row height to the size of the checkboxes QCheckBox checkBox; unsigned int height = checkBox.sizeHint().height() + 4; + mMastersTable = new QTableView(this); + mMastersTable->setModel(mMastersModel); + mMastersTable->setObjectName("MastersTable"); + mMastersTable->setSelectionBehavior(QAbstractItemView::SelectRows); + mMastersTable->setSelectionMode(QAbstractItemView::SingleSelection); + mMastersTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + mMastersTable->setAlternatingRowColors(true); + mMastersTable->horizontalHeader()->setStretchLastSection(true); + mMastersTable->horizontalHeader()->hide(); + + // Set the row height to the size of the checkboxes + mMastersTable->verticalHeader()->setDefaultSectionSize(height); + mMastersTable->verticalHeader()->setResizeMode(QHeaderView::Fixed); + mMastersTable->verticalHeader()->hide(); + mMastersTable->setColumnHidden(1, true); + mMastersTable->setColumnHidden(2, true); + mMastersTable->setColumnHidden(3, true); + mMastersTable->setColumnHidden(4, true); + mMastersTable->setColumnHidden(5, true); + mMastersTable->setColumnHidden(6, true); + mMastersTable->setColumnHidden(7, true); + mMastersTable->setColumnHidden(8, true); + + mPluginsTable = new QTableView(this); + mPluginsTable->setModel(mPluginsProxyModel); + mPluginsTable->setObjectName("PluginsTable"); + mPluginsTable->setContextMenuPolicy(Qt::CustomContextMenu); + mPluginsTable->setSelectionBehavior(QAbstractItemView::SelectRows); + mPluginsTable->setSelectionMode(QAbstractItemView::SingleSelection); + mPluginsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + mPluginsTable->setAlternatingRowColors(true); + mPluginsTable->setVerticalScrollMode(QAbstractItemView::ScrollPerItem); + mPluginsTable->horizontalHeader()->setStretchLastSection(true); + mPluginsTable->horizontalHeader()->hide(); + mPluginsTable->verticalHeader()->setDefaultSectionSize(height); + mPluginsTable->verticalHeader()->setResizeMode(QHeaderView::Fixed); + mPluginsTable->setColumnHidden(1, true); + mPluginsTable->setColumnHidden(2, true); + mPluginsTable->setColumnHidden(3, true); + mPluginsTable->setColumnHidden(4, true); + mPluginsTable->setColumnHidden(5, true); + mPluginsTable->setColumnHidden(6, true); + mPluginsTable->setColumnHidden(7, true); + mPluginsTable->setColumnHidden(8, true); // Add both tables to a splitter QSplitter *splitter = new QSplitter(this); splitter->setOrientation(Qt::Horizontal); - - splitter->addWidget(mMastersWidget); + splitter->addWidget(mMastersTable); splitter->addWidget(mPluginsTable); // Adjust the default widget widths inside the splitter QList sizeList; - sizeList << 100 << 300; + sizeList << 175 << 200; splitter->setSizes(sizeList); // Bottom part with profile options QLabel *profileLabel = new QLabel(tr("Current Profile: "), this); - mProfilesComboBox = new ComboBox(this); + mProfilesComboBox = new ProfilesComboBox(this); mProfilesComboBox->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum)); - mProfilesComboBox->setInsertPolicy(QComboBox::InsertAtBottom); + mProfilesComboBox->setInsertPolicy(QComboBox::NoInsert); + mProfilesComboBox->setDuplicatesEnabled(false); + mProfilesComboBox->setEditEnabled(false); mProfileToolBar = new QToolBar(this); mProfileToolBar->setMovable(false); @@ -127,35 +159,70 @@ DataFilesPage::DataFilesPage(Files::ConfigurationManager &cfg, QWidget *parent) pageLayout->addWidget(splitter); pageLayout->addWidget(mProfileToolBar); - connect(mMastersWidget->selectionModel(), - SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), - this, SLOT(masterSelectionChanged(const QItemSelection&, const QItemSelection&))); + // Create a dialog for the new profile name input + mNewProfileDialog = new TextInputDialog(tr("New Profile"), tr("Profile name:"), this); - connect(filterLineEdit, SIGNAL(textChanged(QString)), this, SLOT(filterChanged(const QString))); + connect(mNewProfileDialog->lineEdit(), SIGNAL(textChanged(QString)), this, SLOT(updateOkButton(QString))); connect(mPluginsTable, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(setCheckState(QModelIndex))); - connect(mPluginsTable, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&))); + connect(mMastersTable, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(setCheckState(QModelIndex))); - connect(mProfilesComboBox, SIGNAL(textChanged(const QString&, const QString&)), this, SLOT(profileChanged(const QString&, const QString&))); + connect(mMastersModel, SIGNAL(checkedItemsChanged(QStringList,QStringList)), mPluginsModel, SLOT(slotcheckedItemsChanged(QStringList,QStringList))); + + connect(filterLineEdit, SIGNAL(textChanged(QString)), this, SLOT(filterChanged(QString))); + + connect(mPluginsTable, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); + + connect(mProfilesComboBox, SIGNAL(profileRenamed(QString,QString)), this, SLOT(profileRenamed(QString,QString))); + connect(mProfilesComboBox, SIGNAL(profileChanged(QString,QString)), this, SLOT(profileChanged(QString,QString))); createActions(); setupConfig(); - //setupDataFiles(); +} + +void DataFilesPage::createActions() +{ + // Refresh the plugins + QAction *refreshAction = new QAction(tr("Refresh"), this); + refreshAction->setShortcut(QKeySequence(tr("F5"))); + connect(refreshAction, SIGNAL(triggered()), this, SLOT(refresh())); + + // Profile actions + mNewProfileAction = new QAction(QIcon::fromTheme("document-new"), tr("&New Profile"), this); + mNewProfileAction->setToolTip(tr("New Profile")); + mNewProfileAction->setShortcut(QKeySequence(tr("Ctrl+N"))); + connect(mNewProfileAction, SIGNAL(triggered()), this, SLOT(newProfile())); + + mDeleteProfileAction = new QAction(QIcon::fromTheme("edit-delete"), tr("Delete Profile"), this); + mDeleteProfileAction->setToolTip(tr("Delete Profile")); + mDeleteProfileAction->setShortcut(QKeySequence(tr("Delete"))); + connect(mDeleteProfileAction, SIGNAL(triggered()), this, SLOT(deleteProfile())); + + // Add the newly created actions to the toolbar + mProfileToolBar->addSeparator(); + mProfileToolBar->addAction(mNewProfileAction); + mProfileToolBar->addAction(mDeleteProfileAction); + + // Context menu actions + mCheckAction = new QAction(tr("Check selected"), this); + connect(mCheckAction, SIGNAL(triggered()), this, SLOT(check())); + + mUncheckAction = new QAction(tr("Uncheck selected"), this); + connect(mUncheckAction, SIGNAL(triggered()), this, SLOT(uncheck())); + + // Context menu for the plugins table + mContextMenu = new QMenu(this); + + mContextMenu->addAction(mCheckAction); + mContextMenu->addAction(mUncheckAction); } void DataFilesPage::setupConfig() { - QString config = QString::fromStdString((mCfgMgr.getLocalPath() / "launcher.cfg").string()); - QFile file(config); - - if (!file.exists()) { - config = QString::fromStdString((mCfgMgr.getUserPath() / "launcher.cfg").string()); - } - // Open our config file + QString config = QString::fromStdString((mCfgMgr.getUserPath() / "launcher.cfg").string()); mLauncherConfig = new QSettings(config, QSettings::IniFormat); - file.close(); // Make sure we have no groups open while (!mLauncherConfig->group().isEmpty()) { @@ -165,12 +232,21 @@ void DataFilesPage::setupConfig() mLauncherConfig->beginGroup("Profiles"); QStringList profiles = mLauncherConfig->childGroups(); - if (profiles.isEmpty()) { - // Add a default profile - profiles.append("Default"); + // Add the profiles to the combobox + foreach (const QString &profile, profiles) { + + if (profile.contains(QRegExp("[^a-zA-Z0-9_]"))) + continue; // Profile name contains garbage + + + qDebug() << "adding " << profile; + mProfilesComboBox->addItem(profile); } - mProfilesComboBox->addItems(profiles); + // Add a default profile + if (mProfilesComboBox->findText(QString("Default")) == -1) { + mProfilesComboBox->addItem(QString("Default")); + } QString currentProfile = mLauncherConfig->value("CurrentProfile").toString(); @@ -189,823 +265,12 @@ void DataFilesPage::setupConfig() } -void DataFilesPage::addDataFiles(Files::Collections &fileCollections, const QString &encoding) -{ - // First we add all the master files - const Files::MultiDirCollection &esm = fileCollections.getCollection(".esm"); - unsigned int i = 0; // Row number - - for (Files::MultiDirCollection::TIter iter(esm.begin()); iter!=esm.end(); ++iter) { - QString currentMaster = QString::fromStdString( - boost::filesystem::path (iter->second.filename()).string()); - - const QList itemList = mMastersWidget->findItems(currentMaster, Qt::MatchExactly); - - if (itemList.isEmpty()) { // Master is not yet in the widget - mMastersWidget->insertRow(i); - QTableWidgetItem *item = new QTableWidgetItem(currentMaster); - mMastersWidget->setItem(i, 0, item); - ++i; - } - } - - // Now on to the plugins - const Files::MultiDirCollection &esp = fileCollections.getCollection(".esp"); - - for (Files::MultiDirCollection::TIter iter(esp.begin()); iter!=esp.end(); ++iter) { - - try { - ESMReader fileReader; - QStringList availableMasters; // Will contain all found masters - - fileReader.setEncoding(encoding.toStdString()); - fileReader.open(iter->second.string()); - - // First we fill the availableMasters and the mMastersWidget - ESMReader::MasterList mlist = fileReader.getMasters(); - - for (unsigned int i = 0; i < mlist.size(); ++i) { - const QString currentMaster = QString::fromStdString(mlist[i].name); - availableMasters.append(currentMaster); - - const QList itemList = mMastersWidget->findItems(currentMaster, Qt::MatchExactly); - - if (itemList.isEmpty()) { // Master is not yet in the widget - mMastersWidget->insertRow(i); - - QTableWidgetItem *item = new QTableWidgetItem(currentMaster); - item->setForeground(Qt::red); - item->setFlags(item->flags() & ~(Qt::ItemIsSelectable)); - - mMastersWidget->setItem(i, 0, item); - } - } - - availableMasters.sort(); // Sort the masters alphabetically - - // Now we put the current plugin in the mDataFilesModel under its masters - QStandardItem *parent = new QStandardItem(availableMasters.join(",")); - - QString fileName = QString::fromStdString(boost::filesystem::path (iter->second.filename()).string()); - QStandardItem *child = new QStandardItem(fileName); - - // Tooltip information - QString author = QString::fromStdString(fileReader.getAuthor()); - float version = fileReader.getFVer(); - QString description = QString::fromStdString(fileReader.getDesc()); - - // For the date created/modified - QFileInfo fi(QString::fromStdString(iter->second.string())); - - QString toolTip= QString("Author: %1
\ - Version: %2

\ - Description:
\ - %3

\ - Created on: %4
\ - Last modified: %5") - .arg(author) - .arg(version) - .arg(description) - .arg(fi.created().toString(Qt::TextDate)) - .arg(fi.lastModified().toString(Qt::TextDate)); - - child->setToolTip(toolTip); - - const QList masterList = mDataFilesModel->findItems(availableMasters.join(",")); - - if (masterList.isEmpty()) { // Masters node not yet in the mDataFilesModel - parent->appendRow(child); - mDataFilesModel->appendRow(parent); - } else { - // Masters node exists, append current plugin - foreach (QStandardItem *currentItem, masterList) { - currentItem->appendRow(child); - } - } - - } catch(std::runtime_error &e) { - // An error occurred while reading the .esp - std::cerr << "Error reading .esp: " << e.what() << std::endl; - continue; - } - } - - -} - - -bool DataFilesPage::setupDataFiles() -{ - // We use the Configuration Manager to retrieve the configuration values - boost::program_options::variables_map variables; - boost::program_options::options_description desc; - - desc.add_options() - ("data", boost::program_options::value()->default_value(Files::PathContainer(), "data")->multitoken()) - ("data-local", boost::program_options::value()->default_value("")) - ("fs-strict", boost::program_options::value()->implicit_value(true)->default_value(false)) - ("encoding", boost::program_options::value()->default_value("win1252")); - - mCfgMgr.readConfiguration(variables, desc); - - // Put the paths in a boost::filesystem vector to use with Files::Collections - mDataDirs = Files::PathContainer(variables["data"].as()); - - std::string local = variables["data-local"].as(); - if (!local.empty()) { - mDataLocal.push_back(Files::PathContainer::value_type(local)); - } - - mCfgMgr.processPaths(mDataDirs); - mCfgMgr.processPaths(mDataLocal); - - while (mDataDirs.empty()) { - QMessageBox msgBox; - msgBox.setWindowTitle("Error detecting Morrowind installation"); - msgBox.setIcon(QMessageBox::Warning); - msgBox.setStandardButtons(QMessageBox::Cancel); - msgBox.setText(tr("
Could not find the Data Files location

\ - The directory containing the data files was not found.

\ - Press \"Browse...\" to specify the location manually.
")); - - QAbstractButton *dirSelectButton = - msgBox.addButton(tr("B&rowse..."), QMessageBox::ActionRole); - - msgBox.exec(); - - if (msgBox.clickedButton() == dirSelectButton) { - - // Show a custom dir selection dialog which only accepts valid dirs - QString selectedDir = FileDialog::getExistingDirectory( - this, tr("Select Data Files Directory"), - QDir::currentPath(), - QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); - - // Add the user selected data directory - if (!selectedDir.isEmpty()) { - mDataDirs.push_back(Files::PathContainer::value_type(selectedDir.toStdString())); - mCfgMgr.processPaths(mDataDirs); - } else { - // Cancel from within the dir selection dialog - return false; - } - - } else { - // Cancel - return false; - } - } - - // Add the plugins in the data directories - Files::Collections dataCollections(mDataDirs, !variables["fs-strict"].as()); - Files::Collections dataLocalCollections(mDataLocal, !variables["fs-strict"].as()); - - addDataFiles(dataCollections, QString::fromStdString(variables["encoding"].as())); - addDataFiles(dataLocalCollections, QString::fromStdString(variables["encoding"].as())); - - mDataFilesModel->sort(0); - - readConfig(); - return true; -} - -void DataFilesPage::createActions() -{ - // Refresh the plugins - QAction *refreshAction = new QAction(tr("Refresh"), this); - refreshAction->setShortcut(QKeySequence(tr("F5"))); - connect(refreshAction, SIGNAL(triggered()), this, SLOT(refresh())); - - // Profile actions - mNewProfileAction = new QAction(QIcon::fromTheme("document-new"), tr("&New Profile"), this); - mNewProfileAction->setToolTip(tr("New Profile")); - mNewProfileAction->setShortcut(QKeySequence(tr("Ctrl+N"))); - connect(mNewProfileAction, SIGNAL(triggered()), this, SLOT(newProfile())); - - - mCopyProfileAction = new QAction(QIcon::fromTheme("edit-copy"), tr("&Copy Profile"), this); - mCopyProfileAction->setToolTip(tr("Copy Profile")); - mCopyProfileAction->setShortcut(QKeySequence(tr("Ctrl+C"))); - connect(mCopyProfileAction, SIGNAL(triggered()), this, SLOT(copyProfile())); - - mDeleteProfileAction = new QAction(QIcon::fromTheme("edit-delete"), tr("Delete Profile"), this); - mDeleteProfileAction->setToolTip(tr("Delete Profile")); - mDeleteProfileAction->setShortcut(QKeySequence(tr("Delete"))); - connect(mDeleteProfileAction, SIGNAL(triggered()), this, SLOT(deleteProfile())); - - // Add the newly created actions to the toolbar - mProfileToolBar->addSeparator(); - mProfileToolBar->addAction(mNewProfileAction); - mProfileToolBar->addAction(mCopyProfileAction); - mProfileToolBar->addAction(mDeleteProfileAction); - - // Context menu actions - mMoveUpAction = new QAction(QIcon::fromTheme("go-up"), tr("Move &Up"), this); - mMoveUpAction->setShortcut(QKeySequence(tr("Ctrl+U"))); - connect(mMoveUpAction, SIGNAL(triggered()), this, SLOT(moveUp())); - - mMoveDownAction = new QAction(QIcon::fromTheme("go-down"), tr("&Move Down"), this); - mMoveDownAction->setShortcut(QKeySequence(tr("Ctrl+M"))); - connect(mMoveDownAction, SIGNAL(triggered()), this, SLOT(moveDown())); - - mMoveTopAction = new QAction(QIcon::fromTheme("go-top"), tr("Move to Top"), this); - mMoveTopAction->setShortcut(QKeySequence(tr("Ctrl+Shift+U"))); - connect(mMoveTopAction, SIGNAL(triggered()), this, SLOT(moveTop())); - - mMoveBottomAction = new QAction(QIcon::fromTheme("go-bottom"), tr("Move to Bottom"), this); - mMoveBottomAction->setShortcut(QKeySequence(tr("Ctrl+Shift+M"))); - connect(mMoveBottomAction, SIGNAL(triggered()), this, SLOT(moveBottom())); - - mCheckAction = new QAction(tr("Check selected"), this); - connect(mCheckAction, SIGNAL(triggered()), this, SLOT(check())); - - mUncheckAction = new QAction(tr("Uncheck selected"), this); - connect(mUncheckAction, SIGNAL(triggered()), this, SLOT(uncheck())); - - // Makes shortcuts work even if the context menu is hidden - this->addAction(refreshAction); - this->addAction(mMoveUpAction); - this->addAction(mMoveDownAction); - this->addAction(mMoveTopAction); - this->addAction(mMoveBottomAction); - - // Context menu for the plugins table - mContextMenu = new QMenu(this); - - mContextMenu->addAction(mMoveUpAction); - mContextMenu->addAction(mMoveDownAction); - mContextMenu->addSeparator(); - mContextMenu->addAction(mMoveTopAction); - mContextMenu->addAction(mMoveBottomAction); - mContextMenu->addSeparator(); - mContextMenu->addAction(mCheckAction); - mContextMenu->addAction(mUncheckAction); - -} - -void DataFilesPage::newProfile() -{ - bool ok; - QString text = QInputDialog::getText(this, tr("New Profile"), - tr("Profile Name:"), QLineEdit::Normal, - tr("New Profile"), &ok); - if (ok && !text.isEmpty()) { - if (mProfilesComboBox->findText(text) != -1) { - QMessageBox::warning(this, tr("Profile already exists"), - tr("the profile %0 already exists.").arg(text), - QMessageBox::Ok); - } else { - // Add the new profile to the combobox - mProfilesComboBox->addItem(text); - mProfilesComboBox->setCurrentIndex(mProfilesComboBox->findText(text)); - - } - - } - -} - -void DataFilesPage::copyProfile() -{ - QString profile = mProfilesComboBox->currentText(); - bool ok; - - QString text = QInputDialog::getText(this, tr("Copy Profile"), - tr("Profile Name:"), QLineEdit::Normal, - tr("%0 Copy").arg(profile), &ok); - if (ok && !text.isEmpty()) { - if (mProfilesComboBox->findText(text) != -1) { - QMessageBox::warning(this, tr("Profile already exists"), - tr("the profile %0 already exists.").arg(text), - QMessageBox::Ok); - } else { - // Add the new profile to the combobox - mProfilesComboBox->addItem(text); - - // First write the current profile as the new profile - writeConfig(text); - mProfilesComboBox->setCurrentIndex(mProfilesComboBox->findText(text)); - - } - - } - -} - -void DataFilesPage::deleteProfile() -{ - QString profile = mProfilesComboBox->currentText(); - - - if (profile.isEmpty()) { - return; - } - - QMessageBox msgBox(this); - msgBox.setWindowTitle(tr("Delete Profile")); - msgBox.setIcon(QMessageBox::Warning); - msgBox.setStandardButtons(QMessageBox::Cancel); - msgBox.setText(tr("Are you sure you want to delete %0?").arg(profile)); - - QAbstractButton *deleteButton = - msgBox.addButton(tr("Delete"), QMessageBox::ActionRole); - - msgBox.exec(); - - if (msgBox.clickedButton() == deleteButton) { - // Make sure we have no groups open - while (!mLauncherConfig->group().isEmpty()) { - mLauncherConfig->endGroup(); - } - - mLauncherConfig->beginGroup("Profiles"); - - // Open the profile-name subgroup - mLauncherConfig->beginGroup(profile); - mLauncherConfig->remove(""); // Clear the subgroup - mLauncherConfig->endGroup(); - mLauncherConfig->endGroup(); - - // Remove the profile from the combobox - mProfilesComboBox->removeItem(mProfilesComboBox->findText(profile)); - } -} - -void DataFilesPage::moveUp() -{ - // Shift the selected plugins up one row - - if (!mPluginsTable->selectionModel()->hasSelection()) { - return; - } - - QModelIndexList selectedIndexes = mPluginsTable->selectionModel()->selectedIndexes(); - - //sort selection ascending because selectedIndexes returns an unsorted list - qSort(selectedIndexes.begin(), selectedIndexes.end(), rowSmallerThan); - - QModelIndex firstIndex = mPluginsProxyModel->mapToSource(selectedIndexes.first()); - - // Check if the first selected plugin is the top one - if (firstIndex.row() == 0) { - return; - } - - foreach (const QModelIndex ¤tIndex, selectedIndexes) { - const QModelIndex sourceModelIndex = mPluginsProxyModel->mapToSource(currentIndex); - int currentRow = sourceModelIndex.row(); - - if (sourceModelIndex.isValid() && currentRow > 0) { - mPluginsModel->insertRow((currentRow - 1), mPluginsModel->takeRow(currentRow)); - - const QModelIndex targetIndex = mPluginsModel->index((currentRow - 1), 0, QModelIndex()); - - mPluginsTable->selectionModel()->select(targetIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows); - scrollToSelection(); - } - } -} - -void DataFilesPage::moveDown() -{ - // Shift the selected plugins down one row - if (!mPluginsTable->selectionModel()->hasSelection()) { - return; - } - - QModelIndexList selectedIndexes = mPluginsTable->selectionModel()->selectedIndexes(); - - //sort selection descending because selectedIndexes returns an unsorted list - qSort(selectedIndexes.begin(), selectedIndexes.end(), rowGreaterThan); - - const QModelIndex lastIndex = mPluginsProxyModel->mapToSource(selectedIndexes.first()); - - // Check if last selected plugin is bottom one - if ((lastIndex.row() + 1) == mPluginsModel->rowCount()) { - return; - } - - foreach (const QModelIndex ¤tIndex, selectedIndexes) { - const QModelIndex sourceModelIndex = mPluginsProxyModel->mapToSource(currentIndex); - int currentRow = sourceModelIndex.row(); - - if (sourceModelIndex.isValid() && (currentRow + 1) < mPluginsModel->rowCount()) { - mPluginsModel->insertRow((currentRow + 1), mPluginsModel->takeRow(currentRow)); - - const QModelIndex targetIndex = mPluginsModel->index((currentRow + 1), 0, QModelIndex()); - - mPluginsTable->selectionModel()->select(targetIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows); - scrollToSelection(); - } - } -} - -void DataFilesPage::moveTop() -{ - // Move the selection to the top of the table - - if (!mPluginsTable->selectionModel()->hasSelection()) { - return; - } - - QModelIndexList selectedIndexes = mPluginsTable->selectionModel()->selectedIndexes(); - - //sort selection ascending because selectedIndexes returns an unsorted list - qSort(selectedIndexes.begin(), selectedIndexes.end(), rowSmallerThan); - - QModelIndex firstIndex = mPluginsProxyModel->mapToSource(selectedIndexes.first()); - - // Check if the first selected plugin is the top one - if (firstIndex.row() == 0) { - return; - } - - for (int i=0; i < selectedIndexes.count(); ++i) { - - const QModelIndex sourceModelIndex = mPluginsProxyModel->mapToSource(selectedIndexes.at(i)); - - int currentRow = sourceModelIndex.row(); - - if (sourceModelIndex.isValid() && currentRow > 0) { - - mPluginsModel->insertRow(i, mPluginsModel->takeRow(currentRow)); - mPluginsTable->selectionModel()->select(mPluginsModel->index(i, 0, QModelIndex()), QItemSelectionModel::Select | QItemSelectionModel::Rows); - mPluginsTable->scrollToTop(); - } - } -} - -void DataFilesPage::moveBottom() -{ - // Move the selection to the bottom of the table - - if (!mPluginsTable->selectionModel()->hasSelection()) { - return; - } - - QModelIndexList selectedIndexes = mPluginsTable->selectionModel()->selectedIndexes(); - - //sort selection descending because selectedIndexes returns an unsorted list - qSort(selectedIndexes.begin(), selectedIndexes.end(), rowSmallerThan); - - const QModelIndex lastIndex = mPluginsProxyModel->mapToSource(selectedIndexes.last()); - - // Check if last selected plugin is bottom one - if ((lastIndex.row() + 1) == mPluginsModel->rowCount()) { - return; - } - - for (int i=0; i < selectedIndexes.count(); ++i) { - - const QModelIndex sourceModelIndex = mPluginsProxyModel->mapToSource(selectedIndexes.at(i)); - - // Subtract iterations because takeRow shifts the rows below the taken row up - int currentRow = sourceModelIndex.row() - i; - - if (sourceModelIndex.isValid() && (currentRow + 1) < mPluginsModel->rowCount()) { - mPluginsModel->appendRow(mPluginsModel->takeRow(currentRow)); - - // Rowcount starts with 1, row numbers start with 0 - const QModelIndex lastRow = mPluginsModel->index((mPluginsModel->rowCount() -1), 0, QModelIndex()); - - mPluginsTable->selectionModel()->select(lastRow, QItemSelectionModel::Select | QItemSelectionModel::Rows); - mPluginsTable->scrollToBottom(); - } - } -} - -void DataFilesPage::check() -{ - // Check the current selection - - if (!mPluginsTable->selectionModel()->hasSelection()) { - return; - } - - QModelIndexList selectedIndexes = mPluginsTable->selectionModel()->selectedIndexes(); - - //sort selection ascending because selectedIndexes returns an unsorted list - qSort(selectedIndexes.begin(), selectedIndexes.end(), rowSmallerThan); - - foreach (const QModelIndex ¤tIndex, selectedIndexes) { - QModelIndex sourceModelIndex = mPluginsProxyModel->mapToSource(currentIndex); - - if (sourceModelIndex.isValid()) { - mPluginsModel->setData(sourceModelIndex, Qt::Checked, Qt::CheckStateRole); - } - } -} - -void DataFilesPage::uncheck() -{ - // Uncheck the current selection - - if (!mPluginsTable->selectionModel()->hasSelection()) { - return; - } - - QModelIndexList selectedIndexes = mPluginsTable->selectionModel()->selectedIndexes(); - - //sort selection ascending because selectedIndexes returns an unsorted list - qSort(selectedIndexes.begin(), selectedIndexes.end(), rowSmallerThan); - - foreach (const QModelIndex ¤tIndex, selectedIndexes) { - QModelIndex sourceModelIndex = mPluginsProxyModel->mapToSource(currentIndex); - - if (sourceModelIndex.isValid()) { - mPluginsModel->setData(sourceModelIndex, Qt::Unchecked, Qt::CheckStateRole); - } - } -} - -void DataFilesPage::refresh() -{ - // Refresh the plugins table - - writeConfig(); - readConfig(); -} - -void DataFilesPage::scrollToSelection() -{ - // Scroll to the selected plugins - - if (!mPluginsTable->selectionModel()->hasSelection()) { - return; - } - - // Get the selected indexes visible by determining the middle index - QModelIndexList selectedIndexes = mPluginsTable->selectionModel()->selectedIndexes(); - qSort(selectedIndexes.begin(), selectedIndexes.end(), rowSmallerThan); - - // The selected rows including non-selected inside selection - unsigned int selectedRows = selectedIndexes.last().row() - selectedIndexes.first().row(); - - // Determine the row which is roughly in the middle of the selection - unsigned int middleRow = selectedIndexes.first().row() + (int)(selectedRows / 2) + 1; - - - const QModelIndex middleIndex = mPluginsProxyModel->mapFromSource(mPluginsModel->index(middleRow, 0, QModelIndex())); - - // Make sure the whole selection is visible - mPluginsTable->scrollTo(selectedIndexes.first()); - mPluginsTable->scrollTo(selectedIndexes.last()); - mPluginsTable->scrollTo(middleIndex); -} - -void DataFilesPage::showContextMenu(const QPoint &point) -{ - // Make sure there are plugins in the view - if (!mPluginsTable->selectionModel()->hasSelection()) { - return; - } - - QPoint globalPos = mPluginsTable->mapToGlobal(point); - - QModelIndexList selectedIndexes = mPluginsTable->selectionModel()->selectedIndexes(); - - // Show the check/uncheck actions depending on the state of the selected items - mUncheckAction->setEnabled(false); - mCheckAction->setEnabled(false); - - foreach (const QModelIndex ¤tIndex, selectedIndexes) { - if (currentIndex.isValid()) { - - const QModelIndex sourceIndex = mPluginsProxyModel->mapToSource(currentIndex); - - if (!sourceIndex.isValid()) { - return; - } - - const QStandardItem *currentItem = mPluginsModel->itemFromIndex(sourceIndex); - - if (currentItem->checkState() == Qt::Checked) { - mUncheckAction->setEnabled(true); - } else { - mCheckAction->setEnabled(true); - } - } - - } - - // Make sure these are enabled because they might still be disabled - mMoveUpAction->setEnabled(true); - mMoveTopAction->setEnabled(true); - mMoveDownAction->setEnabled(true); - mMoveBottomAction->setEnabled(true); - - QModelIndex firstIndex = mPluginsProxyModel->mapToSource(selectedIndexes.first()); - QModelIndex lastIndex = mPluginsProxyModel->mapToSource(selectedIndexes.last()); - - // Check if selected first item is top row in model - if (firstIndex.row() == 0) { - mMoveUpAction->setEnabled(false); - mMoveTopAction->setEnabled(false); - } - - // Check if last row is bottom row in model - if ((lastIndex.row() + 1) == mPluginsModel->rowCount()) { - mMoveDownAction->setEnabled(false); - mMoveBottomAction->setEnabled(false); - } - - // Show menu - mContextMenu->exec(globalPos); -} - -void DataFilesPage::masterSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) -{ - if (mMastersWidget->selectionModel()->hasSelection()) { - - QStringList masters; - QString masterstr; - - // Create a QStringList containing all the masters - const QStringList masterList = selectedMasters(); - - foreach (const QString ¤tMaster, masterList) { - masters.append(currentMaster); - } - - masters.sort(); - masterstr = masters.join(","); // Make a comma-separated QString - - // Iterate over all masters in the datafilesmodel to see if they are selected - for (int r=0; rrowCount(); ++r) { - QModelIndex currentIndex = mDataFilesModel->index(r, 0); - QString master = currentIndex.data().toString(); - - if (currentIndex.isValid()) { - // See if the current master is in the string with selected masters - if (masterstr.contains(master)) - { - // Append the plugins from the current master to pluginsmodel - addPlugins(currentIndex); - } - } - } - } - - // See what plugins to remove - QModelIndexList deselectedIndexes = deselected.indexes(); - - if (!deselectedIndexes.isEmpty()) { - foreach (const QModelIndex ¤tIndex, deselectedIndexes) { - - QString master = currentIndex.data().toString(); - master.prepend("*"); - master.append("*"); - const QList itemList = mDataFilesModel->findItems(master, Qt::MatchWildcard); - - foreach (const QStandardItem *currentItem, itemList) { - QModelIndex index = currentItem->index(); - removePlugins(index); - } - } - } - -} - -void DataFilesPage::addPlugins(const QModelIndex &index) -{ - // Find the plugins in the datafilesmodel and append them to the pluginsmodel - if (!index.isValid()) - return; - - for (int r=0; rrowCount(index); ++r ) { - QModelIndex childIndex = index.child(r, 0); - - if (childIndex.isValid()) { - // Now we see if the pluginsmodel already contains this plugin - const QString childIndexData = QVariant(mDataFilesModel->data(childIndex)).toString(); - const QString childIndexToolTip = QVariant(mDataFilesModel->data(childIndex, Qt::ToolTipRole)).toString(); - - const QList itemList = mPluginsModel->findItems(childIndexData); - - if (itemList.isEmpty()) - { - // Plugin not yet in the pluginsmodel, add it - QStandardItem *item = new QStandardItem(childIndexData); - item->setFlags(item->flags() & ~(Qt::ItemIsDropEnabled)); - item->setCheckable(true); - item->setToolTip(childIndexToolTip); - - mPluginsModel->appendRow(item); - } - } - - } - -} - -void DataFilesPage::removePlugins(const QModelIndex &index) -{ - - if (!index.isValid()) - return; - - for (int r=0; rrowCount(index); ++r) { - QModelIndex childIndex = index.child(r, 0); - - const QList itemList = mPluginsModel->findItems(QVariant(childIndex.data()).toString()); - - if (!itemList.isEmpty()) { - foreach (const QStandardItem *currentItem, itemList) { - mPluginsModel->removeRow(currentItem->row()); - } - } - } - -} - -void DataFilesPage::setCheckState(QModelIndex index) -{ - if (!index.isValid()) - return; - - QModelIndex sourceModelIndex = mPluginsProxyModel->mapToSource(index); - - if (mPluginsModel->data(sourceModelIndex, Qt::CheckStateRole) == Qt::Checked) { - // Selected row is checked, uncheck it - mPluginsModel->setData(sourceModelIndex, Qt::Unchecked, Qt::CheckStateRole); - } else { - mPluginsModel->setData(sourceModelIndex, Qt::Checked, Qt::CheckStateRole); - } -} - -const QStringList DataFilesPage::selectedMasters() -{ - QStringList masters; - const QList selectedMasters = mMastersWidget->selectedItems(); - - foreach (const QTableWidgetItem *item, selectedMasters) { - masters.append(item->data(Qt::DisplayRole).toString()); - } - - return masters; -} - -const QStringList DataFilesPage::checkedPlugins() -{ - QStringList checkedItems; - - for (int r=0; rrowCount(); ++r ) { - QModelIndex index = mPluginsModel->index(r, 0); - - if (index.isValid()) { - // See if the current item is checked - if (mPluginsModel->data(index, Qt::CheckStateRole) == Qt::Checked) { - checkedItems.append(index.data().toString()); - } - } - } - return checkedItems; -} - -void DataFilesPage::uncheckPlugins() -{ - for (int r=0; rrowCount(); ++r ) { - QModelIndex index = mPluginsModel->index(r, 0); - - if (index.isValid()) { - // See if the current item is checked - if (mPluginsModel->data(index, Qt::CheckStateRole) == Qt::Checked) { - mPluginsModel->setData(index, Qt::Unchecked, Qt::CheckStateRole); - } - } - } -} - -void DataFilesPage::filterChanged(const QString filter) -{ - QRegExp regExp(filter, Qt::CaseInsensitive, QRegExp::FixedString); - mPluginsProxyModel->setFilterRegExp(regExp); -} - -void DataFilesPage::profileChanged(const QString &previous, const QString ¤t) -{ - // Prevent the deletion of the default profile - if (current == "Default") { - mDeleteProfileAction->setEnabled(false); - } else { - mDeleteProfileAction->setEnabled(true); - } - - if (!previous.isEmpty()) { - writeConfig(previous); - mLauncherConfig->sync(); - } else { - return; - } - - uncheckPlugins(); - // Deselect the masters - mMastersWidget->selectionModel()->clearSelection(); - readConfig(); -} - void DataFilesPage::readConfig() { + // Don't read the config if no masters are found + if (mMastersModel->rowCount() < 1) + return; + QString profile = mProfilesComboBox->currentText(); // Make sure we have no groups open @@ -1027,46 +292,170 @@ void DataFilesPage::readConfig() const QString keyValue = mLauncherConfig->value(key).toString(); if (key.startsWith("Plugin")) { - plugins.append(keyValue); - continue; + //QStringList checked = mPluginsModel->checkedItems(); + EsmFile *file = mPluginsModel->findItem(keyValue); + QModelIndex index = mPluginsModel->indexFromItem(file); + + mPluginsModel->setCheckState(index, Qt::Checked); + // Move the row to the top of te view + //mPluginsModel->moveRow(index.row(), checked.count()); + plugins << keyValue; } if (key.startsWith("Master")) { - const QList masterList = mMastersWidget->findItems(keyValue, Qt::MatchFixedString); - - if (!masterList.isEmpty()) { - foreach (QTableWidgetItem *currentMaster, masterList) { - mMastersWidget->selectionModel()->select(mMastersWidget->model()->index(currentMaster->row(), 0), QItemSelectionModel::Select); - } - } + EsmFile *file = mMastersModel->findItem(keyValue); + mMastersModel->setCheckState(mMastersModel->indexFromItem(file), Qt::Checked); } } + qDebug() << plugins; + + +// // Set the checked item positions +// const QStringList checked = mPluginsModel->checkedItems(); +// for (int i = 0; i < plugins.size(); ++i) { +// EsmFile *file = mPluginsModel->findItem(plugins.at(i)); +// QModelIndex index = mPluginsModel->indexFromItem(file); +// mPluginsModel->moveRow(index.row(), i); +// qDebug() << "Moving: " << plugins.at(i) << " from: " << index.row() << " to: " << i << " count: " << checked.count(); + +// } + // Iterate over the plugins to set their checkstate and position - for (int i = 0; i < plugins.size(); ++i) { - const QString plugin = plugins.at(i); +// for (int i = 0; i < plugins.size(); ++i) { +// const QString plugin = plugins.at(i); - const QList pluginList = mPluginsModel->findItems(plugin); +// const QList pluginList = mPluginsModel->findItems(plugin); - if (!pluginList.isEmpty()) - { - foreach (const QStandardItem *currentPlugin, pluginList) { - mPluginsModel->setData(currentPlugin->index(), Qt::Checked, Qt::CheckStateRole); +// if (!pluginList.isEmpty()) +// { +// foreach (const QStandardItem *currentPlugin, pluginList) { +// mPluginsModel->setData(currentPlugin->index(), Qt::Checked, Qt::CheckStateRole); - // Move the plugin to the position specified in the config file - mPluginsModel->insertRow(i, mPluginsModel->takeRow(currentPlugin->row())); - } +// // Move the plugin to the position specified in the config file +// mPluginsModel->insertRow(i, mPluginsModel->takeRow(currentPlugin->row())); +// } +// } +// } + +} + +bool DataFilesPage::showDataFilesWarning() +{ + + QMessageBox msgBox; + msgBox.setWindowTitle("Error detecting Morrowind installation"); + msgBox.setIcon(QMessageBox::Warning); + msgBox.setStandardButtons(QMessageBox::Cancel); + msgBox.setText(tr("
Could not find the Data Files location

\ + The directory containing the data files was not found.

\ + Press \"Browse...\" to specify the location manually.
")); + + QAbstractButton *dirSelectButton = + msgBox.addButton(tr("B&rowse..."), QMessageBox::ActionRole); + + msgBox.exec(); + + if (msgBox.clickedButton() == dirSelectButton) { + + // Show a custom dir selection dialog which only accepts valid dirs + QString selectedDir = FileDialog::getExistingDirectory( + this, tr("Select Data Files Directory"), + QDir::currentPath(), + QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + + // Add the user selected data directory + if (!selectedDir.isEmpty()) { + mDataDirs.push_back(Files::PathContainer::value_type(selectedDir.toStdString())); + mCfgMgr.processPaths(mDataDirs); + } else { + // Cancel from within the dir selection dialog + return false; } + + } else { + // Cancel + return false; } + return true; +} + +bool DataFilesPage::setupDataFiles() +{ + // We use the Configuration Manager to retrieve the configuration values + boost::program_options::variables_map variables; + boost::program_options::options_description desc; + + desc.add_options() + ("data", boost::program_options::value()->default_value(Files::PathContainer(), "data")->multitoken()) + ("data-local", boost::program_options::value()->default_value("")) + ("fs-strict", boost::program_options::value()->implicit_value(true)->default_value(false)) + ("encoding", boost::program_options::value()->default_value("win1252")); + + boost::program_options::notify(variables); + + mCfgMgr.readConfiguration(variables, desc); + + if (variables["data"].empty()) { + if (!showDataFilesWarning()) + return false; + } else { + mDataDirs = Files::PathContainer(variables["data"].as()); + } + + std::string local = variables["data-local"].as(); + if (!local.empty()) { + mDataLocal.push_back(Files::PathContainer::value_type(local)); + } + + mCfgMgr.processPaths(mDataDirs); + mCfgMgr.processPaths(mDataLocal); + + // Second chance to display the warning, the data= entries are invalid + while (mDataDirs.empty()) { + if (!showDataFilesWarning()) + return false; + } + + // Set the charset for reading the esm/esp files + QString encoding = QString::fromStdString(variables["encoding"].as()); + if (!encoding.isEmpty() && encoding != QLatin1String("win1252")) { + mMastersModel->setEncoding(encoding); + mPluginsModel->setEncoding(encoding); + } + + // Add the paths to the respective models + for (Files::PathContainer::iterator it = mDataDirs.begin(); it != mDataDirs.end(); ++it) { + QString path = QString::fromStdString(it->string()); + path.remove(QChar('\"')); + mMastersModel->addMasters(path); + mPluginsModel->addPlugins(path); + } + + // Same for the data-local paths + for (Files::PathContainer::iterator it = mDataLocal.begin(); it != mDataLocal.end(); ++it) { + QString path = QString::fromStdString(it->string()); + path.remove(QChar('\"')); + mMastersModel->addMasters(path); + mPluginsModel->addPlugins(path); + } + + mMastersModel->sort(0); + mPluginsModel->sort(0); +// mMastersTable->sortByColumn(3, Qt::AscendingOrder); +// mPluginsTable->sortByColumn(3, Qt::AscendingOrder); + + + readConfig(); + return true; } void DataFilesPage::writeConfig(QString profile) { // Don't overwrite the config if no masters are found - if (mMastersWidget->rowCount() < 1) { + if (mMastersModel->rowCount() < 1) return; - } QString pathStr = QString::fromStdString(mCfgMgr.getUserPath().string()); QDir userPath(pathStr); @@ -1150,13 +539,11 @@ void DataFilesPage::writeConfig(QString profile) path = QString::fromStdString(it->string()); path.remove(QChar('\"')); - QDir dir(path); - // Make sure the string is quoted when it contains spaces if (path.contains(" ")) { - gameConfig << "data=\"" << dir.absolutePath() << "\"" << endl; + gameConfig << "data=\"" << path << "\"" << endl; } else { - gameConfig << "data=" << dir.absolutePath() << endl; + gameConfig << "data=" << path << endl; } } @@ -1165,23 +552,19 @@ void DataFilesPage::writeConfig(QString profile) path = QString::fromStdString(mDataLocal.front().string()); path.remove(QChar('\"')); - QDir dir(path); - if (path.contains(" ")) { - gameConfig << "data-local=\"" << dir.absolutePath() << "\"" << endl; + gameConfig << "data-local=\"" << path << "\"" << endl; } else { - gameConfig << "data-local=" << dir.absolutePath() << endl; + gameConfig << "data-local=" << path << endl; } } - if (profile.isEmpty()) { + if (profile.isEmpty()) profile = mProfilesComboBox->currentText(); - } - if (profile.isEmpty()) { + if (profile.isEmpty()) return; - } // Make sure we have no groups open while (!mLauncherConfig->group().isEmpty()) { @@ -1196,7 +579,7 @@ void DataFilesPage::writeConfig(QString profile) mLauncherConfig->remove(""); // Clear the subgroup // Now write the masters to the configs - const QStringList masters = selectedMasters(); + const QStringList masters = mMastersModel->checkedItems(); // We don't use foreach because we need i for (int i = 0; i < masters.size(); ++i) { @@ -1208,7 +591,7 @@ void DataFilesPage::writeConfig(QString profile) } // And finally write all checked plugins - const QStringList plugins = checkedPlugins(); + const QStringList plugins = mPluginsModel->checkedItems(); for (int i = 0; i < plugins.size(); ++i) { const QString currentPlugin = plugins.at(i); @@ -1221,3 +604,241 @@ void DataFilesPage::writeConfig(QString profile) mLauncherConfig->endGroup(); mLauncherConfig->sync(); } + + +void DataFilesPage::newProfile() +{ + if (mNewProfileDialog->exec() == QDialog::Accepted) { + + const QString text = mNewProfileDialog->lineEdit()->text(); + mProfilesComboBox->addItem(text); + + // Copy the currently checked items to cfg + writeConfig(text); + mLauncherConfig->sync(); + + mProfilesComboBox->setCurrentIndex(mProfilesComboBox->findText(text)); + } +} + +void DataFilesPage::updateOkButton(const QString &text) +{ + if (text.isEmpty()) { + mNewProfileDialog->setOkButtonEnabled(false); + return; + } + + (mProfilesComboBox->findText(text) == -1) + ? mNewProfileDialog->setOkButtonEnabled(true) + : mNewProfileDialog->setOkButtonEnabled(false); +} + +void DataFilesPage::deleteProfile() +{ + QString profile = mProfilesComboBox->currentText(); + + if (profile.isEmpty()) + return; + + QMessageBox msgBox(this); + msgBox.setWindowTitle(tr("Delete Profile")); + msgBox.setIcon(QMessageBox::Warning); + msgBox.setStandardButtons(QMessageBox::Cancel); + msgBox.setText(tr("Are you sure you want to delete %0?").arg(profile)); + + QAbstractButton *deleteButton = + msgBox.addButton(tr("Delete"), QMessageBox::ActionRole); + + msgBox.exec(); + + if (msgBox.clickedButton() == deleteButton) { + // Make sure we have no groups open + while (!mLauncherConfig->group().isEmpty()) { + mLauncherConfig->endGroup(); + } + + mLauncherConfig->beginGroup("Profiles"); + + // Open the profile-name subgroup + mLauncherConfig->beginGroup(profile); + mLauncherConfig->remove(""); // Clear the subgroup + mLauncherConfig->endGroup(); + mLauncherConfig->endGroup(); + + // Remove the profile from the combobox + mProfilesComboBox->removeItem(mProfilesComboBox->findText(profile)); + } +} + +void DataFilesPage::check() +{ + // Check the current selection + if (!mPluginsTable->selectionModel()->hasSelection()) { + return; + } + + QModelIndexList indexes = mPluginsTable->selectionModel()->selectedIndexes(); + + //sort selection ascending because selectedIndexes returns an unsorted list + //qSort(indexes.begin(), indexes.end(), rowSmallerThan); + + foreach (const QModelIndex &index, indexes) { + if (!index.isValid()) + return; + + mPluginsModel->setCheckState(index, Qt::Checked); + } +} + +void DataFilesPage::uncheck() +{ + // uncheck the current selection + if (!mPluginsTable->selectionModel()->hasSelection()) { + return; + } + + QModelIndexList indexes = mPluginsTable->selectionModel()->selectedIndexes(); + + //sort selection ascending because selectedIndexes returns an unsorted list + //qSort(indexes.begin(), indexes.end(), rowSmallerThan); + + foreach (const QModelIndex &index, indexes) { + if (!index.isValid()) + return; + + mPluginsModel->setCheckState(index, Qt::Unchecked); + } +} + +void DataFilesPage::refresh() +{ + mPluginsModel->sort(0); + + + // Refresh the plugins table + mPluginsTable->scrollToTop(); + writeConfig(); + readConfig(); +} + + +void DataFilesPage::setCheckState(QModelIndex index) +{ + if (!index.isValid()) + return; + + QObject *object = QObject::sender(); + + // Not a signal-slot call + if (!object) + return; + + if (object->objectName() == QLatin1String("PluginsTable")) { + QModelIndex sourceIndex = mPluginsProxyModel->mapToSource(index); + + (mPluginsModel->checkState(sourceIndex) == Qt::Checked) + ? mPluginsModel->setCheckState(sourceIndex, Qt::Unchecked) + : mPluginsModel->setCheckState(sourceIndex, Qt::Checked); + } + + if (object->objectName() == QLatin1String("MastersTable")) { + (mMastersModel->checkState(index) == Qt::Checked) + ? mMastersModel->setCheckState(index, Qt::Unchecked) + : mMastersModel->setCheckState(index, Qt::Checked); + } + + return; + +} + +void DataFilesPage::filterChanged(const QString filter) +{ + QRegExp regExp(filter, Qt::CaseInsensitive, QRegExp::FixedString); + mPluginsProxyModel->setFilterRegExp(regExp); +} + +void DataFilesPage::profileChanged(const QString &previous, const QString ¤t) +{ + qDebug() << "Profile is changed from: " << previous << " to " << current; + // Prevent the deletion of the default profile + if (current == QLatin1String("Default")) { + mDeleteProfileAction->setEnabled(false); + mProfilesComboBox->setEditEnabled(false); + } else { + mDeleteProfileAction->setEnabled(true); + mProfilesComboBox->setEditEnabled(true); + } + + if (!previous.isEmpty()) { + writeConfig(previous); + mLauncherConfig->sync(); + + if (mProfilesComboBox->currentIndex() == -1) + return; + + } else { + return; + } + + mMastersModel->uncheckAll(); + mPluginsModel->uncheckAll(); + readConfig(); +} + +void DataFilesPage::profileRenamed(const QString &previous, const QString ¤t) +{ + if (previous.isEmpty()) + return; + + // Save the new profile name + writeConfig(current); + + // Make sure we have no groups open + while (!mLauncherConfig->group().isEmpty()) { + mLauncherConfig->endGroup(); + } + + mLauncherConfig->beginGroup("Profiles"); + + // Open the profile-name subgroup + mLauncherConfig->beginGroup(previous); + mLauncherConfig->remove(""); // Clear the subgroup + mLauncherConfig->endGroup(); + mLauncherConfig->endGroup(); + mLauncherConfig->sync(); + + // Remove the profile from the combobox + mProfilesComboBox->removeItem(mProfilesComboBox->findText(previous)); + + mMastersModel->uncheckAll(); + mPluginsModel->uncheckAll(); + readConfig(); +} + +void DataFilesPage::showContextMenu(const QPoint &point) +{ + // Make sure there are plugins in the view + if (!mPluginsTable->selectionModel()->hasSelection()) { + return; + } + + QPoint globalPos = mPluginsTable->mapToGlobal(point); + + QModelIndexList indexes = mPluginsTable->selectionModel()->selectedIndexes(); + + // Show the check/uncheck actions depending on the state of the selected items + mUncheckAction->setEnabled(false); + mCheckAction->setEnabled(false); + + foreach (const QModelIndex &index, indexes) { + if (!index.isValid()) + return; + + (mPluginsModel->checkState(index) == Qt::Checked) + ? mUncheckAction->setEnabled(true) + : mCheckAction->setEnabled(true); + } + + // Show menu + mContextMenu->exec(globalPos); +} diff --git a/apps/launcher/datafilespage.hpp b/apps/launcher/datafilespage.hpp index 83b318677..13668ec30 100644 --- a/apps/launcher/datafilespage.hpp +++ b/apps/launcher/datafilespage.hpp @@ -3,24 +3,20 @@ #include #include - +#include "utils/profilescombobox.hpp" #include -#include "combobox.hpp" -class QTableWidget; -class QStandardItemModel; -class QItemSelection; -class QItemSelectionModel; +class QTableView; class QSortFilterProxyModel; -class QStringListModel; class QSettings; class QAction; class QToolBar; class QMenu; -class PluginsModel; -class PluginsView; -class ComboBox; +class ProfilesComboBox; +class DataFilesModel; + +class TextInputDialog; namespace Files { struct ConfigurationManager; } @@ -31,52 +27,51 @@ class DataFilesPage : public QWidget public: DataFilesPage(Files::ConfigurationManager& cfg, QWidget *parent = 0); - ComboBox *mProfilesComboBox; + ProfilesComboBox *mProfilesComboBox; void writeConfig(QString profile = QString()); + bool showDataFilesWarning(); bool setupDataFiles(); public slots: - void masterSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void setCheckState(QModelIndex index); void filterChanged(const QString filter); void showContextMenu(const QPoint &point); void profileChanged(const QString &previous, const QString ¤t); + void profileRenamed(const QString &previous, const QString ¤t); + void updateOkButton(const QString &text); // Action slots void newProfile(); - void copyProfile(); void deleteProfile(); - void moveUp(); - void moveDown(); - void moveTop(); - void moveBottom(); +// void moveUp(); +// void moveDown(); +// void moveTop(); +// void moveBottom(); void check(); void uncheck(); void refresh(); private: - QTableWidget *mMastersWidget; - PluginsView *mPluginsTable; - - QStandardItemModel *mDataFilesModel; - PluginsModel *mPluginsModel; + DataFilesModel *mMastersModel; + DataFilesModel *mPluginsModel; QSortFilterProxyModel *mPluginsProxyModel; - QItemSelectionModel *mPluginsSelectModel; + + QTableView *mMastersTable; + QTableView *mPluginsTable; QToolBar *mProfileToolBar; QMenu *mContextMenu; QAction *mNewProfileAction; - QAction *mCopyProfileAction; QAction *mDeleteProfileAction; - QAction *mMoveUpAction; - QAction *mMoveDownAction; - QAction *mMoveTopAction; - QAction *mMoveBottomAction; +// QAction *mMoveUpAction; +// QAction *mMoveDownAction; +// QAction *mMoveTopAction; +// QAction *mMoveBottomAction; QAction *mCheckAction; QAction *mUncheckAction; @@ -86,17 +81,14 @@ private: QSettings *mLauncherConfig; - const QStringList checkedPlugins(); - const QStringList selectedMasters(); + TextInputDialog *mNewProfileDialog; + +// const QStringList checkedPlugins(); +// const QStringList selectedMasters(); - void addDataFiles(Files::Collections &fileCollections, const QString &encoding); - void addPlugins(const QModelIndex &index); - void removePlugins(const QModelIndex &index); - void uncheckPlugins(); void createActions(); void setupConfig(); void readConfig(); - void scrollToSelection(); }; diff --git a/apps/launcher/graphicspage.cpp b/apps/launcher/graphicspage.cpp index c3c39cffc..2c4f3430c 100644 --- a/apps/launcher/graphicspage.cpp +++ b/apps/launcher/graphicspage.cpp @@ -9,8 +9,9 @@ #include #include +#include "utils/naturalsort.hpp" + #include "graphicspage.hpp" -#include "naturalsort.hpp" QString getAspect(int x, int y) { @@ -280,20 +281,18 @@ QStringList GraphicsPage::getAvailableResolutions(Ogre::RenderSystem *renderer) assert (tokens.size() >= 3); QString resolutionStr = tokens.at(0) + QString(" x ") + tokens.at(2); - // do not add duplicate resolutions - if (!result.contains(resolutionStr)) { + QString aspect = getAspect(tokens.at(0).toInt(),tokens.at(2).toInt()); - QString aspect = getAspect(tokens.at(0).toInt(),tokens.at(2).toInt()); + if (aspect == QLatin1String("16:9") || aspect == QLatin1String("16:10")) { + resolutionStr.append(tr("\t(Widescreen ") + aspect + ")"); - if (aspect == QLatin1String("16:9") || aspect == QLatin1String("16:10")) { - resolutionStr.append(tr("\t(Widescreen ") + aspect + ")"); - - } else if (aspect == QLatin1String("4:3")) { - resolutionStr.append(tr("\t(Standard 4:3)")); - } - - result << resolutionStr; + } else if (aspect == QLatin1String("4:3")) { + resolutionStr.append(tr("\t(Standard 4:3)")); } + + // do not add duplicate resolutions + if (!result.contains(resolutionStr)) + result << resolutionStr; } } diff --git a/apps/launcher/main.cpp b/apps/launcher/main.cpp index 4ae09f844..7c4cb5f7e 100644 --- a/apps/launcher/main.cpp +++ b/apps/launcher/main.cpp @@ -11,7 +11,7 @@ int main(int argc, char *argv[]) // Now we make sure the current dir is set to application path QDir dir(QCoreApplication::applicationDirPath()); - #if defined(Q_OS_MAC) + #ifdef Q_OS_MAC if (dir.dirName() == "MacOS") { dir.cdUp(); dir.cdUp(); diff --git a/apps/launcher/maindialog.cpp b/apps/launcher/maindialog.cpp index f7dafd3af..674ccdf67 100644 --- a/apps/launcher/maindialog.cpp +++ b/apps/launcher/maindialog.cpp @@ -141,11 +141,11 @@ void MainDialog::createPages() connect(mPlayPage->mProfilesComboBox, SIGNAL(currentIndexChanged(int)), - this, SLOT(profileChanged(int))); + mDataFilesPage->mProfilesComboBox, SLOT(setCurrentIndex(int))); connect(mDataFilesPage->mProfilesComboBox, SIGNAL(currentIndexChanged(int)), - this, SLOT(profileChanged(int))); + mPlayPage->mProfilesComboBox, SLOT(setCurrentIndex(int))); } @@ -196,23 +196,6 @@ bool MainDialog::setup() return true; } -void MainDialog::profileChanged(int index) -{ - // Just to be sure, should always have a selection - if (!mIconWidget->selectionModel()->hasSelection()) { - return; - } - - QString currentPage = mIconWidget->currentItem()->data(Qt::DisplayRole).toString(); - if (currentPage == QLatin1String("Play")) { - mDataFilesPage->mProfilesComboBox->setCurrentIndex(index); - } - - if (currentPage == QLatin1String("Data Files")) { - mPlayPage->mProfilesComboBox->setCurrentIndex(index); - } -} - void MainDialog::changePage(QListWidgetItem *current, QListWidgetItem *previous) { if (!current) @@ -244,10 +227,10 @@ void MainDialog::play() const std::string settingspath = (mCfgMgr.getUserPath() / "settings.cfg").string(); mSettings.saveUser(settingspath); -#ifdef Q_WS_WIN +#ifdef Q_OS_WIN QString game = "./openmw.exe"; QFile file(game); -#elif defined(Q_WS_MAC) +#elif defined(Q_OS_MAC) QDir dir(QCoreApplication::applicationDirPath()); QString game = dir.absoluteFilePath("openmw"); QFile file(game); diff --git a/apps/launcher/maindialog.hpp b/apps/launcher/maindialog.hpp index 683cd58c2..bf98011cc 100644 --- a/apps/launcher/maindialog.hpp +++ b/apps/launcher/maindialog.hpp @@ -27,7 +27,6 @@ public: public slots: void changePage(QListWidgetItem *current, QListWidgetItem *previous); void play(); - void profileChanged(int index); bool setup(); private: diff --git a/apps/launcher/model/datafilesmodel.cpp b/apps/launcher/model/datafilesmodel.cpp new file mode 100644 index 000000000..d85a15e73 --- /dev/null +++ b/apps/launcher/model/datafilesmodel.cpp @@ -0,0 +1,476 @@ +#include +#include +#include + +#include + +#include + +#include "esm/esmfile.hpp" + +#include "../utils/naturalsort.hpp" + +#include "datafilesmodel.hpp" + +DataFilesModel::DataFilesModel(QObject *parent) : + QAbstractTableModel(parent) +{ + mEncoding = QString("win1252"); +} + +DataFilesModel::~DataFilesModel() +{ +} + +void DataFilesModel::setEncoding(const QString &encoding) +{ + mEncoding = encoding; +} + +void DataFilesModel::setCheckState(const QModelIndex &index, Qt::CheckState state) +{ + setData(index, state, Qt::CheckStateRole); +} + +Qt::CheckState DataFilesModel::checkState(const QModelIndex &index) +{ + EsmFile *file = item(index.row()); + return mCheckStates[file->fileName()]; +} + +int DataFilesModel::columnCount(const QModelIndex &parent) const +{ + return parent.isValid() ? 0 : 9; +} + +int DataFilesModel::rowCount(const QModelIndex &parent) const +{ + return parent.isValid() ? 0 : mFiles.count(); +} + + +bool DataFilesModel::moveRow(int oldrow, int row, const QModelIndex &parent) +{ + if (oldrow < 0 || row < 0 || oldrow == row) + return false; + + emit layoutAboutToBeChanged(); + //emit beginMoveRows(parent, oldrow, oldrow, parent, row); + mFiles.swap(oldrow, row); + //emit endInsertRows(); + emit layoutChanged(); + + return true; +} + +QVariant DataFilesModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + + EsmFile *file = item(index.row()); + + if (!file) + return QVariant(); + + const int column = index.column(); + + switch (role) { + case Qt::DisplayRole: { + + switch (column) { + case 0: + return file->fileName(); + case 1: + return file->author(); + case 2: + return QString("%1 kB").arg(int((file->size() + 1023) / 1024)); + case 3: + //return file->modified().toString(Qt::TextDate); + return file->modified().toString(Qt::ISODate); + case 4: + return file->accessed().toString(Qt::TextDate); + case 5: + return file->version(); + case 6: + return file->path(); + case 7: + return file->masters().join(", "); + case 8: + return file->description(); + } + } + + case Qt::TextAlignmentRole: { + switch (column) { + case 0: + case 1: + return Qt::AlignLeft + Qt::AlignVCenter; + case 2: + case 3: + case 4: + case 5: + return Qt::AlignRight + Qt::AlignVCenter; + default: + return Qt::AlignLeft + Qt::AlignVCenter; + } + } + + case Qt::CheckStateRole: { + if (column != 0) + return QVariant(); + return mCheckStates[file->fileName()]; + } + case Qt::ToolTipRole: + { + if (column != 0) + return QVariant(); + + if (file->version() == 0.0f) + return QVariant(); // Data not set + + QString tooltip = + QString("Author: %1
\ + Version: %2
\ +
Description:
%3
\ +
Dependencies: %4
") + .arg(file->author()) + .arg(QString::number(file->version())) + .arg(file->description()) + .arg(file->masters().join(", ")); + + + return tooltip; + + } + default: + return QVariant(); + } + +} + +Qt::ItemFlags DataFilesModel::flags(const QModelIndex &index) const +{ + if (!index.isValid()) + return Qt::NoItemFlags; + + EsmFile *file = item(index.row()); + + if (!file) + return Qt::NoItemFlags; + + if (mAvailableFiles.contains(file->fileName())) { + if (index.column() == 0) { + return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; + } else { + return Qt::ItemIsEnabled | Qt::ItemIsSelectable; + } + } else { + if (index.column() == 0) { + return Qt::ItemIsUserCheckable | Qt::ItemIsSelectable; + } else { + return Qt::NoItemFlags | Qt::ItemIsSelectable; + } + } + +} + +QVariant DataFilesModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + if (role != Qt::DisplayRole) + return QVariant(); + + if (orientation == Qt::Horizontal) { + switch (section) { + case 0: return tr("Name"); + case 1: return tr("Author"); + case 2: return tr("Size"); + case 3: return tr("Modified"); + case 4: return tr("Accessed"); + case 5: return tr("Version"); + case 6: return tr("Path"); + case 7: return tr("Masters"); + case 8: return tr("Description"); + } + } else { + // Show row numbers + return ++section; + } + + return QVariant(); +} + +bool DataFilesModel::setData(const QModelIndex &index, const QVariant &value, int role) +{ + if (!index.isValid()) + return false; + + if (role == Qt::CheckStateRole) { + + emit layoutAboutToBeChanged(); + + QString name = item(index.row())->fileName(); + mCheckStates[name] = static_cast(value.toInt()); + + emit checkedItemsChanged(checkedItems(), uncheckedItems()); + emit layoutChanged(); + return true; + } + + return false; +} + +void DataFilesModel::sort(int column, Qt::SortOrder order) +{ + // TODO: Make this more efficient + emit layoutAboutToBeChanged(); + + QList sortedFiles; + + QMultiMap timestamps; + + foreach (EsmFile *file, mFiles) + timestamps.insert(file->modified().toString(Qt::ISODate), file->fileName()); + + QMapIterator ti(timestamps); + + while (ti.hasNext()) { + ti.next(); + + QModelIndex index = indexFromItem(findItem(ti.value())); + + if (!index.isValid()) + continue; + + EsmFile *file = item(index.row()); + + if (!file) + continue; + + sortedFiles.append(file); + } + + mFiles.clear(); + mFiles = sortedFiles; + + emit layoutChanged(); +} + +void DataFilesModel::addFile(EsmFile *file) +{ + emit beginInsertRows(QModelIndex(), mFiles.count(), mFiles.count()); + mFiles.append(file); + emit endInsertRows(); +} + +void DataFilesModel::addMasters(const QString &path) +{ + QDir dir(path); + dir.setNameFilters(QStringList(QLatin1String("*.esp"))); + + // Read the dependencies from the plugins + foreach (const QString &path, dir.entryList()) { + try { + ESM::ESMReader fileReader; + fileReader.setEncoding(mEncoding.toStdString()); + fileReader.open(dir.absoluteFilePath(path).toStdString()); + + ESM::ESMReader::MasterList mlist = fileReader.getMasters(); + + for (unsigned int i = 0; i < mlist.size(); ++i) { + QString master = QString::fromStdString(mlist[i].name); + + // Add the plugin to the internal dependency map + mDependencies[master].append(path); + + // Don't add esps + if (master.endsWith(".esp", Qt::CaseInsensitive)) + continue; + + QFileInfo info(dir.absoluteFilePath(master)); + + EsmFile *file = new EsmFile(master); + file->setDates(info.lastModified(), info.lastRead()); + + // Add the master to the table + if (findItem(master) == 0) + addFile(file); + + + } + + } catch(std::runtime_error &e) { + // An error occurred while reading the .esp + qWarning() << "Error reading esp: " << e.what(); + continue; + } + } + + // See if the masters actually exist in the filesystem + dir.setNameFilters(QStringList(QLatin1String("*.esm"))); + + foreach (const QString &path, dir.entryList()) { + QFileInfo info(dir.absoluteFilePath(path)); + + if (findItem(path) == 0) { + EsmFile *file = new EsmFile(path); + file->setDates(info.lastModified(), info.lastRead()); + + addFile(file); + } + + // Make the master selectable + mAvailableFiles.append(path); + } +} + +void DataFilesModel::addPlugins(const QString &path) +{ + QDir dir(path); + dir.setNameFilters(QStringList(QLatin1String("*.esp"))); + + foreach (const QString &path, dir.entryList()) { + QFileInfo info(dir.absoluteFilePath(path)); + EsmFile *file = new EsmFile(path); + + try { + ESM::ESMReader fileReader; + fileReader.setEncoding(mEncoding.toStdString()); + fileReader.open(dir.absoluteFilePath(path).toStdString()); + + ESM::ESMReader::MasterList mlist = fileReader.getMasters(); + QStringList masters; + + for (unsigned int i = 0; i < mlist.size(); ++i) { + QString master = QString::fromStdString(mlist[i].name); + masters.append(master); + + // Add the plugin to the internal dependency map + mDependencies[master].append(path); + } + + file->setAuthor(QString::fromStdString(fileReader.getAuthor())); + file->setSize(info.size()); + file->setDates(info.lastModified(), info.lastRead()); + file->setVersion(fileReader.getFVer()); + file->setPath(info.absoluteFilePath()); + file->setMasters(masters); + file->setDescription(QString::fromStdString(fileReader.getDesc())); + + + // Put the file in the table + addFile(file); + } catch(std::runtime_error &e) { + // An error occurred while reading the .esp + qWarning() << "Error reading esp: " << e.what(); + continue; + } + + } +} + +QModelIndex DataFilesModel::indexFromItem(EsmFile *item) const +{ + if (item) + return createIndex(mFiles.indexOf(item), 0); + + return QModelIndex(); +} + +EsmFile* DataFilesModel::findItem(const QString &name) +{ + QList::ConstIterator it; + QList::ConstIterator itEnd = mFiles.constEnd(); + + int i = 0; + for (it = mFiles.constBegin(); it != itEnd; ++it) { + EsmFile *file = item(i); + ++i; + + if (name == file->fileName()) + return file; + } + + // Not found + return 0; +} + +EsmFile* DataFilesModel::item(int row) const +{ + if (row >= 0 && row < mFiles.count()) + return mFiles.at(row); + else + return 0; +} + +QStringList DataFilesModel::checkedItems() +{ + QStringList list; + + QList::ConstIterator it; + QList::ConstIterator itEnd = mFiles.constEnd(); + + int i = 0; + for (it = mFiles.constBegin(); it != itEnd; ++it) { + EsmFile *file = item(i); + ++i; + + QString name = file->fileName(); + + // Only add the items that are in the checked list and available + if (mCheckStates[name] == Qt::Checked && mAvailableFiles.contains(name)) + list << name; + } + + return list; +} + +void DataFilesModel::uncheckAll() +{ + emit layoutAboutToBeChanged(); + mCheckStates.clear(); + emit layoutChanged(); +} + +QStringList DataFilesModel::uncheckedItems() +{ + QStringList list; + QStringList checked = checkedItems(); + + QList::ConstIterator it; + QList::ConstIterator itEnd = mFiles.constEnd(); + + int i = 0; + for (it = mFiles.constBegin(); it != itEnd; ++it) { + EsmFile *file = item(i); + ++i; + + // Add the items that are not in the checked list + if (!checked.contains(file->fileName())) + list << file->fileName(); + } + + return list; +} + +void DataFilesModel::slotcheckedItemsChanged(const QStringList &checkedItems, const QStringList &unCheckedItems) +{ + emit layoutAboutToBeChanged(); + + QStringList list; + + foreach (const QString &file, checkedItems) { + list << mDependencies[file]; + } + + foreach (const QString &file, unCheckedItems) { + foreach (const QString &remove, mDependencies[file]) { + list.removeAll(remove); + } + } + + mAvailableFiles.clear(); + mAvailableFiles.append(list); + + emit layoutChanged(); +} diff --git a/apps/launcher/model/datafilesmodel.hpp b/apps/launcher/model/datafilesmodel.hpp new file mode 100644 index 000000000..29a770a86 --- /dev/null +++ b/apps/launcher/model/datafilesmodel.hpp @@ -0,0 +1,71 @@ +#ifndef DATAFILESMODEL_HPP +#define DATAFILESMODEL_HPP + +#include +#include +#include +#include + + +class EsmFile; + +class DataFilesModel : public QAbstractTableModel +{ + Q_OBJECT + +public: + explicit DataFilesModel(QObject *parent = 0); + virtual ~DataFilesModel(); + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; + + bool moveRow(int oldrow, int row, const QModelIndex &parent = QModelIndex()); + + virtual Qt::ItemFlags flags(const QModelIndex &index) const; + + virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + + virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); + void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); + + inline QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const + { return QAbstractTableModel::index(row, column, parent); } + + void setEncoding(const QString &encoding); + + void addFile(EsmFile *file); + + void addMasters(const QString &path); + void addPlugins(const QString &path); + + void uncheckAll(); + + QStringList checkedItems(); + QStringList uncheckedItems(); + + Qt::CheckState checkState(const QModelIndex &index); + void setCheckState(const QModelIndex &index, Qt::CheckState state); + + QModelIndex indexFromItem(EsmFile *item) const; + EsmFile* findItem(const QString &name); + EsmFile* item(int row) const; + +signals: + void checkedItemsChanged(const QStringList checkedItems, const QStringList unCheckedItems); + +public slots: + void slotcheckedItemsChanged(const QStringList &checkedItems, const QStringList &unCheckedItems); + +private: + QList mFiles; + QStringList mAvailableFiles; + + QHash mDependencies; + QHash mCheckStates; + + QString mEncoding; + +}; + +#endif // DATAFILESMODEL_HPP diff --git a/apps/launcher/model/esm/esmfile.cpp b/apps/launcher/model/esm/esmfile.cpp new file mode 100644 index 000000000..93d83091e --- /dev/null +++ b/apps/launcher/model/esm/esmfile.cpp @@ -0,0 +1,50 @@ +#include "esmfile.hpp" + +EsmFile::EsmFile(QString fileName, ModelItem *parent) + : ModelItem(parent) +{ + mFileName = fileName; + mSize = 0; + mVersion = 0.0f; +} + +void EsmFile::setFileName(const QString &fileName) +{ + mFileName = fileName; +} + +void EsmFile::setAuthor(const QString &author) +{ + mAuthor = author; +} + +void EsmFile::setSize(const int size) +{ + mSize = size; +} + +void EsmFile::setDates(const QDateTime &modified, const QDateTime &accessed) +{ + mModified = modified; + mAccessed = accessed; +} + +void EsmFile::setVersion(float version) +{ + mVersion = version; +} + +void EsmFile::setPath(const QString &path) +{ + mPath = path; +} + +void EsmFile::setMasters(const QStringList &masters) +{ + mMasters = masters; +} + +void EsmFile::setDescription(const QString &description) +{ + mDescription = description; +} diff --git a/apps/launcher/model/esm/esmfile.hpp b/apps/launcher/model/esm/esmfile.hpp new file mode 100644 index 000000000..ad267aa75 --- /dev/null +++ b/apps/launcher/model/esm/esmfile.hpp @@ -0,0 +1,54 @@ +#ifndef ESMFILE_HPP +#define ESMFILE_HPP + +#include +#include + +#include "../modelitem.hpp" + +class EsmFile : public ModelItem +{ + Q_OBJECT + Q_PROPERTY(QString filename READ fileName) + +public: + EsmFile(QString fileName = QString(), ModelItem *parent = 0); + + ~EsmFile() + {} + + void setFileName(const QString &fileName); + void setAuthor(const QString &author); + void setSize(const int size); + void setDates(const QDateTime &modified, const QDateTime &accessed); + void setVersion(const float version); + void setPath(const QString &path); + void setMasters(const QStringList &masters); + void setDescription(const QString &description); + + inline QString fileName() { return mFileName; } + inline QString author() { return mAuthor; } + inline int size() { return mSize; } + inline QDateTime modified() { return mModified; } + inline QDateTime accessed() { return mAccessed; } + inline float version() { return mVersion; } + inline QString path() { return mPath; } + inline QStringList masters() { return mMasters; } + inline QString description() { return mDescription; } + + +private: + QString mFileName; + QString mAuthor; + int mSize; + QDateTime mModified; + QDateTime mAccessed; + float mVersion; + QString mPath; + QStringList mMasters; + QString mDescription; + +}; + + +#endif diff --git a/apps/launcher/model/modelitem.cpp b/apps/launcher/model/modelitem.cpp new file mode 100644 index 000000000..0ff7e45cb --- /dev/null +++ b/apps/launcher/model/modelitem.cpp @@ -0,0 +1,57 @@ +#include "modelitem.hpp" + +ModelItem::ModelItem(ModelItem *parent) + : mParentItem(parent) + , QObject(parent) +{ +} + +ModelItem::~ModelItem() +{ + qDeleteAll(mChildItems); +} + + +ModelItem *ModelItem::parent() +{ + return mParentItem; +} + +int ModelItem::row() const +{ + if (mParentItem) + return 1; + //return mParentItem->childRow(const_cast(this)); + //return mParentItem->mChildItems.indexOf(const_cast(this)); + + return -1; +} + + +int ModelItem::childCount() const +{ + return mChildItems.count(); +} + +int ModelItem::childRow(ModelItem *child) const +{ + Q_ASSERT(child); + + return mChildItems.indexOf(child); +} + +ModelItem *ModelItem::child(int row) +{ + return mChildItems.value(row); +} + + +void ModelItem::appendChild(ModelItem *item) +{ + mChildItems.append(item); +} + +void ModelItem::removeChild(int row) +{ + mChildItems.removeAt(row); +} diff --git a/apps/launcher/model/modelitem.hpp b/apps/launcher/model/modelitem.hpp new file mode 100644 index 000000000..f4cb4322f --- /dev/null +++ b/apps/launcher/model/modelitem.hpp @@ -0,0 +1,32 @@ +#ifndef MODELITEM_HPP +#define MODELITEM_HPP + +#include +#include + +class ModelItem : public QObject +{ + Q_OBJECT + +public: + ModelItem(ModelItem *parent = 0); + ~ModelItem(); + + ModelItem *parent(); + int row() const; + + int childCount() const; + int childRow(ModelItem *child) const; + ModelItem *child(int row); + + void appendChild(ModelItem *child); + void removeChild(int row); + + //virtual bool acceptChild(ModelItem *child); + +protected: + ModelItem *mParentItem; + QList mChildItems; +}; + +#endif diff --git a/apps/launcher/pluginsmodel.cpp b/apps/launcher/pluginsmodel.cpp deleted file mode 100644 index 86bd53027..000000000 --- a/apps/launcher/pluginsmodel.cpp +++ /dev/null @@ -1,149 +0,0 @@ -#include -#include - -#include - -#include "pluginsmodel.hpp" - -PluginsModel::PluginsModel(QObject *parent) : QStandardItemModel(parent) -{ - -} - -void decodeDataRecursive(QDataStream &stream, QStandardItem *item) -{ - int colCount, childCount; - stream >> *item; - stream >> colCount >> childCount; - item->setColumnCount(colCount); - - int childPos = childCount; - - while(childPos > 0) { - childPos--; - QStandardItem *child = new QStandardItem(); - decodeDataRecursive(stream, child); - item->setChild( childPos / colCount, childPos % colCount, child); - } -} - -bool PluginsModel::dropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) -{ - // Code largely based on QStandardItemModel::dropMimeData - - // check if the action is supported - if (!data || !(action == Qt::CopyAction || action == Qt::MoveAction)) - return false; - - // check if the format is supported - QString format = QLatin1String("application/x-qstandarditemmodeldatalist"); - if (!data->hasFormat(format)) - return QAbstractItemModel::dropMimeData(data, action, row, column, parent); - - if (row > rowCount(parent)) - row = rowCount(parent); - if (row == -1) - row = rowCount(parent); - if (column == -1) - column = 0; - - // decode and insert - QByteArray encoded = data->data(format); - QDataStream stream(&encoded, QIODevice::ReadOnly); - - - //code based on QAbstractItemModel::decodeData - // adapted to work with QStandardItem - int top = std::numeric_limits::max(); - int left = std::numeric_limits::max(); - int bottom = 0; - int right = 0; - QVector rows, columns; - QVector items; - - while (!stream.atEnd()) { - int r, c; - QStandardItem *item = new QStandardItem(); - stream >> r >> c; - decodeDataRecursive(stream, item); - - rows.append(r); - columns.append(c); - items.append(item); - top = qMin(r, top); - left = qMin(c, left); - bottom = qMax(r, bottom); - right = qMax(c, right); - } - - // insert the dragged items into the table, use a bit array to avoid overwriting items, - // since items from different tables can have the same row and column - int dragRowCount = 0; - int dragColumnCount = right - left + 1; - - // Compute the number of continuous rows upon insertion and modify the rows to match - QVector rowsToInsert(bottom + 1); - for (int i = 0; i < rows.count(); ++i) - rowsToInsert[rows.at(i)] = 1; - for (int i = 0; i < rowsToInsert.count(); ++i) { - if (rowsToInsert[i] == 1){ - rowsToInsert[i] = dragRowCount; - ++dragRowCount; - } - } - for (int i = 0; i < rows.count(); ++i) - rows[i] = top + rowsToInsert[rows[i]]; - - QBitArray isWrittenTo(dragRowCount * dragColumnCount); - - // make space in the table for the dropped data - int colCount = columnCount(parent); - if (colCount < dragColumnCount + column) { - insertColumns(colCount, dragColumnCount + column - colCount, parent); - colCount = columnCount(parent); - } - insertRows(row, dragRowCount, parent); - - row = qMax(0, row); - column = qMax(0, column); - - QStandardItem *parentItem = itemFromIndex (parent); - if (!parentItem) - parentItem = invisibleRootItem(); - - QVector newIndexes(items.size()); - // set the data in the table - for (int j = 0; j < items.size(); ++j) { - int relativeRow = rows.at(j) - top; - int relativeColumn = columns.at(j) - left; - int destinationRow = relativeRow + row; - int destinationColumn = relativeColumn + column; - int flat = (relativeRow * dragColumnCount) + relativeColumn; - // if the item was already written to, or we just can't fit it in the table, create a new row - if (destinationColumn >= colCount || isWrittenTo.testBit(flat)) { - destinationColumn = qBound(column, destinationColumn, colCount - 1); - destinationRow = row + dragRowCount; - insertRows(row + dragRowCount, 1, parent); - flat = (dragRowCount * dragColumnCount) + relativeColumn; - isWrittenTo.resize(++dragRowCount * dragColumnCount); - } - if (!isWrittenTo.testBit(flat)) { - newIndexes[j] = index(destinationRow, destinationColumn, parentItem->index()); - isWrittenTo.setBit(flat); - } - } - - for(int k = 0; k < newIndexes.size(); k++) { - if (newIndexes.at(k).isValid()) { - parentItem->setChild(newIndexes.at(k).row(), newIndexes.at(k).column(), items.at(k)); - } else { - delete items.at(k); - } - } - - // The important part, tell the view what is dropped - emit indexesDropped(newIndexes); - - return true; -} diff --git a/apps/launcher/pluginsmodel.hpp b/apps/launcher/pluginsmodel.hpp deleted file mode 100644 index 41df499b5..000000000 --- a/apps/launcher/pluginsmodel.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef PLUGINSMODEL_H -#define PLUGINSMODEL_H - -#include - -class PluginsModel : public QStandardItemModel -{ - Q_OBJECT - -public: - PluginsModel(QObject *parent = 0); - ~PluginsModel() {}; - - bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent); - -signals: - void indexesDropped(QVector indexes); - -}; - -#endif \ No newline at end of file diff --git a/apps/launcher/pluginsview.cpp b/apps/launcher/pluginsview.cpp deleted file mode 100644 index 26cf337fb..000000000 --- a/apps/launcher/pluginsview.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include - -#include "pluginsview.hpp" - -PluginsView::PluginsView(QWidget *parent) : QTableView(parent) -{ - setSelectionBehavior(QAbstractItemView::SelectRows); - setSelectionMode(QAbstractItemView::ExtendedSelection); - setEditTriggers(QAbstractItemView::NoEditTriggers); - setAlternatingRowColors(true); - setDragEnabled(true); - setDragDropMode(QAbstractItemView::InternalMove); - setDropIndicatorShown(true); - setDragDropOverwriteMode(false); - setContextMenuPolicy(Qt::CustomContextMenu); - -} - -void PluginsView::startDrag(Qt::DropActions supportedActions) -{ - selectionModel()->select( selectionModel()->selection(), - QItemSelectionModel::Select | QItemSelectionModel::Rows ); - QAbstractItemView::startDrag( supportedActions ); -} - -void PluginsView::setModel(QSortFilterProxyModel *model) -{ - QTableView::setModel(model); - - qRegisterMetaType< QVector >(); - - connect(model->sourceModel(), SIGNAL(indexesDropped(QVector)), - this, SLOT(selectIndexes(QVector)), Qt::QueuedConnection); -} - -void PluginsView::selectIndexes( QVector aIndexes ) -{ - selectionModel()->clearSelection(); - foreach( QPersistentModelIndex pIndex, aIndexes ) - selectionModel()->select( pIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows ); -} diff --git a/apps/launcher/pluginsview.hpp b/apps/launcher/pluginsview.hpp deleted file mode 100644 index b3dfb79ff..000000000 --- a/apps/launcher/pluginsview.hpp +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef PLUGINSVIEW_H -#define PLUGINSVIEW_H - -#include - -#include "pluginsmodel.hpp" - -class QSortFilterProxyModel; - -class PluginsView : public QTableView -{ - Q_OBJECT -public: - PluginsView(QWidget *parent = 0); - - PluginsModel* model() const - { return qobject_cast(QAbstractItemView::model()); } - - void startDrag(Qt::DropActions supportedActions); - void setModel(QSortFilterProxyModel *model); - -public slots: - void selectIndexes(QVector aIndexes); - -}; - -Q_DECLARE_METATYPE(QVector); - -#endif \ No newline at end of file diff --git a/apps/launcher/filedialog.cpp b/apps/launcher/utils/filedialog.cpp similarity index 100% rename from apps/launcher/filedialog.cpp rename to apps/launcher/utils/filedialog.cpp diff --git a/apps/launcher/filedialog.hpp b/apps/launcher/utils/filedialog.hpp similarity index 100% rename from apps/launcher/filedialog.hpp rename to apps/launcher/utils/filedialog.hpp diff --git a/apps/launcher/lineedit.cpp b/apps/launcher/utils/lineedit.cpp similarity index 100% rename from apps/launcher/lineedit.cpp rename to apps/launcher/utils/lineedit.cpp diff --git a/apps/launcher/lineedit.hpp b/apps/launcher/utils/lineedit.hpp similarity index 100% rename from apps/launcher/lineedit.hpp rename to apps/launcher/utils/lineedit.hpp diff --git a/apps/launcher/naturalsort.cpp b/apps/launcher/utils/naturalsort.cpp similarity index 100% rename from apps/launcher/naturalsort.cpp rename to apps/launcher/utils/naturalsort.cpp diff --git a/apps/launcher/naturalsort.hpp b/apps/launcher/utils/naturalsort.hpp similarity index 100% rename from apps/launcher/naturalsort.hpp rename to apps/launcher/utils/naturalsort.hpp diff --git a/apps/launcher/utils/profilescombobox.cpp b/apps/launcher/utils/profilescombobox.cpp new file mode 100644 index 000000000..8354d4a78 --- /dev/null +++ b/apps/launcher/utils/profilescombobox.cpp @@ -0,0 +1,52 @@ +#include +#include +#include + +#include "profilescombobox.hpp" + +ProfilesComboBox::ProfilesComboBox(QWidget *parent) : + QComboBox(parent) +{ + mValidator = new QRegExpValidator(QRegExp("^[a-zA-Z0-9_]*$"), this); // Alpha-numeric + underscore + + setEditable(true); + setValidator(mValidator); + setCompleter(0); + + connect(this, SIGNAL(currentIndexChanged(int)), this, + SLOT(slotIndexChanged(int))); + connect(lineEdit(), SIGNAL(returnPressed()), this, + SLOT(slotReturnPressed())); +} + +void ProfilesComboBox::setEditEnabled(bool editable) +{ + if (!editable) + return setEditable(false); + + // Reset the completer and validator + setEditable(true); + setValidator(mValidator); + setCompleter(0); +} + +void ProfilesComboBox::slotReturnPressed() +{ + QString current = currentText(); + QString previous = itemText(currentIndex()); + + if (findText(current) != -1) + return; + + setItemText(currentIndex(), current); + emit(profileRenamed(previous, current)); +} + +void ProfilesComboBox::slotIndexChanged(int index) +{ + if (index == -1) + return; + + emit(profileChanged(mOldProfile, currentText())); + mOldProfile = itemText(index); +} diff --git a/apps/launcher/utils/profilescombobox.hpp b/apps/launcher/utils/profilescombobox.hpp new file mode 100644 index 000000000..c7da60d2a --- /dev/null +++ b/apps/launcher/utils/profilescombobox.hpp @@ -0,0 +1,30 @@ +#ifndef PROFILESCOMBOBOX_HPP +#define PROFILESCOMBOBOX_HPP + +#include + +class QString; + +class QRegExpValidator; + +class ProfilesComboBox : public QComboBox +{ + Q_OBJECT +public: + explicit ProfilesComboBox(QWidget *parent = 0); + void setEditEnabled(bool editable); + +signals: + void profileChanged(const QString &previous, const QString ¤t); + void profileRenamed(const QString &oldName, const QString &newName); + +private slots: + void slotReturnPressed(); + void slotIndexChanged(int index); + +private: + QString mOldProfile; + QRegExpValidator *mValidator; +}; + +#endif // PROFILESCOMBOBOX_HPP diff --git a/apps/launcher/utils/textinputdialog.cpp b/apps/launcher/utils/textinputdialog.cpp new file mode 100644 index 000000000..16cadb661 --- /dev/null +++ b/apps/launcher/utils/textinputdialog.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include +#include + +#include "lineedit.hpp" + +#include "textinputdialog.hpp" + +TextInputDialog::TextInputDialog(const QString& title, const QString &text, QWidget *parent) : + QDialog(parent) +{ + setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); + mButtonBox = new QDialogButtonBox(this); + mButtonBox->addButton(QDialogButtonBox::Ok); + mButtonBox->addButton(QDialogButtonBox::Cancel); + + setMaximumHeight(height()); + setOkButtonEnabled(false); + setModal(true); + + // Messageboxes on mac have no title +#ifndef Q_OS_MAC + setWindowTitle(title); +#else + Q_UNUSED(title); +#endif + + QLabel *label = new QLabel(this); + label->setText(text); + + // Line edit + QValidator *validator = new QRegExpValidator(QRegExp("^[a-zA-Z0-9_]*$"), this); // Alpha-numeric + underscore + mLineEdit = new LineEdit(this); + mLineEdit->setValidator(validator); + mLineEdit->setCompleter(0); + + QVBoxLayout *dialogLayout = new QVBoxLayout(this); + dialogLayout->addWidget(label); + dialogLayout->addWidget(mLineEdit); + dialogLayout->addWidget(mButtonBox); + + connect(mButtonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(mButtonBox, SIGNAL(rejected()), this, SLOT(reject())); +} + +int TextInputDialog::exec() +{ + mLineEdit->clear(); + mLineEdit->setFocus(); + return QDialog::exec(); +} + +void TextInputDialog::setOkButtonEnabled(bool enabled) +{ + + QPushButton *okButton = mButtonBox->button(QDialogButtonBox::Ok); + okButton->setEnabled(enabled); +} diff --git a/apps/launcher/utils/textinputdialog.hpp b/apps/launcher/utils/textinputdialog.hpp new file mode 100644 index 000000000..cbb453ac8 --- /dev/null +++ b/apps/launcher/utils/textinputdialog.hpp @@ -0,0 +1,28 @@ +#ifndef TEXTINPUTDIALOG_HPP +#define TEXTINPUTDIALOG_HPP + +#include +//#include "lineedit.hpp" + +class QDialogButtonBox; +class LineEdit; + +class TextInputDialog : public QDialog +{ + Q_OBJECT +public: + explicit TextInputDialog(const QString& title, const QString &text, QWidget *parent = 0); + inline LineEdit *lineEdit() { return mLineEdit; } + void setOkButtonEnabled(bool enabled); + + LineEdit *mLineEdit; + + int exec(); + +private: + QDialogButtonBox *mButtonBox; + + +}; + +#endif // TEXTINPUTDIALOG_HPP diff --git a/apps/mwiniimporter/importer.cpp b/apps/mwiniimporter/importer.cpp index d396df648..19b69794f 100644 --- a/apps/mwiniimporter/importer.cpp +++ b/apps/mwiniimporter/importer.cpp @@ -78,7 +78,7 @@ MwIniImporter::multistrmap MwIniImporter::loadIniFile(std::string filename) { multistrmap::iterator it; if((it = map.find(key)) == map.end()) { - map.insert( std::make_pair > (key, std::vector() ) ); + map.insert( std::make_pair (key, std::vector() ) ); } map[key].push_back(value); } @@ -115,7 +115,7 @@ MwIniImporter::multistrmap MwIniImporter::loadCfgFile(std::string filename) { multistrmap::iterator it; if((it = map.find(key)) == map.end()) { - map.insert( std::make_pair > (key, std::vector() ) ); + map.insert( std::make_pair (key, std::vector() ) ); } map[key].push_back(value); } @@ -152,12 +152,12 @@ void MwIniImporter::mergeFallback(multistrmap &cfg, multistrmap &ini) { } } } -}; +} void MwIniImporter::insertMultistrmap(multistrmap &cfg, std::string key, std::string value) { multistrmap::iterator it = cfg.find(key); if(it == cfg.end()) { - cfg.insert(std::make_pair >(key, std::vector() )); + cfg.insert(std::make_pair (key, std::vector() )); } cfg[key].push_back(value); } diff --git a/apps/openmw/CMakeLists.txt b/apps/openmw/CMakeLists.txt index da1b3e15d..57e81e5ee 100644 --- a/apps/openmw/CMakeLists.txt +++ b/apps/openmw/CMakeLists.txt @@ -29,11 +29,12 @@ add_openmw_dir (mwgui map_window window_pinnable_base cursorreplace tooltips scrollwindow bookwindow list formatting inventorywindow container hud countdialog tradewindow settingswindow confirmationdialog alchemywindow referenceinterface spellwindow mainmenu quickkeysmenu - itemselection spellbuyingwindow loadingscreen levelupdialog waitdialog + itemselection spellbuyingwindow loadingscreen levelupdialog waitdialog spellcreationdialog + enchantingdialog trainingwindow travelwindow ) add_openmw_dir (mwdialogue - dialoguemanagerimp journalimp journalentry quest topic + dialoguemanagerimp journalimp journalentry quest topic filter selectwrapper ) add_openmw_dir (mwscript @@ -49,9 +50,10 @@ add_openmw_dir (mwsound add_openmw_dir (mwworld refdata worldimp physicssystem scene globals class action nullaction actionteleport - containerstore actiontalk actiontake manualref player cellfunctors + containerstore actiontalk actiontake manualref player cellfunctors failedaction cells localscripts customdata weather inventorystore ptr actionopen actionread actionequip timestamp actionalchemy cellstore actionapply actioneat + esmstore store recordcmp ) add_openmw_dir (mwclass @@ -61,7 +63,7 @@ add_openmw_dir (mwclass add_openmw_dir (mwmechanics mechanicsmanagerimp stat creaturestats magiceffects movement actors drawstate spells - activespells npcstats aipackage aisequence + activespells npcstats aipackage aisequence alchemy aiwander aitravel aifollow aiescort aiactivate ) add_openmw_dir (mwbase diff --git a/apps/openmw/engine.cpp b/apps/openmw/engine.cpp index adbfca129..2299053cd 100644 --- a/apps/openmw/engine.cpp +++ b/apps/openmw/engine.cpp @@ -20,6 +20,7 @@ #include "mwscript/scriptmanagerimp.hpp" #include "mwscript/extensions.hpp" +#include "mwscript/interpretercontext.hpp" #include "mwsound/soundmanagerimp.hpp" @@ -101,7 +102,7 @@ bool OMW::Engine::frameRenderingQueued (const Ogre::FrameEvent& evt) MWBase::Environment::get().getWorld()->doPhysics (movement, mEnvironment.getFrameDuration()); // update world - MWBase::Environment::get().getWorld()->update (evt.timeSinceLastFrame); + MWBase::Environment::get().getWorld()->update (evt.timeSinceLastFrame, MWBase::Environment::get().getWindowManager()->isGuiMode()); // update GUI Ogre::RenderWindow* window = mOgre->getWindow(); @@ -163,9 +164,8 @@ void OMW::Engine::loadBSA() std::cout << "Data dir " << dataDirectory << std::endl; Bsa::addDir(dataDirectory, mFSStrict); - // Workaround: Mygui does not find textures in non-BSA subfolders, _unless_ they are explicitely added like this - // For splash screens, this is OK to do, but eventually we will need an investigation why this is necessary - Bsa::addDir(dataDirectory + "/Splash", mFSStrict); + // Workaround until resource listing capabilities are added to DirArchive, we need those to list available splash screens + addResourcesDirectory (dataDirectory); } } @@ -356,7 +356,7 @@ void OMW::Engine::go() // Create dialog system mEnvironment.setJournal (new MWDialogue::Journal); - mEnvironment.setDialogueManager (new MWDialogue::DialogueManager (mExtensions)); + mEnvironment.setDialogueManager (new MWDialogue::DialogueManager (mExtensions, mVerboseScripts)); // Sets up the input system mEnvironment.setInputManager (new MWInput::InputManager (*mOgre, @@ -424,21 +424,10 @@ void OMW::Engine::activate() if (handle.empty()) return; - // the faced handle is not updated immediately, so on a cell change it might - // point to an object that doesn't exist anymore - // therefore, we are catching the "Unknown Ogre handle" exception that occurs in this case - MWWorld::Ptr ptr; - try - { - ptr = MWBase::Environment::get().getWorld()->getPtrViaHandle (handle); + MWWorld::Ptr ptr = MWBase::Environment::get().getWorld()->searchPtrViaHandle (handle); - if (ptr.isEmpty()) - return; - } - catch (std::runtime_error&) - { + if (ptr.isEmpty()) return; - } MWScript::InterpreterContext interpreterContext (&ptr.getRefData().getLocals(), ptr); diff --git a/apps/openmw/main.cpp b/apps/openmw/main.cpp index 5c2ba2f80..2da52311f 100644 --- a/apps/openmw/main.cpp +++ b/apps/openmw/main.cpp @@ -68,7 +68,7 @@ void validate(boost::any &v, std::vector const &tokens, FallbackMap if((mapIt = map->mMap.find(key)) == map->mMap.end()) { - map->mMap.insert(std::make_pair(key,value)); + map->mMap.insert(std::make_pair (key,value)); } } } diff --git a/apps/openmw/mwbase/dialoguemanager.hpp b/apps/openmw/mwbase/dialoguemanager.hpp index ccffc6b21..a205e78db 100644 --- a/apps/openmw/mwbase/dialoguemanager.hpp +++ b/apps/openmw/mwbase/dialoguemanager.hpp @@ -33,13 +33,17 @@ namespace MWBase virtual void goodbye() = 0; - ///get the faction of the actor you are talking with - virtual std::string getFaction() const = 0; + virtual MWWorld::Ptr getActor() const = 0; + ///< Return the actor the player is currently talking to. //calbacks for the GUI virtual void keywordSelected (const std::string& keyword) = 0; virtual void goodbyeSelected() = 0; virtual void questionAnswered (const std::string& answer) = 0; + + virtual void persuade (int type) = 0; + virtual int getTemporaryDispositionChange () const = 0; + virtual void applyTemporaryDispositionChange (int delta) = 0; }; } diff --git a/apps/openmw/mwbase/mechanicsmanager.hpp b/apps/openmw/mwbase/mechanicsmanager.hpp index 39d7e6e1a..a1023c986 100644 --- a/apps/openmw/mwbase/mechanicsmanager.hpp +++ b/apps/openmw/mwbase/mechanicsmanager.hpp @@ -39,6 +39,8 @@ namespace MWBase virtual void addActor (const MWWorld::Ptr& ptr) = 0; ///< Register an actor for stats management + /// + /// \note Dead actors are ignored. virtual void removeActor (const MWWorld::Ptr& ptr) = 0; ///< Deregister an actor for stats management @@ -60,7 +62,7 @@ namespace MWBase virtual void setPlayerName (const std::string& name) = 0; ///< Set player name. - virtual void setPlayerRace (const std::string& id, bool male) = 0; + virtual void setPlayerRace (const std::string& id, bool male, const std::string &head, const std::string &hair) = 0; ///< Set player race. virtual void setPlayerBirthsign (const std::string& id) = 0; @@ -74,6 +76,28 @@ namespace MWBase virtual void restoreDynamicStats() = 0; ///< If the player is sleeping, this should be called every hour. + + virtual int getBarterOffer(const MWWorld::Ptr& ptr,int basePrice, bool buying) = 0; + ///< This is used by every service to determine the price of objects given the trading skills of the player and NPC. + + virtual int getDerivedDisposition(const MWWorld::Ptr& ptr) = 0; + ///< Calculate the diposition of an NPC toward the player. + + virtual int countDeaths (const std::string& id) const = 0; + ///< Return the number of deaths for actors with the given ID. + + enum PersuasionType + { + PT_Admire, + PT_Intimidate, + PT_Taunt, + PT_Bribe10, + PT_Bribe100, + PT_Bribe1000 + }; + virtual void getPersuasionDispositionChange (const MWWorld::Ptr& npc, PersuasionType type, + float currentTemporaryDispositionDelta, bool& success, float& tempChange, float& permChange) = 0; + ///< Perform a persuasion action on NPC }; } diff --git a/apps/openmw/mwbase/soundmanager.hpp b/apps/openmw/mwbase/soundmanager.hpp index 745832583..92c177ff3 100644 --- a/apps/openmw/mwbase/soundmanager.hpp +++ b/apps/openmw/mwbase/soundmanager.hpp @@ -37,7 +37,7 @@ namespace MWBase Play_Normal = 0, /* tracked, non-looping, multi-instance, environment */ Play_Loop = 1<<0, /* Sound will continually loop until explicitly stopped */ Play_NoEnv = 1<<1, /* Do not apply environment effects (eg, underwater filters) */ - Play_NoTrack = 1<<2, /* (3D only) Play the sound at the given object's position + Play_NoTrack = 1<<2 /* (3D only) Play the sound at the given object's position * but do not keep it updated (the sound will not move with * the object and will not stop when the object is deleted. */ }; diff --git a/apps/openmw/mwbase/windowmanager.hpp b/apps/openmw/mwbase/windowmanager.hpp index d1daa101d..c177912d4 100644 --- a/apps/openmw/mwbase/windowmanager.hpp +++ b/apps/openmw/mwbase/windowmanager.hpp @@ -42,6 +42,7 @@ namespace MWGui class Console; class SpellWindow; class TradeWindow; + class TravelWindow; class SpellBuyingWindow; class ConfirmationDialog; class CountDialog; @@ -108,6 +109,7 @@ namespace MWBase virtual MWGui::ConfirmationDialog* getConfirmationDialog() = 0; virtual MWGui::TradeWindow* getTradeWindow() = 0; virtual MWGui::SpellBuyingWindow* getSpellBuyingWindow() = 0; + virtual MWGui::TravelWindow* getTravelWindow() = 0; virtual MWGui::SpellWindow* getSpellWindow() = 0; virtual MWGui::Console* getConsole() = 0; @@ -227,6 +229,10 @@ namespace MWBase virtual bool getPlayerSleeping() = 0; virtual void wakeUpPlayer() = 0; + + virtual void startSpellMaking(MWWorld::Ptr actor) = 0; + virtual void startEnchanting(MWWorld::Ptr actor) = 0; + virtual void startTraining(MWWorld::Ptr actor) = 0; }; } diff --git a/apps/openmw/mwbase/world.hpp b/apps/openmw/mwbase/world.hpp index 0ba4b84dd..526f865bc 100644 --- a/apps/openmw/mwbase/world.hpp +++ b/apps/openmw/mwbase/world.hpp @@ -28,11 +28,8 @@ namespace ESM struct Cell; struct Class; struct Potion; -} - -namespace ESMS -{ - struct ESMStore; + struct Spell; + struct NPC; } namespace MWRender @@ -47,6 +44,7 @@ namespace MWWorld class LocalScripts; class Ptr; class TimeStamp; + class ESMStore; } namespace MWBase @@ -67,7 +65,8 @@ namespace MWBase Render_CollisionDebug, Render_Wireframe, Render_Pathgrid, - Render_Compositors + Render_Compositors, + Render_BoundingBoxes }; struct DoorMarker @@ -103,7 +102,7 @@ namespace MWBase virtual MWWorld::Player& getPlayer() = 0; - virtual const ESMS::ESMStore& getStore() const = 0; + virtual const MWWorld::ESMStore& getStore() const = 0; virtual ESM::ESMReader& getEsmReader() = 0; @@ -142,6 +141,9 @@ namespace MWBase virtual MWWorld::Ptr getPtrViaHandle (const std::string& handle) = 0; ///< Return a pointer to a liveCellRef with the given Ogre handle. + virtual MWWorld::Ptr searchPtrViaHandle (const std::string& handle) = 0; + ///< Return a pointer to a liveCellRef with the given Ogre handle or Ptr() if not found + /// \todo enable reference in the OGRE scene virtual void enable (const MWWorld::Ptr& ptr) = 0; @@ -230,19 +232,28 @@ namespace MWBase ///< Toggle a render mode. ///< \return Resulting mode - virtual std::pair createRecord (const ESM::Potion& record) + virtual const ESM::Potion *createRecord (const ESM::Potion& record) = 0; ///< Create a new recrod (of type potion) in the ESM store. - /// \return ID, pointer to created record + /// \return pointer to created record - virtual std::pair createRecord (const ESM::Class& record) + virtual const ESM::Spell *createRecord (const ESM::Spell& record) + = 0; + ///< Create a new recrod (of type spell) in the ESM store. + /// \return pointer to created record + + virtual const ESM::Class *createRecord (const ESM::Class& record) = 0; ///< Create a new recrod (of type class) in the ESM store. - /// \return ID, pointer to created record + /// \return pointer to created record virtual const ESM::Cell *createRecord (const ESM::Cell& record) = 0; ///< Create a new recrod (of type cell) in the ESM store. - /// \return ID, pointer to created record + /// \return pointer to created record + + virtual const ESM::NPC *createRecord(const ESM::NPC &record) = 0; + ///< Create a new recrod (of type npc) in the ESM store. + /// \return pointer to created record virtual void playAnimationGroup (const MWWorld::Ptr& ptr, const std::string& groupName, int mode, int number = 1) = 0; @@ -256,7 +267,7 @@ namespace MWBase ///< Skip the animation for the given MW-reference for one frame. Calls to this function for /// references that are currently not in the rendered scene should be ignored. - virtual void update (float duration) = 0; + virtual void update (float duration, bool paused) = 0; virtual bool placeObject(const MWWorld::Ptr& object, float cursorX, float cursorY) = 0; ///< place an object into the gameworld at the specified cursor position diff --git a/apps/openmw/mwclass/activator.cpp b/apps/openmw/mwclass/activator.cpp index e815549d8..26d286aa1 100644 --- a/apps/openmw/mwclass/activator.cpp +++ b/apps/openmw/mwclass/activator.cpp @@ -30,18 +30,17 @@ namespace MWClass void Activator::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Activator::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -53,7 +52,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } std::string Activator::getScript (const MWWorld::Ptr& ptr) const @@ -61,7 +60,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } void Activator::registerSelf() @@ -76,7 +75,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Activator::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -85,22 +84,22 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); std::string text; if (MWBase::Environment::get().getWindowManager()->getFullHelp()) - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); info.text = text; return info; } - + MWWorld::Ptr Activator::copyToCellImpl(const MWWorld::Ptr &ptr, MWWorld::CellStore &cell) const { MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.activators.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mActivators.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/apparatus.cpp b/apps/openmw/mwclass/apparatus.cpp index a05c24e86..06467bb21 100644 --- a/apps/openmw/mwclass/apparatus.cpp +++ b/apps/openmw/mwclass/apparatus.cpp @@ -33,18 +33,17 @@ namespace MWClass void Apparatus::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Apparatus::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -56,7 +55,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Apparatus::activate (const MWWorld::Ptr& ptr, @@ -75,7 +74,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } int Apparatus::getValue (const MWWorld::Ptr& ptr) const @@ -83,7 +82,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } void Apparatus::registerSelf() @@ -108,7 +107,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Apparatus::hasToolTip (const MWWorld::Ptr& ptr) const @@ -116,7 +115,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Apparatus::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -125,17 +124,17 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.icon = ref->mBase->mIcon; std::string text; - text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->base->mData.mQuality); - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight); - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->mBase->mData.mQuality); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight); + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } info.text = text; @@ -154,6 +153,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.appas.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mAppas.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/armor.cpp b/apps/openmw/mwclass/armor.cpp index 7254c37f8..704173b1c 100644 --- a/apps/openmw/mwclass/armor.cpp +++ b/apps/openmw/mwclass/armor.cpp @@ -36,18 +36,17 @@ namespace MWClass void Armor::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Armor::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -59,7 +58,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Armor::activate (const MWWorld::Ptr& ptr, @@ -82,7 +81,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mHealth; + return ref->mBase->mData.mHealth; } std::string Armor::getScript (const MWWorld::Ptr& ptr) const @@ -90,7 +89,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } std::pair, bool> Armor::getEquipmentSlots (const MWWorld::Ptr& ptr) const @@ -118,7 +117,7 @@ namespace MWClass }; for (int i=0; ibase->mData.mType) + if (sMapping[i][0]==ref->mBase->mData.mType) { slots.push_back (int (sMapping[i][1])); break; @@ -134,7 +133,7 @@ namespace MWClass std::string typeGmst; - switch (ref->base->mData.mType) + switch (ref->mBase->mData.mType) { case ESM::Armor::Helmet: typeGmst = "iHelmWeight"; break; case ESM::Armor::Cuirass: typeGmst = "iCuirassWeight"; break; @@ -152,14 +151,17 @@ namespace MWClass if (typeGmst.empty()) return -1; - float iWeight = MWBase::Environment::get().getWorld()->getStore().gameSettings.find (typeGmst)->getInt(); + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); - if (iWeight * MWBase::Environment::get().getWorld()->getStore().gameSettings.find ("fLightMaxMod")->getFloat()>= - ref->base->mData.mWeight) + float iWeight = gmst.find (typeGmst)->getInt(); + + if (iWeight * gmst.find ("fLightMaxMod")->getFloat()>= + ref->mBase->mData.mWeight) return ESM::Skill::LightArmor; - if (iWeight * MWBase::Environment::get().getWorld()->getStore().gameSettings.find ("fMedMaxMod")->getFloat()>= - ref->base->mData.mWeight) + if (iWeight * gmst.find ("fMedMaxMod")->getFloat()>= + ref->mBase->mData.mWeight) return ESM::Skill::MediumArmor; return ESM::Skill::HeavyArmor; @@ -170,7 +172,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } void Armor::registerSelf() @@ -207,7 +209,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Armor::hasToolTip (const MWWorld::Ptr& ptr) const @@ -215,7 +217,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Armor::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -224,8 +226,8 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.icon = ref->mBase->mIcon; std::string text; @@ -239,20 +241,20 @@ namespace MWClass else typeText = "#{sHeavy}"; - text += "\n#{sArmorRating}: " + MWGui::ToolTips::toString(ref->base->mData.mArmor); + text += "\n#{sArmorRating}: " + MWGui::ToolTips::toString(ref->mBase->mData.mArmor); /// \todo store the current armor health somewhere - text += "\n#{sCondition}: " + MWGui::ToolTips::toString(ref->base->mData.mHealth); + text += "\n#{sCondition}: " + MWGui::ToolTips::toString(ref->mBase->mData.mHealth); - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight) + " (" + typeText + ")"; - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight) + " (" + typeText + ")"; + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } - info.enchant = ref->base->mEnchant; + info.enchant = ref->mBase->mEnchant; info.text = text; @@ -264,7 +266,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mEnchant; + return ref->mBase->mEnchant; } boost::shared_ptr Armor::use (const MWWorld::Ptr& ptr) const @@ -282,6 +284,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.armors.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mArmors.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/book.cpp b/apps/openmw/mwclass/book.cpp index 4a2ad1dcb..6c3b7b86c 100644 --- a/apps/openmw/mwclass/book.cpp +++ b/apps/openmw/mwclass/book.cpp @@ -32,18 +32,17 @@ namespace MWClass void Book::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Book::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -55,7 +54,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Book::activate (const MWWorld::Ptr& ptr, @@ -70,7 +69,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } int Book::getValue (const MWWorld::Ptr& ptr) const @@ -78,7 +77,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } void Book::registerSelf() @@ -103,7 +102,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Book::hasToolTip (const MWWorld::Ptr& ptr) const @@ -111,7 +110,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Book::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -120,20 +119,20 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.icon = ref->mBase->mIcon; std::string text; - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight); - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight); + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } - info.enchant = ref->base->mEnchant; + info.enchant = ref->mBase->mEnchant; info.text = text; @@ -145,7 +144,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mEnchant; + return ref->mBase->mEnchant; } boost::shared_ptr Book::use (const MWWorld::Ptr& ptr) const @@ -159,6 +158,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.books.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mBooks.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/clothing.cpp b/apps/openmw/mwclass/clothing.cpp index d746350df..c411bb193 100644 --- a/apps/openmw/mwclass/clothing.cpp +++ b/apps/openmw/mwclass/clothing.cpp @@ -34,18 +34,17 @@ namespace MWClass void Clothing::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Clothing::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -57,7 +56,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Clothing::activate (const MWWorld::Ptr& ptr, @@ -75,7 +74,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } std::pair, bool> Clothing::getEquipmentSlots (const MWWorld::Ptr& ptr) const @@ -85,7 +84,7 @@ namespace MWClass std::vector slots; - if (ref->base->mData.mType==ESM::Clothing::Ring) + if (ref->mBase->mData.mType==ESM::Clothing::Ring) { slots.push_back (int (MWWorld::InventoryStore::Slot_LeftRing)); slots.push_back (int (MWWorld::InventoryStore::Slot_RightRing)); @@ -108,7 +107,7 @@ namespace MWClass }; for (int i=0; ibase->mData.mType) + if (sMapping[i][0]==ref->mBase->mData.mType) { slots.push_back (int (sMapping[i][1])); break; @@ -123,7 +122,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - if (ref->base->mData.mType==ESM::Clothing::Shoes) + if (ref->mBase->mData.mType==ESM::Clothing::Shoes) return ESM::Skill::Unarmored; return -1; @@ -134,7 +133,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } void Clothing::registerSelf() @@ -149,7 +148,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - if (ref->base->mData.mType == 8) + if (ref->mBase->mData.mType == 8) { return std::string("Item Ring Up"); } @@ -161,7 +160,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - if (ref->base->mData.mType == 8) + if (ref->mBase->mData.mType == 8) { return std::string("Item Ring Down"); } @@ -173,7 +172,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Clothing::hasToolTip (const MWWorld::Ptr& ptr) const @@ -181,7 +180,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Clothing::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -190,20 +189,20 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.icon = ref->mBase->mIcon; std::string text; - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight); - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight); + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } - info.enchant = ref->base->mEnchant; + info.enchant = ref->mBase->mEnchant; info.text = text; @@ -215,7 +214,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mEnchant; + return ref->mBase->mEnchant; } boost::shared_ptr Clothing::use (const MWWorld::Ptr& ptr) const @@ -233,6 +232,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.clothes.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mClothes.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/container.cpp b/apps/openmw/mwclass/container.cpp index 28fa72378..76c1c40f1 100644 --- a/apps/openmw/mwclass/container.cpp +++ b/apps/openmw/mwclass/container.cpp @@ -8,7 +8,7 @@ #include "../mwbase/windowmanager.hpp" #include "../mwworld/ptr.hpp" -#include "../mwworld/nullaction.hpp" +#include "../mwworld/failedaction.hpp" #include "../mwworld/containerstore.hpp" #include "../mwworld/customdata.hpp" #include "../mwworld/cellstore.hpp" @@ -65,18 +65,17 @@ namespace MWClass void Container::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Container::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -95,9 +94,15 @@ namespace MWClass bool needKey = ptr.getCellRef().mLockLevel>0; bool hasKey = false; std::string keyName; + + // make key id lowercase + std::string keyId = ptr.getCellRef().mKey; + std::transform(keyId.begin(), keyId.end(), keyId.begin(), ::tolower); for (MWWorld::ContainerStoreIterator it = invStore.begin(); it != invStore.end(); ++it) { - if (it->getCellRef ().mRefID == ptr.getCellRef().mKey) + std::string refId = it->getCellRef().mRefID; + std::transform(refId.begin(), refId.end(), refId.begin(), ::tolower); + if (refId == keyId) { hasKey = true; keyName = MWWorld::Class::get(*it).getName(*it); @@ -124,7 +129,7 @@ namespace MWClass { // Trap activation goes here std::cout << "Activated trap: " << ptr.getCellRef().mTrap << std::endl; - boost::shared_ptr action(new MWWorld::NullAction); + boost::shared_ptr action(new MWWorld::FailedAction); action->setSound(trapActivationSound); ptr.getCellRef().mTrap = ""; return action; @@ -132,7 +137,7 @@ namespace MWClass } else { - boost::shared_ptr action(new MWWorld::NullAction); + boost::shared_ptr action(new MWWorld::FailedAction); action->setSound(lockedSound); return action; } @@ -143,7 +148,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } MWWorld::ContainerStore& Container::getContainerStore (const MWWorld::Ptr& ptr) @@ -159,7 +164,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } void Container::registerSelf() @@ -174,7 +179,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Container::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -183,17 +188,17 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName; + info.caption = ref->mBase->mName; std::string text; - if (ref->ref.mLockLevel > 0) - text += "\n#{sLockLevel}: " + MWGui::ToolTips::toString(ref->ref.mLockLevel); - if (ref->ref.mTrap != "") + if (ref->mRef.mLockLevel > 0) + text += "\n#{sLockLevel}: " + MWGui::ToolTips::toString(ref->mRef.mLockLevel); + if (ref->mRef.mTrap != "") text += "\n#{sTrapped}"; if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } info.text = text; @@ -206,7 +211,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mWeight; + return ref->mBase->mWeight; } float Container::getEncumbrance (const MWWorld::Ptr& ptr) const @@ -233,6 +238,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.containers.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mContainers.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/creature.cpp b/apps/openmw/mwclass/creature.cpp index 0cf348b14..edf5dd25d 100644 --- a/apps/openmw/mwclass/creature.cpp +++ b/apps/openmw/mwclass/creature.cpp @@ -12,6 +12,7 @@ #include "../mwworld/ptr.hpp" #include "../mwworld/actiontalk.hpp" +#include "../mwworld/actionopen.hpp" #include "../mwworld/customdata.hpp" #include "../mwworld/containerstore.hpp" #include "../mwworld/physicssystem.hpp" @@ -47,28 +48,28 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); // creature stats - data->mCreatureStats.getAttribute(0).set (ref->base->mData.mStrength); - data->mCreatureStats.getAttribute(1).set (ref->base->mData.mIntelligence); - data->mCreatureStats.getAttribute(2).set (ref->base->mData.mWillpower); - data->mCreatureStats.getAttribute(3).set (ref->base->mData.mAgility); - data->mCreatureStats.getAttribute(4).set (ref->base->mData.mSpeed); - data->mCreatureStats.getAttribute(5).set (ref->base->mData.mEndurance); - data->mCreatureStats.getAttribute(6).set (ref->base->mData.mPersonality); - data->mCreatureStats.getAttribute(7).set (ref->base->mData.mLuck); - data->mCreatureStats.getHealth().set (ref->base->mData.mHealth); - data->mCreatureStats.getMagicka().set (ref->base->mData.mMana); - data->mCreatureStats.getFatigue().set (ref->base->mData.mFatigue); + data->mCreatureStats.getAttribute(0).set (ref->mBase->mData.mStrength); + data->mCreatureStats.getAttribute(1).set (ref->mBase->mData.mIntelligence); + data->mCreatureStats.getAttribute(2).set (ref->mBase->mData.mWillpower); + data->mCreatureStats.getAttribute(3).set (ref->mBase->mData.mAgility); + data->mCreatureStats.getAttribute(4).set (ref->mBase->mData.mSpeed); + data->mCreatureStats.getAttribute(5).set (ref->mBase->mData.mEndurance); + data->mCreatureStats.getAttribute(6).set (ref->mBase->mData.mPersonality); + data->mCreatureStats.getAttribute(7).set (ref->mBase->mData.mLuck); + data->mCreatureStats.setHealth (ref->mBase->mData.mHealth); + data->mCreatureStats.setMagicka (ref->mBase->mData.mMana); + data->mCreatureStats.setFatigue (ref->mBase->mData.mFatigue); - data->mCreatureStats.setLevel(ref->base->mData.mLevel); + data->mCreatureStats.setLevel(ref->mBase->mData.mLevel); - data->mCreatureStats.setHello(ref->base->mAiData.mHello); - data->mCreatureStats.setFight(ref->base->mAiData.mFight); - data->mCreatureStats.setFlee(ref->base->mAiData.mFlee); - data->mCreatureStats.setAlarm(ref->base->mAiData.mAlarm); + data->mCreatureStats.setAiSetting (0, ref->mBase->mAiData.mHello); + data->mCreatureStats.setAiSetting (1, ref->mBase->mAiData.mFight); + data->mCreatureStats.setAiSetting (2, ref->mBase->mAiData.mFlee); + data->mCreatureStats.setAiSetting (3, ref->mBase->mAiData.mAlarm); // spells - for (std::vector::const_iterator iter (ref->base->mSpells.mList.begin()); - iter!=ref->base->mSpells.mList.end(); ++iter) + for (std::vector::const_iterator iter (ref->mBase->mSpells.mList.begin()); + iter!=ref->mBase->mSpells.mList.end(); ++iter) data->mCreatureStats.getSpells().add (*iter); // store @@ -81,7 +82,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mId; + return ref->mBase->mId; } void Creature::insertObjectRendering (const MWWorld::Ptr& ptr, MWRender::RenderingInterface& renderingInterface) const @@ -93,9 +94,8 @@ namespace MWClass void Creature::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()){ - physics.insertActorPhysics(ptr, model); - } + if(!model.empty()) + physics.addActor(ptr); MWBase::Environment::get().getMechanicsManager()->addActor (ptr); } @@ -103,9 +103,9 @@ namespace MWClass { MWWorld::LiveCellRef *ref = ptr.get(); - assert (ref->base != NULL); + assert (ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -117,7 +117,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } MWMechanics::CreatureStats& Creature::getCreatureStats (const MWWorld::Ptr& ptr) const @@ -130,7 +130,10 @@ namespace MWClass boost::shared_ptr Creature::activate (const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const { - return boost::shared_ptr (new MWWorld::ActionTalk (ptr)); + if (MWWorld::Class::get (ptr).getCreatureStats (ptr).isDead()) + return boost::shared_ptr (new MWWorld::ActionOpen(ptr)); + else + return boost::shared_ptr (new MWWorld::ActionTalk (ptr)); } MWWorld::ContainerStore& Creature::getContainerStore (const MWWorld::Ptr& ptr) @@ -146,7 +149,15 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; + } + + bool Creature::isEssential (const MWWorld::Ptr& ptr) const + { + MWWorld::LiveCellRef *ref = + ptr.get(); + + return ref->mBase->mFlags & ESM::Creature::Essential; } void Creature::registerSelf() @@ -169,11 +180,11 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName; + info.caption = ref->mBase->mName; std::string text; if (MWBase::Environment::get().getWindowManager()->getFullHelp()) - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); info.text = text; return info; @@ -207,6 +218,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.creatures.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mCreatures.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/creature.hpp b/apps/openmw/mwclass/creature.hpp index 4de877b31..a158fa743 100644 --- a/apps/openmw/mwclass/creature.hpp +++ b/apps/openmw/mwclass/creature.hpp @@ -56,6 +56,9 @@ namespace MWClass ///< Returns total weight of objects inside this object (including modifications from magic /// effects). Throws an exception, if the object can't hold other objects. + virtual bool isEssential (const MWWorld::Ptr& ptr) const; + ///< Is \a ptr essential? (i.e. may losing \a ptr make the game unwinnable) + static void registerSelf(); virtual std::string getModel(const MWWorld::Ptr &ptr) const; diff --git a/apps/openmw/mwclass/door.cpp b/apps/openmw/mwclass/door.cpp index b94a24ed5..843d1af4c 100644 --- a/apps/openmw/mwclass/door.cpp +++ b/apps/openmw/mwclass/door.cpp @@ -10,6 +10,7 @@ #include "../mwworld/player.hpp" #include "../mwworld/ptr.hpp" #include "../mwworld/nullaction.hpp" +#include "../mwworld/failedaction.hpp" #include "../mwworld/actionteleport.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/physicssystem.hpp" @@ -35,18 +36,17 @@ namespace MWClass void Door::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Door::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -58,10 +58,10 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - if (ref->ref.mTeleport && !ref->ref.mDestCell.empty()) // TODO doors that lead to exteriors - return ref->ref.mDestCell; + if (ref->mRef.mTeleport && !ref->mRef.mDestCell.empty()) // TODO doors that lead to exteriors + return ref->mRef.mDestCell; - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Door::activate (const MWWorld::Ptr& ptr, @@ -70,8 +70,8 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - const std::string &openSound = ref->base->mOpenSound; - //const std::string &closeSound = ref->base->closeSound; + const std::string &openSound = ref->mBase->mOpenSound; + //const std::string &closeSound = ref->mBase->closeSound; const std::string lockedSound = "LockedDoor"; const std::string trapActivationSound = "Disarm Trap Fail"; @@ -81,9 +81,15 @@ namespace MWClass bool needKey = ptr.getCellRef().mLockLevel>0; bool hasKey = false; std::string keyName; + + // make key id lowercase + std::string keyId = ptr.getCellRef().mKey; + std::transform(keyId.begin(), keyId.end(), keyId.begin(), ::tolower); for (MWWorld::ContainerStoreIterator it = invStore.begin(); it != invStore.end(); ++it) { - if (it->getCellRef ().mRefID == ptr.getCellRef().mKey) + std::string refId = it->getCellRef().mRefID; + std::transform(refId.begin(), refId.end(), refId.begin(), ::tolower); + if (refId == keyId) { hasKey = true; keyName = MWWorld::Class::get(*it).getName(*it); @@ -105,21 +111,20 @@ namespace MWClass // Trap activation std::cout << "Activated trap: " << ptr.getCellRef().mTrap << std::endl; - boost::shared_ptr action(new MWWorld::NullAction); - + boost::shared_ptr action(new MWWorld::FailedAction); action->setSound(trapActivationSound); ptr.getCellRef().mTrap = ""; return action; } - if (ref->ref.mTeleport) + if (ref->mRef.mTeleport) { // teleport door /// \todo remove this if clause once ActionTeleport can also support other actors if (MWBase::Environment::get().getWorld()->getPlayer().getPlayer()==actor) { - boost::shared_ptr action(new MWWorld::ActionTeleport (ref->ref.mDestCell, ref->ref.mDoorDest)); + boost::shared_ptr action(new MWWorld::ActionTeleport (ref->mRef.mDestCell, ref->mRef.mDoorDest)); action->setSound(openSound); @@ -128,7 +133,7 @@ namespace MWClass else { // another NPC or a creature is using the door - return boost::shared_ptr (new MWWorld::NullAction); + return boost::shared_ptr (new MWWorld::FailedAction); } } else @@ -147,7 +152,7 @@ namespace MWClass else { // locked, and we can't open. - boost::shared_ptr action(new MWWorld::NullAction); + boost::shared_ptr action(new MWWorld::FailedAction); action->setSound(lockedSound); return action; } @@ -171,7 +176,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } void Door::registerSelf() @@ -186,7 +191,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Door::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -195,31 +200,32 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName; + info.caption = ref->mBase->mName; std::string text; - const ESMS::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); + const MWWorld::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); - if (ref->ref.mTeleport) + if (ref->mRef.mTeleport) { std::string dest; - if (ref->ref.mDestCell != "") + if (ref->mRef.mDestCell != "") { // door leads to an interior, use interior name as tooltip - dest = ref->ref.mDestCell; + dest = ref->mRef.mDestCell; } else { // door leads to exterior, use cell name (if any), otherwise translated region name int x,y; - MWBase::Environment::get().getWorld()->positionToIndex (ref->ref.mDoorDest.pos[0], ref->ref.mDoorDest.pos[1], x, y); - const ESM::Cell* cell = store.cells.findExt(x,y); + MWBase::Environment::get().getWorld()->positionToIndex (ref->mRef.mDoorDest.pos[0], ref->mRef.mDoorDest.pos[1], x, y); + const ESM::Cell* cell = store.get().find(x,y); if (cell->mName != "") dest = cell->mName; else { - const ESM::Region* region = store.regions.search(cell->mRegion); + const ESM::Region* region = + store.get().find(cell->mRegion); dest = region->mName; } } @@ -227,13 +233,13 @@ namespace MWClass text += "\n"+dest; } - if (ref->ref.mLockLevel > 0) - text += "\n#{sLockLevel}: " + MWGui::ToolTips::toString(ref->ref.mLockLevel); - if (ref->ref.mTrap != "") + if (ref->mRef.mLockLevel > 0) + text += "\n#{sLockLevel}: " + MWGui::ToolTips::toString(ref->mRef.mLockLevel); + if (ref->mRef.mTrap != "") text += "\n#{sTrapped}"; if (MWBase::Environment::get().getWindowManager()->getFullHelp()) - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); info.text = text; @@ -246,6 +252,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.doors.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mDoors.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/ingredient.cpp b/apps/openmw/mwclass/ingredient.cpp index 45779287f..1be8d66b3 100644 --- a/apps/openmw/mwclass/ingredient.cpp +++ b/apps/openmw/mwclass/ingredient.cpp @@ -25,7 +25,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mId; + return ref->mBase->mId; } void Ingredient::insertObjectRendering (const MWWorld::Ptr& ptr, MWRender::RenderingInterface& renderingInterface) const @@ -41,18 +41,17 @@ namespace MWClass void Ingredient::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Ingredient::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -64,7 +63,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Ingredient::activate (const MWWorld::Ptr& ptr, @@ -82,7 +81,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } int Ingredient::getValue (const MWWorld::Ptr& ptr) const @@ -90,7 +89,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } @@ -125,7 +124,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Ingredient::hasToolTip (const MWWorld::Ptr& ptr) const @@ -133,7 +132,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Ingredient::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -142,28 +141,28 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.icon = ref->mBase->mIcon; std::string text; - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight); - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight); + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } MWGui::Widgets::SpellEffectList list; for (int i=0; i<4; ++i) { - if (ref->base->mData.mEffectID[i] < 0) + if (ref->mBase->mData.mEffectID[i] < 0) continue; MWGui::Widgets::SpellEffectParams params; - params.mEffectID = ref->base->mData.mEffectID[i]; - params.mAttribute = ref->base->mData.mAttributes[i]; - params.mSkill = ref->base->mData.mSkills[i]; + params.mEffectID = ref->mBase->mData.mEffectID[i]; + params.mAttribute = ref->mBase->mData.mAttributes[i]; + params.mSkill = ref->mBase->mData.mSkills[i]; list.push_back(params); } info.effects = list; @@ -179,6 +178,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.ingreds.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mIngreds.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/light.cpp b/apps/openmw/mwclass/light.cpp index 6ae9ed661..b94b0d395 100644 --- a/apps/openmw/mwclass/light.cpp +++ b/apps/openmw/mwclass/light.cpp @@ -12,6 +12,7 @@ #include "../mwworld/actiontake.hpp" #include "../mwworld/actionequip.hpp" #include "../mwworld/nullaction.hpp" +#include "../mwworld/failedaction.hpp" #include "../mwworld/inventorystore.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/physicssystem.hpp" @@ -27,9 +28,9 @@ namespace MWClass { MWWorld::LiveCellRef *ref = ptr.get(); - assert (ref->base != NULL); + assert (ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; MWRender::Objects& objects = renderingInterface.getObjects(); objects.insertBegin(ptr, ptr.getRefData().isEnabled(), false); @@ -37,11 +38,11 @@ namespace MWClass if (!model.empty()) objects.insertMesh(ptr, "meshes\\" + model); - const int color = ref->base->mData.mColor; + const int color = ref->mBase->mData.mColor; const float r = ((color >> 0) & 0xFF) / 255.0f; const float g = ((color >> 8) & 0xFF) / 255.0f; const float b = ((color >> 16) & 0xFF) / 255.0f; - const float radius = float (ref->base->mData.mRadius); + const float radius = float (ref->mBase->mData.mRadius); objects.insertLight (ptr, r, g, b, radius); } @@ -49,25 +50,24 @@ namespace MWClass { MWWorld::LiveCellRef *ref = ptr.get(); - assert (ref->base != NULL); + assert (ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; - if(!model.empty()) { - physics.insertObjectPhysics(ptr, "meshes\\" + model); - } - if (!ref->base->mSound.empty()) { - MWBase::Environment::get().getSoundManager()->playSound3D(ptr, ref->base->mSound, 1.0, 1.0, MWBase::SoundManager::Play_Loop); - } + if(!model.empty()) + physics.addObject(ptr); + + if (!ref->mBase->mSound.empty()) + MWBase::Environment::get().getSoundManager()->playSound3D(ptr, ref->mBase->mSound, 1.0, 1.0, MWBase::SoundManager::Play_Loop); } std::string Light::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert (ref->base != NULL); + assert (ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -79,10 +79,10 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - if (ref->base->mModel.empty()) + if (ref->mBase->mModel.empty()) return ""; - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Light::activate (const MWWorld::Ptr& ptr, @@ -91,8 +91,8 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - if (!(ref->base->mData.mFlags & ESM::Light::Carry)) - return boost::shared_ptr (new MWWorld::NullAction); + if (!(ref->mBase->mData.mFlags & ESM::Light::Carry)) + return boost::shared_ptr (new MWWorld::FailedAction); boost::shared_ptr action(new MWWorld::ActionTake (ptr)); @@ -106,7 +106,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } std::pair, bool> Light::getEquipmentSlots (const MWWorld::Ptr& ptr) const @@ -116,7 +116,7 @@ namespace MWClass std::vector slots; - if (ref->base->mData.mFlags & ESM::Light::Carry) + if (ref->mBase->mData.mFlags & ESM::Light::Carry) slots.push_back (int (MWWorld::InventoryStore::Slot_CarriedLeft)); return std::make_pair (slots, false); @@ -127,7 +127,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } void Light::registerSelf() @@ -153,7 +153,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Light::hasToolTip (const MWWorld::Ptr& ptr) const @@ -161,7 +161,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Light::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -170,17 +170,17 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.icon = ref->mBase->mIcon; std::string text; - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight); - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight); + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } info.text = text; @@ -203,6 +203,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.lights.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mLights.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/lockpick.cpp b/apps/openmw/mwclass/lockpick.cpp index a0ec65c98..a667fefb2 100644 --- a/apps/openmw/mwclass/lockpick.cpp +++ b/apps/openmw/mwclass/lockpick.cpp @@ -34,18 +34,17 @@ namespace MWClass void Lockpick::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Lockpick::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -57,7 +56,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Lockpick::activate (const MWWorld::Ptr& ptr, @@ -75,7 +74,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } std::pair, bool> Lockpick::getEquipmentSlots (const MWWorld::Ptr& ptr) const @@ -92,7 +91,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } void Lockpick::registerSelf() @@ -117,7 +116,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Lockpick::hasToolTip (const MWWorld::Ptr& ptr) const @@ -125,7 +124,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Lockpick::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -134,21 +133,21 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.icon = ref->mBase->mIcon; std::string text; /// \todo store remaining uses somewhere - text += "\n#{sUses}: " + MWGui::ToolTips::toString(ref->base->mData.mUses); - text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->base->mData.mQuality); - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight); - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sUses}: " + MWGui::ToolTips::toString(ref->mBase->mData.mUses); + text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->mBase->mData.mQuality); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight); + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } info.text = text; @@ -171,6 +170,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.lockpicks.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mLockpicks.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/misc.cpp b/apps/openmw/mwclass/misc.cpp index edcfc7daa..94d40bcb7 100644 --- a/apps/openmw/mwclass/misc.cpp +++ b/apps/openmw/mwclass/misc.cpp @@ -37,18 +37,17 @@ namespace MWClass void Miscellaneous::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Miscellaneous::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -60,7 +59,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Miscellaneous::activate (const MWWorld::Ptr& ptr, @@ -78,7 +77,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } int Miscellaneous::getValue (const MWWorld::Ptr& ptr) const @@ -86,7 +85,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } void Miscellaneous::registerSelf() @@ -101,7 +100,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - if (ref->base->mName == MWBase::Environment::get().getWorld()->getStore().gameSettings.find("sGold")->getString()) + if (ref->mBase->mName == MWBase::Environment::get().getWorld()->getStore().get().find("sGold")->getString()) { return std::string("Item Gold Up"); } @@ -113,7 +112,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - if (ref->base->mName == MWBase::Environment::get().getWorld()->getStore().gameSettings.find("sGold")->getString()) + if (ref->mBase->mName == MWBase::Environment::get().getWorld()->getStore().get().find("sGold")->getString()) { return std::string("Item Gold Down"); } @@ -125,7 +124,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Miscellaneous::hasToolTip (const MWWorld::Ptr& ptr) const @@ -133,7 +132,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Miscellaneous::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -143,13 +142,13 @@ namespace MWClass MWGui::ToolTipInfo info; - const ESMS::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); + const MWWorld::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); int count = ptr.getRefData().getCount(); - bool isGold = (ref->base->mName == store.gameSettings.find("sGold")->getString()); + bool isGold = (ref->mBase->mName == store.get().find("sGold")->getString()); if (isGold && count == 1) - count = ref->base->mData.mValue; + count = ref->mBase->mData.mValue; std::string countString; if (!isGold) @@ -157,12 +156,12 @@ namespace MWClass else // gold displays its count also if it's 1. countString = " (" + boost::lexical_cast(count) + ")"; - info.caption = ref->base->mName + countString; - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + countString; + info.icon = ref->mBase->mIcon; - if (ref->ref.mSoul != "") + if (ref->mRef.mSoul != "") { - const ESM::Creature *creature = store.creatures.search(ref->ref.mSoul); + const ESM::Creature *creature = store.get().find(ref->mRef.mSoul); info.caption += " (" + creature->mName + ")"; } @@ -170,13 +169,13 @@ namespace MWClass if (!isGold) { - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight); - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight); + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); } if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } info.text = text; @@ -189,10 +188,10 @@ namespace MWClass { MWWorld::Ptr newPtr; - const ESMS::ESMStore &store = + const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); - if (MWWorld::Class::get(ptr).getName(ptr) == store.gameSettings.find("sGold")->getString()) { + if (MWWorld::Class::get(ptr).getName(ptr) == store.get().find("sGold")->getString()) { int goldAmount = ptr.getRefData().getCount(); std::string base = "Gold_001"; @@ -210,11 +209,11 @@ namespace MWClass MWWorld::ManualRef newRef(store, base); MWWorld::LiveCellRef *ref = newRef.getPtr().get(); - newPtr = MWWorld::Ptr(&cell.miscItems.insert(*ref), &cell); + newPtr = MWWorld::Ptr(&cell.mMiscItems.insert(*ref), &cell); } else { MWWorld::LiveCellRef *ref = ptr.get(); - newPtr = MWWorld::Ptr(&cell.miscItems.insert(*ref), &cell); + newPtr = MWWorld::Ptr(&cell.mMiscItems.insert(*ref), &cell); } return newPtr; } diff --git a/apps/openmw/mwclass/npc.cpp b/apps/openmw/mwclass/npc.cpp index 03b5e56aa..83a002447 100644 --- a/apps/openmw/mwclass/npc.cpp +++ b/apps/openmw/mwclass/npc.cpp @@ -20,6 +20,7 @@ #include "../mwworld/ptr.hpp" #include "../mwworld/actiontalk.hpp" +#include "../mwworld/actionopen.hpp" #include "../mwworld/inventorystore.hpp" #include "../mwworld/customdata.hpp" #include "../mwworld/physicssystem.hpp" @@ -61,53 +62,62 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); // NPC stats - if (!ref->base->mFaction.empty()) + if (!ref->mBase->mFaction.empty()) { - std::string faction = ref->base->mFaction; + std::string faction = ref->mBase->mFaction; boost::algorithm::to_lower(faction); - if(ref->base->mNpdt52.mGold != -10) + if(ref->mBase->mNpdt52.mGold != -10) { - data->mNpcStats.getFactionRanks()[faction] = (int)ref->base->mNpdt52.mRank; + data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt52.mRank; } else { - data->mNpcStats.getFactionRanks()[faction] = (int)ref->base->mNpdt12.mRank; + data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt12.mRank; } } // creature stats - if(ref->base->mNpdt52.mGold != -10) + if(ref->mBase->mNpdt52.mGold != -10) { for (int i=0; i<27; ++i) - data->mNpcStats.getSkill (i).setBase (ref->base->mNpdt52.mSkills[i]); + data->mNpcStats.getSkill (i).setBase (ref->mBase->mNpdt52.mSkills[i]); - data->mCreatureStats.getAttribute(0).set (ref->base->mNpdt52.mStrength); - data->mCreatureStats.getAttribute(1).set (ref->base->mNpdt52.mIntelligence); - data->mCreatureStats.getAttribute(2).set (ref->base->mNpdt52.mWillpower); - data->mCreatureStats.getAttribute(3).set (ref->base->mNpdt52.mAgility); - data->mCreatureStats.getAttribute(4).set (ref->base->mNpdt52.mSpeed); - data->mCreatureStats.getAttribute(5).set (ref->base->mNpdt52.mEndurance); - data->mCreatureStats.getAttribute(6).set (ref->base->mNpdt52.mPersonality); - data->mCreatureStats.getAttribute(7).set (ref->base->mNpdt52.mLuck); - data->mCreatureStats.getHealth().set (ref->base->mNpdt52.mHealth); - data->mCreatureStats.getMagicka().set (ref->base->mNpdt52.mMana); - data->mCreatureStats.getFatigue().set (ref->base->mNpdt52.mFatigue); + data->mCreatureStats.getAttribute(0).set (ref->mBase->mNpdt52.mStrength); + data->mCreatureStats.getAttribute(1).set (ref->mBase->mNpdt52.mIntelligence); + data->mCreatureStats.getAttribute(2).set (ref->mBase->mNpdt52.mWillpower); + data->mCreatureStats.getAttribute(3).set (ref->mBase->mNpdt52.mAgility); + data->mCreatureStats.getAttribute(4).set (ref->mBase->mNpdt52.mSpeed); + data->mCreatureStats.getAttribute(5).set (ref->mBase->mNpdt52.mEndurance); + data->mCreatureStats.getAttribute(6).set (ref->mBase->mNpdt52.mPersonality); + data->mCreatureStats.getAttribute(7).set (ref->mBase->mNpdt52.mLuck); + data->mCreatureStats.setHealth (ref->mBase->mNpdt52.mHealth); + data->mCreatureStats.setMagicka (ref->mBase->mNpdt52.mMana); + data->mCreatureStats.setFatigue (ref->mBase->mNpdt52.mFatigue); - data->mCreatureStats.setLevel(ref->base->mNpdt52.mLevel); + data->mCreatureStats.setLevel(ref->mBase->mNpdt52.mLevel); + data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt52.mDisposition); + data->mNpcStats.setReputation(ref->mBase->mNpdt52.mReputation); } else { /// \todo do something with mNpdt12 maybe:p + for (int i=0; i<8; ++i) + data->mCreatureStats.getAttribute (i).set (10); + + for (int i=0; i<3; ++i) + data->mCreatureStats.setDynamic (i, 10); + + data->mCreatureStats.setLevel (1); } - data->mCreatureStats.setHello(ref->base->mAiData.mHello); - data->mCreatureStats.setFight(ref->base->mAiData.mFight); - data->mCreatureStats.setFlee(ref->base->mAiData.mFlee); - data->mCreatureStats.setAlarm(ref->base->mAiData.mAlarm); + data->mCreatureStats.setAiSetting (0, ref->mBase->mAiData.mHello); + data->mCreatureStats.setAiSetting (1, ref->mBase->mAiData.mFight); + data->mCreatureStats.setAiSetting (2, ref->mBase->mAiData.mFlee); + data->mCreatureStats.setAiSetting (3, ref->mBase->mAiData.mAlarm); // spells - for (std::vector::const_iterator iter (ref->base->mSpells.mList.begin()); - iter!=ref->base->mSpells.mList.end(); ++iter) + for (std::vector::const_iterator iter (ref->mBase->mSpells.mList.begin()); + iter!=ref->mBase->mSpells.mList.end(); ++iter) data->mCreatureStats.getSpells().add (*iter); // store @@ -120,7 +130,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mId; + return ref->mBase->mId; } void Npc::insertObjectRendering (const MWWorld::Ptr& ptr, MWRender::RenderingInterface& renderingInterface) const @@ -130,7 +140,7 @@ namespace MWClass void Npc::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { - physics.insertActorPhysics(ptr, getModel(ptr)); + physics.addActor(ptr); MWBase::Environment::get().getMechanicsManager()->addActor(ptr); } @@ -138,9 +148,9 @@ namespace MWClass { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - std::string headID = ref->base->mHead; + std::string headID = ref->mBase->mHead; int end = headID.find_last_of("head_") - 4; std::string bodyRaceID = headID.substr(0, end); @@ -162,7 +172,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } MWMechanics::CreatureStats& Npc::getCreatureStats (const MWWorld::Ptr& ptr) const @@ -182,7 +192,10 @@ namespace MWClass boost::shared_ptr Npc::activate (const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const { - return boost::shared_ptr (new MWWorld::ActionTalk (ptr)); + if (MWWorld::Class::get (ptr).getCreatureStats (ptr).isDead()) + return boost::shared_ptr (new MWWorld::ActionOpen(ptr)); + else + return boost::shared_ptr (new MWWorld::ActionTalk (ptr)); } MWWorld::ContainerStore& Npc::getContainerStore (const MWWorld::Ptr& ptr) @@ -206,7 +219,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } void Npc::setForceStance (const MWWorld::Ptr& ptr, Stance stance, bool force) const @@ -308,7 +321,15 @@ namespace MWClass return vector; } + + bool Npc::isEssential (const MWWorld::Ptr& ptr) const + { + MWWorld::LiveCellRef *ref = + ptr.get(); + return ref->mBase->mFlags & ESM::NPC::Essential; + } + void Npc::registerSelf() { boost::shared_ptr instance (new Npc); @@ -328,11 +349,11 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName; + info.caption = ref->mBase->mName; std::string text; if (MWBase::Environment::get().getWindowManager()->getFullHelp()) - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); info.text = text; return info; @@ -376,8 +397,10 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - const ESM::Class *class_ = MWBase::Environment::get().getWorld()->getStore().classes.find ( - ref->base->mClass); + const ESM::Class *class_ = + MWBase::Environment::get().getWorld()->getStore().get().find ( + ref->mBase->mClass + ); stats.useSkill (skill, *class_, usageType); } @@ -394,6 +417,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.npcs.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mNpcs.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/npc.hpp b/apps/openmw/mwclass/npc.hpp index edb6ca40f..20c2da4b1 100644 --- a/apps/openmw/mwclass/npc.hpp +++ b/apps/openmw/mwclass/npc.hpp @@ -90,6 +90,9 @@ namespace MWClass virtual void adjustRotation(const MWWorld::Ptr& ptr,float& x,float& y,float& z) const; + virtual bool isEssential (const MWWorld::Ptr& ptr) const; + ///< Is \a ptr essential? (i.e. may losing \a ptr make the game unwinnable) + static void registerSelf(); virtual std::string getModel(const MWWorld::Ptr &ptr) const; diff --git a/apps/openmw/mwclass/potion.cpp b/apps/openmw/mwclass/potion.cpp index f641cc719..09d152de7 100644 --- a/apps/openmw/mwclass/potion.cpp +++ b/apps/openmw/mwclass/potion.cpp @@ -34,18 +34,17 @@ namespace MWClass void Potion::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Potion::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -57,7 +56,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Potion::activate (const MWWorld::Ptr& ptr, @@ -76,7 +75,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } int Potion::getValue (const MWWorld::Ptr& ptr) const @@ -84,7 +83,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } void Potion::registerSelf() @@ -109,7 +108,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Potion::hasToolTip (const MWWorld::Ptr& ptr) const @@ -117,7 +116,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Potion::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -126,20 +125,20 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.icon = ref->mBase->mIcon; std::string text; - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight); - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight); + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); - info.effects = MWGui::Widgets::MWEffectList::effectListFromESM(&ref->base->mEffects); + info.effects = MWGui::Widgets::MWEffectList::effectListFromESM(&ref->mBase->mEffects); info.isPotion = true; if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } info.text = text; @@ -157,7 +156,7 @@ namespace MWClass MWWorld::Ptr actor = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); boost::shared_ptr action ( - new MWWorld::ActionApply (actor, ref->base->mId)); + new MWWorld::ActionApply (actor, ref->mBase->mId)); action->setSound ("Drink"); @@ -170,6 +169,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.potions.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mPotions.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/probe.cpp b/apps/openmw/mwclass/probe.cpp index 39472f2ec..0d8653aa8 100644 --- a/apps/openmw/mwclass/probe.cpp +++ b/apps/openmw/mwclass/probe.cpp @@ -34,18 +34,17 @@ namespace MWClass void Probe::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Probe::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -57,7 +56,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Probe::activate (const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) const @@ -74,7 +73,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } std::pair, bool> Probe::getEquipmentSlots (const MWWorld::Ptr& ptr) const @@ -91,7 +90,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } void Probe::registerSelf() @@ -116,7 +115,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Probe::hasToolTip (const MWWorld::Ptr& ptr) const @@ -124,7 +123,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Probe::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -133,21 +132,21 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.icon = ref->mBase->mIcon; std::string text; /// \todo store remaining uses somewhere - text += "\n#{sUses}: " + MWGui::ToolTips::toString(ref->base->mData.mUses); - text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->base->mData.mQuality); - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight); - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sUses}: " + MWGui::ToolTips::toString(ref->mBase->mData.mUses); + text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->mBase->mData.mQuality); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight); + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } info.text = text; @@ -170,6 +169,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.probes.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mProbes.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/repair.cpp b/apps/openmw/mwclass/repair.cpp index 7ccb34913..edb28d16c 100644 --- a/apps/openmw/mwclass/repair.cpp +++ b/apps/openmw/mwclass/repair.cpp @@ -32,18 +32,17 @@ namespace MWClass void Repair::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Repair::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -55,7 +54,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Repair::activate (const MWWorld::Ptr& ptr, @@ -73,7 +72,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } int Repair::getValue (const MWWorld::Ptr& ptr) const @@ -81,7 +80,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } void Repair::registerSelf() @@ -106,7 +105,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Repair::hasToolTip (const MWWorld::Ptr& ptr) const @@ -114,7 +113,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Repair::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -123,21 +122,21 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.icon = ref->mBase->mIcon; std::string text; /// \todo store remaining uses somewhere - text += "\n#{sUses}: " + MWGui::ToolTips::toString(ref->base->mData.mUses); - text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->base->mData.mQuality); - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight); - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sUses}: " + MWGui::ToolTips::toString(ref->mBase->mData.mUses); + text += "\n#{sQuality}: " + MWGui::ToolTips::toString(ref->mBase->mData.mQuality); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight); + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } info.text = text; @@ -151,6 +150,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.repairs.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mRepairs.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/static.cpp b/apps/openmw/mwclass/static.cpp index 07ab54256..026eada7b 100644 --- a/apps/openmw/mwclass/static.cpp +++ b/apps/openmw/mwclass/static.cpp @@ -24,18 +24,17 @@ namespace MWClass void Static::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Static::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -60,6 +59,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.statics.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mStatics.insert(*ref), &cell); } } diff --git a/apps/openmw/mwclass/weapon.cpp b/apps/openmw/mwclass/weapon.cpp index fee0dfdf1..c8fe0d276 100644 --- a/apps/openmw/mwclass/weapon.cpp +++ b/apps/openmw/mwclass/weapon.cpp @@ -34,18 +34,17 @@ namespace MWClass void Weapon::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const { const std::string model = getModel(ptr); - if(!model.empty()) { - physics.insertObjectPhysics(ptr, model); - } + if(!model.empty()) + physics.addObject(ptr); } std::string Weapon::getModel(const MWWorld::Ptr &ptr) const { MWWorld::LiveCellRef *ref = ptr.get(); - assert(ref->base != NULL); + assert(ref->mBase != NULL); - const std::string &model = ref->base->mModel; + const std::string &model = ref->mBase->mModel; if (!model.empty()) { return "meshes\\" + model; } @@ -57,7 +56,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mName; + return ref->mBase->mName; } boost::shared_ptr Weapon::activate (const MWWorld::Ptr& ptr, @@ -80,7 +79,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mHealth; + return ref->mBase->mData.mHealth; } std::string Weapon::getScript (const MWWorld::Ptr& ptr) const @@ -88,7 +87,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mScript; + return ref->mBase->mScript; } std::pair, bool> Weapon::getEquipmentSlots (const MWWorld::Ptr& ptr) const @@ -99,12 +98,12 @@ namespace MWClass std::vector slots; bool stack = false; - if (ref->base->mData.mType==ESM::Weapon::Arrow || ref->base->mData.mType==ESM::Weapon::Bolt) + if (ref->mBase->mData.mType==ESM::Weapon::Arrow || ref->mBase->mData.mType==ESM::Weapon::Bolt) { slots.push_back (int (MWWorld::InventoryStore::Slot_Ammunition)); stack = true; } - else if (ref->base->mData.mType==ESM::Weapon::MarksmanThrown) + else if (ref->mBase->mData.mType==ESM::Weapon::MarksmanThrown) { slots.push_back (int (MWWorld::InventoryStore::Slot_CarriedRight)); stack = true; @@ -139,7 +138,7 @@ namespace MWClass }; for (int i=0; ibase->mData.mType) + if (sMapping[i][0]==ref->mBase->mData.mType) return sMapping[i][1]; return -1; @@ -150,7 +149,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mData.mValue; + return ref->mBase->mData.mValue; } void Weapon::registerSelf() @@ -165,7 +164,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - int type = ref->base->mData.mType; + int type = ref->mBase->mData.mType; // Ammo if (type == 12 || type == 13) { @@ -211,7 +210,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - int type = ref->base->mData.mType; + int type = ref->mBase->mData.mType; // Ammo if (type == 12 || type == 13) { @@ -257,7 +256,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mIcon; + return ref->mBase->mIcon; } bool Weapon::hasToolTip (const MWWorld::Ptr& ptr) const @@ -265,7 +264,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return (ref->base->mName != ""); + return (ref->mBase->mName != ""); } MWGui::ToolTipInfo Weapon::getToolTipInfo (const MWWorld::Ptr& ptr) const @@ -274,15 +273,15 @@ namespace MWClass ptr.get(); MWGui::ToolTipInfo info; - info.caption = ref->base->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); - info.icon = ref->base->mIcon; + info.caption = ref->mBase->mName + MWGui::ToolTips::getCountString(ptr.getRefData().getCount()); + info.icon = ref->mBase->mIcon; - const ESMS::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); + const MWWorld::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); std::string text; // weapon type & damage. arrows / bolts don't have his info. - if (ref->base->mData.mType < 12) + if (ref->mBase->mData.mType < 12) { text += "\n#{sType} "; @@ -300,49 +299,49 @@ namespace MWClass mapping[ESM::Weapon::MarksmanCrossbow] = std::make_pair("sSkillMarksman", ""); mapping[ESM::Weapon::MarksmanThrown] = std::make_pair("sSkillMarksman", ""); - std::string type = mapping[ref->base->mData.mType].first; - std::string oneOrTwoHanded = mapping[ref->base->mData.mType].second; + std::string type = mapping[ref->mBase->mData.mType].first; + std::string oneOrTwoHanded = mapping[ref->mBase->mData.mType].second; - text += store.gameSettings.find(type)->getString() + - ((oneOrTwoHanded != "") ? ", " + store.gameSettings.find(oneOrTwoHanded)->getString() : ""); + text += store.get().find(type)->getString() + + ((oneOrTwoHanded != "") ? ", " + store.get().find(oneOrTwoHanded)->getString() : ""); // weapon damage - if (ref->base->mData.mType >= 9) + if (ref->mBase->mData.mType >= 9) { // marksman text += "\n#{sAttack}: " - + MWGui::ToolTips::toString(static_cast(ref->base->mData.mChop[0])) - + " - " + MWGui::ToolTips::toString(static_cast(ref->base->mData.mChop[1])); + + MWGui::ToolTips::toString(static_cast(ref->mBase->mData.mChop[0])) + + " - " + MWGui::ToolTips::toString(static_cast(ref->mBase->mData.mChop[1])); } else { // Chop text += "\n#{sChop}: " - + MWGui::ToolTips::toString(static_cast(ref->base->mData.mChop[0])) - + " - " + MWGui::ToolTips::toString(static_cast(ref->base->mData.mChop[1])); + + MWGui::ToolTips::toString(static_cast(ref->mBase->mData.mChop[0])) + + " - " + MWGui::ToolTips::toString(static_cast(ref->mBase->mData.mChop[1])); // Slash text += "\n#{sSlash}: " - + MWGui::ToolTips::toString(static_cast(ref->base->mData.mSlash[0])) - + " - " + MWGui::ToolTips::toString(static_cast(ref->base->mData.mSlash[1])); + + MWGui::ToolTips::toString(static_cast(ref->mBase->mData.mSlash[0])) + + " - " + MWGui::ToolTips::toString(static_cast(ref->mBase->mData.mSlash[1])); // Thrust text += "\n#{sThrust}: " - + MWGui::ToolTips::toString(static_cast(ref->base->mData.mThrust[0])) - + " - " + MWGui::ToolTips::toString(static_cast(ref->base->mData.mThrust[1])); + + MWGui::ToolTips::toString(static_cast(ref->mBase->mData.mThrust[0])) + + " - " + MWGui::ToolTips::toString(static_cast(ref->mBase->mData.mThrust[1])); } } /// \todo store the current weapon health somewhere - if (ref->base->mData.mType < 11) // thrown weapons and arrows/bolts don't have health, only quantity - text += "\n#{sCondition}: " + MWGui::ToolTips::toString(ref->base->mData.mHealth); + if (ref->mBase->mData.mType < 11) // thrown weapons and arrows/bolts don't have health, only quantity + text += "\n#{sCondition}: " + MWGui::ToolTips::toString(ref->mBase->mData.mHealth); - text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->base->mData.mWeight); - text += MWGui::ToolTips::getValueString(ref->base->mData.mValue, "#{sValue}"); + text += "\n#{sWeight}: " + MWGui::ToolTips::toString(ref->mBase->mData.mWeight); + text += MWGui::ToolTips::getValueString(ref->mBase->mData.mValue, "#{sValue}"); - info.enchant = ref->base->mEnchant; + info.enchant = ref->mBase->mEnchant; if (MWBase::Environment::get().getWindowManager()->getFullHelp()) { - text += MWGui::ToolTips::getMiscString(ref->ref.mOwner, "Owner"); - text += MWGui::ToolTips::getMiscString(ref->base->mScript, "Script"); + text += MWGui::ToolTips::getMiscString(ref->mRef.mOwner, "Owner"); + text += MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script"); } info.text = text; @@ -355,7 +354,7 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return ref->base->mEnchant; + return ref->mBase->mEnchant; } boost::shared_ptr Weapon::use (const MWWorld::Ptr& ptr) const @@ -373,6 +372,6 @@ namespace MWClass MWWorld::LiveCellRef *ref = ptr.get(); - return MWWorld::Ptr(&cell.weapons.insert(*ref), &cell); + return MWWorld::Ptr(&cell.mWeapons.insert(*ref), &cell); } } diff --git a/apps/openmw/mwdialogue/dialoguemanagerimp.cpp b/apps/openmw/mwdialogue/dialoguemanagerimp.cpp index f37955c7e..31cef7f70 100644 --- a/apps/openmw/mwdialogue/dialoguemanagerimp.cpp +++ b/apps/openmw/mwdialogue/dialoguemanagerimp.cpp @@ -6,23 +6,7 @@ #include #include - -#include - -#include "../mwbase/environment.hpp" -#include "../mwbase/world.hpp" -#include "../mwbase/scriptmanager.hpp" -#include "../mwbase/journal.hpp" -#include "../mwbase/windowmanager.hpp" - -#include "../mwworld/class.hpp" -#include "../mwworld/refdata.hpp" -#include "../mwworld/player.hpp" -#include "../mwworld/containerstore.hpp" - -#include "../mwgui/dialogue.hpp" - -#include +#include #include #include @@ -30,15 +14,31 @@ #include #include #include + #include +#include "../mwbase/environment.hpp" +#include "../mwbase/world.hpp" +#include "../mwbase/scriptmanager.hpp" +#include "../mwbase/windowmanager.hpp" +#include "../mwbase/mechanicsmanager.hpp" + +#include "../mwworld/class.hpp" +#include "../mwworld/containerstore.hpp" +#include "../mwworld/esmstore.hpp" +#include "../mwworld/player.hpp" + +#include "../mwgui/dialogue.hpp" + #include "../mwscript/compilercontext.hpp" #include "../mwscript/interpretercontext.hpp" #include "../mwscript/extensions.hpp" -#include "../mwclass/npc.hpp" +#include "../mwmechanics/creaturestats.hpp" #include "../mwmechanics/npcstats.hpp" +#include "filter.hpp" + namespace { std::string toLower (const std::string& name) @@ -66,533 +66,34 @@ namespace return false; } - template - bool selectCompare (char comp, T1 value1, T2 value2) - { - switch (comp) - { - case '0': return value1==value2; - case '1': return value1!=value2; - case '2': return value1>value2; - case '3': return value1>=value2; - case '4': return value1 - bool checkLocal (char comp, const std::string& name, T value, const MWWorld::Ptr& actor, - const ESMS::ESMStore& store) - { - std::string scriptName = MWWorld::Class::get (actor).getScript (actor); - - if (scriptName.empty()) - return false; // no script - - const ESM::Script *script = store.scripts.find (scriptName); - - int i = 0; - - for (; i (script->mVarNames.size()); ++i) - if (script->mVarNames[i]==name) - break; - - if (i>=static_cast (script->mVarNames.size())) - return false; // script does not have a variable of this name - - const MWScript::Locals& locals = actor.getRefData().getLocals(); - - if (imData.mNumShorts) - return selectCompare (comp, locals.mShorts[i], value); - else - i -= script->mData.mNumShorts; - - if (imData.mNumLongs) - return selectCompare (comp, locals.mLongs[i], value); - else - i -= script->mData.mNumShorts; - - return selectCompare (comp, locals.mFloats.at (i), value); - } - - template - bool checkGlobal (char comp, const std::string& name, T value) - { - switch (MWBase::Environment::get().getWorld()->getGlobalVariableType (name)) - { - case 's': - return selectCompare (comp, MWBase::Environment::get().getWorld()->getGlobalVariable (name).mShort, value); - - case 'l': - - return selectCompare (comp, MWBase::Environment::get().getWorld()->getGlobalVariable (name).mLong, value); - - case 'f': - - return selectCompare (comp, MWBase::Environment::get().getWorld()->getGlobalVariable (name).mFloat, value); - - case ' ': - - MWBase::Environment::get().getWorld()->getGlobalVariable (name); // trigger exception - break; - - default: - - throw std::runtime_error ("unsupported gobal variable type"); - } - - return false; - } -} - -namespace MWDialogue -{ - //helper function std::string::size_type find_str_ci(const std::string& str, const std::string& substr,size_t pos) { return toLower(str).find(toLower(substr),pos); } +} - bool DialogueManager::functionFilter(const MWWorld::Ptr& actor, const ESM::DialInfo& info,bool choice) - { - bool isCreature = (actor.getTypeName() != typeid(ESM::NPC).name()); - - for (std::vector::const_iterator iter (info.mSelects.begin()); - iter != info.mSelects.end(); ++iter) - { - ESM::DialInfo::SelectStruct select = *iter; - char type = select.mSelectRule[1]; - if(type == '1') - { - char comp = select.mSelectRule[4]; - std::string name = select.mSelectRule.substr (5); - std::string function = select.mSelectRule.substr(2,2); - - int ifunction; - std::istringstream iss(function); - iss >> ifunction; - switch(ifunction) - { - case 39://PC Expelled - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 40://PC Common Disease - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 41://PC Blight Disease - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 43://PC Crime level - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 46://Same faction - { - if (isCreature) - return false; - - MWMechanics::NpcStats PCstats = MWWorld::Class::get(MWBase::Environment::get().getWorld()->getPlayer().getPlayer()).getNpcStats(MWBase::Environment::get().getWorld()->getPlayer().getPlayer()); - MWMechanics::NpcStats NPCstats = MWWorld::Class::get(actor).getNpcStats(actor); - int sameFaction = 0; - if(!NPCstats.getFactionRanks().empty()) - { - std::string NPCFaction = NPCstats.getFactionRanks().begin()->first; - if(PCstats.getFactionRanks().find(toLower(NPCFaction)) != PCstats.getFactionRanks().end()) sameFaction = 1; - } - if(!selectCompare(comp,sameFaction,select.mI)) return false; - } - break; - - case 48://Detected - if(!selectCompare(comp,1,select.mI)) return false; - break; - - case 49://Alarmed - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 50://choice - if(choice) - { - if(!selectCompare(comp,mChoice,select.mI)) return false; - } - break; - - case 60://PC Vampire - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 61://Level - if(!selectCompare(comp,1,select.mI)) return false; - break; - - case 62://Attacked - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 63://Talked to PC - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 64://PC Health - if(!selectCompare(comp,50,select.mI)) return false; - break; - - case 65://Creature target - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 66://Friend hit - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 67://Fight - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 68://Hello???? - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 69://Alarm - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 70://Flee - if(!selectCompare(comp,0,select.mI)) return false; - break; - - case 71://Should Attack - if(!selectCompare(comp,0,select.mI)) return false; - break; - - default: - break; - - } - } - } - - return true; - } - - bool DialogueManager::isMatching (const MWWorld::Ptr& actor, - const ESM::DialInfo::SelectStruct& select) const - { - bool isCreature = (actor.getTypeName() != typeid(ESM::NPC).name()); - - char type = select.mSelectRule[1]; - - if (type!='0') - { - char comp = select.mSelectRule[4]; - std::string name = select.mSelectRule.substr (5); - std::string function = select.mSelectRule.substr(1,2); - - switch (type) - { - case '1': // function - - return true; // Done elsewhere. - - case '2': // global - - if (select.mType==ESM::VT_Short || select.mType==ESM::VT_Int || - select.mType==ESM::VT_Long) - { - if (!checkGlobal (comp, toLower (name), select.mI)) - return false; - } - else if (select.mType==ESM::VT_Float) - { - if (!checkGlobal (comp, toLower (name), select.mF)) - return false; - } - else - throw std::runtime_error ( - "unsupported variable type in dialogue info select"); - - return true; - - case '3': // local - - if (select.mType==ESM::VT_Short || select.mType==ESM::VT_Int || - select.mType==ESM::VT_Long) - { - if (!checkLocal (comp, toLower (name), select.mI, actor, - MWBase::Environment::get().getWorld()->getStore())) - return false; - } - else if (select.mType==ESM::VT_Float) - { - if (!checkLocal (comp, toLower (name), select.mF, actor, - MWBase::Environment::get().getWorld()->getStore())) - return false; - } - else - throw std::runtime_error ( - "unsupported variable type in dialogue info select"); - - return true; - - case '4'://journal - if(select.mType==ESM::VT_Int) - { - if(!selectCompare(comp,MWBase::Environment::get().getJournal()->getJournalIndex(toLower(name)),select.mI)) return false; - } - else - throw std::runtime_error ( - "unsupported variable type in dialogue info select"); - - return true; - - case '5'://item - { - MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); - MWWorld::ContainerStore& store = MWWorld::Class::get (player).getContainerStore (player); - - int sum = 0; - - for (MWWorld::ContainerStoreIterator iter (store.begin()); iter!=store.end(); ++iter) - if (toLower(iter->getCellRef().mRefID) == toLower(name)) - sum += iter->getRefData().getCount(); - if(!selectCompare(comp,sum,select.mI)) return false; - } - - return true; - - - case '6'://dead - if(!selectCompare(comp,0,select.mI)) return false; - - case '7':// not ID - if(select.mType==ESM::VT_String ||select.mType==ESM::VT_Int)//bug in morrowind here? it's not a short, it's a string - { - int isID = int(toLower(name)==toLower(MWWorld::Class::get (actor).getId (actor))); - if (selectCompare(comp,!isID,select.mI)) return false; - } - else - throw std::runtime_error ( - "unsupported variable type in dialogue info select"); - - return true; - - case '8':// not faction - if (isCreature) - return false; - - if(select.mType==ESM::VT_Int) - { - MWWorld::LiveCellRef* npc = actor.get(); - int isFaction = int(toLower(npc->base->mFaction) == toLower(name)); - if(selectCompare(comp,!isFaction,select.mI)) - return false; - } - else - throw std::runtime_error ( - "unsupported variable type in dialogue info select"); - - return true; - - case '9':// not class - if (isCreature) - return false; - - if(select.mType==ESM::VT_Int) - { - MWWorld::LiveCellRef* npc = actor.get(); - int isClass = int(toLower(npc->base->mClass) == toLower(name)); - if(selectCompare(comp,!isClass,select.mI)) - return false; - } - else - throw std::runtime_error ( - "unsupported variable type in dialogue info select"); - - return true; - - case 'A'://not Race - if (isCreature) - return false; - - if(select.mType==ESM::VT_Int) - { - MWWorld::LiveCellRef* npc = actor.get(); - int isRace = int(toLower(npc->base->mRace) == toLower(name)); - if(selectCompare(comp,!isRace,select.mI)) - return false; - } - else - throw std::runtime_error ( - "unsupported variable type in dialogue info select"); - - return true; - - case 'B'://not Cell - if(select.mType==ESM::VT_Int) - { - int isCell = int(toLower(actor.getCell()->cell->mName) == toLower(name)); - if(selectCompare(comp,!isCell,select.mI)) - return false; - } - else - throw std::runtime_error ( - "unsupported variable type in dialogue info select"); - return true; - - case 'C'://not local - if (select.mType==ESM::VT_Short || select.mType==ESM::VT_Int || - select.mType==ESM::VT_Long) - { - if (checkLocal (comp, toLower (name), select.mI, actor, - MWBase::Environment::get().getWorld()->getStore())) - return false; - } - else if (select.mType==ESM::VT_Float) - { - if (checkLocal (comp, toLower (name), select.mF, actor, - MWBase::Environment::get().getWorld()->getStore())) - return false; - } - else - throw std::runtime_error ( - "unsupported variable type in dialogue info select"); - return true; - - - default: - - std::cout << "unchecked select: " << type << " " << comp << " " << name << std::endl; - } - } - - return true; - } - - bool DialogueManager::isMatching (const MWWorld::Ptr& actor, const ESM::DialInfo& info) const - { - bool isCreature = (actor.getTypeName() != typeid(ESM::NPC).name()); - - // actor id - if (!info.mActor.empty()) - if (toLower (info.mActor)!=MWWorld::Class::get (actor).getId (actor)) - return false; - - //NPC race - if (!info.mRace.empty()) - { - if (isCreature) - return false; - - MWWorld::LiveCellRef *cellRef = actor.get(); - - if (!cellRef) - return false; - - if (toLower (info.mRace)!=toLower (cellRef->base->mRace)) - return false; - } - - //NPC class - if (!info.mClass.empty()) - { - if (isCreature) - return false; - - MWWorld::LiveCellRef *cellRef = actor.get(); - - if (!cellRef) - return false; - - if (toLower (info.mClass)!=toLower (cellRef->base->mClass)) - return false; - } - - //NPC faction - if (!info.mNpcFaction.empty()) - { - if (isCreature) - return false; - - //MWWorld::Class npcClass = MWWorld::Class::get(actor); - MWMechanics::NpcStats stats = MWWorld::Class::get(actor).getNpcStats(actor); - std::map::iterator it = stats.getFactionRanks().find(toLower(info.mNpcFaction)); - if(it!=stats.getFactionRanks().end()) - { - //check rank - if(it->second < (int)info.mData.mRank) return false; - } - else - { - //not in the faction - return false; - } - } - - // TODO check player faction - if(!info.mPcFaction.empty()) - { - MWMechanics::NpcStats stats = MWWorld::Class::get(MWBase::Environment::get().getWorld()->getPlayer().getPlayer()).getNpcStats(MWBase::Environment::get().getWorld()->getPlayer().getPlayer()); - std::map::iterator it = stats.getFactionRanks().find(toLower(info.mPcFaction)); - if(it!=stats.getFactionRanks().end()) - { - //check rank - if(it->second < (int)info.mData.mPCrank) return false; - } - else - { - //not in the faction - return false; - } - } - - //check gender - if (!isCreature) - { - MWWorld::LiveCellRef* npc = actor.get(); - if(npc->base->mFlags & npc->base->Female) - { - if(static_cast (info.mData.mGender)==0) return false; - } - else - { - if(static_cast (info.mData.mGender)==1) return false; - } - } - - // check cell - if (!info.mCell.empty()) - if (MWBase::Environment::get().getWorld()->getPlayer().getPlayer().getCell()->cell->mName != info.mCell) - return false; - - // TODO check DATAstruct - for (std::vector::const_iterator iter (info.mSelects.begin()); - iter != info.mSelects.end(); ++iter) - if (!isMatching (actor, *iter)) - return false; - - return true; - } - - DialogueManager::DialogueManager (const Compiler::Extensions& extensions) : +namespace MWDialogue +{ + DialogueManager::DialogueManager (const Compiler::Extensions& extensions, bool scriptVerbose) : mCompilerContext (MWScript::CompilerContext::Type_Dialgoue), mErrorStream(std::cout.rdbuf()),mErrorHandler(mErrorStream) + , mTemporaryDispositionChange(0.f) + , mPermanentDispositionChange(0.f), mScriptVerbose (scriptVerbose) { mChoice = -1; mIsInChoice = false; mCompilerContext.setExtensions (&extensions); mDialogueMap.clear(); mActorKnownTopics.clear(); - ESMS::RecListCaseT::MapType dialogueList = MWBase::Environment::get().getWorld()->getStore().dialogs.list; - for(ESMS::RecListCaseT::MapType::iterator it = dialogueList.begin(); it!=dialogueList.end();it++) + + const MWWorld::Store &dialogs = + MWBase::Environment::get().getWorld()->getStore().get(); + + MWWorld::Store::iterator it = dialogs.begin(); + for (; it != dialogs.end(); ++it) { - mDialogueMap[toLower(it->first)] = it->second; + mDialogueMap[toLower(it->mId)] = *it; } } @@ -601,7 +102,7 @@ namespace MWDialogue mKnownTopics[toLower(topic)] = true; } - void DialogueManager::parseText (std::string text) + void DialogueManager::parseText (const std::string& text) { std::list::iterator it; for(it = mActorKnownTopics.begin();it != mActorKnownTopics.end();++it) @@ -629,6 +130,10 @@ namespace MWDialogue mActor = actor; + MWMechanics::CreatureStats& creatureStats = MWWorld::Class::get (actor).getCreatureStats (actor); + mTalkedTo = creatureStats.hasTalkedToPlayer(); + creatureStats.talkedToPlayer(); + mActorKnownTopics.clear(); //initialise the GUI @@ -640,34 +145,28 @@ namespace MWDialogue updateTopics(); //greeting - bool greetingFound = false; - //ESMS::RecListT::MapType dialogueList = MWBase::Environment::get().getWorld()->getStore().dialogs.list; - ESMS::RecListCaseT::MapType dialogueList = MWBase::Environment::get().getWorld()->getStore().dialogs.list; - for(ESMS::RecListCaseT::MapType::iterator it = dialogueList.begin(); it!=dialogueList.end();it++) - { - ESM::Dialogue ndialogue = it->second; - if(ndialogue.mType == ESM::Dialogue::Greeting) - { - if (greetingFound) break; - for (std::vector::const_iterator iter (it->second.mInfo.begin()); - iter!=it->second.mInfo.end(); ++iter) - { - if (isMatching (actor, *iter) && functionFilter(mActor,*iter,true)) - { - if (!iter->mSound.empty()) - { - // TODO play sound - } + const MWWorld::Store &dialogs = + MWBase::Environment::get().getWorld()->getStore().get(); - std::string text = iter->mResponse; - parseText(text); - win->addText(iter->mResponse); - executeScript(iter->mResultScript); - greetingFound = true; - mLastTopic = it->first; - mLastDialogue = *iter; - break; + Filter filter (actor, mChoice, mTalkedTo); + + for (MWWorld::Store::iterator it = dialogs.begin(); it != dialogs.end(); ++it) + { + if(it->mType == ESM::Dialogue::Greeting) + { + if (const ESM::DialInfo *info = filter.search (*it)) + { + if (!info->mSound.empty()) + { + // TODO play sound } + + parseText (info->mResponse); + win->addText (info->mResponse); + executeScript (info->mResultScript); + mLastTopic = it->mId; + mLastDialogue = *info; + break; } } } @@ -675,6 +174,8 @@ namespace MWDialogue bool DialogueManager::compile (const std::string& cmd,std::vector& code) { + bool success = true; + try { mErrorHandler.reset(); @@ -696,26 +197,36 @@ namespace MWDialogue Compiler::ScriptParser parser(mErrorHandler,mCompilerContext, locals, false); scanner.scan (parser); - if(mErrorHandler.isGood()) - { - parser.getCode(code); - return true; - } - return false; + + if (!mErrorHandler.isGood()) + success = false; + + if (success) + parser.getCode (code); } catch (const Compiler::SourceException& /* error */) { // error has already been reported via error handler + success = false; } catch (const std::exception& error) { - printError (std::string ("An exception has been thrown: ") + error.what()); + std::cerr << std::string ("Dialogue error: An exception has been thrown: ") + error.what() << std::endl; + success = false; } - return false; + if (!success && mScriptVerbose) + { + std::cerr + << "compiling failed (dialogue script)" << std::endl + << cmd + << std::endl << std::endl; + } + + return success; } - void DialogueManager::executeScript(std::string script) + void DialogueManager::executeScript (const std::string& script) { std::vector code; if(compile(script,code)) @@ -729,7 +240,7 @@ namespace MWDialogue } catch (const std::exception& error) { - printError (std::string ("An exception has been thrown: ") + error.what()); + std::cerr << std::string ("Dialogue error: An exception has been thrown: ") + error.what(); } } } @@ -740,25 +251,24 @@ namespace MWDialogue int choice = mChoice; mChoice = -1; mActorKnownTopics.clear(); - MWGui::DialogueWindow* win = MWBase::Environment::get().getWindowManager()->getDialogueWindow(); - ESMS::RecListCaseT::MapType dialogueList = MWBase::Environment::get().getWorld()->getStore().dialogs.list; - for(ESMS::RecListCaseT::MapType::iterator it = dialogueList.begin(); it!=dialogueList.end();it++) + + const MWWorld::Store &dialogs = + MWBase::Environment::get().getWorld()->getStore().get(); + + Filter filter (mActor, mChoice, mTalkedTo); + + for (MWWorld::Store::iterator iter = dialogs.begin(); iter != dialogs.end(); ++iter) { - ESM::Dialogue ndialogue = it->second; - if(ndialogue.mType == ESM::Dialogue::Topic) + if (iter->mType == ESM::Dialogue::Topic) { - for (std::vector::const_iterator iter (it->second.mInfo.begin()); - iter!=it->second.mInfo.end(); ++iter) + if (filter.search (*iter)) { - if (isMatching (mActor, *iter) && functionFilter(mActor,*iter,true)) + mActorKnownTopics.push_back (toLower (iter->mId)); + + //does the player know the topic? + if (mKnownTopics.find (toLower (iter->mId)) != mKnownTopics.end()) { - mActorKnownTopics.push_back(toLower(it->first)); - //does the player know the topic? - if(mKnownTopics.find(toLower(it->first)) != mKnownTopics.end()) - { - keywordList.push_back(it->first); - break; - } + keywordList.push_back (iter->mId); } } } @@ -769,16 +279,18 @@ namespace MWDialogue if (mActor.getTypeName() == typeid(ESM::NPC).name()) { MWWorld::LiveCellRef* ref = mActor.get(); - if (ref->base->mHasAI) - services = ref->base->mAiData.mServices; + if (ref->mBase->mHasAI) + services = ref->mBase->mAiData.mServices; } else if (mActor.getTypeName() == typeid(ESM::Creature).name()) { MWWorld::LiveCellRef* ref = mActor.get(); - if (ref->base->mHasAI) - services = ref->base->mAiData.mServices; + if (ref->mBase->mHasAI) + services = ref->mBase->mAiData.mServices; } + int windowServices = 0; + if (services & ESM::NPC::Weapon || services & ESM::NPC::Armor || services & ESM::NPC::Clothing @@ -790,14 +302,26 @@ namespace MWDialogue || services & ESM::NPC::Apparatus || services & ESM::NPC::RepairItem || services & ESM::NPC::Misc) - win->setShowTrade(true); - else - win->setShowTrade(false); + windowServices |= MWGui::DialogueWindow::Service_Trade; + + if(mActor.getTypeName() == typeid(ESM::NPC).name() && !mActor.get()->mBase->mTransport.empty()) + windowServices |= MWGui::DialogueWindow::Service_Travel; if (services & ESM::NPC::Spells) - win->setShowSpells(true); - else - win->setShowSpells(false); + windowServices |= MWGui::DialogueWindow::Service_BuySpells; + + if (services & ESM::NPC::Spellmaking) + windowServices |= MWGui::DialogueWindow::Service_CreateSpells; + + if (services & ESM::NPC::Training) + windowServices |= MWGui::DialogueWindow::Service_Training; + + if (services & ESM::NPC::Enchanting) + windowServices |= MWGui::DialogueWindow::Service_Enchant; + + MWGui::DialogueWindow* win = MWBase::Environment::get().getWindowManager()->getDialogueWindow(); + + win->setServices (windowServices); // sort again, because the previous sort was case-sensitive keywordList.sort(stringCompareNoCase); @@ -813,28 +337,25 @@ namespace MWDialogue if(mDialogueMap.find(keyword) != mDialogueMap.end()) { ESM::Dialogue ndialogue = mDialogueMap[keyword]; - if(ndialogue.mType == ESM::Dialogue::Topic) + if (mDialogueMap[keyword].mType == ESM::Dialogue::Topic) { - for (std::vector::const_iterator iter = ndialogue.mInfo.begin(); - iter!=ndialogue.mInfo.end(); ++iter) + Filter filter (mActor, mChoice, mTalkedTo); + + if (const ESM::DialInfo *info = filter.search (mDialogueMap[keyword])) { - if (isMatching (mActor, *iter) && functionFilter(mActor,*iter,true)) - { - std::string text = iter->mResponse; - std::string script = iter->mResultScript; + std::string text = info->mResponse; + std::string script = info->mResultScript; - parseText(text); + parseText (text); - MWGui::DialogueWindow* win = MWBase::Environment::get().getWindowManager()->getDialogueWindow(); - win->addTitle(keyword); - win->addText(iter->mResponse); + MWGui::DialogueWindow* win = MWBase::Environment::get().getWindowManager()->getDialogueWindow(); + win->addTitle (keyword); + win->addText (info->mResponse); - executeScript(script); + executeScript (script); - mLastTopic = keyword; - mLastDialogue = *iter; - break; - } + mLastTopic = keyword; + mLastDialogue = *info; } } } @@ -846,45 +367,49 @@ namespace MWDialogue void DialogueManager::goodbyeSelected() { MWBase::Environment::get().getWindowManager()->removeGuiMode(MWGui::GM_Dialogue); + + // Apply disposition change to NPC's base disposition + if (mActor.getTypeName() == typeid(ESM::NPC).name()) + { + MWMechanics::NpcStats& npcStats = MWWorld::Class::get(mActor).getNpcStats(mActor); + npcStats.setBaseDisposition(npcStats.getBaseDisposition() + mPermanentDispositionChange); + } + mPermanentDispositionChange = 0; + mTemporaryDispositionChange = 0; } void DialogueManager::questionAnswered (const std::string& answer) { - if(mChoiceMap.find(answer) != mChoiceMap.end()) + if (mChoiceMap.find(answer) != mChoiceMap.end()) { mChoice = mChoiceMap[answer]; - std::vector::const_iterator iter; - if(mDialogueMap.find(mLastTopic) != mDialogueMap.end()) + if (mDialogueMap.find(mLastTopic) != mDialogueMap.end()) { - ESM::Dialogue ndialogue = mDialogueMap[mLastTopic]; - if(ndialogue.mType == ESM::Dialogue::Topic) + if (mDialogueMap[mLastTopic].mType == ESM::Dialogue::Topic) { - for (std::vector::const_iterator iter = ndialogue.mInfo.begin(); - iter!=ndialogue.mInfo.end(); ++iter) + Filter filter (mActor, mChoice, mTalkedTo); + + if (const ESM::DialInfo *info = filter.search (mDialogueMap[mLastTopic])) { - if (isMatching (mActor, *iter) && functionFilter(mActor,*iter,true)) - { - mChoiceMap.clear(); - mChoice = -1; - mIsInChoice = false; - MWGui::DialogueWindow* win = MWBase::Environment::get().getWindowManager()->getDialogueWindow(); - std::string text = iter->mResponse; - parseText(text); - win->addText(text); - executeScript(iter->mResultScript); - mLastTopic = mLastTopic; - mLastDialogue = *iter; - break; - } + mChoiceMap.clear(); + mChoice = -1; + mIsInChoice = false; + std::string text = info->mResponse; + parseText (text); + MWBase::Environment::get().getWindowManager()->getDialogueWindow()->addText (text); + executeScript (info->mResultScript); + mLastTopic = mLastTopic; + mLastDialogue = *info; } } } + updateTopics(); } } - void DialogueManager::printError (std::string error) + void DialogueManager::printError (const std::string& error) { MWGui::DialogueWindow* win = MWBase::Environment::get().getWindowManager()->getDialogueWindow(); win->addText(error); @@ -898,22 +423,9 @@ namespace MWDialogue mIsInChoice = true; } - std::string DialogueManager::getFaction() const + MWWorld::Ptr DialogueManager::getActor() const { - if (mActor.getTypeName() != typeid(ESM::NPC).name()) - return ""; - - std::string factionID(""); - MWMechanics::NpcStats stats = MWWorld::Class::get(mActor).getNpcStats(mActor); - if(stats.getFactionRanks().empty()) - { - std::cout << "No faction for this actor!"; - } - else - { - factionID = stats.getFactionRanks().begin()->first; - } - return factionID; + return mActor; } void DialogueManager::goodbye() @@ -922,4 +434,57 @@ namespace MWDialogue win->goodbye(); } + + void DialogueManager::persuade(int type) + { + bool success; + float temp, perm; + MWBase::Environment::get().getMechanicsManager()->getPersuasionDispositionChange( + mActor, MWBase::MechanicsManager::PersuasionType(type), mTemporaryDispositionChange, + success, temp, perm); + mTemporaryDispositionChange += temp; + mPermanentDispositionChange += perm; + + // change temp disposition so that final disposition is between 0...100 + int curDisp = MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(mActor); + if (curDisp + mTemporaryDispositionChange < 0) + mTemporaryDispositionChange = -curDisp; + else if (curDisp + mTemporaryDispositionChange > 100) + mTemporaryDispositionChange = 100 - curDisp; + + // practice skill + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + + if (success) + MWWorld::Class::get(player).skillUsageSucceeded(player, ESM::Skill::Speechcraft, 0); + + // add status message to dialogue window + std::string text; + + if (type == MWBase::MechanicsManager::PT_Admire) + text = "sAdmire"; + else if (type == MWBase::MechanicsManager::PT_Taunt) + text = "sTaunt"; + else if (type == MWBase::MechanicsManager::PT_Intimidate) + text = "sIntimidate"; + else + text = "sBribe"; + + text += (success ? "Success" : "Fail"); + + MWGui::DialogueWindow* win = MWBase::Environment::get().getWindowManager()->getDialogueWindow(); + win->addTitle(MyGUI::LanguageManager::getInstance().replaceTags("#{"+text+"}")); + + /// \todo text from INFO record, how to get the ID? + } + + int DialogueManager::getTemporaryDispositionChange() const + { + return mTemporaryDispositionChange; + } + + void DialogueManager::applyTemporaryDispositionChange(int delta) + { + mTemporaryDispositionChange += delta; + } } diff --git a/apps/openmw/mwdialogue/dialoguemanagerimp.hpp b/apps/openmw/mwdialogue/dialoguemanagerimp.hpp index e3e9fd752..9e1971b0f 100644 --- a/apps/openmw/mwdialogue/dialoguemanagerimp.hpp +++ b/apps/openmw/mwdialogue/dialoguemanagerimp.hpp @@ -3,55 +3,52 @@ #include "../mwbase/dialoguemanager.hpp" -#include +#include +#include #include -#include "../mwscript/compilercontext.hpp" -#include "../mwscript/interpretercontext.hpp" -#include #include "../mwworld/ptr.hpp" -#include +#include "../mwscript/compilercontext.hpp" namespace MWDialogue { class DialogueManager : public MWBase::DialogueManager { - bool isMatching (const MWWorld::Ptr& actor, const ESM::DialInfo::SelectStruct& select) const; - - bool isMatching (const MWWorld::Ptr& actor, const ESM::DialInfo& info) const; - - bool functionFilter(const MWWorld::Ptr& actor, const ESM::DialInfo& info,bool choice); - - void parseText(std::string text); - - void updateTopics(); - - std::map mDialogueMap; - std::map mKnownTopics;// Those are the topics the player knows. + std::map mDialogueMap; + std::map mKnownTopics;// Those are the topics the player knows. std::list mActorKnownTopics; MWScript::CompilerContext mCompilerContext; std::ostream mErrorStream; Compiler::StreamErrorHandler mErrorHandler; - - - bool compile (const std::string& cmd,std::vector& code); - void executeScript(std::string script); + MWWorld::Ptr mActor; - - void printError(std::string error); + bool mTalkedTo; int mChoice; - std::map mChoiceMap; + std::map mChoiceMap; std::string mLastTopic; ESM::DialInfo mLastDialogue; bool mIsInChoice; + float mTemporaryDispositionChange; + float mPermanentDispositionChange; + bool mScriptVerbose; + + void parseText (const std::string& text); + + void updateTopics(); + + bool compile (const std::string& cmd,std::vector& code); + void executeScript (const std::string& script); + + void printError (const std::string& error); + public: - DialogueManager (const Compiler::Extensions& extensions); + DialogueManager (const Compiler::Extensions& extensions, bool scriptVerbose); virtual void startDialogue (const MWWorld::Ptr& actor); @@ -61,14 +58,17 @@ namespace MWDialogue virtual void goodbye(); - ///get the faction of the actor you are talking with - virtual std::string getFaction() const; + virtual MWWorld::Ptr getActor() const; + ///< Return the actor the player is currently talking to. //calbacks for the GUI virtual void keywordSelected (const std::string& keyword); virtual void goodbyeSelected(); virtual void questionAnswered (const std::string& answer); + virtual void persuade (int type); + virtual int getTemporaryDispositionChange () const; + virtual void applyTemporaryDispositionChange (int delta); }; } diff --git a/apps/openmw/mwdialogue/filter.cpp b/apps/openmw/mwdialogue/filter.cpp new file mode 100644 index 000000000..0deef7fd0 --- /dev/null +++ b/apps/openmw/mwdialogue/filter.cpp @@ -0,0 +1,570 @@ + +#include "filter.hpp" + +#include "../mwbase/environment.hpp" +#include "../mwbase/world.hpp" +#include "../mwbase/journal.hpp" +#include "../mwbase/mechanicsmanager.hpp" + +#include "../mwworld/class.hpp" +#include "../mwworld/player.hpp" +#include "../mwworld/containerstore.hpp" +#include "../mwworld/inventorystore.hpp" + +#include "../mwmechanics/npcstats.hpp" +#include "../mwmechanics/creaturestats.hpp" +#include "../mwmechanics/magiceffects.hpp" + +#include "selectwrapper.hpp" + +namespace +{ + std::string toLower (const std::string& name) + { + std::string lowerCase; + + std::transform (name.begin(), name.end(), std::back_inserter (lowerCase), + (int(*)(int)) std::tolower); + + return lowerCase; + } +} + +bool MWDialogue::Filter::testActor (const ESM::DialInfo& info) const +{ + // actor id + if (!info.mActor.empty()) + if (toLower (info.mActor)!=MWWorld::Class::get (mActor).getId (mActor)) + return false; + + bool isCreature = (mActor.getTypeName() != typeid (ESM::NPC).name()); + + // NPC race + if (!info.mRace.empty()) + { + if (isCreature) + return false; + + MWWorld::LiveCellRef *cellRef = mActor.get(); + + if (toLower (info.mRace)!=toLower (cellRef->mBase->mRace)) + return false; + } + + // NPC class + if (!info.mClass.empty()) + { + if (isCreature) + return false; + + MWWorld::LiveCellRef *cellRef = mActor.get(); + + if (toLower (info.mClass)!=toLower (cellRef->mBase->mClass)) + return false; + } + + // NPC faction + if (!info.mNpcFaction.empty()) + { + if (isCreature) + return false; + + MWMechanics::NpcStats& stats = MWWorld::Class::get (mActor).getNpcStats (mActor); + std::map::iterator iter = stats.getFactionRanks().find (toLower (info.mNpcFaction)); + + if (iter==stats.getFactionRanks().end()) + return false; + + // check rank + if (iter->second < info.mData.mRank) + return false; + } + + // Gender + if (!isCreature) + { + MWWorld::LiveCellRef* npc = mActor.get(); + if (info.mData.mGender==(npc->mBase->mFlags & npc->mBase->Female ? 0 : 1)) + return false; + } + + return true; +} + +bool MWDialogue::Filter::testPlayer (const ESM::DialInfo& info) const +{ + const MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + + // check player faction + if (!info.mPcFaction.empty()) + { + MWMechanics::NpcStats& stats = MWWorld::Class::get (player).getNpcStats (player); + std::map::iterator iter = stats.getFactionRanks().find (toLower (info.mPcFaction)); + + if(iter==stats.getFactionRanks().end()) + return false; + + // check rank + if (iter->second < info.mData.mPCrank) + return false; + } + + // check cell + if (!info.mCell.empty()) + if (toLower (player.getCell()->mCell->mName) != toLower (info.mCell)) + return false; + + return true; +} + +bool MWDialogue::Filter::testSelectStructs (const ESM::DialInfo& info) const +{ + for (std::vector::const_iterator iter (info.mSelects.begin()); + iter != info.mSelects.end(); ++iter) + if (!testSelectStruct (*iter)) + return false; + + return true; +} + +bool MWDialogue::Filter::testSelectStruct (const SelectWrapper& select) const +{ + if (select.isNpcOnly() && mActor.getTypeName()!=typeid (ESM::NPC).name()) + return select.isInverted(); + + switch (select.getType()) + { + case SelectWrapper::Type_None: return true; + case SelectWrapper::Type_Integer: return select.selectCompare (getSelectStructInteger (select)); + case SelectWrapper::Type_Numeric: return testSelectStructNumeric (select); + case SelectWrapper::Type_Boolean: return select.selectCompare (getSelectStructBoolean (select)); + } + + return true; +} + +bool MWDialogue::Filter::testSelectStructNumeric (const SelectWrapper& select) const +{ + switch (select.getFunction()) + { + case SelectWrapper::Function_Global: + + // internally all globals are float :( + return select.selectCompare ( + MWBase::Environment::get().getWorld()->getGlobalVariable (select.getName()).mFloat); + + case SelectWrapper::Function_Local: + { + std::string scriptName = MWWorld::Class::get (mActor).getScript (mActor); + + if (scriptName.empty()) + return false; // no script + + const ESM::Script *script = + MWBase::Environment::get().getWorld()->getStore().get().find (scriptName); + + std::string name = select.getName(); + + int i = 0; + + for (; i (script->mVarNames.size()); ++i) + if (script->mVarNames[i]==name) + break; + + if (i>=static_cast (script->mVarNames.size())) + return false; // script does not have a variable of this name + + const MWScript::Locals& locals = mActor.getRefData().getLocals(); + + if (imData.mNumShorts) + return select.selectCompare (static_cast (locals.mShorts[i])); + + i -= script->mData.mNumShorts; + + if (imData.mNumLongs) + return select.selectCompare (locals.mLongs[i]); + + i -= script->mData.mNumShorts; + + return select.selectCompare (locals.mFloats.at (i)); + } + + case SelectWrapper::Function_PcHealthPercent: + { + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + + float ratio = MWWorld::Class::get (player).getCreatureStats (player).getHealth().getCurrent() / + MWWorld::Class::get (player).getCreatureStats (player).getHealth().getModified(); + + return select.selectCompare (ratio); + } + + case SelectWrapper::Function_PcDynamicStat: + { + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + + float value = MWWorld::Class::get (player).getCreatureStats (player). + getDynamic (select.getArgument()).getCurrent(); + + return select.selectCompare (value); + } + + case SelectWrapper::Function_HealthPercent: + { + float ratio = MWWorld::Class::get (mActor).getCreatureStats (mActor).getHealth().getCurrent() / + MWWorld::Class::get (mActor).getCreatureStats (mActor).getHealth().getModified(); + + return select.selectCompare (ratio); + } + + default: + + throw std::runtime_error ("unknown numeric select function"); + } +} + +int MWDialogue::Filter::getSelectStructInteger (const SelectWrapper& select) const +{ + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + + switch (select.getFunction()) + { + case SelectWrapper::Function_Journal: + + return MWBase::Environment::get().getJournal()->getJournalIndex (select.getName()); + + case SelectWrapper::Function_Item: + { + MWWorld::ContainerStore& store = MWWorld::Class::get (player).getContainerStore (player); + + int sum = 0; + + std::string name = select.getName(); + + for (MWWorld::ContainerStoreIterator iter (store.begin()); iter!=store.end(); ++iter) + if (toLower(iter->getCellRef().mRefID) == name) + sum += iter->getRefData().getCount(); + + return sum; + } + + case SelectWrapper::Function_Dead: + + return MWBase::Environment::get().getMechanicsManager()->countDeaths (select.getName()); + + case SelectWrapper::Function_Choice: + + return mChoice; + + case SelectWrapper::Function_AiSetting: + + return MWWorld::Class::get (mActor).getCreatureStats (mActor).getAiSetting (select.getArgument()); + + case SelectWrapper::Function_PcAttribute: + + return MWWorld::Class::get (player).getCreatureStats (player). + getAttribute (select.getArgument()).getModified(); + + case SelectWrapper::Function_PcSkill: + + return static_cast (MWWorld::Class::get (player). + getNpcStats (player).getSkill (select.getArgument()).getModified()); + + case SelectWrapper::Function_FriendlyHit: + { + int hits = MWWorld::Class::get (mActor).getCreatureStats (mActor).getFriendlyHits(); + + return hits>4 ? 4 : hits; + } + + case SelectWrapper::Function_PcLevel: + + return MWWorld::Class::get (player).getCreatureStats (player).getLevel(); + + case SelectWrapper::Function_PcGender: + + return player.get()->mBase->mFlags & ESM::NPC::Female ? 0 : 1; + + case SelectWrapper::Function_PcClothingModifier: + { + MWWorld::InventoryStore& store = MWWorld::Class::get (player).getInventoryStore (player); + + int value = 0; + + for (int i=0; i<=15; ++i) // everything except thigns held in hands and amunition + { + MWWorld::ContainerStoreIterator slot = store.getSlot (i); + + if (slot!=store.end()) + value += MWWorld::Class::get (*slot).getValue (*slot); + } + + return value; + } + + case SelectWrapper::Function_PcCrimeLevel: + + return MWWorld::Class::get (player).getNpcStats (player).getBounty(); + + case SelectWrapper::Function_RankRequirement: + { + if (MWWorld::Class::get (mActor).getNpcStats (mActor).getFactionRanks().empty()) + return 0; + + std::string faction = + MWWorld::Class::get (mActor).getNpcStats (mActor).getFactionRanks().begin()->first; + + int rank = getFactionRank (player, faction); + + if (rank>=9) + return 0; // max rank + + int result = 0; + + if (hasFactionRankSkillRequirements (player, faction, rank+1)) + result += 1; + + if (hasFactionRankReputationRequirements (player, faction, rank+1)) + result += 2; + + return result; + } + + case SelectWrapper::Function_Level: + + return MWWorld::Class::get (mActor).getCreatureStats (mActor).getLevel(); + + case SelectWrapper::Function_PCReputation: + + return MWWorld::Class::get (player).getNpcStats (player).getReputation(); + + case SelectWrapper::Function_Weather: + + return MWBase::Environment::get().getWorld()->getCurrentWeather(); + + case SelectWrapper::Function_Reputation: + + return MWWorld::Class::get (mActor).getNpcStats (mActor).getReputation(); + + case SelectWrapper::Function_FactionRankDiff: + { + if (MWWorld::Class::get (mActor).getNpcStats (mActor).getFactionRanks().empty()) + return 0; + + std::pair faction = + *MWWorld::Class::get (mActor).getNpcStats (mActor).getFactionRanks().begin(); + + int rank = getFactionRank (player, faction.first); + + return rank-faction.second; + } + + case SelectWrapper::Function_WerewolfKills: + + return MWWorld::Class::get (player).getNpcStats (player).getWerewolfKills(); + + case SelectWrapper::Function_RankLow: + case SelectWrapper::Function_RankHigh: + { + bool low = select.getFunction()==SelectWrapper::Function_RankLow; + + if (MWWorld::Class::get (mActor).getNpcStats (mActor).getFactionRanks().empty()) + return 0; + + std::string factionId = + MWWorld::Class::get (mActor).getNpcStats (mActor).getFactionRanks().begin()->first; + + int value = 0; + + const ESM::Faction& faction = + *MWBase::Environment::get().getWorld()->getStore().get().find (factionId); + + MWMechanics::NpcStats& playerStats = MWWorld::Class::get (player).getNpcStats (player); + + for (std::vector::const_iterator iter (faction.mReactions.begin()); + iter!=faction.mReactions.end(); ++iter) + if (playerStats.getFactionRanks().find (iter->mFaction)!=playerStats.getFactionRanks().end()) + if (low ? iter->mReactionmReaction>value) + value = iter->mReaction; + + return value; + } + + default: + + throw std::runtime_error ("unknown integer select function"); + } +} + +bool MWDialogue::Filter::getSelectStructBoolean (const SelectWrapper& select) const +{ + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + + switch (select.getFunction()) + { + case SelectWrapper::Function_False: + + return false; + + case SelectWrapper::Function_Id: + + return select.getName()==toLower (MWWorld::Class::get (mActor).getId (mActor)); + + case SelectWrapper::Function_Faction: + + return toLower (mActor.get()->mBase->mFaction)==select.getName(); + + case SelectWrapper::Function_Class: + + return toLower (mActor.get()->mBase->mClass)==select.getName(); + + case SelectWrapper::Function_Race: + + return toLower (mActor.get()->mBase->mRace)==select.getName(); + + case SelectWrapper::Function_Cell: + + return toLower (mActor.getCell()->mCell->mName)==select.getName(); + + case SelectWrapper::Function_SameGender: + + return (player.get()->mBase->mFlags & ESM::NPC::Female)== + (mActor.get()->mBase->mFlags & ESM::NPC::Female); + + case SelectWrapper::Function_SameRace: + + return toLower (mActor.get()->mBase->mRace)!= + toLower (player.get()->mBase->mRace); + + case SelectWrapper::Function_SameFaction: + + return MWWorld::Class::get (mActor).getNpcStats (mActor).isSameFaction ( + MWWorld::Class::get (player).getNpcStats (player)); + + case SelectWrapper::Function_PcCommonDisease: + + return MWWorld::Class::get (player).getCreatureStats (player).hasCommonDisease(); + + case SelectWrapper::Function_PcBlightDisease: + + return MWWorld::Class::get (player).getCreatureStats (player).hasBlightDisease(); + + case SelectWrapper::Function_PcCorprus: + + return MWWorld::Class::get (player).getCreatureStats (player). + getMagicEffects().get (132).mMagnitude!=0; + + case SelectWrapper::Function_PcExpelled: + { + if (MWWorld::Class::get (mActor).getNpcStats (mActor).getFactionRanks().empty()) + return false; + + std::string faction = + MWWorld::Class::get (mActor).getNpcStats (mActor).getFactionRanks().begin()->first; + + std::set& expelled = MWWorld::Class::get (player).getNpcStats (player).getExpelled(); + + return expelled.find (faction)!=expelled.end(); + } + + case SelectWrapper::Function_PcVampire: + + return MWWorld::Class::get (player).getNpcStats (player).isVampire(); + + case SelectWrapper::Function_TalkedToPc: + + return mTalkedToPlayer; + + case SelectWrapper::Function_Alarmed: + + return MWWorld::Class::get (mActor).getCreatureStats (mActor).isAlarmed(); + + case SelectWrapper::Function_Detected: + + return MWWorld::Class::get (mActor).hasDetected (mActor, player); + + case SelectWrapper::Function_Attacked: + + return MWWorld::Class::get (mActor).getCreatureStats (mActor).getAttacked(); + + case SelectWrapper::Function_ShouldAttack: + + return MWWorld::Class::get (mActor).getCreatureStats (mActor).isHostile(); + + case SelectWrapper::Function_CreatureTargetted: + + return MWWorld::Class::get (mActor).getCreatureStats (mActor).getCreatureTargetted(); + + case SelectWrapper::Function_PCWerewolf: + + return MWWorld::Class::get (player).getNpcStats (player).isWerewolf(); + + default: + + throw std::runtime_error ("unknown boolean select function"); + } +} + +int MWDialogue::Filter::getFactionRank (const MWWorld::Ptr& actor, const std::string& factionId) const +{ + MWMechanics::NpcStats& stats = MWWorld::Class::get (actor).getNpcStats (actor); + + std::map::const_iterator iter = stats.getFactionRanks().find (factionId); + + if (iter==stats.getFactionRanks().end()) + return -1; + + return iter->second; +} + +bool MWDialogue::Filter::hasFactionRankSkillRequirements (const MWWorld::Ptr& actor, + const std::string& factionId, int rank) const +{ + if (rank<0 || rank>=10) + throw std::runtime_error ("rank index out of range"); + + if (!MWWorld::Class::get (actor).getNpcStats (actor).hasSkillsForRank (factionId, rank)) + return false; + + const ESM::Faction& faction = + *MWBase::Environment::get().getWorld()->getStore().get().find (factionId); + + MWMechanics::CreatureStats& stats = MWWorld::Class::get (actor).getCreatureStats (actor); + + return stats.getAttribute (faction.mData.mAttribute1).getBase()>=faction.mData.mRankData[rank].mAttribute1 && + stats.getAttribute (faction.mData.mAttribute2).getBase()>=faction.mData.mRankData[rank].mAttribute2; +} + +bool MWDialogue::Filter::hasFactionRankReputationRequirements (const MWWorld::Ptr& actor, + const std::string& factionId, int rank) const +{ + if (rank<0 || rank>=10) + throw std::runtime_error ("rank index out of range"); + + MWMechanics::NpcStats& stats = MWWorld::Class::get (actor).getNpcStats (actor); + + const ESM::Faction& faction = + *MWBase::Environment::get().getWorld()->getStore().get().find (factionId); + + return stats.getFactionReputation (factionId)>=faction.mData.mRankData[rank].mFactReaction; +} + +MWDialogue::Filter::Filter (const MWWorld::Ptr& actor, int choice, bool talkedToPlayer) +: mActor (actor), mChoice (choice), mTalkedToPlayer (talkedToPlayer) +{} + +bool MWDialogue::Filter::operator() (const ESM::DialInfo& info) const +{ + return testActor (info) && testPlayer (info) && testSelectStructs (info); +} + +const ESM::DialInfo *MWDialogue::Filter::search (const ESM::Dialogue& dialogue) const +{ + for (std::vector::const_iterator iter = dialogue.mInfo.begin(); + iter!=dialogue.mInfo.end(); ++iter) + if ((*this) (*iter)) + return &*iter; + + return 0; +} + diff --git a/apps/openmw/mwdialogue/filter.hpp b/apps/openmw/mwdialogue/filter.hpp new file mode 100644 index 000000000..7c8f1116f --- /dev/null +++ b/apps/openmw/mwdialogue/filter.hpp @@ -0,0 +1,58 @@ +#ifndef GAME_MWDIALOGUE_FILTER_H +#define GAME_MWDIALOGUE_FILTER_H + +#include "../mwworld/ptr.hpp" + +namespace ESM +{ + struct DialInfo; + struct Dialogue; +} + +namespace MWDialogue +{ + class SelectWrapper; + + class Filter + { + MWWorld::Ptr mActor; + int mChoice; + bool mTalkedToPlayer; + + bool testActor (const ESM::DialInfo& info) const; + ///< Is this the right actor for this \a info? + + bool testPlayer (const ESM::DialInfo& info) const; + ///< Do the player and the cell the player is currently in match \a info? + + bool testSelectStructs (const ESM::DialInfo& info) const; + ///< Are all select structs matching? + + bool testSelectStruct (const SelectWrapper& select) const; + + bool testSelectStructNumeric (const SelectWrapper& select) const; + + int getSelectStructInteger (const SelectWrapper& select) const; + + bool getSelectStructBoolean (const SelectWrapper& select) const; + + int getFactionRank (const MWWorld::Ptr& actor, const std::string& factionId) const; + + bool hasFactionRankSkillRequirements (const MWWorld::Ptr& actor, const std::string& factionId, + int rank) const; + + bool hasFactionRankReputationRequirements (const MWWorld::Ptr& actor, const std::string& factionId, + int rank) const; + + public: + + Filter (const MWWorld::Ptr& actor, int choice, bool talkedToPlayer); + + bool operator() (const ESM::DialInfo& info) const; + ///< \return does the dialogue match? + + const ESM::DialInfo *search (const ESM::Dialogue& dialogue) const; + }; +} + +#endif diff --git a/apps/openmw/mwdialogue/journalentry.cpp b/apps/openmw/mwdialogue/journalentry.cpp index 1c6addb6e..e6141884c 100644 --- a/apps/openmw/mwdialogue/journalentry.cpp +++ b/apps/openmw/mwdialogue/journalentry.cpp @@ -3,11 +3,11 @@ #include -#include - #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" +#include "../mwworld/esmstore.hpp" + namespace MWDialogue { JournalEntry::JournalEntry() {} @@ -16,9 +16,10 @@ namespace MWDialogue : mTopic (topic), mInfoId (infoId) {} - std::string JournalEntry::getText (const ESMS::ESMStore& store) const + std::string JournalEntry::getText (const MWWorld::ESMStore& store) const { - const ESM::Dialogue *dialogue = store.dialogs.find (mTopic); + const ESM::Dialogue *dialogue = + store.get().find (mTopic); for (std::vector::const_iterator iter (dialogue->mInfo.begin()); iter!=dialogue->mInfo.end(); ++iter) @@ -35,7 +36,8 @@ namespace MWDialogue std::string JournalEntry::idFromIndex (const std::string& topic, int index) { - const ESM::Dialogue *dialogue = MWBase::Environment::get().getWorld()->getStore().dialogs.find (topic); + const ESM::Dialogue *dialogue = + MWBase::Environment::get().getWorld()->getStore().get().find (topic); for (std::vector::const_iterator iter (dialogue->mInfo.begin()); iter!=dialogue->mInfo.end(); ++iter) diff --git a/apps/openmw/mwdialogue/journalentry.hpp b/apps/openmw/mwdialogue/journalentry.hpp index 3e8640185..19a9f42b5 100644 --- a/apps/openmw/mwdialogue/journalentry.hpp +++ b/apps/openmw/mwdialogue/journalentry.hpp @@ -3,7 +3,7 @@ #include -namespace ESMS +namespace MWWorld { struct ESMStore; } @@ -20,7 +20,7 @@ namespace MWDialogue JournalEntry (const std::string& topic, const std::string& infoId); - std::string getText (const ESMS::ESMStore& store) const; + std::string getText (const MWWorld::ESMStore& store) const; static JournalEntry makeFromQuest (const std::string& topic, int index); diff --git a/apps/openmw/mwdialogue/journalimp.cpp b/apps/openmw/mwdialogue/journalimp.cpp index ac4b7a6de..2b2c60381 100644 --- a/apps/openmw/mwdialogue/journalimp.cpp +++ b/apps/openmw/mwdialogue/journalimp.cpp @@ -1,7 +1,7 @@ #include "journalimp.hpp" -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" diff --git a/apps/openmw/mwdialogue/quest.cpp b/apps/openmw/mwdialogue/quest.cpp index b4f02e128..5e2739be1 100644 --- a/apps/openmw/mwdialogue/quest.cpp +++ b/apps/openmw/mwdialogue/quest.cpp @@ -1,7 +1,7 @@ #include "quest.hpp" -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -18,7 +18,8 @@ namespace MWDialogue const std::string Quest::getName() const { - const ESM::Dialogue *dialogue = MWBase::Environment::get().getWorld()->getStore().dialogs.find (mTopic); + const ESM::Dialogue *dialogue = + MWBase::Environment::get().getWorld()->getStore().get().find (mTopic); for (std::vector::const_iterator iter (dialogue->mInfo.begin()); iter!=dialogue->mInfo.end(); ++iter) @@ -35,7 +36,8 @@ namespace MWDialogue void Quest::setIndex (int index) { - const ESM::Dialogue *dialogue = MWBase::Environment::get().getWorld()->getStore().dialogs.find (mTopic); + const ESM::Dialogue *dialogue = + MWBase::Environment::get().getWorld()->getStore().get().find (mTopic); for (std::vector::const_iterator iter (dialogue->mInfo.begin()); iter!=dialogue->mInfo.end(); ++iter) @@ -63,7 +65,8 @@ namespace MWDialogue { int index = -1; - const ESM::Dialogue *dialogue = MWBase::Environment::get().getWorld()->getStore().dialogs.find (entry.mTopic); + const ESM::Dialogue *dialogue = + MWBase::Environment::get().getWorld()->getStore().get().find (entry.mTopic); for (std::vector::const_iterator iter (dialogue->mInfo.begin()); iter!=dialogue->mInfo.end(); ++iter) diff --git a/apps/openmw/mwdialogue/selectwrapper.cpp b/apps/openmw/mwdialogue/selectwrapper.cpp new file mode 100644 index 000000000..1462ee8ba --- /dev/null +++ b/apps/openmw/mwdialogue/selectwrapper.cpp @@ -0,0 +1,311 @@ + +#include "selectwrapper.hpp" + +#include + +#include +#include +#include +#include + +namespace +{ + std::string toLower (const std::string& name) + { + std::string lowerCase; + + std::transform (name.begin(), name.end(), std::back_inserter (lowerCase), + (int(*)(int)) std::tolower); + + return lowerCase; + } + + template + bool selectCompareImp (char comp, T1 value1, T2 value2) + { + switch (comp) + { + case '0': return value1==value2; + case '1': return value1!=value2; + case '2': return value1>value2; + case '3': return value1>=value2; + case '4': return value1 + bool selectCompareImp (const ESM::DialInfo::SelectStruct& select, T value1) + { + if (select.mType==ESM::VT_Short || select.mType==ESM::VT_Int || + select.mType==ESM::VT_Long) + { + return selectCompareImp (select.mSelectRule[4], value1, select.mI); + } + else if (select.mType==ESM::VT_Float) + { + return selectCompareImp (select.mSelectRule[4], value1, select.mF); + } + else + throw std::runtime_error ( + "unsupported variable type in dialogue info select"); + } +} + +MWDialogue::SelectWrapper::Function MWDialogue::SelectWrapper::decodeFunction() const +{ + int index = 0; + + std::istringstream (mSelect.mSelectRule.substr(2,2)) >> index; + + switch (index) + { + case 0: return Function_RankLow; + case 1: return Function_RankHigh; + case 2: return Function_RankRequirement; + case 3: return Function_Reputation; + case 4: return Function_HealthPercent; + case 5: return Function_PCReputation; + case 6: return Function_PcLevel; + case 7: return Function_PcHealthPercent; + case 8: case 9: return Function_PcDynamicStat; + case 10: return Function_PcAttribute; + case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: + case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: + case 31: case 32: case 33: case 34: case 35: case 36: case 37: return Function_PcSkill; + case 38: return Function_PcGender; + case 39: return Function_PcExpelled; + case 40: return Function_PcCommonDisease; + case 41: return Function_PcBlightDisease; + case 42: return Function_PcClothingModifier; + case 43: return Function_PcCrimeLevel; + case 44: return Function_SameGender; + case 45: return Function_SameRace; + case 46: return Function_SameFaction; + case 47: return Function_FactionRankDiff; + case 48: return Function_Detected; + case 49: return Function_Alarmed; + case 50: return Function_Choice; + case 51: case 52: case 53: case 54: case 55: case 56: case 57: return Function_PcAttribute; + case 58: return Function_PcCorprus; + case 59: return Function_Weather; + case 60: return Function_PcVampire; + case 61: return Function_Level; + case 62: return Function_Attacked; + case 63: return Function_TalkedToPc; + case 64: return Function_PcDynamicStat; + case 65: return Function_CreatureTargetted; + case 66: return Function_FriendlyHit; + case 67: case 68: case 69: case 70: return Function_AiSetting; + case 71: return Function_ShouldAttack; + case 72: return Function_PCWerewolf; + case 73: return Function_WerewolfKills; + } + + return Function_False; +} + +MWDialogue::SelectWrapper::SelectWrapper (const ESM::DialInfo::SelectStruct& select) : mSelect (select) {} + +MWDialogue::SelectWrapper::Function MWDialogue::SelectWrapper::getFunction() const +{ + char type = mSelect.mSelectRule[1]; + + switch (type) + { + case '1': return decodeFunction(); + case '2': return Function_Global; + case '3': return Function_Local; + case '4': return Function_Journal; + case '5': return Function_Item; + case '6': return Function_Dead; + case '7': return Function_Id; + case '8': return Function_Faction; + case '9': return Function_Class; + case 'A': return Function_Race; + case 'B': return Function_Cell; + case 'C': return Function_Local; + } + + return Function_None; +} + +int MWDialogue::SelectWrapper::getArgument() const +{ + if (mSelect.mSelectRule[1]!='1') + return 0; + + int index = 0; + + std::istringstream (mSelect.mSelectRule.substr(2,2)) >> index; + + switch (index) + { + // AI settings + case 67: return 1; + case 68: return 0; + case 69: return 3; + case 70: return 2; + + // attributes + case 10: return 0; + case 51: return 1; + case 52: return 2; + case 53: return 3; + case 54: return 4; + case 55: return 5; + case 56: return 6; + case 57: return 7; + + // skills + case 11: return 0; + case 12: return 1; + case 13: return 2; + case 14: return 3; + case 15: return 4; + case 16: return 5; + case 17: return 6; + case 18: return 7; + case 19: return 8; + case 20: return 9; + case 21: return 10; + case 22: return 11; + case 23: return 12; + case 24: return 13; + case 25: return 14; + case 26: return 15; + case 27: return 16; + case 28: return 17; + case 29: return 18; + case 30: return 19; + case 31: return 20; + case 32: return 21; + case 33: return 22; + case 34: return 23; + case 35: return 24; + case 36: return 25; + case 37: return 26; + + // dynamic stats + case 8: return 1; + case 9: return 2; + case 64: return 0; + } + + return 0; +} + +MWDialogue::SelectWrapper::Type MWDialogue::SelectWrapper::getType() const +{ + static const Function integerFunctions[] = + { + Function_Journal, Function_Item, Function_Dead, + Function_Choice, + Function_AiSetting, + Function_PcAttribute, Function_PcSkill, + Function_FriendlyHit, + Function_PcLevel, Function_PcGender, Function_PcClothingModifier, + Function_PcCrimeLevel, + Function_RankRequirement, + Function_Level, Function_PCReputation, + Function_Weather, + Function_Reputation, Function_FactionRankDiff, + Function_WerewolfKills, + Function_RankLow, Function_RankHigh, + Function_None // end marker + }; + + static const Function numericFunctions[] = + { + Function_Global, Function_Local, + Function_PcDynamicStat, Function_PcHealthPercent, + Function_HealthPercent, + Function_None // end marker + }; + + static const Function booleanFunctions[] = + { + Function_False, + Function_Id, Function_Faction, Function_Class, Function_Race, Function_Cell, + Function_SameGender, Function_SameRace, Function_SameFaction, + Function_PcCommonDisease, Function_PcBlightDisease, Function_PcCorprus, + Function_PcExpelled, + Function_PcVampire, Function_TalkedToPc, + Function_Alarmed, Function_Detected, + Function_Attacked, Function_ShouldAttack, + Function_CreatureTargetted, + Function_PCWerewolf, + Function_None // end marker + }; + + Function function = getFunction(); + + for (int i=0; integerFunctions[i]!=Function_None; ++i) + if (integerFunctions[i]==function) + return Type_Integer; + + for (int i=0; numericFunctions[i]!=Function_None; ++i) + if (numericFunctions[i]==function) + return Type_Numeric; + + for (int i=0; booleanFunctions[i]!=Function_None; ++i) + if (booleanFunctions[i]==function) + return Type_Boolean; + + return Type_None; +} + +bool MWDialogue::SelectWrapper::isInverted() const +{ + char type = mSelect.mSelectRule[1]; + + return type=='7' || type=='8' || type=='9' || type=='A' || type=='B' || type=='C'; +} + +bool MWDialogue::SelectWrapper::isNpcOnly() const +{ + static const Function functions[] = + { + Function_Faction, SelectWrapper::Function_Class, SelectWrapper::Function_Race, + Function_SameGender, Function_SameRace, Function_SameFaction, + Function_PcSkill, + Function_PcExpelled, + Function_PcVampire, + Function_PcCrimeLevel, + Function_RankRequirement, + Function_Reputation, Function_FactionRankDiff, + Function_PCWerewolf, Function_WerewolfKills, + Function_RankLow, Function_RankHigh, + Function_None // end marker + }; + + Function function = getFunction(); + + for (int i=0; functions[i]!=Function_None; ++i) + if (functions[i]==function) + return true; + + return false; +} + +bool MWDialogue::SelectWrapper::selectCompare (int value) const +{ + return selectCompareImp (mSelect, value)!=isInverted(); // logic XOR +} + +bool MWDialogue::SelectWrapper::selectCompare (float value) const +{ + return selectCompareImp (mSelect, value)!=isInverted(); // logic XOR +} + +bool MWDialogue::SelectWrapper::selectCompare (bool value) const +{ + return selectCompareImp (mSelect, static_cast (value))!=isInverted(); // logic XOR +} + +std::string MWDialogue::SelectWrapper::getName() const +{ + return toLower (mSelect.mSelectRule.substr (5)); +} diff --git a/apps/openmw/mwdialogue/selectwrapper.hpp b/apps/openmw/mwdialogue/selectwrapper.hpp new file mode 100644 index 000000000..b77ed7985 --- /dev/null +++ b/apps/openmw/mwdialogue/selectwrapper.hpp @@ -0,0 +1,86 @@ +#ifndef GAME_MWDIALOGUE_SELECTWRAPPER_H +#define GAME_MWDIALOGUE_SELECTWRAPPER_H + +#include + +namespace MWDialogue +{ + class SelectWrapper + { + const ESM::DialInfo::SelectStruct& mSelect; + + public: + + enum Function + { + Function_None, Function_False, + Function_Journal, + Function_Item, + Function_Dead, + Function_Id, + Function_Faction, + Function_Class, + Function_Race, + Function_Cell, + Function_Local, + Function_Global, + Function_SameGender, Function_SameRace, Function_SameFaction, + Function_Choice, + Function_PcCommonDisease, Function_PcBlightDisease, Function_PcCorprus, + Function_AiSetting, + Function_PcAttribute, Function_PcSkill, + Function_PcExpelled, + Function_PcVampire, + Function_FriendlyHit, + Function_TalkedToPc, + Function_PcLevel, Function_PcHealthPercent, Function_PcDynamicStat, + Function_PcGender, Function_PcClothingModifier, Function_PcCrimeLevel, + Function_RankRequirement, + Function_HealthPercent, Function_Level, Function_PCReputation, + Function_Weather, + Function_Reputation, Function_Alarmed, Function_FactionRankDiff, Function_Detected, + Function_Attacked, Function_ShouldAttack, + Function_CreatureTargetted, + Function_PCWerewolf, Function_WerewolfKills, + Function_RankLow, Function_RankHigh + }; + + enum Type + { + Type_None, + Type_Integer, + Type_Numeric, + Type_Boolean + }; + + private: + + Function decodeFunction() const; + + public: + + SelectWrapper (const ESM::DialInfo::SelectStruct& select); + + Function getFunction() const; + + int getArgument() const; + + Type getType() const; + + bool isInverted() const; + + bool isNpcOnly() const; + ///< \attention Do not call any of the select functions for this select struct! + + bool selectCompare (int value) const; + + bool selectCompare (float value) const; + + bool selectCompare (bool value) const; + + std::string getName() const; + ///< Return case-smashed name. + }; +} + +#endif diff --git a/apps/openmw/mwdialogue/topic.cpp b/apps/openmw/mwdialogue/topic.cpp index 8c1dfafb8..b6e7c07ae 100644 --- a/apps/openmw/mwdialogue/topic.cpp +++ b/apps/openmw/mwdialogue/topic.cpp @@ -1,7 +1,7 @@ #include "topic.hpp" -#include +#include "../mwworld/esmstore.hpp" namespace MWDialogue { diff --git a/apps/openmw/mwgui/alchemywindow.cpp b/apps/openmw/mwgui/alchemywindow.cpp index 4a419c0c0..fc06e866c 100644 --- a/apps/openmw/mwgui/alchemywindow.cpp +++ b/apps/openmw/mwgui/alchemywindow.cpp @@ -28,25 +28,25 @@ namespace MWGui { AlchemyWindow::AlchemyWindow(MWBase::WindowManager& parWindowManager) : WindowBase("openmw_alchemy_window.layout", parWindowManager) - , ContainerBase(0) + , ContainerBase(0), mApparatus (4), mIngredients (4) { getWidget(mCreateButton, "CreateButton"); getWidget(mCancelButton, "CancelButton"); - getWidget(mIngredient1, "Ingredient1"); - getWidget(mIngredient2, "Ingredient2"); - getWidget(mIngredient3, "Ingredient3"); - getWidget(mIngredient4, "Ingredient4"); - getWidget(mApparatus1, "Apparatus1"); - getWidget(mApparatus2, "Apparatus2"); - getWidget(mApparatus3, "Apparatus3"); - getWidget(mApparatus4, "Apparatus4"); + 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(mNameEdit, "NameEdit"); - mIngredient1->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onIngredientSelected); - mIngredient2->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onIngredientSelected); - mIngredient3->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onIngredientSelected); - mIngredient4->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onIngredientSelected); + 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); mCreateButton->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onCreateButtonClicked); mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &AlchemyWindow::onCancelButtonClicked); @@ -62,157 +62,52 @@ namespace MWGui void AlchemyWindow::onCancelButtonClicked(MyGUI::Widget* _sender) { + mAlchemy.clear(); + mWindowManager.removeGuiMode(GM_Alchemy); mWindowManager.removeGuiMode(GM_Inventory); } void AlchemyWindow::onCreateButtonClicked(MyGUI::Widget* _sender) { + std::string name = mNameEdit->getCaption(); + boost::algorithm::trim(name); + + MWMechanics::Alchemy::Result result = mAlchemy.create (mNameEdit->getCaption ()); + + if (result == MWMechanics::Alchemy::Result_NoName) + { + mWindowManager.messageBox("#{sNotifyMessage37}", std::vector()); + return; + } + // check if mortar & pestle is available (always needed) - /// \todo check albemic, calcinator, retort (sometimes needed) - if (!mApparatus1->isUserString("ToolTipType")) + if (result == MWMechanics::Alchemy::Result_NoMortarAndPestle) { mWindowManager.messageBox("#{sNotifyMessage45}", std::vector()); return; } // make sure 2 or more ingredients were selected - int numIngreds = 0; - if (mIngredient1->isUserString("ToolTipType")) - ++numIngreds; - if (mIngredient2->isUserString("ToolTipType")) - ++numIngreds; - if (mIngredient3->isUserString("ToolTipType")) - ++numIngreds; - if (mIngredient4->isUserString("ToolTipType")) - ++numIngreds; - if (numIngreds < 2) + if (result == MWMechanics::Alchemy::Result_LessThanTwoIngredients) { mWindowManager.messageBox("#{sNotifyMessage6a}", std::vector()); return; } - // make sure a name was entered - std::string name = mNameEdit->getCaption(); - boost::algorithm::trim(name); - if (name == "") - { - mWindowManager.messageBox("#{sNotifyMessage37}", std::vector()); - return; - } - - // if there are no created effects, the potion will always fail (but the ingredients won't be destroyed) - if (mEffects.empty()) + if (result == MWMechanics::Alchemy::Result_NoEffects) { mWindowManager.messageBox("#{sNotifyMessage8}", std::vector()); MWBase::Environment::get().getSoundManager()->playSound("potion fail", 1.f, 1.f); return; } - if (rand() % 2 == 0) /// \todo + if (result == MWMechanics::Alchemy::Result_Success) { - ESM::Potion newPotion; - newPotion.mName = mNameEdit->getCaption(); - ESM::EffectList effects; - for (unsigned int i=0; i<4; ++i) - { - if (mEffects.size() >= i+1) - { - ESM::ENAMstruct effect; - effect.mEffectID = mEffects[i].mEffectID; - effect.mArea = 0; - effect.mRange = ESM::RT_Self; - effect.mSkill = mEffects[i].mSkill; - effect.mAttribute = mEffects[i].mAttribute; - effect.mMagnMin = 1; /// \todo - effect.mMagnMax = 10; /// \todo - effect.mDuration = 60; /// \todo - effects.mList.push_back(effect); - } - } - - // UESP Wiki / Morrowind:Alchemy - // "The weight of a potion is an average of the weight of the ingredients, rounded down." - // note by scrawl: not rounding down here, I can't imagine a created potion to - // have 0 weight when using ingredients with 0.1 weight respectively - float weight = 0; - if (mIngredient1->isUserString("ToolTipType")) - weight += mIngredient1->getUserData()->get()->base->mData.mWeight; - if (mIngredient2->isUserString("ToolTipType")) - weight += mIngredient2->getUserData()->get()->base->mData.mWeight; - if (mIngredient3->isUserString("ToolTipType")) - weight += mIngredient3->getUserData()->get()->base->mData.mWeight; - if (mIngredient4->isUserString("ToolTipType")) - weight += mIngredient4->getUserData()->get()->base->mData.mWeight; - newPotion.mData.mWeight = weight / float(numIngreds); - - newPotion.mData.mValue = 100; /// \todo - newPotion.mEffects = effects; - // pick a random mesh and icon - std::vector names; - /// \todo is the mesh/icon dependent on alchemy skill? - names.push_back("standard"); - names.push_back("bargain"); - names.push_back("cheap"); - names.push_back("fresh"); - names.push_back("exclusive"); - names.push_back("quality"); - int random = rand() % names.size(); - newPotion.mModel = "m\\misc_potion_" + names[random ] + "_01.nif"; - newPotion.mIcon = "m\\tx_potion_" + names[random ] + "_01.dds"; - - // check if a similiar potion record exists already - bool found = false; - std::string objectId; - typedef std::map PotionMap; - PotionMap potions = MWBase::Environment::get().getWorld()->getStore().potions.list; - for (PotionMap::const_iterator it = potions.begin(); it != potions.end(); ++it) - { - if (found) break; - - if (it->second.mData.mValue == newPotion.mData.mValue - && it->second.mData.mWeight == newPotion.mData.mWeight - && it->second.mName == newPotion.mName - && it->second.mEffects.mList.size() == newPotion.mEffects.mList.size()) - { - // check effects - for (unsigned int i=0; i < it->second.mEffects.mList.size(); ++i) - { - const ESM::ENAMstruct& a = it->second.mEffects.mList[i]; - const ESM::ENAMstruct& b = newPotion.mEffects.mList[i]; - if (a.mEffectID == b.mEffectID - && a.mArea == b.mArea - && a.mRange == b.mRange - && a.mSkill == b.mSkill - && a.mAttribute == b.mAttribute - && a.mMagnMin == b.mMagnMin - && a.mMagnMax == b.mMagnMax - && a.mDuration == b.mDuration) - { - found = true; - objectId = it->first; - break; - } - } - } - } - - if (!found) - { - std::pair result = MWBase::Environment::get().getWorld()->createRecord(newPotion); - objectId = result.first; - } - - // create a reference and add it to player inventory - MWWorld::ManualRef ref(MWBase::Environment::get().getWorld()->getStore(), objectId); - MWWorld::ContainerStore& store = MWWorld::Class::get(mPtr).getContainerStore(mPtr); - ref.getPtr().getRefData().setCount(1); - store.add(ref.getPtr()); - mWindowManager.messageBox("#{sPotionSuccess}", std::vector()); MWBase::Environment::get().getSoundManager()->playSound("potion success", 1.f, 1.f); } - else + else if (result == MWMechanics::Alchemy::Result_RandomFailure) { // potion failed mWindowManager.messageBox("#{sNotifyMessage8}", std::vector()); @@ -220,155 +115,55 @@ namespace MWGui } // reduce count of the ingredients - if (mIngredient1->isUserString("ToolTipType")) - { - MWWorld::Ptr ingred = *mIngredient1->getUserData(); - ingred.getRefData().setCount(ingred.getRefData().getCount()-1); - if (ingred.getRefData().getCount() == 0) - removeIngredient(mIngredient1); - } - if (mIngredient2->isUserString("ToolTipType")) - { - MWWorld::Ptr ingred = *mIngredient2->getUserData(); - ingred.getRefData().setCount(ingred.getRefData().getCount()-1); - if (ingred.getRefData().getCount() == 0) - removeIngredient(mIngredient2); - } - if (mIngredient3->isUserString("ToolTipType")) - { - MWWorld::Ptr ingred = *mIngredient3->getUserData(); - ingred.getRefData().setCount(ingred.getRefData().getCount()-1); - if (ingred.getRefData().getCount() == 0) - removeIngredient(mIngredient3); - } - if (mIngredient4->isUserString("ToolTipType")) - { - MWWorld::Ptr ingred = *mIngredient4->getUserData(); - ingred.getRefData().setCount(ingred.getRefData().getCount()-1); - if (ingred.getRefData().getCount() == 0) - removeIngredient(mIngredient4); + for (int i=0; i<4; ++i) + if (mIngredients[i]->isUserString("ToolTipType")) + { + MWWorld::Ptr ingred = *mIngredients[i]->getUserData(); + ingred.getRefData().setCount(ingred.getRefData().getCount()-1); + if (ingred.getRefData().getCount() == 0) + removeIngredient(mIngredients[i]); } + update(); } void AlchemyWindow::open() { - openContainer(MWBase::Environment::get().getWorld()->getPlayer().getPlayer()); - setFilter(ContainerBase::Filter_Ingredients); + openContainer (MWBase::Environment::get().getWorld()->getPlayer().getPlayer()); // this sets mPtr + setFilter (ContainerBase::Filter_Ingredients); - // pick the best available apparatus - MWWorld::ContainerStore& store = MWWorld::Class::get(mPtr).getContainerStore(mPtr); + mNameEdit->setCaption(""); - MWWorld::Ptr bestAlbemic; - MWWorld::Ptr bestMortarPestle; - MWWorld::Ptr bestCalcinator; - MWWorld::Ptr bestRetort; + mAlchemy.setAlchemist (mPtr); - for (MWWorld::ContainerStoreIterator it(store.begin(MWWorld::ContainerStore::Type_Apparatus)); - it != store.end(); ++it) + int index = 0; + + for (MWMechanics::Alchemy::TToolsIterator iter (mAlchemy.beginTools()); + iter!=mAlchemy.endTools() && index (mApparatus.size()); ++iter, ++index) { - MWWorld::LiveCellRef* ref = it->get(); - if (ref->base->mData.mType == ESM::Apparatus::Albemic - && (bestAlbemic.isEmpty() || ref->base->mData.mQuality > bestAlbemic.get()->base->mData.mQuality)) - bestAlbemic = *it; - else if (ref->base->mData.mType == ESM::Apparatus::MortarPestle - && (bestMortarPestle.isEmpty() || ref->base->mData.mQuality > bestMortarPestle.get()->base->mData.mQuality)) - bestMortarPestle = *it; - else if (ref->base->mData.mType == ESM::Apparatus::Calcinator - && (bestCalcinator.isEmpty() || ref->base->mData.mQuality > bestCalcinator.get()->base->mData.mQuality)) - bestCalcinator = *it; - else if (ref->base->mData.mType == ESM::Apparatus::Retort - && (bestRetort.isEmpty() || ref->base->mData.mQuality > bestRetort.get()->base->mData.mQuality)) - bestRetort = *it; + if (!iter->isEmpty()) + { + mApparatus.at (index)->setUserString ("ToolTipType", "ItemPtr"); + mApparatus.at (index)->setUserData (*iter); + mApparatus.at (index)->setImageTexture (getIconPath (*iter)); + } } - if (!bestMortarPestle.isEmpty()) - { - mApparatus1->setUserString("ToolTipType", "ItemPtr"); - mApparatus1->setUserData(bestMortarPestle); - mApparatus1->setImageTexture(getIconPath(bestMortarPestle)); - } - if (!bestAlbemic.isEmpty()) - { - mApparatus2->setUserString("ToolTipType", "ItemPtr"); - mApparatus2->setUserData(bestAlbemic); - mApparatus2->setImageTexture(getIconPath(bestAlbemic)); - } - if (!bestCalcinator.isEmpty()) - { - mApparatus3->setUserString("ToolTipType", "ItemPtr"); - mApparatus3->setUserData(bestCalcinator); - mApparatus3->setImageTexture(getIconPath(bestCalcinator)); - } - if (!bestRetort.isEmpty()) - { - mApparatus4->setUserString("ToolTipType", "ItemPtr"); - mApparatus4->setUserData(bestRetort); - mApparatus4->setImageTexture(getIconPath(bestRetort)); - } + update(); } void AlchemyWindow::onIngredientSelected(MyGUI::Widget* _sender) { removeIngredient(_sender); - drawItems(); update(); } void AlchemyWindow::onSelectedItemImpl(MWWorld::Ptr item) { - MyGUI::ImageBox* add = NULL; + int res = mAlchemy.addIngredient(item); - // don't allow to add an ingredient that is already added - // (which could happen if two similiar ingredients don't stack because of script / owner) - bool alreadyAdded = false; - std::string name = MWWorld::Class::get(item).getName(item); - if (mIngredient1->isUserString("ToolTipType")) + if (res != -1) { - MWWorld::Ptr item2 = *mIngredient1->getUserData(); - std::string name2 = MWWorld::Class::get(item2).getName(item2); - if (name == name2) - alreadyAdded = true; - } - if (mIngredient2->isUserString("ToolTipType")) - { - MWWorld::Ptr item2 = *mIngredient2->getUserData(); - std::string name2 = MWWorld::Class::get(item2).getName(item2); - if (name == name2) - alreadyAdded = true; - } - if (mIngredient3->isUserString("ToolTipType")) - { - MWWorld::Ptr item2 = *mIngredient3->getUserData(); - std::string name2 = MWWorld::Class::get(item2).getName(item2); - if (name == name2) - alreadyAdded = true; - } - if (mIngredient4->isUserString("ToolTipType")) - { - MWWorld::Ptr item2 = *mIngredient4->getUserData(); - std::string name2 = MWWorld::Class::get(item2).getName(item2); - if (name == name2) - alreadyAdded = true; - } - if (alreadyAdded) - return; - - if (!mIngredient1->isUserString("ToolTipType")) - add = mIngredient1; - if (add == NULL && !mIngredient2->isUserString("ToolTipType")) - add = mIngredient2; - if (add == NULL && !mIngredient3->isUserString("ToolTipType")) - add = mIngredient3; - if (add == NULL && !mIngredient4->isUserString("ToolTipType")) - add = mIngredient4; - - if (add != NULL) - { - add->setUserString("ToolTipType", "ItemPtr"); - add->setUserData(item); - add->setImageTexture(getIconPath(item)); - drawItems(); update(); std::string sound = MWWorld::Class::get(item).getUpSoundId(item); @@ -380,54 +175,40 @@ namespace MWGui { std::vector ignore; // don't show ingredients that are currently selected in the "available ingredients" box. - if (mIngredient1->isUserString("ToolTipType")) - ignore.push_back(*mIngredient1->getUserData()); - if (mIngredient2->isUserString("ToolTipType")) - ignore.push_back(*mIngredient2->getUserData()); - if (mIngredient3->isUserString("ToolTipType")) - ignore.push_back(*mIngredient3->getUserData()); - if (mIngredient4->isUserString("ToolTipType")) - ignore.push_back(*mIngredient4->getUserData()); + for (int i=0; i<4; ++i) + if (mIngredients[i]->isUserString("ToolTipType")) + ignore.push_back(*mIngredients[i]->getUserData()); return ignore; } void AlchemyWindow::update() { - Widgets::SpellEffectList effects; - + MWMechanics::Alchemy::TIngredientsIterator it = mAlchemy.beginIngredients (); for (int i=0; i<4; ++i) { - MyGUI::ImageBox* ingredient; - if (i==0) - ingredient = mIngredient1; - else if (i==1) - ingredient = mIngredient2; - else if (i==2) - ingredient = mIngredient3; - else if (i==3) - ingredient = mIngredient4; + MyGUI::ImageBox* ingredient = mIngredients[i]; - if (!ingredient->isUserString("ToolTipType")) - continue; - - // add the effects of this ingredient to list of effects - MWWorld::LiveCellRef* ref = ingredient->getUserData()->get(); - for (int i=0; i<4; ++i) + MWWorld::Ptr item; + if (it != mAlchemy.endIngredients ()) { - if (ref->base->mData.mEffectID[i] < 0) - continue; - MWGui::Widgets::SpellEffectParams params; - params.mEffectID = ref->base->mData.mEffectID[i]; - params.mAttribute = ref->base->mData.mAttributes[i]; - params.mSkill = ref->base->mData.mSkills[i]; - effects.push_back(params); + item = *it; + ++it; } - // update ingredient count labels if (ingredient->getChildCount()) MyGUI::Gui::getInstance().destroyWidget(ingredient->getChildAt(0)); + ingredient->setImageTexture(""); + ingredient->clearUserStrings (); + + if (item.isEmpty ()) + continue; + + ingredient->setUserString("ToolTipType", "ItemPtr"); + ingredient->setUserData(item); + ingredient->setImageTexture(getIconPath(item)); + MyGUI::TextBox* text = ingredient->createWidget("SandBrightText", MyGUI::IntCoord(0, 14, 32, 18), MyGUI::Align::Default, std::string("Label")); text->setTextAlign(MyGUI::Align::Right); text->setNeedMouseFocus(false); @@ -436,49 +217,15 @@ namespace MWGui text->setCaption(getCountString(ingredient->getUserData()->getRefData().getCount())); } - // now remove effects that are only present once - Widgets::SpellEffectList::iterator it = effects.begin(); - while (it != effects.end()) - { - Widgets::SpellEffectList::iterator next = it; - ++next; - bool found = false; - for (; next != effects.end(); ++next) - { - if (*next == *it) - found = true; - } + drawItems(); - if (!found) - it = effects.erase(it); - else - ++it; - } - - // now remove duplicates, and don't allow more than 4 effects - Widgets::SpellEffectList old = effects; - effects.clear(); - int i=0; - for (Widgets::SpellEffectList::iterator it = old.begin(); - it != old.end(); ++it) + std::vector effects; + ESM::EffectList list; + list.mList = effects; + for (MWMechanics::Alchemy::TEffectsIterator it = mAlchemy.beginEffects (); it != mAlchemy.endEffects (); ++it) { - bool found = false; - for (Widgets::SpellEffectList::iterator it2 = effects.begin(); - it2 != effects.end(); ++it2) - { - // MW considers all "foritfy attribute" effects as the same effect. See the - // "Can't create multi-state boost potions" discussion on http://www.uesp.net/wiki/Morrowind_talk:Alchemy - // thus, we are only checking effectID here and not attribute or skill - if (it2->mEffectID == it->mEffectID) - found = true; - } - if (!found && i<4) - { - ++i; - effects.push_back(*it); - } + list.mList.push_back(*it); } - mEffects = effects; while (mEffectsBox->getChildCount()) MyGUI::Gui::getInstance().destroyWidget(mEffectsBox->getChildAt(0)); @@ -487,7 +234,9 @@ namespace MWGui Widgets::MWEffectListPtr effectsWidget = mEffectsBox->createWidget ("MW_StatName", coord, MyGUI::Align::Left | MyGUI::Align::Top); effectsWidget->setWindowManager(&mWindowManager); - effectsWidget->setEffectList(effects); + + Widgets::SpellEffectList _list = Widgets::MWEffectList::effectListFromESM(&list); + effectsWidget->setEffectList(_list); std::vector effectItems; effectsWidget->createEffectWidgets(effectItems, mEffectsBox, coord, false, 0); @@ -496,9 +245,10 @@ namespace MWGui void AlchemyWindow::removeIngredient(MyGUI::Widget* ingredient) { - ingredient->clearUserStrings(); - static_cast(ingredient)->setImageTexture(""); - if (ingredient->getChildCount()) - MyGUI::Gui::getInstance().destroyWidget(ingredient->getChildAt(0)); + for (int i=0; i<4; ++i) + if (mIngredients[i] == ingredient) + mAlchemy.removeIngredient (i); + + update(); } } diff --git a/apps/openmw/mwgui/alchemywindow.hpp b/apps/openmw/mwgui/alchemywindow.hpp index 53e7178d5..5f84e73e9 100644 --- a/apps/openmw/mwgui/alchemywindow.hpp +++ b/apps/openmw/mwgui/alchemywindow.hpp @@ -1,6 +1,10 @@ #ifndef MWGUI_ALCHEMY_H #define MWGUI_ALCHEMY_H +#include + +#include "../mwmechanics/alchemy.hpp" + #include "window_base.hpp" #include "container.hpp" #include "widgets.hpp" @@ -18,22 +22,10 @@ namespace MWGui MyGUI::Button* mCreateButton; MyGUI::Button* mCancelButton; - MyGUI::ImageBox* mIngredient1; - MyGUI::ImageBox* mIngredient2; - MyGUI::ImageBox* mIngredient3; - MyGUI::ImageBox* mIngredient4; - - MyGUI::ImageBox* mApparatus1; - MyGUI::ImageBox* mApparatus2; - MyGUI::ImageBox* mApparatus3; - MyGUI::ImageBox* mApparatus4; - MyGUI::Widget* mEffectsBox; MyGUI::EditBox* mNameEdit; - Widgets::SpellEffectList mEffects; // effects of created potion - void onCancelButtonClicked(MyGUI::Widget* _sender); void onCreateButtonClicked(MyGUI::Widget* _sender); void onIngredientSelected(MyGUI::Widget* _sender); @@ -46,6 +38,13 @@ namespace MWGui virtual void onReferenceUnavailable() { ; } void update(); + + private: + + MWMechanics::Alchemy mAlchemy; + + std::vector mApparatus; + std::vector mIngredients; }; } diff --git a/apps/openmw/mwgui/birth.cpp b/apps/openmw/mwgui/birth.cpp index c8ef35be3..4837821e0 100644 --- a/apps/openmw/mwgui/birth.cpp +++ b/apps/openmw/mwgui/birth.cpp @@ -3,7 +3,7 @@ #include #include -#include "components/esm_store/store.hpp" +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -14,6 +14,16 @@ using namespace MWGui; using namespace Widgets; +namespace +{ + +bool sortBirthSigns(const std::pair& left, const std::pair& right) +{ + return left.second->mName.compare (right.second->mName) < 0; +} + +} + BirthDialog::BirthDialog(MWBase::WindowManager& parWindowManager) : WindowBase("openmw_chargen_birth.layout", parWindowManager) { @@ -38,6 +48,7 @@ BirthDialog::BirthDialog(MWBase::WindowManager& parWindowManager) getWidget(okButton, "OKButton"); okButton->setCaption(mWindowManager.getGameSettingString("sOK", "")); okButton->eventMouseButtonClick += MyGUI::newDelegate(this, &BirthDialog::onOkClicked); + okButton->setEnabled(false); updateBirths(); updateSpells(); @@ -72,6 +83,9 @@ void BirthDialog::setBirthId(const std::string &birthId) if (boost::iequals(*mBirthList->getItemDataAt(i), birthId)) { mBirthList->setIndexSelected(i); + MyGUI::ButtonPtr okButton; + getWidget(okButton, "OKButton"); + okButton->setEnabled(true); break; } } @@ -83,6 +97,8 @@ void BirthDialog::setBirthId(const std::string &birthId) void BirthDialog::onOkClicked(MyGUI::Widget* _sender) { + if(mBirthList->getIndexSelected() == MyGUI::ITEM_NONE) + return; eventDone(this); } @@ -96,6 +112,10 @@ void BirthDialog::onSelectBirth(MyGUI::ListBox* _sender, size_t _index) if (_index == MyGUI::ITEM_NONE) return; + MyGUI::ButtonPtr okButton; + getWidget(okButton, "OKButton"); + okButton->setEnabled(true); + const std::string *birthId = mBirthList->getItemDataAt(_index); if (boost::iequals(mCurrentBirthId, *birthId)) return; @@ -110,16 +130,25 @@ void BirthDialog::updateBirths() { mBirthList->removeAllItems(); - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); + const MWWorld::Store &signs = + MWBase::Environment::get().getWorld()->getStore().get(); - ESMS::RecListT::MapType::const_iterator it = store.birthSigns.list.begin(); - ESMS::RecListT::MapType::const_iterator end = store.birthSigns.list.end(); int index = 0; - for (; it != end; ++it) + + // sort by name + std::vector < std::pair > birthSigns; + + MWWorld::Store::iterator it = signs.begin(); + for (; it != signs.end(); ++it) { - const ESM::BirthSign &birth = it->second; - mBirthList->addItem(birth.mName, it->first); - if (boost::iequals(it->first, mCurrentBirthId)) + birthSigns.push_back(std::make_pair(it->mId, &(*it))); + } + std::sort(birthSigns.begin(), birthSigns.end(), sortBirthSigns); + + for (std::vector < std::pair >::const_iterator it2 = birthSigns.begin(); it2 != birthSigns.end(); ++it2) + { + mBirthList->addItem(it2->second->mName, it2->first); + if (boost::iequals(it2->first, mCurrentBirthId)) mBirthList->setIndexSelected(index); ++index; } @@ -140,8 +169,11 @@ void BirthDialog::updateSpells() const int lineHeight = 18; MyGUI::IntCoord coord(0, 0, mSpellArea->getWidth(), 18); - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); - const ESM::BirthSign *birth = store.birthSigns.find(mCurrentBirthId); + const MWWorld::ESMStore &store = + MWBase::Environment::get().getWorld()->getStore(); + + const ESM::BirthSign *birth = + store.get().find(mCurrentBirthId); std::string texturePath = std::string("textures\\") + birth->mTexture; fixTexturePath(texturePath); @@ -154,7 +186,7 @@ void BirthDialog::updateSpells() for (; it != end; ++it) { const std::string &spellId = *it; - const ESM::Spell *spell = store.spells.search(spellId); + const ESM::Spell *spell = store.get().search(spellId); if (!spell) continue; // Skip spells which cannot be found ESM::Spell::SpellType type = static_cast(spell->mData.mType); @@ -170,11 +202,17 @@ void BirthDialog::updateSpells() } int i = 0; - struct{ const std::vector &spells; const char *label; } categories[3] = { + + struct { + const std::vector &spells; + const char *label; + } + categories[3] = { {abilities, "sBirthsignmenu1"}, {powers, "sPowers"}, {spells, "sBirthsignmenu2"} }; + for (int category = 0; category < 3; ++category) { if (!categories[category].spells.empty()) diff --git a/apps/openmw/mwgui/bookwindow.cpp b/apps/openmw/mwgui/bookwindow.cpp index cb142db60..bc3cd7b40 100644 --- a/apps/openmw/mwgui/bookwindow.cpp +++ b/apps/openmw/mwgui/bookwindow.cpp @@ -60,7 +60,7 @@ void BookWindow::open (MWWorld::Ptr book) MWWorld::LiveCellRef *ref = mBook.get(); BookTextParser parser; - std::vector results = parser.split(ref->base->mText, mLeftPage->getSize().width, mLeftPage->getSize().height); + std::vector results = parser.split(ref->mBase->mText, mLeftPage->getSize().width, mLeftPage->getSize().height); int i=0; for (std::vector::iterator it=results.begin(); diff --git a/apps/openmw/mwgui/charactercreation.cpp b/apps/openmw/mwgui/charactercreation.cpp index e5bcdbaf8..1719c5768 100644 --- a/apps/openmw/mwgui/charactercreation.cpp +++ b/apps/openmw/mwgui/charactercreation.cpp @@ -7,6 +7,7 @@ #include "review.hpp" #include "dialogue.hpp" #include "mode.hpp" +#include "inventorywindow.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/soundmanager.hpp" @@ -232,6 +233,7 @@ void CharacterCreation::spawnDialog(const char id) mBirthSignDialog = 0; mBirthSignDialog = new BirthDialog(*mWM); 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); @@ -356,7 +358,9 @@ void CharacterCreation::onPickClassDialogDone(WindowBase* parWindow) const std::string &classId = mPickClassDialog->getClassId(); if (!classId.empty()) MWBase::Environment::get().getMechanicsManager()->setPlayerClass(classId); - const ESM::Class *klass = MWBase::Environment::get().getWorld()->getStore().classes.find(classId); + + const ESM::Class *klass = + MWBase::Environment::get().getWorld()->getStore().get().find(classId); if (klass) { mPlayerClass = *klass; @@ -456,9 +460,16 @@ void CharacterCreation::onRaceDialogBack() { if (mRaceDialog) { - mPlayerRaceId = mRaceDialog->getRaceId(); - if (!mPlayerRaceId.empty()) - MWBase::Environment::get().getMechanicsManager()->setPlayerRace(mPlayerRaceId, mRaceDialog->getGender() == RaceDialog::GM_Male); + 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 + ); + } mWM->removeDialog(mRaceDialog); mRaceDialog = 0; } @@ -471,10 +482,18 @@ void CharacterCreation::onRaceDialogDone(WindowBase* parWindow) { if (mRaceDialog) { - mPlayerRaceId = mRaceDialog->getRaceId(); - mWM->setValue("race", mPlayerRaceId); - if (!mPlayerRaceId.empty()) - MWBase::Environment::get().getMechanicsManager()->setPlayerRace(mPlayerRaceId, mRaceDialog->getGender() == RaceDialog::GM_Male); + 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 + ); + } + mWM->getInventoryWindow()->rebuildAvatar(); + mWM->removeDialog(mRaceDialog); mRaceDialog = 0; } @@ -556,6 +575,7 @@ void CharacterCreation::onCreateClassDialogDone(WindowBase* parWindow) klass.mData.mSkills[i][1] = majorSkills[i]; klass.mData.mSkills[i][0] = minorSkills[i]; } + MWBase::Environment::get().getMechanicsManager()->setPlayerClass(klass); mPlayerClass = klass; mWM->setPlayerClass(klass); @@ -728,7 +748,10 @@ void CharacterCreation::onGenerateClassDone(WindowBase* parWindow) mGenerateClassResultDialog = 0; MWBase::Environment::get().getMechanicsManager()->setPlayerClass(mGenerateClass); - const ESM::Class *klass = MWBase::Environment::get().getWorld()->getStore().classes.find(mGenerateClass); + + const ESM::Class *klass = + MWBase::Environment::get().getWorld()->getStore().get().find(mGenerateClass); + mPlayerClass = *klass; mWM->setPlayerClass(mPlayerClass); diff --git a/apps/openmw/mwgui/charactercreation.hpp b/apps/openmw/mwgui/charactercreation.hpp index 28ced2e70..9653aeede 100644 --- a/apps/openmw/mwgui/charactercreation.hpp +++ b/apps/openmw/mwgui/charactercreation.hpp @@ -1,7 +1,7 @@ #ifndef CHARACTER_CREATION_HPP #define CHARACTER_CREATION_HPP -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/world.hpp" #include "../mwbase/windowmanager.hpp" diff --git a/apps/openmw/mwgui/class.cpp b/apps/openmw/mwgui/class.cpp index dfd9bde53..c14c7f74b 100644 --- a/apps/openmw/mwgui/class.cpp +++ b/apps/openmw/mwgui/class.cpp @@ -5,7 +5,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -50,7 +50,7 @@ void GenerateClassResultDialog::setClassId(const std::string &classId) { mCurrentClassId = classId; mClassImage->setImageTexture(std::string("textures\\levelup\\") + mCurrentClassId + ".dds"); - mClassName->setCaption(MWBase::Environment::get().getWorld()->getStore().classes.find(mCurrentClassId)->mName); + mClassName->setCaption(MWBase::Environment::get().getWorld()->getStore().get().find(mCurrentClassId)->mName); } // widget controls @@ -104,6 +104,7 @@ PickClassDialog::PickClassDialog(MWBase::WindowManager& parWindowManager) MyGUI::ButtonPtr okButton; getWidget(okButton, "OKButton"); okButton->eventMouseButtonClick += MyGUI::newDelegate(this, &PickClassDialog::onOkClicked); + okButton->setEnabled(false); updateClasses(); updateStats(); @@ -137,6 +138,9 @@ void PickClassDialog::setClassId(const std::string &classId) if (boost::iequals(*mClassList->getItemDataAt(i), classId)) { mClassList->setIndexSelected(i); + MyGUI::ButtonPtr okButton; + getWidget(okButton, "OKButton"); + okButton->setEnabled(true); break; } } @@ -148,6 +152,8 @@ void PickClassDialog::setClassId(const std::string &classId) void PickClassDialog::onOkClicked(MyGUI::Widget* _sender) { + if(mClassList->getIndexSelected() == MyGUI::ITEM_NONE) + return; eventDone(this); } @@ -161,6 +167,10 @@ void PickClassDialog::onSelectClass(MyGUI::ListBox* _sender, size_t _index) if (_index == MyGUI::ITEM_NONE) return; + MyGUI::ButtonPtr okButton; + getWidget(okButton, "OKButton"); + okButton->setEnabled(true); + const std::string *classId = mClassList->getItemDataAt(_index); if (boost::iequals(mCurrentClassId, *classId)) return; @@ -175,20 +185,18 @@ void PickClassDialog::updateClasses() { mClassList->removeAllItems(); - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); + const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); - ESMS::RecListT::MapType::const_iterator it = store.classes.list.begin(); - ESMS::RecListT::MapType::const_iterator end = store.classes.list.end(); int index = 0; - for (; it != end; ++it) + MWWorld::Store::iterator it = store.get().begin(); + for (; it != store.get().end(); ++it) { - const ESM::Class &klass = it->second; - bool playable = (klass.mData.mIsPlayable != 0); + bool playable = (it->mData.mIsPlayable != 0); if (!playable) // Only display playable classes continue; - const std::string &id = it->first; - mClassList->addItem(klass.mName, id); + const std::string &id = it->mId; + mClassList->addItem(it->mName, id); if (boost::iequals(id, mCurrentClassId)) mClassList->setIndexSelected(index); ++index; @@ -199,8 +207,8 @@ void PickClassDialog::updateStats() { if (mCurrentClassId.empty()) return; - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); - const ESM::Class *klass = store.classes.search(mCurrentClassId); + const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); + const ESM::Class *klass = store.get().search(mCurrentClassId); if (!klass) return; @@ -565,7 +573,7 @@ void CreateClassDialog::onAttributeClicked(Widgets::MWAttributePtr _sender) { delete mAttribDialog; mAttribDialog = new SelectAttributeDialog(mWindowManager); - mAttribDialog->setAffectedWidget(_sender); + mAffectedAttribute = _sender; mAttribDialog->eventCancel += MyGUI::newDelegate(this, &CreateClassDialog::onDialogCancel); mAttribDialog->eventItemSelected += MyGUI::newDelegate(this, &CreateClassDialog::onAttributeSelected); mAttribDialog->setVisible(true); @@ -574,18 +582,17 @@ void CreateClassDialog::onAttributeClicked(Widgets::MWAttributePtr _sender) void CreateClassDialog::onAttributeSelected() { ESM::Attribute::AttributeID id = mAttribDialog->getAttributeId(); - Widgets::MWAttributePtr attribute = mAttribDialog->getAffectedWidget(); - if (attribute == mFavoriteAttribute0) + if (mAffectedAttribute == mFavoriteAttribute0) { if (mFavoriteAttribute1->getAttributeId() == id) mFavoriteAttribute1->setAttributeId(mFavoriteAttribute0->getAttributeId()); } - else if (attribute == mFavoriteAttribute1) + else if (mAffectedAttribute == mFavoriteAttribute1) { if (mFavoriteAttribute0->getAttributeId() == id) mFavoriteAttribute0->setAttributeId(mFavoriteAttribute1->getAttributeId()); } - attribute->setAttributeId(id); + mAffectedAttribute->setAttributeId(id); mWindowManager.removeDialog(mAttribDialog); mAttribDialog = 0; @@ -596,7 +603,7 @@ void CreateClassDialog::onSkillClicked(Widgets::MWSkillPtr _sender) { delete mSkillDialog; mSkillDialog = new SelectSkillDialog(mWindowManager); - mSkillDialog->setAffectedWidget(_sender); + mAffectedSkill = _sender; mSkillDialog->eventCancel += MyGUI::newDelegate(this, &CreateClassDialog::onDialogCancel); mSkillDialog->eventItemSelected += MyGUI::newDelegate(this, &CreateClassDialog::onSkillSelected); mSkillDialog->setVisible(true); @@ -605,22 +612,21 @@ void CreateClassDialog::onSkillClicked(Widgets::MWSkillPtr _sender) void CreateClassDialog::onSkillSelected() { ESM::Skill::SkillEnum id = mSkillDialog->getSkillId(); - Widgets::MWSkillPtr skill = mSkillDialog->getAffectedWidget(); // Avoid duplicate skills by swapping any skill field that matches the selected one std::vector::const_iterator end = mSkills.end(); for (std::vector::const_iterator it = mSkills.begin(); it != end; ++it) { - if (*it == skill) + if (*it == mAffectedSkill) continue; if ((*it)->getSkillId() == id) { - (*it)->setSkillId(skill->getSkillId()); + (*it)->setSkillId(mAffectedSkill->getSkillId()); break; } } - skill->setSkillId(mSkillDialog->getSkillId()); + mAffectedSkill->setSkillId(mSkillDialog->getSkillId()); mWindowManager.removeDialog(mSkillDialog); mSkillDialog = 0; update(); @@ -643,6 +649,8 @@ void CreateClassDialog::onDescriptionEntered(WindowBase* parWindow) void CreateClassDialog::onOkClicked(MyGUI::Widget* _sender) { + if(getName().size() <= 0) + return; eventDone(this); } diff --git a/apps/openmw/mwgui/class.hpp b/apps/openmw/mwgui/class.hpp index 94e8558d0..c7699b308 100644 --- a/apps/openmw/mwgui/class.hpp +++ b/apps/openmw/mwgui/class.hpp @@ -167,8 +167,6 @@ namespace MWGui ~SelectAttributeDialog(); ESM::Attribute::AttributeID getAttributeId() const { return mAttributeId; } - Widgets::MWAttributePtr getAffectedWidget() const { return mAffectedWidget; } - void setAffectedWidget(Widgets::MWAttributePtr widget) { mAffectedWidget = widget; } // Events typedef MyGUI::delegates::CMultiDelegate0 EventHandle_Void; @@ -188,8 +186,6 @@ namespace MWGui void onCancelClicked(MyGUI::Widget* _sender); private: - Widgets::MWAttributePtr mAffectedWidget; - ESM::Attribute::AttributeID mAttributeId; }; @@ -200,8 +196,6 @@ namespace MWGui ~SelectSkillDialog(); ESM::Skill::SkillEnum getSkillId() const { return mSkillId; } - Widgets::MWSkillPtr getAffectedWidget() const { return mAffectedWidget; } - void setAffectedWidget(Widgets::MWSkillPtr widget) { mAffectedWidget = widget; } // Events typedef MyGUI::delegates::CMultiDelegate0 EventHandle_Void; @@ -224,7 +218,6 @@ namespace MWGui Widgets::MWSkillPtr mCombatSkill[9]; Widgets::MWSkillPtr mMagicSkill[9]; Widgets::MWSkillPtr mStealthSkill[9]; - Widgets::MWSkillPtr mAffectedWidget; ESM::Skill::SkillEnum mSkillId; }; @@ -301,6 +294,9 @@ namespace MWGui DescriptionDialog *mDescDialog; ESM::Class::Specialization mSpecializationId; + + Widgets::MWAttributePtr mAffectedAttribute; + Widgets::MWSkillPtr mAffectedSkill; }; } #endif diff --git a/apps/openmw/mwgui/console.cpp b/apps/openmw/mwgui/console.cpp index b939284dd..b2281d87e 100644 --- a/apps/openmw/mwgui/console.cpp +++ b/apps/openmw/mwgui/console.cpp @@ -4,11 +4,10 @@ #include #include -#include -#include - #include +#include "../mwworld/esmstore.hpp" + #include "../mwscript/extensions.hpp" #include "../mwbase/environment.hpp" @@ -93,12 +92,12 @@ namespace MWGui scanner.listKeywords (mNames); // identifier - const ESMS::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); + const MWWorld::ESMStore& store = + MWBase::Environment::get().getWorld()->getStore(); - for (ESMS::RecListList::const_iterator iter (store.recLists.begin()); - iter!=store.recLists.end(); ++iter) + for (MWWorld::ESMStore::iterator it = store.begin(); it != store.end(); ++it) { - iter->second->listIdentifier (mNames); + it->second->listIdentifier (mNames); } // sort diff --git a/apps/openmw/mwgui/container.cpp b/apps/openmw/mwgui/container.cpp index 5c202941f..20bc95445 100644 --- a/apps/openmw/mwgui/container.cpp +++ b/apps/openmw/mwgui/container.cpp @@ -127,10 +127,13 @@ void ContainerBase::onSelectedItem(MyGUI::Widget* _sender) if (isInventory()) { + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); + // the player is trying to sell an item, check if the merchant accepts it // also, don't allow selling gold (let's be better than Morrowind at this, can we?) if (!MWBase::Environment::get().getWindowManager()->getTradeWindow()->npcAcceptsItem(object) || - MWWorld::Class::get(object).getName(object) == MWBase::Environment::get().getWorld()->getStore().gameSettings.find("sGold")->getString()) + MWWorld::Class::get(object).getName(object) == gmst.find("sGold")->getString()) { // user notification "i don't buy this item" MWBase::Environment::get().getWindowManager()-> @@ -274,7 +277,7 @@ void ContainerBase::onContainerClicked(MyGUI::Widget* _sender) if (mPtr.getTypeName() == typeid(ESM::Container).name()) { MWWorld::LiveCellRef* ref = mPtr.get(); - if (ref->base->mFlags & ESM::Container::Organic) + if (ref->mBase->mFlags & ESM::Container::Organic) { // user notification MWBase::Environment::get().getWindowManager()-> diff --git a/apps/openmw/mwgui/container.hpp b/apps/openmw/mwgui/container.hpp index 27c3288ae..08d425032 100644 --- a/apps/openmw/mwgui/container.hpp +++ b/apps/openmw/mwgui/container.hpp @@ -1,7 +1,7 @@ #ifndef MGUI_CONTAINER_H #define MGUI_CONTAINER_H -#include +#include "../mwworld/esmstore.hpp" #include "window_base.hpp" #include "referenceinterface.hpp" diff --git a/apps/openmw/mwgui/dialogue.cpp b/apps/openmw/mwgui/dialogue.cpp index 245487a04..e4c9945b4 100644 --- a/apps/openmw/mwgui/dialogue.cpp +++ b/apps/openmw/mwgui/dialogue.cpp @@ -6,12 +6,15 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/dialoguemanager.hpp" #include "../mwbase/world.hpp" #include "../mwbase/windowmanager.hpp" +#include "../mwbase/mechanicsmanager.hpp" + +#include "../mwmechanics/npcstats.hpp" #include "dialogue_history.hpp" #include "widgets.hpp" @@ -19,6 +22,7 @@ #include "tradewindow.hpp" #include "spellbuyingwindow.hpp" #include "inventorywindow.hpp" +#include "travelwindow.hpp" using namespace MWGui; using namespace Widgets; @@ -27,6 +31,8 @@ using namespace Widgets; *Copied from the internet. */ +namespace { + std::string lower_string(const std::string& str) { std::string lowerCase; @@ -42,16 +48,90 @@ std::string::size_type find_str_ci(const std::string& str, const std::string& su return lower_string(str).find(lower_string(substr),pos); } +} + + + +PersuasionDialog::PersuasionDialog(MWBase::WindowManager &parWindowManager) + : WindowModal("openmw_persuasion_dialog.layout", parWindowManager) +{ + getWidget(mCancelButton, "CancelButton"); + getWidget(mAdmireButton, "AdmireButton"); + getWidget(mIntimidateButton, "IntimidateButton"); + getWidget(mTauntButton, "TauntButton"); + getWidget(mBribe10Button, "Bribe10Button"); + getWidget(mBribe100Button, "Bribe100Button"); + getWidget(mBribe1000Button, "Bribe1000Button"); + getWidget(mGoldLabel, "GoldLabel"); + + mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &PersuasionDialog::onCancel); + mAdmireButton->eventMouseButtonClick += MyGUI::newDelegate(this, &PersuasionDialog::onPersuade); + mIntimidateButton->eventMouseButtonClick += MyGUI::newDelegate(this, &PersuasionDialog::onPersuade); + mTauntButton->eventMouseButtonClick += MyGUI::newDelegate(this, &PersuasionDialog::onPersuade); + mBribe10Button->eventMouseButtonClick += MyGUI::newDelegate(this, &PersuasionDialog::onPersuade); + mBribe100Button->eventMouseButtonClick += MyGUI::newDelegate(this, &PersuasionDialog::onPersuade); + mBribe1000Button->eventMouseButtonClick += MyGUI::newDelegate(this, &PersuasionDialog::onPersuade); +} + +void PersuasionDialog::onCancel(MyGUI::Widget *sender) +{ + setVisible(false); +} + +void PersuasionDialog::onPersuade(MyGUI::Widget *sender) +{ + MWBase::MechanicsManager::PersuasionType type; + if (sender == mAdmireButton) type = MWBase::MechanicsManager::PT_Admire; + else if (sender == mIntimidateButton) type = MWBase::MechanicsManager::PT_Intimidate; + else if (sender == mTauntButton) type = MWBase::MechanicsManager::PT_Taunt; + else if (sender == mBribe10Button) + { + mWindowManager.getTradeWindow()->addOrRemoveGold(-10); + type = MWBase::MechanicsManager::PT_Bribe10; + } + else if (sender == mBribe100Button) + { + mWindowManager.getTradeWindow()->addOrRemoveGold(-100); + type = MWBase::MechanicsManager::PT_Bribe100; + } + else /*if (sender == mBribe1000Button)*/ + { + mWindowManager.getTradeWindow()->addOrRemoveGold(-1000); + type = MWBase::MechanicsManager::PT_Bribe1000; + } + + MWBase::Environment::get().getDialogueManager()->persuade(type); + + setVisible(false); +} + +void PersuasionDialog::open() +{ + WindowModal::open(); + center(); + + int playerGold = mWindowManager.getInventoryWindow()->getPlayerGold(); + + mBribe10Button->setEnabled (playerGold >= 10); + mBribe100Button->setEnabled (playerGold >= 100); + mBribe1000Button->setEnabled (playerGold >= 1000); + + mGoldLabel->setCaptionWithReplacing("#{sGold}: " + boost::lexical_cast(playerGold)); +} + +// -------------------------------------------------------------------------------------------------- DialogueWindow::DialogueWindow(MWBase::WindowManager& parWindowManager) : WindowBase("openmw_dialogue_window.layout", parWindowManager) - , mEnabled(true) - , mShowTrade(false) - , mShowSpells(false) + , mPersuasionDialog(parWindowManager) + , mEnabled(false) + , mServices(0) { // Centre dialog center(); + mPersuasionDialog.setVisible(false); + //History view getWidget(mHistory, "History"); mHistory->setOverflowToTheLeft(true); @@ -123,18 +203,44 @@ void DialogueWindow::onSelectTopic(std::string topic) { if (!mEnabled) return; - if (topic == MWBase::Environment::get().getWorld()->getStore().gameSettings.find("sBarter")->getString()) + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); + + if (topic == gmst.find("sBarter")->getString()) { /// \todo check if the player is allowed to trade with this actor (e.g. faction rank high enough)? mWindowManager.pushGuiMode(GM_Barter); mWindowManager.getTradeWindow()->startTrade(mPtr); } - else if (topic == MWBase::Environment::get().getWorld()->getStore().gameSettings.find("sSpells")->getString()) + if (topic == gmst.find("sPersuasion")->getString()) + { + mPersuasionDialog.setVisible(true); + } + else if (topic == gmst.find("sSpells")->getString()) { mWindowManager.pushGuiMode(GM_SpellBuying); mWindowManager.getSpellBuyingWindow()->startSpellBuying(mPtr); } - + else if (topic == gmst.find("sTravel")->getString()) + { + mWindowManager.pushGuiMode(GM_Travel); + mWindowManager.getTravelWindow()->startTravel(mPtr); + } + else if (topic == gmst.find("sSpellMakingMenuTitle")->getString()) + { + mWindowManager.pushGuiMode(GM_SpellCreation); + mWindowManager.startSpellMaking (mPtr); + } + else if (topic == gmst.find("sEnchanting")->getString()) + { + mWindowManager.pushGuiMode(GM_Enchanting); + mWindowManager.startEnchanting (mPtr); + } + else if (topic == gmst.find("sServiceTrainingTitle")->getString()) + { + mWindowManager.pushGuiMode(GM_Training); + mWindowManager.startTraining (mPtr); + } else MWBase::Environment::get().getDialogueManager()->keywordSelected(lower_string(topic)); } @@ -147,7 +253,7 @@ void DialogueWindow::startDialogue(MWWorld::Ptr actor, std::string npcName) setTitle(npcName); mTopicsList->clear(); - mHistory->eraseText(0,mHistory->getTextLength()); + mHistory->setCaption(""); updateOptions(); } @@ -155,13 +261,31 @@ void DialogueWindow::setKeywords(std::list keyWords) { mTopicsList->clear(); - bool anyService = mShowTrade||mShowSpells; + bool anyService = mServices > 0; - if (mShowTrade) - mTopicsList->addItem(MWBase::Environment::get().getWorld()->getStore().gameSettings.find("sBarter")->getString()); + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); - if (mShowSpells) - mTopicsList->addItem(MWBase::Environment::get().getWorld()->getStore().gameSettings.find("sSpells")->getString()); + if (mPtr.getTypeName() == typeid(ESM::NPC).name()) + mTopicsList->addItem(gmst.find("sPersuasion")->getString()); + + if (mServices & Service_Trade) + mTopicsList->addItem(gmst.find("sBarter")->getString()); + + if (mServices & Service_BuySpells) + mTopicsList->addItem(gmst.find("sSpells")->getString()); + + if (mServices & Service_Travel) + mTopicsList->addItem(gmst.find("sTravel")->getString()); + + if (mServices & Service_CreateSpells) + mTopicsList->addItem(gmst.find("sSpellmakingMenuTitle")->getString()); + +// if (mServices & Service_Enchant) +// mTopicsList->addItem(gmst.find("sEnchanting")->getString()); + + if (mServices & Service_Training) + mTopicsList->addItem(gmst.find("sServiceTrainingTitle")->getString()); if (anyService) mTopicsList->addSeparator(); @@ -258,15 +382,18 @@ void DialogueWindow::updateOptions() mTopicsList->clear(); mHistory->eraseText(0, mHistory->getTextLength()); - mDispositionBar->setProgressRange(100); - mDispositionBar->setProgressPosition(40); - mDispositionText->eraseText(0, mDispositionText->getTextLength()); - mDispositionText->addText("#B29154"+std::string("40/100")+"#B29154"); + if (mPtr.getTypeName() == typeid(ESM::NPC).name()) + { + mDispositionBar->setProgressRange(100); + mDispositionBar->setProgressPosition(MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(mPtr)); + mDispositionText->eraseText(0, mDispositionText->getTextLength()); + mDispositionText->addText("#B29154"+boost::lexical_cast(MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(mPtr))+std::string("/100")+"#B29154"); + } } void DialogueWindow::goodbye() { - mHistory->addDialogText("\n#572D21" + MWBase::Environment::get().getWorld()->getStore().gameSettings.find("sGoodbye")->getString()); + mHistory->addDialogText("\n#572D21" + MWBase::Environment::get().getWorld()->getStore().get().find("sGoodbye")->getString()); mTopicsList->setEnabled(false); mEnabled = false; } @@ -275,3 +402,17 @@ void DialogueWindow::onReferenceUnavailable() { mWindowManager.removeGuiMode(GM_Dialogue); } + +void DialogueWindow::onFrame() +{ + if(mEnabled && mPtr.getTypeName() == typeid(ESM::NPC).name()) + { + int disp = std::max(0, std::min(100, + MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(mPtr) + + MWBase::Environment::get().getDialogueManager()->getTemporaryDispositionChange())); + mDispositionBar->setProgressRange(100); + mDispositionBar->setProgressPosition(disp); + mDispositionText->eraseText(0, mDispositionText->getTextLength()); + mDispositionText->addText("#B29154"+boost::lexical_cast(disp)+std::string("/100")+"#B29154"); + } +} diff --git a/apps/openmw/mwgui/dialogue.hpp b/apps/openmw/mwgui/dialogue.hpp index a43b0d5a7..082d92524 100644 --- a/apps/openmw/mwgui/dialogue.hpp +++ b/apps/openmw/mwgui/dialogue.hpp @@ -26,6 +26,27 @@ namespace MWGui { class DialogueHistory; + class PersuasionDialog : public WindowModal + { + public: + PersuasionDialog(MWBase::WindowManager& parWindowManager); + + virtual void open(); + + private: + MyGUI::Button* mCancelButton; + MyGUI::Button* mAdmireButton; + MyGUI::Button* mIntimidateButton; + MyGUI::Button* mTauntButton; + MyGUI::Button* mBribe10Button; + MyGUI::Button* mBribe100Button; + MyGUI::Button* mBribe1000Button; + MyGUI::TextBox* mGoldLabel; + + void onCancel (MyGUI::Widget* sender); + void onPersuade (MyGUI::Widget* sender); + }; + class DialogueWindow: public WindowBase, public ReferenceInterface { public: @@ -47,11 +68,20 @@ namespace MWGui void addTitle(std::string text); void askQuestion(std::string question); void goodbye(); + void onFrame(); - // various service button visibilities, depending if the npc/creature talked to has these services // make sure to call these before setKeywords() - void setShowTrade(bool show) { mShowTrade = show; } - void setShowSpells(bool show) { mShowSpells = show; } + void setServices(int services) { mServices = services; } + + enum Services + { + Service_Trade = 0x01, + Service_BuySpells = 0x02, + Service_CreateSpells = 0x04, + Service_Enchant = 0x08, + Service_Training = 0x10, + Service_Travel = 0x20 + }; protected: void onSelectTopic(std::string topic); @@ -69,9 +99,7 @@ namespace MWGui */ std::string parseText(std::string text); - // various service button visibilities, depending if the npc/creature talked to has these services - bool mShowTrade; - bool mShowSpells; + int mServices; bool mEnabled; @@ -79,6 +107,8 @@ namespace MWGui Widgets::MWList* mTopicsList; MyGUI::ProgressPtr mDispositionBar; MyGUI::EditPtr mDispositionText; + + PersuasionDialog mPersuasionDialog; }; } #endif diff --git a/apps/openmw/mwgui/dialogue_history.cpp b/apps/openmw/mwgui/dialogue_history.cpp index 4ca764c82..13f72545e 100644 --- a/apps/openmw/mwgui/dialogue_history.cpp +++ b/apps/openmw/mwgui/dialogue_history.cpp @@ -3,7 +3,8 @@ #include "../mwbase/windowmanager.hpp" #include "widgets.hpp" -#include "components/esm_store/store.hpp" + +#include "../mwworld/esmstore.hpp" #include #include diff --git a/apps/openmw/mwgui/enchantingdialog.cpp b/apps/openmw/mwgui/enchantingdialog.cpp new file mode 100644 index 000000000..3bd67ade6 --- /dev/null +++ b/apps/openmw/mwgui/enchantingdialog.cpp @@ -0,0 +1,43 @@ +#include "enchantingdialog.hpp" + + +namespace MWGui +{ + + + EnchantingDialog::EnchantingDialog(MWBase::WindowManager &parWindowManager) + : WindowBase("openmw_enchanting_dialog.layout", parWindowManager) + , EffectEditorBase(parWindowManager) + { + getWidget(mCancelButton, "CancelButton"); + getWidget(mAvailableEffectsList, "AvailableEffects"); + getWidget(mUsedEffectsView, "UsedEffects"); + + setWidgets(mAvailableEffectsList, mUsedEffectsView); + + mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &EnchantingDialog::onCancelButtonClicked); + } + + void EnchantingDialog::open() + { + center(); + } + + void EnchantingDialog::startEnchanting (MWWorld::Ptr actor) + { + mPtr = actor; + + startEditing (); + } + + void EnchantingDialog::onReferenceUnavailable () + { + mWindowManager.removeGuiMode (GM_Dialogue); + mWindowManager.removeGuiMode (GM_Enchanting); + } + + void EnchantingDialog::onCancelButtonClicked(MyGUI::Widget* sender) + { + mWindowManager.removeGuiMode (GM_Enchanting); + } +} diff --git a/apps/openmw/mwgui/enchantingdialog.hpp b/apps/openmw/mwgui/enchantingdialog.hpp new file mode 100644 index 000000000..0415c9d8d --- /dev/null +++ b/apps/openmw/mwgui/enchantingdialog.hpp @@ -0,0 +1,31 @@ +#ifndef MWGUI_ENCHANTINGDIALOG_H +#define MWGUI_ENCHANTINGDIALOG_H + +#include "window_base.hpp" +#include "referenceinterface.hpp" +#include "spellcreationdialog.hpp" + +#include "../mwbase/windowmanager.hpp" + +namespace MWGui +{ + + class EnchantingDialog : public WindowBase, public ReferenceInterface, public EffectEditorBase + { + public: + EnchantingDialog(MWBase::WindowManager& parWindowManager); + + virtual void open(); + void startEnchanting(MWWorld::Ptr actor); + + protected: + virtual void onReferenceUnavailable(); + + void onCancelButtonClicked(MyGUI::Widget* sender); + + MyGUI::Button* mCancelButton; + }; + +} + +#endif diff --git a/apps/openmw/mwgui/hud.cpp b/apps/openmw/mwgui/hud.cpp index ed0e59226..9b4075f57 100644 --- a/apps/openmw/mwgui/hud.cpp +++ b/apps/openmw/mwgui/hud.cpp @@ -245,15 +245,7 @@ void HUD::onWorldClicked(MyGUI::Widget* _sender) return; std::string handle = MWBase::Environment::get().getWorld()->getFacedHandle(); - MWWorld::Ptr object; - try - { - object = MWBase::Environment::get().getWorld()->getPtrViaHandle(handle); - } - catch (std::exception& /* e */) - { - return; - } + MWWorld::Ptr object = MWBase::Environment::get().getWorld()->searchPtrViaHandle(handle); if (mode == GM_Console) MWBase::Environment::get().getWindowManager()->getConsole()->setSelectedObject(object); @@ -349,7 +341,9 @@ void HUD::onResChange(int width, int height) void HUD::setSelectedSpell(const std::string& spellId, int successChancePercent) { - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(spellId); + const ESM::Spell* spell = + MWBase::Environment::get().getWorld()->getStore().get().find(spellId); + std::string spellName = spell->mName; if (spellName != mSpellName && mSpellVisible) { @@ -369,7 +363,9 @@ void HUD::setSelectedSpell(const std::string& spellId, int successChancePercent) mSpellBox->setUserString("Spell", spellId); // use the icon of the first effect - const ESM::MagicEffect* effect = MWBase::Environment::get().getWorld()->getStore().magicEffects.find(spell->mEffects.mList.front().mEffectID); + const ESM::MagicEffect* effect = + MWBase::Environment::get().getWorld()->getStore().get().find(spell->mEffects.mList.front().mEffectID); + std::string icon = effect->mIcon; int slashPos = icon.find("\\"); icon.insert(slashPos+1, "b_"); diff --git a/apps/openmw/mwgui/inventorywindow.hpp b/apps/openmw/mwgui/inventorywindow.hpp index 84b576a58..6b45a9980 100644 --- a/apps/openmw/mwgui/inventorywindow.hpp +++ b/apps/openmw/mwgui/inventorywindow.hpp @@ -28,6 +28,10 @@ namespace MWGui MWWorld::Ptr getAvatarSelectedItem(int x, int y); + void rebuildAvatar() { + mPreview.rebuild(); + } + protected: MyGUI::Widget* mAvatar; MyGUI::ImageBox* mAvatarImage; diff --git a/apps/openmw/mwgui/journalwindow.cpp b/apps/openmw/mwgui/journalwindow.cpp index 597c27c6d..9d5d236be 100644 --- a/apps/openmw/mwgui/journalwindow.cpp +++ b/apps/openmw/mwgui/journalwindow.cpp @@ -85,6 +85,7 @@ MWGui::JournalWindow::JournalWindow (MWBase::WindowManager& parWindowManager) : WindowBase("openmw_journal.layout", parWindowManager) , mLastPos(0) , mVisible(false) + , mPageNumber(0) { //setCoord(0,0,498, 342); center(); diff --git a/apps/openmw/mwgui/levelupdialog.cpp b/apps/openmw/mwgui/levelupdialog.cpp index 7dced94f5..45890b89f 100644 --- a/apps/openmw/mwgui/levelupdialog.cpp +++ b/apps/openmw/mwgui/levelupdialog.cpp @@ -8,14 +8,12 @@ #include "../mwworld/player.hpp" #include "../mwworld/class.hpp" +#include "../mwworld/esmstore.hpp" #include "../mwmechanics/creaturestats.hpp" #include "../mwmechanics/npcstats.hpp" #include "../mwmechanics/stat.hpp" -#include -#include - namespace MWGui { @@ -110,7 +108,8 @@ namespace MWGui void LevelupDialog::open() { - MWWorld::Ptr player = MWBase::Environment::get().getWorld ()->getPlayer().getPlayer(); + MWBase::World *world = MWBase::Environment::get().getWorld(); + MWWorld::Ptr player = world->getPlayer().getPlayer(); MWMechanics::CreatureStats& creatureStats = MWWorld::Class::get(player).getCreatureStats (player); MWMechanics::NpcStats& pcStats = MWWorld::Class::get(player).getNpcStats (player); @@ -121,17 +120,13 @@ namespace MWGui setAttributeValues(); + const ESM::NPC *playerData = player.get()->mBase; + // set class image - const ESM::Class& playerClass = MWBase::Environment::get().getWorld ()->getPlayer ().getClass (); - // retrieve the ID to this class - std::string classId; - std::map list = MWBase::Environment::get().getWorld()->getStore ().classes.list; - for (std::map::iterator it = list.begin(); it != list.end(); ++it) - { - if (playerClass.mName == it->second.mName) - classId = it->first; - } - mClassImage->setImageTexture ("textures\\levelup\\" + classId + ".dds"); + const ESM::Class *cls = + world->getStore().get().find(playerData->mClass); + + mClassImage->setImageTexture ("textures\\levelup\\" + cls->mId + ".dds"); /// \todo replace this with INI-imported texts int level = creatureStats.getLevel ()+1; diff --git a/apps/openmw/mwgui/list.cpp b/apps/openmw/mwgui/list.cpp index 661fb2e68..0bafced97 100644 --- a/apps/openmw/mwgui/list.cpp +++ b/apps/openmw/mwgui/list.cpp @@ -128,4 +128,10 @@ void MWList::onItemSelected(MyGUI::Widget* _sender) std::string name = static_cast(_sender)->getCaption(); eventItemSelected(name); + eventWidgetSelected(_sender); +} + +MyGUI::Widget* MWList::getItemWidget(const std::string& name) +{ + return mScrollView->findWidget (getName() + "_item_" + name); } diff --git a/apps/openmw/mwgui/list.hpp b/apps/openmw/mwgui/list.hpp index 2b765c2e1..d07d49de6 100644 --- a/apps/openmw/mwgui/list.hpp +++ b/apps/openmw/mwgui/list.hpp @@ -18,6 +18,7 @@ namespace MWGui MWList(); typedef MyGUI::delegates::CMultiDelegate1 EventHandle_String; + typedef MyGUI::delegates::CMultiDelegate1 EventHandle_Widget; /** * Event: Item selected with the mouse. @@ -25,6 +26,13 @@ namespace MWGui */ EventHandle_String eventItemSelected; + /** + * Event: Item selected with the mouse. + * signature: void method(MyGUI::Widget* sender) + */ + EventHandle_Widget eventWidgetSelected; + + /** * Call after the size of the list changed, or items were inserted/removed */ @@ -38,6 +46,9 @@ namespace MWGui std::string getItemNameAt(unsigned int at); ///< \attention if there are separators, this method will return "" at the place where the separator is void clear(); + MyGUI::Widget* getItemWidget(const std::string& name); + ///< get widget for an item name, useful to set up tooltip + protected: void initialiseOverride(); diff --git a/apps/openmw/mwgui/loadingscreen.cpp b/apps/openmw/mwgui/loadingscreen.cpp index 170fc3bc5..8bcaa6ce0 100644 --- a/apps/openmw/mwgui/loadingscreen.cpp +++ b/apps/openmw/mwgui/loadingscreen.cpp @@ -6,10 +6,13 @@ #include #include +#include +#include #include "../mwbase/environment.hpp" #include "../mwbase/inputmanager.hpp" +#include "../mwbase/world.hpp" #include "../mwbase/windowmanager.hpp" @@ -106,6 +109,7 @@ namespace MWGui if (mTimer.getMilliseconds () > mLastRenderTime + (1.f/loadingScreenFps) * 1000.f) { + float dt = mTimer.getMilliseconds () - mLastRenderTime; mLastRenderTime = mTimer.getMilliseconds (); if (mFirstLoad && mTimer.getMilliseconds () > mLastWallpaperChangeTime + 3000*1) @@ -151,6 +155,8 @@ namespace MWGui } } + MWBase::Environment::get().getWorld ()->getFader ()->update (dt); + mWindow->update(); if (!hasCompositor) @@ -207,20 +213,22 @@ namespace MWGui void LoadingScreen::changeWallpaper () { - /// \todo use a directory listing here std::vector splash; - splash.push_back ("Splash_Bonelord.tga"); - splash.push_back ("Splash_ClannDaddy.tga"); - splash.push_back ("Splash_Clannfear.tga"); - splash.push_back ("Splash_Daedroth.tga"); - splash.push_back ("Splash_Hunger.tga"); - splash.push_back ("Splash_KwamaWarrior.tga"); - splash.push_back ("Splash_Netch.tga"); - splash.push_back ("Splash_NixHound.tga"); - splash.push_back ("Splash_Siltstriker.tga"); - splash.push_back ("Splash_Skeleton.tga"); - splash.push_back ("Splash_SphereCenturion.tga"); - mBackgroundImage->setImageTexture (splash[rand() % splash.size()]); + Ogre::StringVectorPtr resources = Ogre::ResourceGroupManager::getSingleton ().listResourceNames ("General", false); + for (Ogre::StringVector::const_iterator it = resources->begin(); it != resources->end(); ++it) + { + if (it->size() < 6) + continue; + std::string start = it->substr(0, 6); + boost::to_lower(start); + + if (start == "splash") + splash.push_back (*it); + } + std::string randomSplash = splash[rand() % splash.size()]; + + Ogre::TexturePtr tex = Ogre::TextureManager::getSingleton ().load (randomSplash, "General"); + mBackgroundImage->setImageTexture (randomSplash); } } diff --git a/apps/openmw/mwgui/map_window.cpp b/apps/openmw/mwgui/map_window.cpp index 1913ed8dd..0a26ebb8f 100644 --- a/apps/openmw/mwgui/map_window.cpp +++ b/apps/openmw/mwgui/map_window.cpp @@ -269,10 +269,12 @@ MapWindow::MapWindow(MWBase::WindowManager& parWindowManager, const std::string& getWidget(mLocalMap, "LocalMap"); getWidget(mGlobalMap, "GlobalMap"); getWidget(mGlobalMapImage, "GlobalMapImage"); + getWidget(mGlobalMapOverlay, "GlobalMapOverlay"); getWidget(mPlayerArrowLocal, "CompassLocal"); getWidget(mPlayerArrowGlobal, "CompassGlobal"); mGlobalMapImage->setImageTexture("GlobalMap.png"); + mGlobalMapOverlay->setImageTexture("GlobalMapOverlay"); mGlobalMap->setVisible (false); @@ -328,6 +330,11 @@ void MapWindow::addVisitedLocation(const std::string& name, int x, int y) markerWidget->setUserString("Caption_Text", name); } +void MapWindow::cellExplored(int x, int y) +{ + mGlobalMapRender->exploreCell(x,y); +} + void MapWindow::onDragStart(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id) { if (_id!=MyGUI::MouseButton::Left) return; diff --git a/apps/openmw/mwgui/map_window.hpp b/apps/openmw/mwgui/map_window.hpp index 73eaad1cd..4e2dd6756 100644 --- a/apps/openmw/mwgui/map_window.hpp +++ b/apps/openmw/mwgui/map_window.hpp @@ -70,6 +70,7 @@ namespace MWGui void setCellName(const std::string& cellName); void addVisitedLocation(const std::string& name, int x, int y); // adds the marker to the global map + void cellExplored(int x, int y); virtual void open(); @@ -82,6 +83,7 @@ namespace MWGui MyGUI::ScrollView* mGlobalMap; MyGUI::ImageBox* mGlobalMapImage; + MyGUI::ImageBox* mGlobalMapOverlay; MyGUI::ImageBox* mPlayerArrowLocal; MyGUI::ImageBox* mPlayerArrowGlobal; MyGUI::Button* mButton; diff --git a/apps/openmw/mwgui/mode.hpp b/apps/openmw/mwgui/mode.hpp index 74ecd531a..319537297 100644 --- a/apps/openmw/mwgui/mode.hpp +++ b/apps/openmw/mwgui/mode.hpp @@ -22,6 +22,10 @@ namespace MWGui GM_Rest, GM_RestBed, GM_SpellBuying, + GM_Travel, + GM_SpellCreation, + GM_Enchanting, + GM_Training, GM_Levelup, diff --git a/apps/openmw/mwgui/quickkeysmenu.cpp b/apps/openmw/mwgui/quickkeysmenu.cpp index e927af95d..02512425d 100644 --- a/apps/openmw/mwgui/quickkeysmenu.cpp +++ b/apps/openmw/mwgui/quickkeysmenu.cpp @@ -29,8 +29,11 @@ namespace bool sortSpells(const std::string& left, const std::string& right) { - const ESM::Spell* a = MWBase::Environment::get().getWorld()->getStore().spells.find(left); - const ESM::Spell* b = MWBase::Environment::get().getWorld()->getStore().spells.find(right); + const MWWorld::Store &spells = + MWBase::Environment::get().getWorld()->getStore().get(); + + const ESM::Spell* a = spells.find(left); + const ESM::Spell* b = spells.find(right); int cmp = a->mName.compare(b->mName); return cmp < 0; @@ -234,9 +237,15 @@ namespace MWGui MyGUI::ImageBox* image = frame->createWidget("ImageBox", MyGUI::IntCoord(5, 5, 32, 32), MyGUI::Align::Default); + const MWWorld::ESMStore &esmStore = + MWBase::Environment::get().getWorld()->getStore(); + // use the icon of the first effect - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(spellId); - const ESM::MagicEffect* effect = MWBase::Environment::get().getWorld()->getStore().magicEffects.find(spell->mEffects.mList.front().mEffectID); + const ESM::Spell* spell = esmStore.get().find(spellId); + + const ESM::MagicEffect* effect = + esmStore.get().find(spell->mEffects.mList.front().mEffectID); + std::string path = effect->mIcon; int slashPos = path.find("\\"); path.insert(slashPos+1, "b_"); @@ -434,11 +443,14 @@ namespace MWGui spellList.push_back(*it); } + const MWWorld::ESMStore &esmStore = + MWBase::Environment::get().getWorld()->getStore(); + std::vector powers; std::vector::iterator it = spellList.begin(); while (it != spellList.end()) { - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(*it); + const ESM::Spell* spell = esmStore.get().find(*it); if (spell->mData.mType == ESM::Spell::ST_Power) { powers.push_back(*it); @@ -465,7 +477,9 @@ namespace MWGui if (enchantId != "") { // only add items with "Cast once" or "Cast on use" - const ESM::Enchantment* enchant = MWBase::Environment::get().getWorld()->getStore().enchants.find(enchantId); + const ESM::Enchantment* enchant = + esmStore.get().find(enchantId); + int type = enchant->mData.mType; if (type != ESM::Enchantment::CastOnce && type != ESM::Enchantment::WhenUsed) @@ -487,7 +501,7 @@ namespace MWGui for (std::vector::const_iterator it = powers.begin(); it != powers.end(); ++it) { - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(*it); + const ESM::Spell* spell = esmStore.get().find(*it); MyGUI::Button* t = mMagicList->createWidget("SpellText", MyGUI::IntCoord(4, mHeight, mWidth-8, spellHeight), MyGUI::Align::Left | MyGUI::Align::Top); t->setCaption(spell->mName); @@ -504,7 +518,7 @@ namespace MWGui addGroup("#{sSpells}", ""); for (std::vector::const_iterator it = spellList.begin(); it != spellList.end(); ++it) { - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(*it); + const ESM::Spell* spell = esmStore.get().find(*it); MyGUI::Button* t = mMagicList->createWidget("SpellText", MyGUI::IntCoord(4, mHeight, mWidth-8, spellHeight), MyGUI::Align::Left | MyGUI::Align::Top); t->setCaption(spell->mName); diff --git a/apps/openmw/mwgui/race.cpp b/apps/openmw/mwgui/race.cpp index 019a59cf4..d2714fb51 100644 --- a/apps/openmw/mwgui/race.cpp +++ b/apps/openmw/mwgui/race.cpp @@ -5,8 +5,9 @@ #include #include +#include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -80,6 +81,7 @@ RaceDialog::RaceDialog(MWBase::WindowManager& parWindowManager) getWidget(okButton, "OKButton"); okButton->setCaption(mWindowManager.getGameSettingString("sOK", "")); okButton->eventMouseButtonClick += MyGUI::newDelegate(this, &RaceDialog::onOkClicked); + okButton->setEnabled(false); updateRaces(); updateSkills(); @@ -107,6 +109,16 @@ void RaceDialog::open() MWBase::Environment::get().getWorld ()->setupExternalRendering (*mPreview); mPreview->update (0); + const ESM::NPC proto = mPreview->getPrototype(); + setRaceId(proto.mRace); + recountParts(); + + std::string index = proto.mHead.substr(proto.mHead.size() - 2, 2); + mFaceIndex = boost::lexical_cast(index) - 1; + + index = proto.mHair.substr(proto.mHair.size() - 2, 2); + mHairIndex = boost::lexical_cast(index) - 1; + mPreviewImage->setImageTexture ("CharacterHeadPreview"); } @@ -121,6 +133,9 @@ void RaceDialog::setRaceId(const std::string &raceId) if (boost::iequals(*mRaceList->getItemDataAt(i), raceId)) { mRaceList->setIndexSelected(i); + MyGUI::ButtonPtr okButton; + getWidget(okButton, "OKButton"); + okButton->setEnabled(true); break; } } @@ -139,6 +154,35 @@ int wrap(int index, int max) return index; } +int countParts(const std::string &part, const std::string &race, bool male) +{ + const MWWorld::Store &store = + MWBase::Environment::get().getWorld()->getStore().get(); + + std::string prefix = + "b_n_" + race + ((male) ? "_m_" : "_f_") + part; + + std::string suffix; + suffix.reserve(prefix.size() + 3); + + int count = -1; + do { + ++count; + suffix = "_" + (boost::format("%02d") % (count + 1)).str(); + } + while (store.search(prefix + suffix) != 0); + + if (count == 0 && part == "hair") { + count = -1; + do { + ++count; + suffix = (boost::format("%02d") % (count + 1)).str(); + } + while (store.search(prefix + suffix) != 0); + } + return count; +} + void RaceDialog::close() { delete mPreview; @@ -149,6 +193,8 @@ void RaceDialog::close() void RaceDialog::onOkClicked(MyGUI::Widget* _sender) { + if(mRaceList->getIndexSelected() == MyGUI::ITEM_NONE) + return; eventDone(this); } @@ -168,31 +214,41 @@ void RaceDialog::onHeadRotate(MyGUI::ScrollBar*, size_t _position) void RaceDialog::onSelectPreviousGender(MyGUI::Widget*) { mGenderIndex = wrap(mGenderIndex - 1, 2); + + recountParts(); + updatePreview(); } void RaceDialog::onSelectNextGender(MyGUI::Widget*) { mGenderIndex = wrap(mGenderIndex + 1, 2); + + recountParts(); + updatePreview(); } void RaceDialog::onSelectPreviousFace(MyGUI::Widget*) { mFaceIndex = wrap(mFaceIndex - 1, mFaceCount); + updatePreview(); } void RaceDialog::onSelectNextFace(MyGUI::Widget*) { mFaceIndex = wrap(mFaceIndex + 1, mFaceCount); + updatePreview(); } void RaceDialog::onSelectPreviousHair(MyGUI::Widget*) { mHairIndex = wrap(mHairIndex - 1, mHairCount); + updatePreview(); } void RaceDialog::onSelectNextHair(MyGUI::Widget*) { - mHairIndex = wrap(mHairIndex - 1, mHairCount); + mHairIndex = wrap(mHairIndex + 1, mHairCount); + updatePreview(); } void RaceDialog::onSelectRace(MyGUI::ListBox* _sender, size_t _index) @@ -200,35 +256,75 @@ void RaceDialog::onSelectRace(MyGUI::ListBox* _sender, size_t _index) if (_index == MyGUI::ITEM_NONE) return; + MyGUI::ButtonPtr okButton; + getWidget(okButton, "OKButton"); + okButton->setEnabled(true); const std::string *raceId = mRaceList->getItemDataAt(_index); if (boost::iequals(mCurrentRaceId, *raceId)) return; mCurrentRaceId = *raceId; + + recountParts(); + + updatePreview(); updateSkills(); updateSpellPowers(); } +void RaceDialog::recountParts() +{ + mFaceIndex = 0; + mHairIndex = 0; + + mFaceCount = countParts("head", mCurrentRaceId, mGenderIndex == 0); + mHairCount = countParts("hair", mCurrentRaceId, mGenderIndex == 0); +} + // update widget content +void RaceDialog::updatePreview() +{ + ESM::NPC record = mPreview->getPrototype(); + record.mRace = mCurrentRaceId; + record.setIsMale(mGenderIndex == 0); + + std::string prefix = + "b_n_" + mCurrentRaceId + ((record.isMale()) ? "_m_" : "_f_"); + + std::string headIndex = (boost::format("%02d") % (mFaceIndex + 1)).str(); + std::string hairIndex = (boost::format("%02d") % (mHairIndex + 1)).str(); + + record.mHead = prefix + "head_" + headIndex; + record.mHair = prefix + "hair_" + hairIndex; + + const MWWorld::Store &parts = + MWBase::Environment::get().getWorld()->getStore().get(); + + if (parts.search(record.mHair) == 0) { + record.mHair = prefix + "hair" + hairIndex; + } + mPreview->setPrototype(record); +} + void RaceDialog::updateRaces() { mRaceList->removeAllItems(); - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); + const MWWorld::Store &races = + MWBase::Environment::get().getWorld()->getStore().get(); - ESMS::RecListT::MapType::const_iterator it = store.races.list.begin(); - ESMS::RecListT::MapType::const_iterator end = store.races.list.end(); + int index = 0; - for (; it != end; ++it) + MWWorld::Store::iterator it = races.begin(); + for (; it != races.end(); ++it) { - const ESM::Race &race = it->second; - bool playable = race.mData.mFlags & ESM::Race::Playable; + bool playable = it->mData.mFlags & ESM::Race::Playable; if (!playable) // Only display playable races continue; - mRaceList->addItem(race.mName, it->first); - if (boost::iequals(it->first, mCurrentRaceId)) + mRaceList->addItem(it->mName, it->mId); + if (boost::iequals(it->mId, mCurrentRaceId)) mRaceList->setIndexSelected(index); ++index; } @@ -249,8 +345,8 @@ void RaceDialog::updateSkills() const int lineHeight = 18; MyGUI::IntCoord coord1(0, 0, mSkillList->getWidth(), 18); - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); - const ESM::Race *race = store.races.find(mCurrentRaceId); + const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); + const ESM::Race *race = store.get().find(mCurrentRaceId); int count = sizeof(race->mData.mBonus)/sizeof(race->mData.mBonus[0]); // TODO: Find a portable macro for this ARRAYSIZE? for (int i = 0; i < count; ++i) { @@ -287,8 +383,8 @@ void RaceDialog::updateSpellPowers() const int lineHeight = 18; MyGUI::IntCoord coord(0, 0, mSpellPowerList->getWidth(), 18); - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); - const ESM::Race *race = store.races.find(mCurrentRaceId); + const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); + const ESM::Race *race = store.get().find(mCurrentRaceId); std::vector::const_iterator it = race->mPowers.mList.begin(); std::vector::const_iterator end = race->mPowers.mList.end(); diff --git a/apps/openmw/mwgui/race.hpp b/apps/openmw/mwgui/race.hpp index c4734eae8..e0dc3306a 100644 --- a/apps/openmw/mwgui/race.hpp +++ b/apps/openmw/mwgui/race.hpp @@ -4,7 +4,7 @@ #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwrender/characterpreview.hpp" @@ -34,6 +34,7 @@ namespace MWGui GM_Female }; + const ESM::NPC &getResult() const { return mPreview->getPrototype(); } const std::string &getRaceId() const { return mCurrentRaceId; } Gender getGender() const { return mGenderIndex == 0 ? GM_Male : GM_Female; } // getFace() @@ -77,6 +78,8 @@ namespace MWGui void updateRaces(); void updateSkills(); void updateSpellPowers(); + void updatePreview(); + void recountParts(); MyGUI::ImageBox* mPreviewImage; MyGUI::ListBox* mRaceList; diff --git a/apps/openmw/mwgui/review.cpp b/apps/openmw/mwgui/review.cpp index 984c7d1ae..45adb5383 100644 --- a/apps/openmw/mwgui/review.cpp +++ b/apps/openmw/mwgui/review.cpp @@ -5,7 +5,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -108,7 +108,9 @@ void ReviewDialog::setPlayerName(const std::string &name) void ReviewDialog::setRace(const std::string &raceId) { mRaceId = raceId; - const ESM::Race *race = MWBase::Environment::get().getWorld()->getStore().races.search(mRaceId); + + const ESM::Race *race = + MWBase::Environment::get().getWorld()->getStore().get().search(mRaceId); if (race) { ToolTips::createRaceToolTip(mRaceWidget, race); @@ -126,7 +128,9 @@ void ReviewDialog::setClass(const ESM::Class& class_) void ReviewDialog::setBirthSign(const std::string& signId) { mBirthSignId = signId; - const ESM::BirthSign *sign = MWBase::Environment::get().getWorld()->getStore().birthSigns.search(mBirthSignId); + + const ESM::BirthSign *sign = + MWBase::Environment::get().getWorld()->getStore().get().search(mBirthSignId); if (sign) { mBirthSignWidget->setCaption(sign->mName); @@ -281,7 +285,7 @@ void ReviewDialog::addSkills(const SkillList &skills, const std::string &titleId if (skillId < 0 || skillId > ESM::Skill::Length) // Skip unknown skill indexes continue; assert(skillId >= 0 && skillId < ESM::Skill::Length); - const std::string &skillNameId = ESMS::Skill::sSkillNameIds[skillId]; + const std::string &skillNameId = ESM::Skill::sSkillNameIds[skillId]; const MWMechanics::Stat &stat = mSkillValues.find(skillId)->second; float base = stat.getBase(); float modified = stat.getModified(); diff --git a/apps/openmw/mwgui/scrollwindow.cpp b/apps/openmw/mwgui/scrollwindow.cpp index c839e9b73..8317025e0 100644 --- a/apps/openmw/mwgui/scrollwindow.cpp +++ b/apps/openmw/mwgui/scrollwindow.cpp @@ -36,7 +36,7 @@ void ScrollWindow::open (MWWorld::Ptr scroll) MWWorld::LiveCellRef *ref = mScroll.get(); BookTextParser parser; - MyGUI::IntSize size = parser.parse(ref->base->mText, mTextView, 390); + MyGUI::IntSize size = parser.parse(ref->mBase->mText, mTextView, 390); if (size.height > mTextView->getSize().height) mTextView->setCanvasSize(MyGUI::IntSize(410, size.height)); diff --git a/apps/openmw/mwgui/spellbuyingwindow.cpp b/apps/openmw/mwgui/spellbuyingwindow.cpp index f8d5649b9..a41f401a5 100644 --- a/apps/openmw/mwgui/spellbuyingwindow.cpp +++ b/apps/openmw/mwgui/spellbuyingwindow.cpp @@ -8,6 +8,7 @@ #include "../mwbase/world.hpp" #include "../mwbase/soundmanager.hpp" #include "../mwbase/windowmanager.hpp" +#include "../mwbase/mechanicsmanager.hpp" #include "../mwworld/player.hpp" #include "../mwworld/manualref.hpp" @@ -24,7 +25,6 @@ namespace MWGui SpellBuyingWindow::SpellBuyingWindow(MWBase::WindowManager& parWindowManager) : WindowBase("openmw_spell_buying_window.layout", parWindowManager) - , ContainerBase(NULL) // no drag&drop , mCurrentY(0) , mLastPos(0) { @@ -50,12 +50,16 @@ namespace MWGui void SpellBuyingWindow::addSpell(const std::string& spellId) { - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(spellId); - int price = spell->mData.mCost*MWBase::Environment::get().getWorld()->getStore().gameSettings.find("fSpellValueMult")->getFloat(); + const MWWorld::ESMStore &store = + MWBase::Environment::get().getWorld()->getStore(); + + const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().get().find(spellId); + int price = spell->mData.mCost*store.get().find("fSpellValueMult")->getFloat(); + price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr,price,true); MyGUI::Button* toAdd = mSpellsView->createWidget( - (price>mWindowManager.getInventoryWindow()->getPlayerGold()) ? "SandTextGreyedOut" : "SpellText", + (price>mWindowManager.getInventoryWindow()->getPlayerGold()) ? "SandTextGreyedOut" : "SandTextButton", 0, mCurrentY, 200, @@ -64,7 +68,6 @@ namespace MWGui ); mCurrentY += sLineHeight; - /// \todo price adjustment depending on merchantile skill toAdd->setUserData(price); toAdd->setCaptionWithReplacing(spell->mName+" - "+boost::lexical_cast(price)+"#{sgp}"); @@ -88,7 +91,7 @@ namespace MWGui void SpellBuyingWindow::startSpellBuying(const MWWorld::Ptr& actor) { center(); - mActor = actor; + mPtr = actor; clearSpells(); MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); @@ -98,7 +101,8 @@ namespace MWGui for (MWMechanics::Spells::TIterator iter = merchantSpells.begin(); iter!=merchantSpells.end(); ++iter) { - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find (*iter); + const ESM::Spell* spell = + MWBase::Environment::get().getWorld()->getStore().get().find (*iter); if (spell->mData.mType!=ESM::Spell::ST_Spell) continue; // don't try to sell diseases, curses or powers @@ -125,7 +129,7 @@ namespace MWGui MWMechanics::Spells& spells = stats.getSpells(); spells.add (mSpellsWidgetMap.find(_sender)->second); mWindowManager.getTradeWindow()->addOrRemoveGold(-price); - startSpellBuying(mActor); + startSpellBuying(mPtr); MWBase::Environment::get().getSoundManager()->playSound ("Item Gold Up", 1.0, 1.0); } diff --git a/apps/openmw/mwgui/spellbuyingwindow.hpp b/apps/openmw/mwgui/spellbuyingwindow.hpp index 970498cd9..1d0ac28e0 100644 --- a/apps/openmw/mwgui/spellbuyingwindow.hpp +++ b/apps/openmw/mwgui/spellbuyingwindow.hpp @@ -1,10 +1,8 @@ #ifndef MWGUI_SpellBuyingWINDOW_H #define MWGUI_SpellBuyingWINDOW_H -#include "container.hpp" #include "window_base.hpp" - -#include "../mwworld/ptr.hpp" +#include "referenceinterface.hpp" namespace MyGUI { @@ -20,7 +18,7 @@ namespace MWGui namespace MWGui { - class SpellBuyingWindow : public ContainerBase, public WindowBase + class SpellBuyingWindow : public ReferenceInterface, public WindowBase { public: SpellBuyingWindow(MWBase::WindowManager& parWindowManager); @@ -35,8 +33,6 @@ namespace MWGui MyGUI::ScrollView* mSpellsView; - MWWorld::Ptr mActor; - std::map mSpellsWidgetMap; void onCancelButtonClicked(MyGUI::Widget* _sender); diff --git a/apps/openmw/mwgui/spellcreationdialog.cpp b/apps/openmw/mwgui/spellcreationdialog.cpp new file mode 100644 index 000000000..69d69519f --- /dev/null +++ b/apps/openmw/mwgui/spellcreationdialog.cpp @@ -0,0 +1,632 @@ +#include "spellcreationdialog.hpp" + +#include + +#include "../mwbase/windowmanager.hpp" + +#include "../mwbase/world.hpp" +#include "../mwbase/environment.hpp" +#include "../mwbase/soundmanager.hpp" +#include "../mwbase/mechanicsmanager.hpp" + +#include "../mwworld/esmstore.hpp" +#include "../mwworld/player.hpp" +#include "../mwworld/class.hpp" + +#include "../mwmechanics/spells.hpp" +#include "../mwmechanics/creaturestats.hpp" +#include "../mwmechanics/spellsuccess.hpp" + + +#include "tooltips.hpp" +#include "widgets.hpp" +#include "class.hpp" +#include "inventorywindow.hpp" +#include "tradewindow.hpp" + +namespace +{ + + bool sortMagicEffects (short id1, short id2) + { + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); + + return gmst.find(ESM::MagicEffect::effectIdToString (id1))->getString() + < gmst.find(ESM::MagicEffect::effectIdToString (id2))->getString(); + } +} + +namespace MWGui +{ + + EditEffectDialog::EditEffectDialog(MWBase::WindowManager &parWindowManager) + : WindowModal("openmw_edit_effect.layout", parWindowManager) + , mEditing(false) + { + getWidget(mCancelButton, "CancelButton"); + getWidget(mOkButton, "OkButton"); + getWidget(mDeleteButton, "DeleteButton"); + getWidget(mRangeButton, "RangeButton"); + getWidget(mMagnitudeMinValue, "MagnitudeMinValue"); + getWidget(mMagnitudeMaxValue, "MagnitudeMaxValue"); + getWidget(mDurationValue, "DurationValue"); + getWidget(mAreaValue, "AreaValue"); + getWidget(mMagnitudeMinSlider, "MagnitudeMinSlider"); + getWidget(mMagnitudeMaxSlider, "MagnitudeMaxSlider"); + getWidget(mDurationSlider, "DurationSlider"); + getWidget(mAreaSlider, "AreaSlider"); + getWidget(mEffectImage, "EffectImage"); + getWidget(mEffectName, "EffectName"); + getWidget(mAreaText, "AreaText"); + getWidget(mDurationBox, "DurationBox"); + getWidget(mAreaBox, "AreaBox"); + getWidget(mMagnitudeBox, "MagnitudeBox"); + + mRangeButton->eventMouseButtonClick += MyGUI::newDelegate(this, &EditEffectDialog::onRangeButtonClicked); + mOkButton->eventMouseButtonClick += MyGUI::newDelegate(this, &EditEffectDialog::onOkButtonClicked); + mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &EditEffectDialog::onCancelButtonClicked); + mDeleteButton->eventMouseButtonClick += MyGUI::newDelegate(this, &EditEffectDialog::onDeleteButtonClicked); + + mMagnitudeMinSlider->eventScrollChangePosition += MyGUI::newDelegate(this, &EditEffectDialog::onMagnitudeMinChanged); + mMagnitudeMaxSlider->eventScrollChangePosition += MyGUI::newDelegate(this, &EditEffectDialog::onMagnitudeMaxChanged); + mDurationSlider->eventScrollChangePosition += MyGUI::newDelegate(this, &EditEffectDialog::onDurationChanged); + mAreaSlider->eventScrollChangePosition += MyGUI::newDelegate(this, &EditEffectDialog::onAreaChanged); + } + + void EditEffectDialog::open() + { + WindowModal::open(); + center(); + } + + void EditEffectDialog::newEffect (const ESM::MagicEffect *effect) + { + setMagicEffect(effect); + mEditing = false; + + mDeleteButton->setVisible (false); + + mEffect.mRange = ESM::RT_Self; + + onRangeButtonClicked(mRangeButton); + + mMagnitudeMinSlider->setScrollPosition (0); + mMagnitudeMaxSlider->setScrollPosition (0); + mAreaSlider->setScrollPosition (0); + mDurationSlider->setScrollPosition (0); + + mDurationValue->setCaption("1"); + mMagnitudeMinValue->setCaption("1"); + mMagnitudeMaxValue->setCaption("- 1"); + mAreaValue->setCaption("0"); + + mEffect.mMagnMin = 1; + mEffect.mMagnMax = 1; + mEffect.mDuration = 1; + mEffect.mArea = 0; + } + + void EditEffectDialog::editEffect (ESM::ENAMstruct effect) + { + const ESM::MagicEffect* magicEffect = + MWBase::Environment::get().getWorld()->getStore().get().find(effect.mEffectID); + + setMagicEffect(magicEffect); + + mEffect = effect; + mEditing = true; + + mDeleteButton->setVisible (true); + + mMagnitudeMinSlider->setScrollPosition (effect.mMagnMin-1); + mMagnitudeMaxSlider->setScrollPosition (effect.mMagnMax-1); + mAreaSlider->setScrollPosition (effect.mArea); + mDurationSlider->setScrollPosition (effect.mDuration-1); + + onMagnitudeMinChanged (mMagnitudeMinSlider, effect.mMagnMin-1); + onMagnitudeMaxChanged (mMagnitudeMinSlider, effect.mMagnMax-1); + onAreaChanged (mAreaSlider, effect.mArea); + onDurationChanged (mDurationSlider, effect.mDuration-1); + } + + void EditEffectDialog::setMagicEffect (const ESM::MagicEffect *effect) + { + std::string icon = effect->mIcon; + icon[icon.size()-3] = 'd'; + icon[icon.size()-2] = 'd'; + icon[icon.size()-1] = 's'; + icon = "icons\\" + icon; + + mEffectImage->setImageTexture (icon); + + mEffectName->setCaptionWithReplacing("#{"+ESM::MagicEffect::effectIdToString (effect->mIndex)+"}"); + + mEffect.mEffectID = effect->mIndex; + + mMagicEffect = effect; + + updateBoxes(); + } + + void EditEffectDialog::updateBoxes() + { + static int startY = mMagnitudeBox->getPosition().top; + int curY = startY; + + mMagnitudeBox->setVisible (false); + mDurationBox->setVisible (false); + mAreaBox->setVisible (false); + + if (!(mMagicEffect->mData.mFlags & ESM::MagicEffect::NoMagnitude)) + { + mMagnitudeBox->setPosition(mMagnitudeBox->getPosition().left, curY); + mMagnitudeBox->setVisible (true); + curY += mMagnitudeBox->getSize().height; + } + if (!(mMagicEffect->mData.mFlags & ESM::MagicEffect::NoDuration)) + { + mDurationBox->setPosition(mDurationBox->getPosition().left, curY); + mDurationBox->setVisible (true); + curY += mDurationBox->getSize().height; + } + if (mEffect.mRange == ESM::RT_Target) + { + mAreaBox->setPosition(mAreaBox->getPosition().left, curY); + mAreaBox->setVisible (true); + curY += mAreaBox->getSize().height; + } + } + + void EditEffectDialog::onRangeButtonClicked (MyGUI::Widget* sender) + { + mEffect.mRange = (mEffect.mRange+1)%3; + + if (mEffect.mRange == ESM::RT_Self) + mRangeButton->setCaptionWithReplacing ("#{sRangeSelf}"); + else if (mEffect.mRange == ESM::RT_Target) + mRangeButton->setCaptionWithReplacing ("#{sRangeTarget}"); + else if (mEffect.mRange == ESM::RT_Touch) + mRangeButton->setCaptionWithReplacing ("#{sRangeTouch}"); + + mAreaSlider->setVisible (mEffect.mRange != ESM::RT_Self); + mAreaText->setVisible (mEffect.mRange != ESM::RT_Self); + + // cycle through range types until we find something that's allowed + if (mEffect.mRange == ESM::RT_Target && !(mMagicEffect->mData.mFlags & ESM::MagicEffect::CastTarget)) + onRangeButtonClicked(sender); + if (mEffect.mRange == ESM::RT_Self && !(mMagicEffect->mData.mFlags & ESM::MagicEffect::CastSelf)) + onRangeButtonClicked(sender); + if (mEffect.mRange == ESM::RT_Touch && !(mMagicEffect->mData.mFlags & ESM::MagicEffect::CastTouch)) + onRangeButtonClicked(sender); + + updateBoxes(); + } + + void EditEffectDialog::onDeleteButtonClicked (MyGUI::Widget* sender) + { + setVisible(false); + + eventEffectRemoved(mEffect); + } + + void EditEffectDialog::onOkButtonClicked (MyGUI::Widget* sender) + { + setVisible(false); + + if (mEditing) + eventEffectModified(mEffect); + else + eventEffectAdded(mEffect); + } + + void EditEffectDialog::onCancelButtonClicked (MyGUI::Widget* sender) + { + setVisible(false); + } + + void EditEffectDialog::setSkill (int skill) + { + mEffect.mSkill = skill; + } + + void EditEffectDialog::setAttribute (int attribute) + { + mEffect.mAttribute = attribute; + } + + void EditEffectDialog::onMagnitudeMinChanged (MyGUI::ScrollBar* sender, size_t pos) + { + mMagnitudeMinValue->setCaption(boost::lexical_cast(pos+1)); + mEffect.mMagnMin = pos+1; + + // trigger the check again (see below) + onMagnitudeMaxChanged(mMagnitudeMaxSlider, mMagnitudeMaxSlider->getScrollPosition ()); + } + + void EditEffectDialog::onMagnitudeMaxChanged (MyGUI::ScrollBar* sender, size_t pos) + { + // make sure the max value is actually larger or equal than the min value + size_t magnMin = std::abs(mEffect.mMagnMin); // should never be < 0, this is just here to avoid the compiler warning + if (pos+1 < magnMin) + { + pos = mEffect.mMagnMin-1; + sender->setScrollPosition (pos); + } + + mEffect.mMagnMax = pos+1; + + mMagnitudeMaxValue->setCaption("- " + boost::lexical_cast(pos+1)); + } + + void EditEffectDialog::onDurationChanged (MyGUI::ScrollBar* sender, size_t pos) + { + mDurationValue->setCaption(boost::lexical_cast(pos+1)); + mEffect.mDuration = pos+1; + } + + void EditEffectDialog::onAreaChanged (MyGUI::ScrollBar* sender, size_t pos) + { + mAreaValue->setCaption(boost::lexical_cast(pos)); + mEffect.mArea = pos; + } + + // ------------------------------------------------------------------------------------------------ + + SpellCreationDialog::SpellCreationDialog(MWBase::WindowManager &parWindowManager) + : WindowBase("openmw_spellcreation_dialog.layout", parWindowManager) + , EffectEditorBase(parWindowManager) + { + getWidget(mNameEdit, "NameEdit"); + getWidget(mMagickaCost, "MagickaCost"); + getWidget(mSuccessChance, "SuccessChance"); + getWidget(mAvailableEffectsList, "AvailableEffects"); + getWidget(mUsedEffectsView, "UsedEffects"); + getWidget(mPriceLabel, "PriceLabel"); + getWidget(mBuyButton, "BuyButton"); + getWidget(mCancelButton, "CancelButton"); + + mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &SpellCreationDialog::onCancelButtonClicked); + mBuyButton->eventMouseButtonClick += MyGUI::newDelegate(this, &SpellCreationDialog::onBuyButtonClicked); + + setWidgets(mAvailableEffectsList, mUsedEffectsView); + } + + void SpellCreationDialog::startSpellMaking (MWWorld::Ptr actor) + { + mPtr = actor; + mNameEdit->setCaption(""); + + startEditing(); + } + + void SpellCreationDialog::onCancelButtonClicked (MyGUI::Widget* sender) + { + mWindowManager.removeGuiMode (MWGui::GM_SpellCreation); + } + + void SpellCreationDialog::onBuyButtonClicked (MyGUI::Widget* sender) + { + if (mEffects.size() <= 0) + { + mWindowManager.messageBox ("#{sNotifyMessage30}", std::vector()); + return; + } + + if (mNameEdit->getCaption () == "") + { + mWindowManager.messageBox ("#{sNotifyMessage10}", std::vector()); + return; + } + + if (mMagickaCost->getCaption() == "0") + { + mWindowManager.messageBox ("#{sEnchantmentMenu8}", std::vector()); + return; + } + + if (boost::lexical_cast(mPriceLabel->getCaption()) > mWindowManager.getInventoryWindow()->getPlayerGold()) + { + mWindowManager.messageBox ("#{sNotifyMessage18}", std::vector()); + return; + } + + mSpell.mName = mNameEdit->getCaption(); + + mWindowManager.getTradeWindow()->addOrRemoveGold(-boost::lexical_cast(mPriceLabel->getCaption())); + + MWBase::Environment::get().getSoundManager()->playSound ("Item Gold Up", 1.0, 1.0); + + const ESM::Spell* spell = MWBase::Environment::get().getWorld()->createRecord(mSpell); + + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + MWMechanics::CreatureStats& stats = MWWorld::Class::get(player).getCreatureStats(player); + MWMechanics::Spells& spells = stats.getSpells(); + spells.add (spell->mId); + + MWBase::Environment::get().getSoundManager()->playSound ("Item Gold Up", 1.0, 1.0); + + mWindowManager.removeGuiMode (GM_SpellCreation); + } + + void SpellCreationDialog::open() + { + center(); + } + + void SpellCreationDialog::onReferenceUnavailable () + { + mWindowManager.removeGuiMode (GM_Dialogue); + mWindowManager.removeGuiMode (GM_SpellCreation); + } + + void SpellCreationDialog::notifyEffectsChanged () + { + float y = 0; + + const MWWorld::ESMStore &store = + MWBase::Environment::get().getWorld()->getStore(); + + for (std::vector::const_iterator it = mEffects.begin(); it != mEffects.end(); ++it) + { + float x = 0.5 * it->mMagnMin + it->mMagnMax; + + const ESM::MagicEffect* effect = + store.get().find(it->mEffectID); + + x *= 0.1 * effect->mData.mBaseCost; + x *= 1 + it->mDuration; + x += 0.05 * std::max(1, it->mArea) * effect->mData.mBaseCost; + + float fEffectCostMult = + store.get().find("fEffectCostMult")->getFloat(); + + y += x * fEffectCostMult; + y = std::max(1.f,y); + + if (effect->mData.mFlags & ESM::MagicEffect::CastTarget) + y *= 1.5; + } + + mSpell.mData.mCost = int(y); + + ESM::EffectList effectList; + effectList.mList = mEffects; + mSpell.mEffects = effectList; + mSpell.mData.mType = ESM::Spell::ST_Spell; + + mMagickaCost->setCaption(boost::lexical_cast(int(y))); + + float fSpellMakingValueMult = + store.get().find("fSpellMakingValueMult")->getFloat(); + + int price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr,int(y) * fSpellMakingValueMult,true); + + mPriceLabel->setCaption(boost::lexical_cast(int(price))); + + float chance = MWMechanics::getSpellSuccessChance(&mSpell, MWBase::Environment::get().getWorld()->getPlayer().getPlayer()); + mSuccessChance->setCaption(boost::lexical_cast(int(chance))); + } + + // ------------------------------------------------------------------------------------------------ + + + EffectEditorBase::EffectEditorBase(MWBase::WindowManager& parWindowManager) + : mAddEffectDialog(parWindowManager) + , mSelectAttributeDialog(NULL) + , mSelectSkillDialog(NULL) + { + mAddEffectDialog.eventEffectAdded += MyGUI::newDelegate(this, &EffectEditorBase::onEffectAdded); + mAddEffectDialog.eventEffectModified += MyGUI::newDelegate(this, &EffectEditorBase::onEffectModified); + mAddEffectDialog.eventEffectRemoved += MyGUI::newDelegate(this, &EffectEditorBase::onEffectRemoved); + + mAddEffectDialog.setVisible (false); + } + + void EffectEditorBase::startEditing () + { + // get the list of magic effects that are known to the player + + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + MWMechanics::CreatureStats& stats = MWWorld::Class::get(player).getCreatureStats(player); + MWMechanics::Spells& spells = stats.getSpells(); + + std::vector knownEffects; + + for (MWMechanics::Spells::TIterator it = spells.begin(); it != spells.end(); ++it) + { + const ESM::Spell* spell = + MWBase::Environment::get().getWorld()->getStore().get().find(*it); + + // only normal spells count + if (spell->mData.mType != ESM::Spell::ST_Spell) + continue; + + const std::vector& list = spell->mEffects.mList; + for (std::vector::const_iterator it2 = list.begin(); it2 != list.end(); ++it2) + { + if (std::find(knownEffects.begin(), knownEffects.end(), it2->mEffectID) == knownEffects.end()) + knownEffects.push_back(it2->mEffectID); + } + } + + std::sort(knownEffects.begin(), knownEffects.end(), sortMagicEffects); + + mAvailableEffectsList->clear (); + + for (std::vector::const_iterator it = knownEffects.begin(); it != knownEffects.end(); ++it) + { + mAvailableEffectsList->addItem(MWBase::Environment::get().getWorld ()->getStore ().get().find( + ESM::MagicEffect::effectIdToString (*it))->getString()); + } + mAvailableEffectsList->adjustSize (); + + for (std::vector::const_iterator it = knownEffects.begin(); it != knownEffects.end(); ++it) + { + std::string name = MWBase::Environment::get().getWorld ()->getStore ().get().find( + ESM::MagicEffect::effectIdToString (*it))->getString(); + MyGUI::Widget* w = mAvailableEffectsList->getItemWidget(name); + w->setUserData(*it); + + ToolTips::createMagicEffectToolTip (w, *it); + } + + mEffects.clear(); + updateEffectsView (); + } + + void EffectEditorBase::setWidgets (Widgets::MWList *availableEffectsList, MyGUI::ScrollView *usedEffectsView) + { + mAvailableEffectsList = availableEffectsList; + mUsedEffectsView = usedEffectsView; + + mAvailableEffectsList->eventWidgetSelected += MyGUI::newDelegate(this, &EffectEditorBase::onAvailableEffectClicked); + } + + void EffectEditorBase::onSelectAttribute () + { + mAddEffectDialog.setVisible(true); + mAddEffectDialog.setAttribute (mSelectAttributeDialog->getAttributeId()); + MWBase::Environment::get().getWindowManager ()->removeDialog (mSelectAttributeDialog); + mSelectAttributeDialog = 0; + } + + void EffectEditorBase::onSelectSkill () + { + mAddEffectDialog.setVisible(true); + mAddEffectDialog.setSkill (mSelectSkillDialog->getSkillId ()); + MWBase::Environment::get().getWindowManager ()->removeDialog (mSelectSkillDialog); + mSelectSkillDialog = 0; + } + + void EffectEditorBase::onAttributeOrSkillCancel () + { + if (mSelectSkillDialog) + MWBase::Environment::get().getWindowManager ()->removeDialog (mSelectSkillDialog); + if (mSelectAttributeDialog) + MWBase::Environment::get().getWindowManager ()->removeDialog (mSelectAttributeDialog); + + mSelectSkillDialog = 0; + mSelectAttributeDialog = 0; + } + + void EffectEditorBase::onAvailableEffectClicked (MyGUI::Widget* sender) + { + if (mEffects.size() >= 8) + { + MWBase::Environment::get().getWindowManager()->messageBox("#{sNotifyMessage28}", std::vector()); + return; + } + + short effectId = *sender->getUserData(); + + for (std::vector::const_iterator it = mEffects.begin(); it != mEffects.end(); ++it) + { + if (it->mEffectID == effectId) + { + MWBase::Environment::get().getWindowManager()->messageBox ("#{sOnetypeEffectMessage}", std::vector()); + return; + } + } + + const ESM::MagicEffect* effect = + MWBase::Environment::get().getWorld()->getStore().get().find(effectId); + + mAddEffectDialog.newEffect (effect); + + if (effect->mData.mFlags & ESM::MagicEffect::TargetSkill) + { + delete mSelectSkillDialog; + mSelectSkillDialog = new SelectSkillDialog(*MWBase::Environment::get().getWindowManager ()); + mSelectSkillDialog->eventCancel += MyGUI::newDelegate(this, &SpellCreationDialog::onAttributeOrSkillCancel); + mSelectSkillDialog->eventItemSelected += MyGUI::newDelegate(this, &SpellCreationDialog::onSelectSkill); + mSelectSkillDialog->setVisible (true); + } + else if (effect->mData.mFlags & ESM::MagicEffect::TargetAttribute) + { + delete mSelectAttributeDialog; + mSelectAttributeDialog = new SelectAttributeDialog(*MWBase::Environment::get().getWindowManager ()); + mSelectAttributeDialog->eventCancel += MyGUI::newDelegate(this, &SpellCreationDialog::onAttributeOrSkillCancel); + mSelectAttributeDialog->eventItemSelected += MyGUI::newDelegate(this, &SpellCreationDialog::onSelectAttribute); + mSelectAttributeDialog->setVisible (true); + } + else + { + mAddEffectDialog.setVisible(true); + } + } + + void EffectEditorBase::onEffectModified (ESM::ENAMstruct effect) + { + mEffects[mSelectedEffect] = effect; + + updateEffectsView(); + } + + void EffectEditorBase::onEffectRemoved (ESM::ENAMstruct effect) + { + mEffects.erase(mEffects.begin() + mSelectedEffect); + updateEffectsView(); + } + + void EffectEditorBase::updateEffectsView () + { + MyGUI::EnumeratorWidgetPtr oldWidgets = mUsedEffectsView->getEnumerator (); + MyGUI::Gui::getInstance ().destroyWidgets (oldWidgets); + + MyGUI::IntSize size(0,0); + + int i = 0; + for (std::vector::const_iterator it = mEffects.begin(); it != mEffects.end(); ++it) + { + Widgets::SpellEffectParams params; + params.mEffectID = it->mEffectID; + params.mSkill = it->mSkill; + params.mAttribute = it->mAttribute; + params.mDuration = it->mDuration; + params.mMagnMin = it->mMagnMin; + params.mMagnMax = it->mMagnMax; + params.mRange = it->mRange; + params.mArea = it->mArea; + + MyGUI::Button* button = mUsedEffectsView->createWidget("", MyGUI::IntCoord(0, size.height, 0, 24), MyGUI::Align::Default); + button->setUserData(i); + button->eventMouseButtonClick += MyGUI::newDelegate(this, &SpellCreationDialog::onEditEffect); + button->setNeedMouseFocus (true); + + Widgets::MWSpellEffectPtr effect = button->createWidget("MW_EffectImage", MyGUI::IntCoord(0,0,0,24), MyGUI::Align::Default); + + effect->setNeedMouseFocus (false); + effect->setWindowManager (MWBase::Environment::get().getWindowManager ()); + effect->setSpellEffect (params); + + effect->setSize(effect->getRequestedWidth (), 24); + button->setSize(effect->getRequestedWidth (), 24); + + size.width = std::max(size.width, effect->getRequestedWidth ()); + size.height += 24; + ++i; + } + + mUsedEffectsView->setCanvasSize(size); + + notifyEffectsChanged(); + } + + void EffectEditorBase::onEffectAdded (ESM::ENAMstruct effect) + { + mEffects.push_back(effect); + + updateEffectsView(); + } + + void EffectEditorBase::onEditEffect (MyGUI::Widget *sender) + { + int id = *sender->getUserData(); + + mSelectedEffect = id; + + mAddEffectDialog.editEffect (mEffects[id]); + mAddEffectDialog.setVisible (true); + } +} diff --git a/apps/openmw/mwgui/spellcreationdialog.hpp b/apps/openmw/mwgui/spellcreationdialog.hpp new file mode 100644 index 000000000..4d27ec1c6 --- /dev/null +++ b/apps/openmw/mwgui/spellcreationdialog.hpp @@ -0,0 +1,154 @@ +#ifndef MWGUI_SPELLCREATION_H +#define MWGUI_SPELLCREATION_H + +#include "window_base.hpp" +#include "referenceinterface.hpp" +#include "list.hpp" +#include "widgets.hpp" + +namespace MWGui +{ + + class SelectSkillDialog; + class SelectAttributeDialog; + + class EditEffectDialog : public WindowModal + { + public: + EditEffectDialog(MWBase::WindowManager& parWindowManager); + + virtual void open(); + + void setSkill(int skill); + void setAttribute(int attribute); + + void newEffect (const ESM::MagicEffect* effect); + void editEffect (ESM::ENAMstruct effect); + + typedef MyGUI::delegates::CMultiDelegate1 EventHandle_Effect; + + EventHandle_Effect eventEffectAdded; + EventHandle_Effect eventEffectModified; + EventHandle_Effect eventEffectRemoved; + + protected: + MyGUI::Button* mCancelButton; + MyGUI::Button* mOkButton; + MyGUI::Button* mDeleteButton; + + MyGUI::Button* mRangeButton; + + MyGUI::Widget* mDurationBox; + MyGUI::Widget* mMagnitudeBox; + MyGUI::Widget* mAreaBox; + + MyGUI::TextBox* mMagnitudeMinValue; + MyGUI::TextBox* mMagnitudeMaxValue; + MyGUI::TextBox* mDurationValue; + MyGUI::TextBox* mAreaValue; + + MyGUI::ScrollBar* mMagnitudeMinSlider; + MyGUI::ScrollBar* mMagnitudeMaxSlider; + MyGUI::ScrollBar* mDurationSlider; + MyGUI::ScrollBar* mAreaSlider; + + MyGUI::TextBox* mAreaText; + + MyGUI::ImageBox* mEffectImage; + MyGUI::TextBox* mEffectName; + + bool mEditing; + + protected: + void onRangeButtonClicked (MyGUI::Widget* sender); + void onDeleteButtonClicked (MyGUI::Widget* sender); + void onOkButtonClicked (MyGUI::Widget* sender); + void onCancelButtonClicked (MyGUI::Widget* sender); + + void onMagnitudeMinChanged (MyGUI::ScrollBar* sender, size_t pos); + void onMagnitudeMaxChanged (MyGUI::ScrollBar* sender, size_t pos); + void onDurationChanged (MyGUI::ScrollBar* sender, size_t pos); + void onAreaChanged (MyGUI::ScrollBar* sender, size_t pos); + + void setMagicEffect(const ESM::MagicEffect* effect); + + void updateBoxes(); + + protected: + ESM::ENAMstruct mEffect; + + const ESM::MagicEffect* mMagicEffect; + }; + + + class EffectEditorBase + { + public: + EffectEditorBase(MWBase::WindowManager& parWindowManager); + + + protected: + Widgets::MWList* mAvailableEffectsList; + MyGUI::ScrollView* mUsedEffectsView; + + EditEffectDialog mAddEffectDialog; + SelectAttributeDialog* mSelectAttributeDialog; + SelectSkillDialog* mSelectSkillDialog; + + int mSelectedEffect; + + std::vector mEffects; + + void onEffectAdded(ESM::ENAMstruct effect); + void onEffectModified(ESM::ENAMstruct effect); + void onEffectRemoved(ESM::ENAMstruct effect); + + void onAvailableEffectClicked (MyGUI::Widget* sender); + + void onAttributeOrSkillCancel(); + void onSelectAttribute(); + void onSelectSkill(); + + void onEditEffect(MyGUI::Widget* sender); + + void updateEffectsView(); + + void startEditing(); + void setWidgets (Widgets::MWList* availableEffectsList, MyGUI::ScrollView* usedEffectsView); + + virtual void notifyEffectsChanged () {} + }; + + class SpellCreationDialog : public WindowBase, public ReferenceInterface, public EffectEditorBase + { + public: + SpellCreationDialog(MWBase::WindowManager& parWindowManager); + + virtual void open(); + + void startSpellMaking(MWWorld::Ptr actor); + + protected: + virtual void onReferenceUnavailable (); + + void onCancelButtonClicked (MyGUI::Widget* sender); + void onBuyButtonClicked (MyGUI::Widget* sender); + + virtual void notifyEffectsChanged (); + + MyGUI::EditBox* mNameEdit; + MyGUI::TextBox* mMagickaCost; + MyGUI::TextBox* mSuccessChance; + MyGUI::Button* mBuyButton; + MyGUI::Button* mCancelButton; + MyGUI::TextBox* mPriceLabel; + + Widgets::MWEffectList* mUsedEffectsList; + + ESM::Spell mSpell; + + }; + +} + +#endif diff --git a/apps/openmw/mwgui/spellwindow.cpp b/apps/openmw/mwgui/spellwindow.cpp index a203ac92b..d62b23de4 100644 --- a/apps/openmw/mwgui/spellwindow.cpp +++ b/apps/openmw/mwgui/spellwindow.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/world.hpp" #include "../mwbase/environment.hpp" @@ -26,8 +26,11 @@ namespace { bool sortSpells(const std::string& left, const std::string& right) { - const ESM::Spell* a = MWBase::Environment::get().getWorld()->getStore().spells.find(left); - const ESM::Spell* b = MWBase::Environment::get().getWorld()->getStore().spells.find(right); + const MWWorld::Store &spells = + MWBase::Environment::get().getWorld()->getStore().get(); + + const ESM::Spell* a = spells.find(left); + const ESM::Spell* b = spells.find(right); int cmp = a->mName.compare(b->mName); return cmp < 0; @@ -139,11 +142,15 @@ namespace MWGui spellList.push_back(*it); } + const MWWorld::ESMStore &esmStore = + MWBase::Environment::get().getWorld()->getStore(); + std::vector powers; std::vector::iterator it = spellList.begin(); while (it != spellList.end()) { - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(*it); + const ESM::Spell* spell = esmStore.get().find(*it); + if (spell->mData.mType == ESM::Spell::ST_Power) { powers.push_back(*it); @@ -170,7 +177,9 @@ namespace MWGui if (enchantId != "") { // only add items with "Cast once" or "Cast on use" - const ESM::Enchantment* enchant = MWBase::Environment::get().getWorld()->getStore().enchants.find(enchantId); + const ESM::Enchantment* enchant = + esmStore.get().find(enchantId); + int type = enchant->mData.mType; if (type != ESM::Enchantment::CastOnce && type != ESM::Enchantment::WhenUsed) @@ -191,7 +200,7 @@ namespace MWGui for (std::vector::const_iterator it = powers.begin(); it != powers.end(); ++it) { - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(*it); + const ESM::Spell* spell = esmStore.get().find(*it); MyGUI::Button* t = mSpellView->createWidget("SpellText", MyGUI::IntCoord(4, mHeight, mWidth-8, spellHeight), MyGUI::Align::Left | MyGUI::Align::Top); t->setCaption(spell->mName); @@ -211,7 +220,7 @@ namespace MWGui addGroup("#{sSpells}", "#{sCostChance}"); for (std::vector::const_iterator it = spellList.begin(); it != spellList.end(); ++it) { - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(*it); + const ESM::Spell* spell = esmStore.get().find(*it); MyGUI::Button* t = mSpellView->createWidget("SpellText", MyGUI::IntCoord(4, mHeight, mWidth-8, spellHeight), MyGUI::Align::Left | MyGUI::Align::Top); t->setCaption(spell->mName); @@ -244,7 +253,8 @@ namespace MWGui { MWWorld::Ptr item = *it; - const ESM::Enchantment* enchant = MWBase::Environment::get().getWorld()->getStore().enchants.find(MWWorld::Class::get(item).getEnchantment(item)); + const ESM::Enchantment* enchant = + esmStore.get().find(MWWorld::Class::get(item).getEnchantment(item)); // check if the item is currently equipped (will display in a different color) bool equipped = false; @@ -378,7 +388,9 @@ namespace MWGui if (MyGUI::InputManager::getInstance().isShiftPressed()) { // delete spell, if allowed - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(spellId); + const ESM::Spell* spell = + MWBase::Environment::get().getWorld()->getStore().get().find(spellId); + if (spell->mData.mFlags & ESM::Spell::F_Always || spell->mData.mType == ESM::Spell::ST_Power) { diff --git a/apps/openmw/mwgui/stats_window.cpp b/apps/openmw/mwgui/stats_window.cpp index 5a670968e..4b47bb025 100644 --- a/apps/openmw/mwgui/stats_window.cpp +++ b/apps/openmw/mwgui/stats_window.cpp @@ -54,10 +54,10 @@ StatsWindow::StatsWindow (MWBase::WindowManager& parWindowManager) { 0, 0 } }; - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); + const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); for (int i=0; names[i][0]; ++i) { - setText (names[i][0], store.gameSettings.find (names[i][1])->getString()); + setText (names[i][0], store.get().find (names[i][1])->getString()); } getWidget(mSkillView, "SkillView"); @@ -67,7 +67,7 @@ StatsWindow::StatsWindow (MWBase::WindowManager& parWindowManager) for (int i = 0; i < ESM::Skill::Length; ++i) { mSkillValues.insert(std::pair >(i, MWMechanics::Stat())); - mSkillWidgetMap.insert(std::pair(i, nullptr)); + mSkillWidgetMap.insert(std::pair(i, (MyGUI::TextBox*)nullptr)); } MyGUI::WindowPtr t = static_cast(mMainWidget); @@ -253,7 +253,10 @@ void StatsWindow::onFrame () setFactions(PCstats.getFactionRanks()); - setBirthSign(MWBase::Environment::get().getWorld()->getPlayer().getBirthsign()); + const std::string &signId = + MWBase::Environment::get().getWorld()->getPlayer().getBirthSign(); + + setBirthSign(signId); if (mChanged) updateSkillArea(); @@ -357,18 +360,22 @@ void StatsWindow::addSkills(const SkillList &skills, const std::string &titleId, if (skillId < 0 || skillId > ESM::Skill::Length) // Skip unknown skill indexes continue; assert(skillId >= 0 && skillId < ESM::Skill::Length); - const std::string &skillNameId = ESMS::Skill::sSkillNameIds[skillId]; + const std::string &skillNameId = ESM::Skill::sSkillNameIds[skillId]; const MWMechanics::Stat &stat = mSkillValues.find(skillId)->second; float base = stat.getBase(); float modified = stat.getModified(); int progressPercent = (modified - float(static_cast(modified))) * 100; - const ESM::Skill* skill = MWBase::Environment::get().getWorld()->getStore().skills.search(skillId); + const MWWorld::ESMStore &esmStore = + MWBase::Environment::get().getWorld()->getStore(); + + const ESM::Skill* skill = esmStore.get().find(skillId); assert(skill); std::string icon = "icons\\k\\" + ESM::Skill::sIconNames[skillId]; - const ESM::Attribute* attr = MWBase::Environment::get().getWorld()->getStore().attributes.search(skill->mData.mAttribute); + const ESM::Attribute* attr = + esmStore.get().find(skill->mData.mAttribute); assert(attr); std::string state = "normal"; @@ -422,10 +429,14 @@ void StatsWindow::updateSkillArea() if (!mMiscSkills.empty()) addSkills(mMiscSkills, "sSkillClassMisc", "Misc Skills", coord1, coord2); - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); + MWBase::World *world = MWBase::Environment::get().getWorld(); + const MWWorld::ESMStore &store = world->getStore(); + const ESM::NPC *player = + world->getPlayer().getPlayer().get()->mBase; // race tooltip - const ESM::Race* playerRace = store.races.find (MWBase::Environment::get().getWorld()->getPlayer().getRace()); + const ESM::Race* playerRace = store.get().find(player->mRace); + MyGUI::Widget* raceWidget; getWidget(raceWidget, "RaceText"); ToolTips::createRaceToolTip(raceWidget, playerRace); @@ -434,11 +445,14 @@ void StatsWindow::updateSkillArea() // class tooltip MyGUI::Widget* classWidget; - const ESM::Class& playerClass = MWBase::Environment::get().getWorld()->getPlayer().getClass(); + + const ESM::Class *playerClass = + store.get().find(player->mClass); + getWidget(classWidget, "ClassText"); - ToolTips::createClassToolTip(classWidget, playerClass); + ToolTips::createClassToolTip(classWidget, *playerClass); getWidget(classWidget, "Class_str"); - ToolTips::createClassToolTip(classWidget, playerClass); + ToolTips::createClassToolTip(classWidget, *playerClass); if (!mFactions.empty()) { @@ -450,7 +464,8 @@ void StatsWindow::updateSkillArea() FactionList::const_iterator end = mFactions.end(); for (FactionList::const_iterator it = mFactions.begin(); it != end; ++it) { - const ESM::Faction *faction = store.factions.find(it->first); + const ESM::Faction *faction = + store.get().find(it->first); MyGUI::Widget* w = addItem(faction->mName, coord1, coord2); std::string text; @@ -464,8 +479,8 @@ void StatsWindow::updateSkillArea() text += std::string("\n\n#DDC79E#{sNextRank} ") + faction->mRanks[it->second+1]; ESM::RankData rankData = faction->mData.mRankData[it->second+1]; - const ESM::Attribute* attr1 = MWBase::Environment::get().getWorld()->getStore().attributes.search(faction->mData.mAttribute1); - const ESM::Attribute* attr2 = MWBase::Environment::get().getWorld()->getStore().attributes.search(faction->mData.mAttribute2); + const ESM::Attribute* attr1 = store.get().find(faction->mData.mAttribute1); + const ESM::Attribute* attr2 = store.get().find(faction->mData.mAttribute2); assert(attr1 && attr2); text += "\n#BF9959#{" + attr1->mName + "}: " + boost::lexical_cast(rankData.mAttribute1) @@ -501,7 +516,8 @@ void StatsWindow::updateSkillArea() addSeparator(coord1, coord2); addGroup(mWindowManager.getGameSettingString("sBirthSign", "Sign"), coord1, coord2); - const ESM::BirthSign *sign = store.birthSigns.find(mBirthSignId); + const ESM::BirthSign *sign = + store.get().find(mBirthSignId); MyGUI::Widget* w = addItem(sign->mName, coord1, coord2); ToolTips::createBirthsignToolTip(w, mBirthSignId); diff --git a/apps/openmw/mwgui/stats_window.hpp b/apps/openmw/mwgui/stats_window.hpp index 75f8c568b..5186b6328 100644 --- a/apps/openmw/mwgui/stats_window.hpp +++ b/apps/openmw/mwgui/stats_window.hpp @@ -1,7 +1,7 @@ #ifndef MWGUI_STATS_WINDOW_H #define MWGUI_STATS_WINDOW_H -#include +#include "../mwworld/esmstore.hpp" #include #include diff --git a/apps/openmw/mwgui/tooltips.cpp b/apps/openmw/mwgui/tooltips.cpp index cc4843841..510bcb58f 100644 --- a/apps/openmw/mwgui/tooltips.cpp +++ b/apps/openmw/mwgui/tooltips.cpp @@ -79,14 +79,10 @@ void ToolTips::onFrame(float frameDuration) || (mWindowManager->getMode() == GM_Inventory))) { std::string handle = MWBase::Environment::get().getWorld()->getFacedHandle(); - try - { - mFocusObject = MWBase::Environment::get().getWorld()->getPtrViaHandle(handle); - } - catch (std::exception /* & e */) - { + + mFocusObject = MWBase::Environment::get().getWorld()->searchPtrViaHandle(handle); + if (mFocusObject.isEmpty ()) return; - } MyGUI::IntSize tooltipSize = getToolTipViaPtr(true); @@ -183,7 +179,9 @@ void ToolTips::onFrame(float frameDuration) else if (type == "Spell") { ToolTipInfo info; - const ESM::Spell *spell = MWBase::Environment::get().getWorld()->getStore().spells.find(focus->getUserString("Spell")); + + const ESM::Spell *spell = + MWBase::Environment::get().getWorld()->getStore().get().find(focus->getUserString("Spell")); info.caption = spell->mName; Widgets::SpellEffectList effects; std::vector::const_iterator end = spell->mEffects.mList.end(); @@ -368,11 +366,14 @@ IntSize ToolTips::createToolTip(const MWGui::ToolTipInfo& info) if (text.size() > 0 && text[0] == '\n') text.erase(0, 1); + if(caption.size() > 0 && isalnum(caption[0])) + caption[0] = toupper(caption[0]); + const ESM::Enchantment* enchant = 0; - const ESMS::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); + const MWWorld::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); if (info.enchant != "") { - enchant = store.enchants.search(info.enchant); + enchant = store.get().find(info.enchant); if (enchant->mData.mType == ESM::Enchantment::CastOnce) text += "\n#{sItemCastOnce}"; else if (enchant->mData.mType == ESM::Enchantment::WhenStrikes) @@ -575,10 +576,15 @@ void ToolTips::createSkillToolTip(MyGUI::Widget* widget, int skillId) if (skillId == -1) return; - const std::string &skillNameId = ESMS::Skill::sSkillNameIds[skillId]; - const ESM::Skill* skill = MWBase::Environment::get().getWorld()->getStore().skills.search(skillId); + const MWWorld::ESMStore &store = + MWBase::Environment::get().getWorld()->getStore(); + + const std::string &skillNameId = ESM::Skill::sSkillNameIds[skillId]; + const ESM::Skill* skill = store.get().find(skillId); assert(skill); - const ESM::Attribute* attr = MWBase::Environment::get().getWorld()->getStore().attributes.search(skill->mData.mAttribute); + + const ESM::Attribute* attr = + store.get().find(skill->mData.mAttribute); assert(attr); std::string icon = "icons\\k\\" + ESM::Skill::sIconNames[skillId]; @@ -588,8 +594,6 @@ void ToolTips::createSkillToolTip(MyGUI::Widget* widget, int skillId) widget->setUserString("Caption_SkillNoProgressDescription", skill->mDescription); widget->setUserString("Caption_SkillNoProgressAttribute", "#{sGoverningAttribute}: #{" + attr->mName + "}"); widget->setUserString("ImageTexture_SkillNoProgressImage", icon); - widget->setUserString("ToolTipLayout", "SkillNoProgressToolTip"); - widget->setUserString("ToolTipLayout", "SkillNoProgressToolTip"); } void ToolTips::createAttributeToolTip(MyGUI::Widget* widget, int attributeId) @@ -613,12 +617,14 @@ void ToolTips::createSpecializationToolTip(MyGUI::Widget* widget, const std::str widget->setUserString("Caption_CenteredCaption", name); std::string specText; // get all skills of this specialisation - std::map skills = MWBase::Environment::get().getWorld()->getStore().skills.list; - for (std::map::const_iterator it = skills.begin(); - it != skills.end(); ++it) + const MWWorld::Store &skills = + MWBase::Environment::get().getWorld()->getStore().get(); + + MWWorld::Store::iterator it = skills.begin(); + for (; it != skills.end(); ++it) { - if (it->second.mData.mSpecialization == specId) - specText += std::string("\n#{") + ESM::Skill::sSkillNameIds[it->second.mIndex] + "}"; + if (it->mData.mSpecialization == specId) + specText += std::string("\n#{") + ESM::Skill::sSkillNameIds[it->mIndex] + "}"; } widget->setUserString("Caption_CenteredCaptionText", specText); widget->setUserString("ToolTipLayout", "TextWithCenteredCaptionToolTip"); @@ -627,7 +633,10 @@ void ToolTips::createSpecializationToolTip(MyGUI::Widget* widget, const std::str void ToolTips::createBirthsignToolTip(MyGUI::Widget* widget, const std::string& birthsignId) { - const ESM::BirthSign *sign = MWBase::Environment::get().getWorld()->getStore().birthSigns.find(birthsignId); + const MWWorld::ESMStore &store = + MWBase::Environment::get().getWorld()->getStore(); + + const ESM::BirthSign *sign = store.get().find(birthsignId); widget->setUserString("ToolTipType", "Layout"); widget->setUserString("ToolTipLayout", "BirthSignToolTip"); @@ -646,7 +655,7 @@ void ToolTips::createBirthsignToolTip(MyGUI::Widget* widget, const std::string& for (; it != end; ++it) { const std::string &spellId = *it; - const ESM::Spell *spell = MWBase::Environment::get().getWorld()->getStore().spells.search(spellId); + const ESM::Spell *spell = store.get().search(spellId); if (!spell) continue; // Skip spells which cannot be found ESM::Spell::SpellType type = static_cast(spell->mData.mType); @@ -661,7 +670,11 @@ void ToolTips::createBirthsignToolTip(MyGUI::Widget* widget, const std::string& spells.push_back(spellId); } - struct{ const std::vector &spells; std::string label; } categories[3] = { + struct { + const std::vector &spells; + std::string label; + } + categories[3] = { {abilities, "sBirthsignmenu1"}, {powers, "sPowers"}, {spells, "sBirthsignmenu2"} @@ -678,7 +691,7 @@ void ToolTips::createBirthsignToolTip(MyGUI::Widget* widget, const std::string& const std::string &spellId = *it; - const ESM::Spell *spell = MWBase::Environment::get().getWorld()->getStore().spells.search(spellId); + const ESM::Spell *spell = store.get().find(spellId); text += "\n#BF9959" + spell->mName; } } @@ -715,6 +728,39 @@ void ToolTips::createClassToolTip(MyGUI::Widget* widget, const ESM::Class& playe widget->setUserString("ToolTipLayout", "ClassToolTip"); } +void ToolTips::createMagicEffectToolTip(MyGUI::Widget* widget, short id) +{ + const ESM::MagicEffect* effect = + MWBase::Environment::get().getWorld ()->getStore ().get().find(id); + const std::string &name = ESM::MagicEffect::effectIdToString (id); + + std::string icon = effect->mIcon; + + int slashPos = icon.find("\\"); + icon.insert(slashPos+1, "b_"); + + icon[icon.size()-3] = 'd'; + icon[icon.size()-2] = 'd'; + icon[icon.size()-1] = 's'; + + icon = "icons\\" + icon; + + std::vector schools; + schools.push_back ("#{sSchoolAlteration}"); + schools.push_back ("#{sSchoolConjuration}"); + schools.push_back ("#{sSchoolDestruction}"); + schools.push_back ("#{sSchoolIllusion}"); + schools.push_back ("#{sSchoolMysticism}"); + schools.push_back ("#{sSchoolRestoration}"); + + widget->setUserString("ToolTipType", "Layout"); + widget->setUserString("ToolTipLayout", "MagicEffectToolTip"); + widget->setUserString("Caption_MagicEffectName", "#{" + name + "}"); + widget->setUserString("Caption_MagicEffectDescription", effect->mDescription); + widget->setUserString("Caption_MagicEffectSchool", "#{sSchool}: " + schools[effect->mData.mSchool]); + widget->setUserString("ImageTexture_MagicEffectImage", icon); +} + void ToolTips::setDelay(float delay) { mDelay = delay; diff --git a/apps/openmw/mwgui/tooltips.hpp b/apps/openmw/mwgui/tooltips.hpp index f67b6ea5c..270df4ae2 100644 --- a/apps/openmw/mwgui/tooltips.hpp +++ b/apps/openmw/mwgui/tooltips.hpp @@ -71,6 +71,7 @@ namespace MWGui static void createBirthsignToolTip(MyGUI::Widget* widget, const std::string& birthsignId); static void createRaceToolTip(MyGUI::Widget* widget, const ESM::Race* playerRace); static void createClassToolTip(MyGUI::Widget* widget, const ESM::Class& playerClass); + static void createMagicEffectToolTip(MyGUI::Widget* widget, short id); private: MyGUI::Widget* mDynamicToolTipBox; diff --git a/apps/openmw/mwgui/tradewindow.cpp b/apps/openmw/mwgui/tradewindow.cpp index 64710c279..c6a21c461 100644 --- a/apps/openmw/mwgui/tradewindow.cpp +++ b/apps/openmw/mwgui/tradewindow.cpp @@ -6,10 +6,17 @@ #include "../mwbase/world.hpp" #include "../mwbase/soundmanager.hpp" #include "../mwbase/windowmanager.hpp" +#include "../mwbase/mechanicsmanager.hpp" +#include "../mwbase/dialoguemanager.hpp" #include "../mwworld/inventorystore.hpp" #include "../mwworld/manualref.hpp" +#include "../mwmechanics/creaturestats.hpp" +#include "../mwmechanics/npcstats.hpp" + +#include "../mwworld/player.hpp" + #include "inventorywindow.hpp" namespace MWGui @@ -52,6 +59,8 @@ namespace MWGui mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onCancelButtonClicked); mOfferButton->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onOfferButtonClicked); + mIncreaseButton->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onIncreaseButtonClicked); + mDecreaseButton->eventMouseButtonClick += MyGUI::newDelegate(this, &TradeWindow::onDecreaseButtonClicked); setCoord(400, 0, 400, 300); @@ -63,6 +72,7 @@ namespace MWGui setTitle(MWWorld::Class::get(actor).getName(actor)); mCurrentBalance = 0; + mCurrentMerchantOffer = 0; mWindowManager.getInventoryWindow()->startTrade(); @@ -107,10 +117,14 @@ namespace MWGui bool goldFound = false; MWWorld::Ptr gold; MWWorld::ContainerStore& playerStore = mWindowManager.getInventoryWindow()->getContainerStore(); + + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); + for (MWWorld::ContainerStoreIterator it = playerStore.begin(); it != playerStore.end(); ++it) { - if (MWWorld::Class::get(*it).getName(*it) == MWBase::Environment::get().getWorld()->getStore().gameSettings.find("sGold")->getString()) + if (MWWorld::Class::get(*it).getName(*it) == gmst.find("sGold")->getString()) { goldFound = true; gold = *it; @@ -131,6 +145,9 @@ namespace MWGui void TradeWindow::onOfferButtonClicked(MyGUI::Widget* _sender) { + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); + // were there any items traded at all? MWWorld::ContainerStore& playerBought = mWindowManager.getInventoryWindow()->getBoughtItems(); MWWorld::ContainerStore& merchantBought = getBoughtItems(); @@ -156,15 +173,15 @@ namespace MWGui if (mPtr.getTypeName() == typeid(ESM::NPC).name()) { MWWorld::LiveCellRef* ref = mPtr.get(); - if (ref->base->mNpdt52.mGold == -10) - merchantgold = ref->base->mNpdt12.mGold; + if (ref->mBase->mNpdt52.mGold == -10) + merchantgold = ref->mBase->mNpdt12.mGold; else - merchantgold = ref->base->mNpdt52.mGold; + merchantgold = ref->mBase->mNpdt52.mGold; } else // ESM::Creature { MWWorld::LiveCellRef* ref = mPtr.get(); - merchantgold = ref->base->mData.mGold; + merchantgold = ref->mBase->mData.mGold; } if (mCurrentBalance > 0 && merchantgold < mCurrentBalance) { @@ -174,6 +191,59 @@ namespace MWGui return; } + if(mCurrentBalance > mCurrentMerchantOffer) + { + //if npc is a creature: reject (no haggle) + if (mPtr.getTypeName() != typeid(ESM::NPC).name()) + { + MWBase::Environment::get().getWindowManager()-> + messageBox("#{sNotifyMessage9}", std::vector()); + return; + } + + int a = abs(mCurrentMerchantOffer); + int b = abs(mCurrentBalance); + int d = 0; + if (mCurrentMerchantOffer<0) d = int(100 * (a - b) / a); + else d = int(100 * (b - a) / a); + + float clampedDisposition = std::max(0,std::min(int(MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(mPtr) + + MWBase::Environment::get().getDialogueManager()->getTemporaryDispositionChange()),100)); + + MWMechanics::NpcStats sellerSkill = MWWorld::Class::get(mPtr).getNpcStats(mPtr); + MWMechanics::CreatureStats sellerStats = MWWorld::Class::get(mPtr).getCreatureStats(mPtr); + MWWorld::Ptr playerPtr = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + MWMechanics::NpcStats playerSkill = MWWorld::Class::get(playerPtr).getNpcStats(playerPtr); + MWMechanics::CreatureStats playerStats = MWWorld::Class::get(playerPtr).getCreatureStats(playerPtr); + + float a1 = std::min(playerSkill.getSkill(ESM::Skill::Mercantile).getModified(), 100.f); + float b1 = std::min(0.1f * playerStats.getAttribute(ESM::Attribute::Luck).getModified(), 10.f); + float c1 = std::min(0.2f * playerStats.getAttribute(ESM::Attribute::Personality).getModified(), 10.f); + float d1 = std::min(sellerSkill.getSkill(ESM::Skill::Mercantile).getModified(), 100.f); + float e1 = std::min(0.1f * sellerStats.getAttribute(ESM::Attribute::Luck).getModified(), 10.f); + float f1 = std::min(0.2f * sellerStats.getAttribute(ESM::Attribute::Personality).getModified(), 10.f); + + float pcTerm = (clampedDisposition - 50 + a1 + b1 + c1) * playerStats.getFatigueTerm(); + float npcTerm = (d1 + e1 + f1) * sellerStats.getFatigueTerm(); + float x = gmst.find("fBargainOfferMulti")->getFloat() * d + gmst.find("fBargainOfferBase")->getFloat(); + if (mCurrentMerchantOffer<0) x += abs(int(pcTerm - npcTerm)); + else x += abs(int(npcTerm - pcTerm)); + + int roll = std::rand()%100 + 1; + if(roll > x) //trade refused + { + MWBase::Environment::get().getWindowManager()-> + messageBox("#{sNotifyMessage9}", std::vector()); + + int iBarterFailDisposition = gmst.find("iBarterFailDisposition")->getInt(); + MWBase::Environment::get().getDialogueManager()->applyTemporaryDispositionChange(iBarterFailDisposition); + return; + } + } + + int iBarterSuccessDisposition = gmst.find("iBarterSuccessDisposition")->getInt(); + MWBase::Environment::get().getDialogueManager()->applyTemporaryDispositionChange(iBarterSuccessDisposition); + // success! make the item transfer. transferBoughtItems(); mWindowManager.getInventoryWindow()->transferBoughtItems(); @@ -198,6 +268,20 @@ namespace MWGui mWindowManager.removeGuiMode(GM_Barter); } + void TradeWindow::onIncreaseButtonClicked(MyGUI::Widget* _sender) + { + if(mCurrentBalance<=-1) mCurrentBalance -= 1; + if(mCurrentBalance>=1) mCurrentBalance += 1; + updateLabels(); + } + + void TradeWindow::onDecreaseButtonClicked(MyGUI::Widget* _sender) + { + if(mCurrentBalance<-1) mCurrentBalance += 1; + if(mCurrentBalance>1) mCurrentBalance -= 1; + updateLabels(); + } + void TradeWindow::updateLabels() { mPlayerGold->setCaptionWithReplacing("#{sYourGold} " + boost::lexical_cast(mWindowManager.getInventoryWindow()->getPlayerGold())); @@ -217,15 +301,15 @@ namespace MWGui if (mPtr.getTypeName() == typeid(ESM::NPC).name()) { MWWorld::LiveCellRef* ref = mPtr.get(); - if (ref->base->mNpdt52.mGold == -10) - merchantgold = ref->base->mNpdt12.mGold; + if (ref->mBase->mNpdt52.mGold == -10) + merchantgold = ref->mBase->mNpdt12.mGold; else - merchantgold = ref->base->mNpdt52.mGold; + merchantgold = ref->mBase->mNpdt52.mGold; } else // ESM::Creature { MWWorld::LiveCellRef* ref = mPtr.get(); - merchantgold = ref->base->mData.mGold; + merchantgold = ref->mBase->mData.mGold; } mMerchantGold->setCaptionWithReplacing("#{sSellerGold} " + boost::lexical_cast(merchantgold)); @@ -261,14 +345,14 @@ namespace MWGui if (mPtr.getTypeName() == typeid(ESM::NPC).name()) { MWWorld::LiveCellRef* ref = mPtr.get(); - if (ref->base->mHasAI) - services = ref->base->mAiData.mServices; + if (ref->mBase->mHasAI) + services = ref->mBase->mAiData.mServices; } else if (mPtr.getTypeName() == typeid(ESM::Creature).name()) { MWWorld::LiveCellRef* ref = mPtr.get(); - if (ref->base->mHasAI) - services = ref->base->mAiData.mServices; + if (ref->mBase->mHasAI) + services = ref->mBase->mAiData.mServices; } /// \todo what about potions, there doesn't seem to be a flag for them?? @@ -316,19 +400,17 @@ namespace MWGui void TradeWindow::sellToNpc(MWWorld::Ptr item, int count) { - /// \todo price adjustment depending on merchantile skill - - mCurrentBalance -= MWWorld::Class::get(item).getValue(item) * count; + mCurrentBalance -= MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr, MWWorld::Class::get(item).getValue(item) * count,true); + mCurrentMerchantOffer -= MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr, MWWorld::Class::get(item).getValue(item) * count,true); updateLabels(); } void TradeWindow::buyFromNpc(MWWorld::Ptr item, int count) { - /// \todo price adjustment depending on merchantile skill - - mCurrentBalance += MWWorld::Class::get(item).getValue(item) * count; + mCurrentBalance += MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr, MWWorld::Class::get(item).getValue(item) * count,false); + mCurrentMerchantOffer += MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr, MWWorld::Class::get(item).getValue(item) * count,false); updateLabels(); } diff --git a/apps/openmw/mwgui/tradewindow.hpp b/apps/openmw/mwgui/tradewindow.hpp index 4ec55045c..db386d8b6 100644 --- a/apps/openmw/mwgui/tradewindow.hpp +++ b/apps/openmw/mwgui/tradewindow.hpp @@ -55,11 +55,14 @@ namespace MWGui MyGUI::TextBox* mMerchantGold; int mCurrentBalance; + int mCurrentMerchantOffer; void onWindowResize(MyGUI::Window* _sender); void onFilterChanged(MyGUI::Widget* _sender); void onOfferButtonClicked(MyGUI::Widget* _sender); void onCancelButtonClicked(MyGUI::Widget* _sender); + void onIncreaseButtonClicked(MyGUI::Widget* _sender); + void onDecreaseButtonClicked(MyGUI::Widget* _sender); // don't show items that the NPC has equipped in his trade-window. virtual bool ignoreEquippedItems() { return true; } diff --git a/apps/openmw/mwgui/trainingwindow.cpp b/apps/openmw/mwgui/trainingwindow.cpp new file mode 100644 index 000000000..ba39ee601 --- /dev/null +++ b/apps/openmw/mwgui/trainingwindow.cpp @@ -0,0 +1,167 @@ +#include "trainingwindow.hpp" + +#include + +#include + +#include "../mwbase/windowmanager.hpp" +#include "../mwbase/environment.hpp" +#include "../mwbase/world.hpp" +#include "../mwbase/mechanicsmanager.hpp" + +#include "../mwworld/player.hpp" + +#include "../mwmechanics/npcstats.hpp" + +#include "inventorywindow.hpp" +#include "tradewindow.hpp" +#include "tooltips.hpp" + +namespace MWGui +{ + + TrainingWindow::TrainingWindow(MWBase::WindowManager &parWindowManager) + : WindowBase("openmw_trainingwindow.layout", parWindowManager) + , mFadeTimeRemaining(0) + { + getWidget(mTrainingOptions, "TrainingOptions"); + getWidget(mCancelButton, "CancelButton"); + getWidget(mPlayerGold, "PlayerGold"); + + mCancelButton->eventMouseButtonClick += MyGUI::newDelegate(this, &TrainingWindow::onCancelButtonClicked); + } + + void TrainingWindow::open() + { + center(); + } + + void TrainingWindow::startTraining (MWWorld::Ptr actor) + { + mPtr = actor; + + mPlayerGold->setCaptionWithReplacing("#{sGold}: " + boost::lexical_cast(mWindowManager.getInventoryWindow()->getPlayerGold())); + + MWMechanics::NpcStats& npcStats = MWWorld::Class::get(actor).getNpcStats (actor); + + // NPC can train you in his best 3 skills + std::vector< std::pair > bestSkills; + bestSkills.push_back (std::make_pair(-1, -1)); + bestSkills.push_back (std::make_pair(-1, -1)); + bestSkills.push_back (std::make_pair(-1, -1)); + + for (int i=0; i bestSkills[j].second) + { + if (j<2) + { + bestSkills[j+1] = bestSkills[j]; + } + bestSkills[j] = std::make_pair(i, value); + break; + } + } + } + + MyGUI::EnumeratorWidgetPtr widgets = mTrainingOptions->getEnumerator (); + MyGUI::Gui::getInstance ().destroyWidgets (widgets); + + MWWorld::Ptr player = MWBase::Environment::get().getWorld ()->getPlayer ().getPlayer (); + MWMechanics::NpcStats& pcStats = MWWorld::Class::get(player).getNpcStats (player); + + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); + + for (int i=0; i<3; ++i) + { + int price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer + (mPtr,pcStats.getSkill (bestSkills[i].first).getBase() * gmst.find("iTrainingMod")->getInt (),true); + + std::string skin = (price > mWindowManager.getInventoryWindow ()->getPlayerGold ()) ? "SandTextGreyedOut" : "SandTextButton"; + + MyGUI::Button* button = mTrainingOptions->createWidget(skin, + MyGUI::IntCoord(5, 5+i*18, mTrainingOptions->getWidth()-10, 18), MyGUI::Align::Default); + + button->setUserData(bestSkills[i].first); + button->eventMouseButtonClick += MyGUI::newDelegate(this, &TrainingWindow::onTrainingSelected); + + button->setCaptionWithReplacing("#{" + ESM::Skill::sSkillNameIds[bestSkills[i].first] + "} - " + boost::lexical_cast(price)); + + button->setSize(button->getTextSize ().width+12, button->getSize().height); + + ToolTips::createSkillToolTip (button, bestSkills[i].first); + } + + center(); + } + + void TrainingWindow::onReferenceUnavailable () + { + mWindowManager.removeGuiMode(GM_Training); + } + + void TrainingWindow::onCancelButtonClicked (MyGUI::Widget *sender) + { + mWindowManager.removeGuiMode (GM_Training); + } + + void TrainingWindow::onTrainingSelected (MyGUI::Widget *sender) + { + int skillId = *sender->getUserData(); + + MWWorld::Ptr player = MWBase::Environment::get().getWorld ()->getPlayer ().getPlayer (); + MWMechanics::NpcStats& pcStats = MWWorld::Class::get(player).getNpcStats (player); + + const MWWorld::ESMStore &store = + MWBase::Environment::get().getWorld()->getStore(); + + int price = pcStats.getSkill (skillId).getBase() * store.get().find("iTrainingMod")->getInt (); + price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr,price,true); + + if (mWindowManager.getInventoryWindow()->getPlayerGold()()); + return; + } + + // increase skill + MWWorld::LiveCellRef *playerRef = player.get(); + + const ESM::Class *class_ = + store.get().find(playerRef->mBase->mClass); + pcStats.increaseSkill (skillId, *class_, true); + + // remove gold + mWindowManager.getTradeWindow()->addOrRemoveGold(-price); + + // go back to game mode + mWindowManager.removeGuiMode (GM_Training); + mWindowManager.removeGuiMode (GM_Dialogue); + + // advance time + MWBase::Environment::get().getWorld ()->advanceTime (2); + + MWBase::Environment::get().getWorld ()->getFader()->fadeOut(0.25); + mFadeTimeRemaining = 0.5; + } + + void TrainingWindow::onFrame(float dt) + { + if (mFadeTimeRemaining <= 0) + return; + + mFadeTimeRemaining -= dt; + + if (mFadeTimeRemaining <= 0) + MWBase::Environment::get().getWorld ()->getFader()->fadeIn(0.25); + } +} diff --git a/apps/openmw/mwgui/trainingwindow.hpp b/apps/openmw/mwgui/trainingwindow.hpp new file mode 100644 index 000000000..f2ef1714e --- /dev/null +++ b/apps/openmw/mwgui/trainingwindow.hpp @@ -0,0 +1,36 @@ +#ifndef MWGUI_TRAININGWINDOW_H +#define MWGUI_TRAININGWINDOW_H + +#include "window_base.hpp" +#include "referenceinterface.hpp" + +namespace MWGui +{ + + class TrainingWindow : public WindowBase, public ReferenceInterface + { + public: + TrainingWindow(MWBase::WindowManager& parWindowManager); + + virtual void open(); + + void startTraining(MWWorld::Ptr actor); + + void onFrame(float dt); + + protected: + virtual void onReferenceUnavailable (); + + void onCancelButtonClicked (MyGUI::Widget* sender); + void onTrainingSelected(MyGUI::Widget* sender); + + MyGUI::Widget* mTrainingOptions; + MyGUI::Button* mCancelButton; + MyGUI::TextBox* mPlayerGold; + + float mFadeTimeRemaining; + }; + +} + +#endif diff --git a/apps/openmw/mwgui/travelwindow.cpp b/apps/openmw/mwgui/travelwindow.cpp new file mode 100644 index 000000000..abbc6172f --- /dev/null +++ b/apps/openmw/mwgui/travelwindow.cpp @@ -0,0 +1,191 @@ +#include "travelwindow.hpp" + +#include + +#include + +#include + +#include "../mwbase/environment.hpp" +#include "../mwbase/world.hpp" +#include "../mwbase/soundmanager.hpp" +#include "../mwbase/windowmanager.hpp" +#include "../mwbase/mechanicsmanager.hpp" + +#include "../mwworld/player.hpp" +#include "../mwworld/manualref.hpp" + +#include "../mwmechanics/spells.hpp" +#include "../mwmechanics/creaturestats.hpp" + +#include "inventorywindow.hpp" +#include "tradewindow.hpp" + +namespace MWGui +{ + const int TravelWindow::sLineHeight = 18; + + TravelWindow::TravelWindow(MWBase::WindowManager& parWindowManager) : + WindowBase("openmw_travel_window.layout", parWindowManager) + , mCurrentY(0) + , mLastPos(0) + { + setCoord(0, 0, 450, 300); + + 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 std::string& travelId,ESM::Position pos,bool interior) + { + int price = 0; + + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); + + if(interior) + { + price = gmst.find("fMagesGuildTravel")->getFloat(); + } + else + { + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + 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) ); + price = d/gmst.find("fTravelMult")->getFloat(); + } + + price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr,price,true); + + MyGUI::Button* toAdd = mDestinationsView->createWidget((price>mWindowManager.getInventoryWindow()->getPlayerGold()) ? "SandTextGreyedOut" : "SandTextButton", 0, mCurrentY, 200, sLineHeight, MyGUI::Align::Default); + mCurrentY += sLineHeight; + if(interior) + toAdd->setUserString("interior","y"); + else + toAdd->setUserString("interior","n"); + + std::ostringstream oss; + oss << price; + toAdd->setUserString("price",oss.str()); + + toAdd->setCaptionWithReplacing(travelId+" - "+boost::lexical_cast(price)+"#{sgp}"); + toAdd->setSize(toAdd->getTextSize().width,sLineHeight); + toAdd->eventMouseWheel += MyGUI::newDelegate(this, &TravelWindow::onMouseWheel); + toAdd->setUserString("Destination", travelId); + toAdd->setUserData(pos); + toAdd->eventMouseButtonClick += MyGUI::newDelegate(this, &TravelWindow::onTravelButtonClick); + mDestinationsWidgetMap.insert(std::make_pair (toAdd, travelId)); + } + + void TravelWindow::clearDestinations() + { + mDestinationsView->setViewOffset(MyGUI::IntPoint(0,0)); + mCurrentY = 0; + while (mDestinationsView->getChildCount()) + MyGUI::Gui::getInstance().destroyWidget(mDestinationsView->getChildAt(0)); + mDestinationsWidgetMap.clear(); + } + + void TravelWindow::startTravel(const MWWorld::Ptr& actor) + { + center(); + mPtr = actor; + clearDestinations(); + + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + + for(unsigned int i = 0;i()->mBase->mTransport.size();i++) + { + std::string cellname = mPtr.get()->mBase->mTransport[i].mCellName; + bool interior = true; + int x,y; + MWBase::Environment::get().getWorld()->positionToIndex(mPtr.get()->mBase->mTransport[i].mPos.pos[0], + mPtr.get()->mBase->mTransport[i].mPos.pos[1],x,y); + if(cellname == "") {cellname = MWBase::Environment::get().getWorld()->getExterior(x,y)->mCell->mName; interior= false;} + addDestination(cellname,mPtr.get()->mBase->mTransport[i].mPos,interior); + } + + updateLabels(); + mDestinationsView->setCanvasSize (MyGUI::IntSize(mDestinationsView->getWidth(), std::max(mDestinationsView->getHeight(), mCurrentY))); + } + + void TravelWindow::onTravelButtonClick(MyGUI::Widget* _sender) + { + std::istringstream iss(_sender->getUserString("price")); + int price; + iss >> price; + + if (mWindowManager.getInventoryWindow()->getPlayerGold()getFader ()->fadeOut(1); + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + ESM::Position pos = *_sender->getUserData(); + std::string cellname = _sender->getUserString("Destination"); + int x,y; + bool interior = _sender->getUserString("interior") == "y"; + MWBase::Environment::get().getWorld()->positionToIndex(pos.pos[0],pos.pos[1],x,y); + MWWorld::CellStore* cell; + if(interior) cell = MWBase::Environment::get().getWorld()->getInterior(cellname); + else + { + cell = MWBase::Environment::get().getWorld()->getExterior(x,y); + 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) ); + int time = int(d /MWBase::Environment::get().getWorld()->getStore().get().find("fTravelTimeMult")->getFloat()); + for(int i = 0;i < time;i++) + { + MWBase::Environment::get().getMechanicsManager ()->restoreDynamicStats (); + } + MWBase::Environment::get().getWorld()->advanceTime(time); + } + MWBase::Environment::get().getWorld()->moveObject(player,*cell,pos.pos[0],pos.pos[1],pos.pos[2]); + mWindowManager.removeGuiMode(GM_Travel); + mWindowManager.removeGuiMode(GM_Dialogue); + MWBase::Environment::get().getWorld ()->getFader ()->fadeOut(0); + MWBase::Environment::get().getWorld ()->getFader ()->fadeIn(1); + } + + void TravelWindow::onCancelButtonClicked(MyGUI::Widget* _sender) + { + mWindowManager.removeGuiMode(GM_Travel); + } + + void TravelWindow::updateLabels() + { + mPlayerGold->setCaptionWithReplacing("#{sGold}: " + boost::lexical_cast(mWindowManager.getInventoryWindow()->getPlayerGold())); + mPlayerGold->setCoord(8, + mPlayerGold->getTop(), + mPlayerGold->getTextSize().width, + mPlayerGold->getHeight()); + } + + void TravelWindow::onReferenceUnavailable() + { + mWindowManager.removeGuiMode(GM_Travel); + mWindowManager.removeGuiMode(GM_Dialogue); + } + + void TravelWindow::onMouseWheel(MyGUI::Widget* _sender, int _rel) + { + if (mDestinationsView->getViewOffset().top + _rel*0.3 > 0) + mDestinationsView->setViewOffset(MyGUI::IntPoint(0, 0)); + else + mDestinationsView->setViewOffset(MyGUI::IntPoint(0, mDestinationsView->getViewOffset().top + _rel*0.3)); + } +} + diff --git a/apps/openmw/mwgui/travelwindow.hpp b/apps/openmw/mwgui/travelwindow.hpp new file mode 100644 index 000000000..cc3d6a31f --- /dev/null +++ b/apps/openmw/mwgui/travelwindow.hpp @@ -0,0 +1,55 @@ +#ifndef MWGUI_TravelWINDOW_H +#define MWGUI_TravelWINDOW_H + +#include "container.hpp" +#include "window_base.hpp" + +#include "../mwworld/ptr.hpp" + +namespace MyGUI +{ + class Gui; + class Widget; +} + +namespace MWGui +{ + class WindowManager; +} + + +namespace MWGui +{ + class TravelWindow : public ReferenceInterface, public WindowBase + { + public: + TravelWindow(MWBase::WindowManager& parWindowManager); + + void startTravel(const MWWorld::Ptr& actor); + + protected: + MyGUI::Button* mCancelButton; + MyGUI::TextBox* mPlayerGold; + MyGUI::TextBox* mDestinations; + MyGUI::TextBox* mSelect; + + MyGUI::ScrollView* mDestinationsView; + + std::map mDestinationsWidgetMap; + + void onCancelButtonClicked(MyGUI::Widget* _sender); + void onTravelButtonClick(MyGUI::Widget* _sender); + void onMouseWheel(MyGUI::Widget* _sender, int _rel); + void addDestination(const std::string& destinationID,ESM::Position pos,bool interior); + void clearDestinations(); + int mLastPos,mCurrentY; + + static const int sLineHeight; + + void updateLabels(); + + virtual void onReferenceUnavailable(); + }; +} + +#endif diff --git a/apps/openmw/mwgui/waitdialog.cpp b/apps/openmw/mwgui/waitdialog.cpp index 380fb8dd5..31b5cce35 100644 --- a/apps/openmw/mwgui/waitdialog.cpp +++ b/apps/openmw/mwgui/waitdialog.cpp @@ -120,9 +120,10 @@ namespace MWGui int hour = MWBase::Environment::get().getWorld ()->getTimeStamp ().getHour (); bool pm = hour >= 12; if (hour >= 13) hour -= 12; + if (hour == 0) hour = 12; std::string dateTimeText = - boost::lexical_cast(MWBase::Environment::get().getWorld ()->getDay ()+1) + " " + boost::lexical_cast(MWBase::Environment::get().getWorld ()->getDay ()) + " " + month + " (#{sDay} " + boost::lexical_cast(MWBase::Environment::get().getWorld ()->getTimeStamp ().getDay ()+1) + ") " + boost::lexical_cast(hour) + " " + (pm ? "#{sSaveMenuHelp05}" : "#{sSaveMenuHelp04}"); diff --git a/apps/openmw/mwgui/widgets.cpp b/apps/openmw/mwgui/widgets.cpp index 33aa1886c..82e112826 100644 --- a/apps/openmw/mwgui/widgets.cpp +++ b/apps/openmw/mwgui/widgets.cpp @@ -2,12 +2,12 @@ #include -#include "components/esm_store/store.hpp" - #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwbase/windowmanager.hpp" +#include "../mwworld/esmstore.hpp" + #undef min #undef max @@ -228,8 +228,10 @@ void MWSpell::setSpellId(const std::string &spellId) void MWSpell::createEffectWidgets(std::vector &effects, MyGUI::WidgetPtr creator, MyGUI::IntCoord &coord, int flags) { - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); - const ESM::Spell *spell = store.spells.search(mId); + const MWWorld::ESMStore &store = + MWBase::Environment::get().getWorld()->getStore(); + + const ESM::Spell *spell = store.get().search(mId); MYGUI_ASSERT(spell, "spell with id '" << mId << "' not found"); MWSpellEffectPtr effect = nullptr; @@ -259,8 +261,10 @@ void MWSpell::updateWidgets() { if (mSpellNameWidget && mWindowManager) { - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); - const ESM::Spell *spell = store.spells.search(mId); + const MWWorld::ESMStore &store = + MWBase::Environment::get().getWorld()->getStore(); + + const ESM::Spell *spell = store.get().search(mId); if (spell) static_cast(mSpellNameWidget)->setCaption(spell->mName); else @@ -362,6 +366,7 @@ SpellEffectList MWEffectList::effectListFromESM(const ESM::EffectList* effects) params.mMagnMin = it->mMagnMin; params.mMagnMax = it->mMagnMax; params.mRange = it->mRange; + params.mArea = it->mArea; result.push_back(params); } return result; @@ -388,340 +393,85 @@ void MWSpellEffect::updateWidgets() if (!mWindowManager) return; - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); - const ESM::MagicEffect *magicEffect = store.magicEffects.search(mEffectParams.mEffectID); - if (!magicEffect) - return; - if (mTextWidget) + const MWWorld::ESMStore &store = + MWBase::Environment::get().getWorld()->getStore(); + + const ESM::MagicEffect *magicEffect = + store.get().search(mEffectParams.mEffectID); + + assert(magicEffect); + assert(mWindowManager); + + std::string pt = mWindowManager->getGameSettingString("spoint", ""); + std::string pts = mWindowManager->getGameSettingString("spoints", ""); + std::string to = " " + mWindowManager->getGameSettingString("sTo", "") + " "; + std::string sec = " " + mWindowManager->getGameSettingString("ssecond", ""); + std::string secs = " " + mWindowManager->getGameSettingString("sseconds", ""); + + std::string effectIDStr = ESM::MagicEffect::effectIdToString(mEffectParams.mEffectID); + std::string spellLine = mWindowManager->getGameSettingString(effectIDStr, ""); + + if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetSkill) { - std::string pt = mWindowManager->getGameSettingString("spoint", ""); - std::string pts = mWindowManager->getGameSettingString("spoints", ""); - std::string to = " " + mWindowManager->getGameSettingString("sTo", "") + " "; - std::string sec = " " + mWindowManager->getGameSettingString("ssecond", ""); - std::string secs = " " + mWindowManager->getGameSettingString("sseconds", ""); - - std::string effectIDStr = effectIDToString(mEffectParams.mEffectID); - std::string spellLine = mWindowManager->getGameSettingString(effectIDStr, ""); - if (effectInvolvesSkill(effectIDStr) && mEffectParams.mSkill >= 0 && mEffectParams.mSkill < ESM::Skill::Length) - { - spellLine += " " + mWindowManager->getGameSettingString(ESM::Skill::sSkillNameIds[mEffectParams.mSkill], ""); - } - if (effectInvolvesAttribute(effectIDStr) && mEffectParams.mAttribute >= 0 && mEffectParams.mAttribute < 8) - { - static const char *attributes[8] = { - "sAttributeStrength", - "sAttributeIntelligence", - "sAttributeWillpower", - "sAttributeAgility", - "sAttributeSpeed", - "sAttributeEndurance", - "sAttributePersonality", - "sAttributeLuck" - }; - spellLine += " " + mWindowManager->getGameSettingString(attributes[mEffectParams.mAttribute], ""); - } - - if ((mEffectParams.mMagnMin >= 0 || mEffectParams.mMagnMax >= 0) && effectHasMagnitude(effectIDStr)) - { - if (mEffectParams.mMagnMin == mEffectParams.mMagnMax) - spellLine += " " + boost::lexical_cast(mEffectParams.mMagnMin) + " " + ((mEffectParams.mMagnMin == 1) ? pt : pts); - else - { - spellLine += " " + boost::lexical_cast(mEffectParams.mMagnMin) + to + boost::lexical_cast(mEffectParams.mMagnMax) + " " + pts; - } - } - - // constant effects have no duration and no target - if (!mEffectParams.mIsConstant) - { - if (mEffectParams.mDuration >= 0 && effectHasDuration(effectIDStr)) - { - spellLine += " " + mWindowManager->getGameSettingString("sfor", "") + " " + boost::lexical_cast(mEffectParams.mDuration) + ((mEffectParams.mDuration == 1) ? sec : secs); - } - - // potions have no target - if (!mEffectParams.mNoTarget) - { - std::string on = mWindowManager->getGameSettingString("sonword", ""); - if (mEffectParams.mRange == ESM::RT_Self) - spellLine += " " + on + " " + mWindowManager->getGameSettingString("sRangeSelf", ""); - else if (mEffectParams.mRange == ESM::RT_Touch) - spellLine += " " + on + " " + mWindowManager->getGameSettingString("sRangeTouch", ""); - else if (mEffectParams.mRange == ESM::RT_Target) - spellLine += " " + on + " " + mWindowManager->getGameSettingString("sRangeTarget", ""); - } - } - - static_cast(mTextWidget)->setCaption(spellLine); - mRequestedWidth = mTextWidget->getTextSize().width + 24; + spellLine += " " + mWindowManager->getGameSettingString(ESM::Skill::sSkillNameIds[mEffectParams.mSkill], ""); } - if (mImageWidget) + if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetAttribute) { - std::string path = std::string("icons\\") + magicEffect->mIcon; - fixTexturePath(path); - mImageWidget->setImageTexture(path); + static const char *attributes[8] = { + "sAttributeStrength", + "sAttributeIntelligence", + "sAttributeWillpower", + "sAttributeAgility", + "sAttributeSpeed", + "sAttributeEndurance", + "sAttributePersonality", + "sAttributeLuck" + }; + spellLine += " " + mWindowManager->getGameSettingString(attributes[mEffectParams.mAttribute], ""); } -} -std::string MWSpellEffect::effectIDToString(const short effectID) -{ - // Map effect ID to GMST name - // http://www.uesp.net/morrow/hints/mweffects.shtml - std::map names; - names[85] ="sEffectAbsorbAttribute"; - names[88] ="sEffectAbsorbFatigue"; - names[86] ="sEffectAbsorbHealth"; - names[87] ="sEffectAbsorbSpellPoints"; - names[89] ="sEffectAbsorbSkill"; - names[63] ="sEffectAlmsiviIntervention"; - names[47] ="sEffectBlind"; - names[123] ="sEffectBoundBattleAxe"; - names[129] ="sEffectBoundBoots"; - names[127] ="sEffectBoundCuirass"; - names[120] ="sEffectBoundDagger"; - names[131] ="sEffectBoundGloves"; - names[128] ="sEffectBoundHelm"; - names[125] ="sEffectBoundLongbow"; - names[121] ="sEffectBoundLongsword"; - names[122] ="sEffectBoundMace"; - names[130] ="sEffectBoundShield"; - names[124] ="sEffectBoundSpear"; - names[7] ="sEffectBurden"; - names[50] ="sEffectCalmCreature"; - names[49] ="sEffectCalmHumanoid"; - names[40] ="sEffectChameleon"; - names[44] ="sEffectCharm"; - names[118] ="sEffectCommandCreatures"; - names[119] ="sEffectCommandHumanoids"; - names[132] ="sEffectCorpus"; // NB this typo. (bethesda made it) - names[70] ="sEffectCureBlightDisease"; - names[69] ="sEffectCureCommonDisease"; - names[71] ="sEffectCureCorprusDisease"; - names[73] ="sEffectCureParalyzation"; - names[72] ="sEffectCurePoison"; - names[22] ="sEffectDamageAttribute"; - names[25] ="sEffectDamageFatigue"; - names[23] ="sEffectDamageHealth"; - names[24] ="sEffectDamageMagicka"; - names[26] ="sEffectDamageSkill"; - names[54] ="sEffectDemoralizeCreature"; - names[53] ="sEffectDemoralizeHumanoid"; - names[64] ="sEffectDetectAnimal"; - names[65] ="sEffectDetectEnchantment"; - names[66] ="sEffectDetectKey"; - names[38] ="sEffectDisintegrateArmor"; - names[37] ="sEffectDisintegrateWeapon"; - names[57] ="sEffectDispel"; - names[62] ="sEffectDivineIntervention"; - names[17] ="sEffectDrainAttribute"; - names[20] ="sEffectDrainFatigue"; - names[18] ="sEffectDrainHealth"; - names[19] ="sEffectDrainSpellpoints"; - names[21] ="sEffectDrainSkill"; - names[8] ="sEffectFeather"; - names[14] ="sEffectFireDamage"; - names[4] ="sEffectFireShield"; - names[117] ="sEffectFortifyAttackBonus"; - names[79] ="sEffectFortifyAttribute"; - names[82] ="sEffectFortifyFatigue"; - names[80] ="sEffectFortifyHealth"; - names[81] ="sEffectFortifySpellpoints"; - names[84] ="sEffectFortifyMagickaMultiplier"; - names[83] ="sEffectFortifySkill"; - names[52] ="sEffectFrenzyCreature"; - names[51] ="sEffectFrenzyHumanoid"; - names[16] ="sEffectFrostDamage"; - names[6] ="sEffectFrostShield"; - names[39] ="sEffectInvisibility"; - names[9] ="sEffectJump"; - names[10] ="sEffectLevitate"; - names[41] ="sEffectLight"; - names[5] ="sEffectLightningShield"; - names[12] ="sEffectLock"; - names[60] ="sEffectMark"; - names[43] ="sEffectNightEye"; - names[13] ="sEffectOpen"; - names[45] ="sEffectParalyze"; - names[27] ="sEffectPoison"; - names[56] ="sEffectRallyCreature"; - names[55] ="sEffectRallyHumanoid"; - names[61] ="sEffectRecall"; - names[68] ="sEffectReflect"; - names[100] ="sEffectRemoveCurse"; - names[95] ="sEffectResistBlightDisease"; - names[94] ="sEffectResistCommonDisease"; - names[96] ="sEffectResistCorprusDisease"; - names[90] ="sEffectResistFire"; - names[91] ="sEffectResistFrost"; - names[93] ="sEffectResistMagicka"; - names[98] ="sEffectResistNormalWeapons"; - names[99] ="sEffectResistParalysis"; - names[97] ="sEffectResistPoison"; - names[92] ="sEffectResistShock"; - names[74] ="sEffectRestoreAttribute"; - names[77] ="sEffectRestoreFatigue"; - names[75] ="sEffectRestoreHealth"; - names[76] ="sEffectRestoreSpellPoints"; - names[78] ="sEffectRestoreSkill"; - names[42] ="sEffectSanctuary"; - names[3] ="sEffectShield"; - names[15] ="sEffectShockDamage"; - names[46] ="sEffectSilence"; - names[11] ="sEffectSlowFall"; - names[58] ="sEffectSoultrap"; - names[48] ="sEffectSound"; - names[67] ="sEffectSpellAbsorption"; - names[136] ="sEffectStuntedMagicka"; - names[106] ="sEffectSummonAncestralGhost"; - names[110] ="sEffectSummonBonelord"; - names[108] ="sEffectSummonLeastBonewalker"; - names[134] ="sEffectSummonCenturionSphere"; - names[103] ="sEffectSummonClannfear"; - names[104] ="sEffectSummonDaedroth"; - names[105] ="sEffectSummonDremora"; - names[114] ="sEffectSummonFlameAtronach"; - names[115] ="sEffectSummonFrostAtronach"; - names[113] ="sEffectSummonGoldenSaint"; - names[109] ="sEffectSummonGreaterBonewalker"; - names[112] ="sEffectSummonHunger"; - names[102] ="sEffectSummonScamp"; - names[107] ="sEffectSummonSkeletalMinion"; - names[116] ="sEffectSummonStormAtronach"; - names[111] ="sEffectSummonWingedTwilight"; - names[135] ="sEffectSunDamage"; - names[1] ="sEffectSwiftSwim"; - names[59] ="sEffectTelekinesis"; - names[101] ="sEffectTurnUndead"; - names[133] ="sEffectVampirism"; - names[0] ="sEffectWaterBreathing"; - names[2] ="sEffectWaterWalking"; - names[33] ="sEffectWeaknesstoBlightDisease"; - names[32] ="sEffectWeaknesstoCommonDisease"; - names[34] ="sEffectWeaknesstoCorprusDisease"; - names[28] ="sEffectWeaknesstoFire"; - names[29] ="sEffectWeaknesstoFrost"; - names[31] ="sEffectWeaknesstoMagicka"; - names[36] ="sEffectWeaknesstoNormalWeapons"; - names[35] ="sEffectWeaknesstoPoison"; - names[30] ="sEffectWeaknesstoShock"; + if ((mEffectParams.mMagnMin >= 0 || mEffectParams.mMagnMax >= 0) && !(magicEffect->mData.mFlags & ESM::MagicEffect::NoMagnitude)) + { + if (mEffectParams.mMagnMin == mEffectParams.mMagnMax) + spellLine += " " + boost::lexical_cast(mEffectParams.mMagnMin) + " " + ((mEffectParams.mMagnMin == 1) ? pt : pts); + else + { + spellLine += " " + boost::lexical_cast(mEffectParams.mMagnMin) + to + boost::lexical_cast(mEffectParams.mMagnMax) + " " + pts; + } + } - // bloodmoon - names[138] ="sEffectSummonCreature01"; - names[139] ="sEffectSummonCreature02"; - names[140] ="sEffectSummonCreature03"; - names[141] ="sEffectSummonCreature04"; - names[142] ="sEffectSummonCreature05"; + // constant effects have no duration and no target + if (!mEffectParams.mIsConstant) + { + if (mEffectParams.mDuration >= 0 && !(magicEffect->mData.mFlags & ESM::MagicEffect::NoDuration)) + { + spellLine += " " + mWindowManager->getGameSettingString("sfor", "") + " " + boost::lexical_cast(mEffectParams.mDuration) + ((mEffectParams.mDuration == 1) ? sec : secs); + } - // tribunal - names[137] ="sEffectSummonFabricant"; + if (mEffectParams.mArea > 0) + { + spellLine += " #{sin} " + boost::lexical_cast(mEffectParams.mArea) + " #{sfootarea}"; + } - assert(names.find(effectID) != names.end() && "Unimplemented effect type"); + // potions have no target + if (!mEffectParams.mNoTarget) + { + std::string on = mWindowManager->getGameSettingString("sonword", ""); + if (mEffectParams.mRange == ESM::RT_Self) + spellLine += " " + on + " " + mWindowManager->getGameSettingString("sRangeSelf", ""); + else if (mEffectParams.mRange == ESM::RT_Touch) + spellLine += " " + on + " " + mWindowManager->getGameSettingString("sRangeTouch", ""); + else if (mEffectParams.mRange == ESM::RT_Target) + spellLine += " " + on + " " + mWindowManager->getGameSettingString("sRangeTarget", ""); + } + } - return names[effectID]; -} + static_cast(mTextWidget)->setCaptionWithReplacing(spellLine); + mRequestedWidth = mTextWidget->getTextSize().width + 24; -bool MWSpellEffect::effectHasDuration(const std::string& effect) -{ - // lists effects that have no duration (e.g. open lock) - std::vector effectsWithoutDuration; - effectsWithoutDuration.push_back("sEffectOpen"); - effectsWithoutDuration.push_back("sEffectLock"); - effectsWithoutDuration.push_back("sEffectDispel"); - effectsWithoutDuration.push_back("sEffectSunDamage"); - effectsWithoutDuration.push_back("sEffectCorpus"); - effectsWithoutDuration.push_back("sEffectVampirism"); - effectsWithoutDuration.push_back("sEffectMark"); - effectsWithoutDuration.push_back("sEffectRecall"); - effectsWithoutDuration.push_back("sEffectDivineIntervention"); - effectsWithoutDuration.push_back("sEffectAlmsiviIntervention"); - effectsWithoutDuration.push_back("sEffectCureCommonDisease"); - effectsWithoutDuration.push_back("sEffectCureBlightDisease"); - effectsWithoutDuration.push_back("sEffectCureCorprusDisease"); - effectsWithoutDuration.push_back("sEffectCurePoison"); - effectsWithoutDuration.push_back("sEffectCureParalyzation"); - effectsWithoutDuration.push_back("sEffectRemoveCurse"); - effectsWithoutDuration.push_back("sEffectRestoreAttribute"); - - return (std::find(effectsWithoutDuration.begin(), effectsWithoutDuration.end(), effect) == effectsWithoutDuration.end()); -} - -bool MWSpellEffect::effectHasMagnitude(const std::string& effect) -{ - // lists effects that have no magnitude (e.g. invisiblity) - std::vector effectsWithoutMagnitude; - effectsWithoutMagnitude.push_back("sEffectInvisibility"); - effectsWithoutMagnitude.push_back("sEffectStuntedMagicka"); - effectsWithoutMagnitude.push_back("sEffectParalyze"); - effectsWithoutMagnitude.push_back("sEffectSoultrap"); - effectsWithoutMagnitude.push_back("sEffectSilence"); - effectsWithoutMagnitude.push_back("sEffectParalyze"); - effectsWithoutMagnitude.push_back("sEffectInvisibility"); - effectsWithoutMagnitude.push_back("sEffectWaterWalking"); - effectsWithoutMagnitude.push_back("sEffectWaterBreathing"); - effectsWithoutMagnitude.push_back("sEffectSummonScamp"); - effectsWithoutMagnitude.push_back("sEffectSummonClannfear"); - effectsWithoutMagnitude.push_back("sEffectSummonDaedroth"); - effectsWithoutMagnitude.push_back("sEffectSummonDremora"); - effectsWithoutMagnitude.push_back("sEffectSummonAncestralGhost"); - effectsWithoutMagnitude.push_back("sEffectSummonSkeletalMinion"); - effectsWithoutMagnitude.push_back("sEffectSummonBonewalker"); - effectsWithoutMagnitude.push_back("sEffectSummonGreaterBonewalker"); - effectsWithoutMagnitude.push_back("sEffectSummonBonelord"); - effectsWithoutMagnitude.push_back("sEffectSummonWingedTwilight"); - effectsWithoutMagnitude.push_back("sEffectSummonHunger"); - effectsWithoutMagnitude.push_back("sEffectSummonGoldenSaint"); - effectsWithoutMagnitude.push_back("sEffectSummonFlameAtronach"); - effectsWithoutMagnitude.push_back("sEffectSummonFrostAtronach"); - effectsWithoutMagnitude.push_back("sEffectSummonStormAtronach"); - effectsWithoutMagnitude.push_back("sEffectSummonCenturionSphere"); - effectsWithoutMagnitude.push_back("sEffectBoundDagger"); - effectsWithoutMagnitude.push_back("sEffectBoundLongsword"); - effectsWithoutMagnitude.push_back("sEffectBoundMace"); - effectsWithoutMagnitude.push_back("sEffectBoundBattleAxe"); - effectsWithoutMagnitude.push_back("sEffectBoundSpear"); - effectsWithoutMagnitude.push_back("sEffectBoundLongbow"); - effectsWithoutMagnitude.push_back("sEffectBoundCuirass"); - effectsWithoutMagnitude.push_back("sEffectBoundHelm"); - effectsWithoutMagnitude.push_back("sEffectBoundBoots"); - effectsWithoutMagnitude.push_back("sEffectBoundShield"); - effectsWithoutMagnitude.push_back("sEffectBoundGloves"); - effectsWithoutMagnitude.push_back("sEffectStuntedMagicka"); - effectsWithoutMagnitude.push_back("sEffectMark"); - effectsWithoutMagnitude.push_back("sEffectRecall"); - effectsWithoutMagnitude.push_back("sEffectDivineIntervention"); - effectsWithoutMagnitude.push_back("sEffectAlmsiviIntervention"); - effectsWithoutMagnitude.push_back("sEffectCureCommonDisease"); - effectsWithoutMagnitude.push_back("sEffectCureBlightDisease"); - effectsWithoutMagnitude.push_back("sEffectCureCorprusDisease"); - effectsWithoutMagnitude.push_back("sEffectCurePoison"); - effectsWithoutMagnitude.push_back("sEffectCureParalyzation"); - effectsWithoutMagnitude.push_back("sEffectRemoveCurse"); - effectsWithoutMagnitude.push_back("sEffectSummonCreature01"); - effectsWithoutMagnitude.push_back("sEffectSummonCreature02"); - effectsWithoutMagnitude.push_back("sEffectSummonCreature03"); - effectsWithoutMagnitude.push_back("sEffectSummonCreature04"); - effectsWithoutMagnitude.push_back("sEffectSummonCreature05"); - effectsWithoutMagnitude.push_back("sEffectSummonFabricant"); - - return (std::find(effectsWithoutMagnitude.begin(), effectsWithoutMagnitude.end(), effect) == effectsWithoutMagnitude.end()); -} - -bool MWSpellEffect::effectInvolvesAttribute (const std::string& effect) -{ - return (effect == "sEffectRestoreAttribute" - || effect == "sEffectAbsorbAttribute" - || effect == "sEffectDrainAttribute" - || effect == "sEffectFortifyAttribute" - || effect == "sEffectDamageAttribute"); -} - -bool MWSpellEffect::effectInvolvesSkill (const std::string& effect) -{ - return (effect == "sEffectRestoreSkill" - || effect == "sEffectAbsorbSkill" - || effect == "sEffectDrainSkill" - || effect == "sEffectFortifySkill" - || effect == "sEffectDamageSkill"); + std::string path = std::string("icons\\") + magicEffect->mIcon; + fixTexturePath(path); + mImageWidget->setImageTexture(path); } MWSpellEffect::~MWSpellEffect() diff --git a/apps/openmw/mwgui/widgets.hpp b/apps/openmw/mwgui/widgets.hpp index 6298ea77d..4ac5383f7 100644 --- a/apps/openmw/mwgui/widgets.hpp +++ b/apps/openmw/mwgui/widgets.hpp @@ -1,7 +1,7 @@ #ifndef MWGUI_WIDGETS_H #define MWGUI_WIDGETS_H -#include +#include "../mwworld/esmstore.hpp" #include @@ -32,6 +32,7 @@ namespace MWGui , mRange(-1) , mDuration(-1) , mSkill(-1) + , mArea(0) , mAttribute(-1) , mEffectID(-1) , mNoTarget(false) @@ -51,6 +52,9 @@ namespace MWGui // value of -1 here means the value is unavailable int mMagnMin, mMagnMax, mRange, mDuration; + // value of 0 -> no area effect + int mArea; + bool operator==(const SpellEffectParams& other) const { if (mEffectID != other.mEffectID) @@ -66,7 +70,7 @@ namespace MWGui || mEffectID == 21 // drain skill || mEffectID == 83 // fortify skill || mEffectID == 26); // damage skill - return ((other.mSkill == mSkill) || !involvesSkill) && ((other.mAttribute == mAttribute) && !involvesAttribute); + return ((other.mSkill == mSkill) || !involvesSkill) && ((other.mAttribute == mAttribute) && !involvesAttribute) && (other.mArea == mArea); } }; @@ -249,12 +253,6 @@ namespace MWGui void setWindowManager(MWBase::WindowManager* parWindowManager) { mWindowManager = parWindowManager; } void setSpellEffect(const SpellEffectParams& params); - std::string effectIDToString(const short effectID); - bool effectHasMagnitude (const std::string& effect); - bool effectHasDuration (const std::string& effect); - bool effectInvolvesAttribute (const std::string& effect); - bool effectInvolvesSkill (const std::string& effect); - int getRequestedWidth() const { return mRequestedWidth; } protected: diff --git a/apps/openmw/mwgui/windowmanagerimp.cpp b/apps/openmw/mwgui/windowmanagerimp.cpp index 555767c8e..258a40e1c 100644 --- a/apps/openmw/mwgui/windowmanagerimp.cpp +++ b/apps/openmw/mwgui/windowmanagerimp.cpp @@ -38,6 +38,7 @@ #include "countdialog.hpp" #include "tradewindow.hpp" #include "spellbuyingwindow.hpp" +#include "travelwindow.hpp" #include "settingswindow.hpp" #include "confirmationdialog.hpp" #include "alchemywindow.hpp" @@ -46,6 +47,9 @@ #include "loadingscreen.hpp" #include "levelupdialog.hpp" #include "waitdialog.hpp" +#include "spellcreationdialog.hpp" +#include "enchantingdialog.hpp" +#include "trainingwindow.hpp" using namespace MWGui; @@ -67,6 +71,7 @@ WindowManager::WindowManager( , mCountDialog(NULL) , mTradeWindow(NULL) , mSpellBuyingWindow(NULL) + , mTravelWindow(NULL) , mSettingsWindow(NULL) , mConfirmationDialog(NULL) , mAlchemyWindow(NULL) @@ -75,7 +80,9 @@ WindowManager::WindowManager( , mCharGen(NULL) , mLevelupDialog(NULL) , mWaitDialog(NULL) - , mPlayerClass() + , mSpellCreationDialog(NULL) + , mEnchantingDialog(NULL) + , mTrainingWindow(NULL) , mPlayerName() , mPlayerRaceId() , mPlayerAttributes() @@ -141,6 +148,7 @@ WindowManager::WindowManager( mInventoryWindow = new InventoryWindow(*this,mDragAndDrop); mTradeWindow = new TradeWindow(*this); mSpellBuyingWindow = new SpellBuyingWindow(*this); + mTravelWindow = new TravelWindow(*this); mDialogueWindow = new DialogueWindow(*this); mContainerWindow = new ContainerWindow(*this,mDragAndDrop); mHud = new HUD(w,h, mShowFPSLevel, mDragAndDrop); @@ -155,6 +163,9 @@ WindowManager::WindowManager( mQuickKeysMenu = new QuickKeysMenu(*this); mLevelupDialog = new LevelupDialog(*this); mWaitDialog = new WaitDialog(*this); + mSpellCreationDialog = new SpellCreationDialog(*this); + mEnchantingDialog = new EnchantingDialog(*this); + mTrainingWindow = new TrainingWindow(*this); mLoadingScreen = new LoadingScreen(mOgre->getScene (), mOgre->getWindow (), *this); mLoadingScreen->onResChange (w,h); @@ -203,6 +214,7 @@ WindowManager::~WindowManager() delete mScrollWindow; delete mTradeWindow; delete mSpellBuyingWindow; + delete mTravelWindow; delete mSettingsWindow; delete mConfirmationDialog; delete mAlchemyWindow; @@ -210,6 +222,9 @@ WindowManager::~WindowManager() delete mLoadingScreen; delete mLevelupDialog; delete mWaitDialog; + delete mSpellCreationDialog; + delete mEnchantingDialog; + delete mTrainingWindow; cleanupGarbage(); @@ -253,12 +268,16 @@ void WindowManager::updateVisible() mBookWindow->setVisible(false); mTradeWindow->setVisible(false); mSpellBuyingWindow->setVisible(false); + mTravelWindow->setVisible(false); mSettingsWindow->setVisible(false); mAlchemyWindow->setVisible(false); mSpellWindow->setVisible(false); mQuickKeysMenu->setVisible(false); mLevelupDialog->setVisible(false); mWaitDialog->setVisible(false); + mSpellCreationDialog->setVisible(false); + mEnchantingDialog->setVisible(false); + mTrainingWindow->setVisible(false); mHud->setVisible(true); @@ -359,6 +378,18 @@ void WindowManager::updateVisible() case GM_SpellBuying: mSpellBuyingWindow->setVisible(true); break; + case GM_Travel: + mTravelWindow->setVisible(true); + break; + case GM_SpellCreation: + mSpellCreationDialog->setVisible(true); + break; + case GM_Enchanting: + mEnchantingDialog->setVisible(true); + break; + case GM_Training: + mTrainingWindow->setVisible(true); + break; case GM_InterMessageBox: break; case GM_Journal: @@ -471,8 +502,7 @@ void WindowManager::setValue (const std::string& id, int value) void WindowManager::setPlayerClass (const ESM::Class &class_) { - mPlayerClass = class_; - mStatsWindow->setValue("class", mPlayerClass.mName); + mStatsWindow->setValue("class", class_.mName); } void WindowManager::configureSkills (const SkillList& major, const SkillList& minor) @@ -526,7 +556,9 @@ int WindowManager::readPressedButton () std::string WindowManager::getGameSettingString(const std::string &id, const std::string &default_) { - const ESM::GameSetting *setting = MWBase::Environment::get().getWorld()->getStore().gameSettings.search(id); + const ESM::GameSetting *setting = + MWBase::Environment::get().getWorld()->getStore().get().search(id); + if (setting && setting->mType == ESM::VT_String) return setting->getString(); return default_; @@ -554,6 +586,8 @@ void WindowManager::onFrame (float frameDuration) mDragAndDrop->mDraggedWidget->setPosition(MyGUI::InputManager::getInstance().getMousePosition()); } + mDialogueWindow->onFrame(); + mInventoryWindow->onFrame(); mStatsWindow->onFrame(); @@ -562,46 +596,54 @@ void WindowManager::onFrame (float frameDuration) mHud->onFrame(frameDuration); + mTrainingWindow->onFrame (frameDuration); + + mTrainingWindow->checkReferenceAvailable(); mDialogueWindow->checkReferenceAvailable(); mTradeWindow->checkReferenceAvailable(); mSpellBuyingWindow->checkReferenceAvailable(); + mSpellCreationDialog->checkReferenceAvailable(); + mEnchantingDialog->checkReferenceAvailable(); mContainerWindow->checkReferenceAvailable(); mConsole->checkReferenceAvailable(); } void WindowManager::changeCell(MWWorld::Ptr::CellStore* cell) { - if (!(cell->cell->mData.mFlags & ESM::Cell::Interior)) + if (cell->mCell->isExterior()) { std::string name; - if (cell->cell->mName != "") + if (cell->mCell->mName != "") { - name = cell->cell->mName; - mMap->addVisitedLocation (name, cell->cell->getGridX (), cell->cell->getGridY ()); + name = cell->mCell->mName; + mMap->addVisitedLocation (name, cell->mCell->getGridX (), cell->mCell->getGridY ()); } else { - const ESM::Region* region = MWBase::Environment::get().getWorld()->getStore().regions.search(cell->cell->mRegion); + const ESM::Region* region = + MWBase::Environment::get().getWorld()->getStore().get().search(cell->mCell->mRegion); if (region) name = region->mName; else name = getGameSettingString("sDefaultCellname", "Wilderness"); } + mMap->cellExplored(cell->mCell->getGridX(), cell->mCell->getGridY()); + mMap->setCellName( name ); mHud->setCellName( name ); mMap->setCellPrefix("Cell"); mHud->setCellPrefix("Cell"); - mMap->setActiveCell( cell->cell->mData.mX, cell->cell->mData.mY ); - mHud->setActiveCell( cell->cell->mData.mX, cell->cell->mData.mY ); + mMap->setActiveCell( cell->mCell->getGridX(), cell->mCell->getGridY() ); + mHud->setActiveCell( cell->mCell->getGridX(), cell->mCell->getGridY() ); } else { - mMap->setCellName( cell->cell->mName ); - mHud->setCellName( cell->cell->mName ); - mMap->setCellPrefix( cell->cell->mName ); - mHud->setCellPrefix( cell->cell->mName ); + mMap->setCellName( cell->mCell->mName ); + mHud->setCellName( cell->mCell->mName ); + mMap->setCellPrefix( cell->mCell->mName ); + mHud->setCellPrefix( cell->mCell->mName ); } } @@ -684,7 +726,9 @@ void WindowManager::setDragDrop(bool dragDrop) void WindowManager::onRetrieveTag(const MyGUI::UString& _tag, MyGUI::UString& _result) { - const ESM::GameSetting *setting = MWBase::Environment::get().getWorld()->getStore().gameSettings.find(_tag); + const ESM::GameSetting *setting = + MWBase::Environment::get().getWorld()->getStore().get().find(_tag); + if (setting && setting->mType == ESM::VT_String) _result = setting->getString(); else @@ -736,6 +780,13 @@ void WindowManager::pushGuiMode(GuiMode mode) if (mode==GM_Inventory && mAllowed==GW_None) return; + + // 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)); + } + mGuiModes.push_back(mode); bool gameMode = !isGuiMode(); @@ -775,7 +826,10 @@ void WindowManager::removeGuiMode(GuiMode mode) void WindowManager::setSelectedSpell(const std::string& spellId, int successChancePercent) { mHud->setSelectedSpell(spellId, successChancePercent); - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(spellId); + + const ESM::Spell* spell = + MWBase::Environment::get().getWorld()->getStore().get().find(spellId); + mSpellWindow->setTitle(spell->mName); } @@ -848,6 +902,7 @@ MWGui::CountDialog* WindowManager::getCountDialog() { return mCountDialog; } MWGui::ConfirmationDialog* WindowManager::getConfirmationDialog() { return mConfirmationDialog; } MWGui::TradeWindow* WindowManager::getTradeWindow() { return mTradeWindow; } MWGui::SpellBuyingWindow* WindowManager::getSpellBuyingWindow() { return mSpellBuyingWindow; } +MWGui::TravelWindow* WindowManager::getTravelWindow() { return mTravelWindow; } MWGui::SpellWindow* WindowManager::getSpellWindow() { return mSpellWindow; } MWGui::Console* WindowManager::getConsole() { return mConsole; } @@ -969,3 +1024,18 @@ void WindowManager::addVisitedLocation(const std::string& name, int x, int y) { mMap->addVisitedLocation (name, x, y); } + +void WindowManager::startSpellMaking(MWWorld::Ptr actor) +{ + mSpellCreationDialog->startSpellMaking (actor); +} + +void WindowManager::startEnchanting (MWWorld::Ptr actor) +{ + mEnchantingDialog->startEnchanting (actor); +} + +void WindowManager::startTraining(MWWorld::Ptr actor) +{ + mTrainingWindow->startTraining(actor); +} diff --git a/apps/openmw/mwgui/windowmanagerimp.hpp b/apps/openmw/mwgui/windowmanagerimp.hpp index f67559ccd..2e684b5da 100644 --- a/apps/openmw/mwgui/windowmanagerimp.hpp +++ b/apps/openmw/mwgui/windowmanagerimp.hpp @@ -64,6 +64,9 @@ namespace MWGui class LoadingScreen; class LevelupDialog; class WaitDialog; + class SpellCreationDialog; + class EnchantingDialog; + class TrainingWindow; class WindowManager : public MWBase::WindowManager { @@ -111,6 +114,7 @@ namespace MWGui virtual MWGui::ConfirmationDialog* getConfirmationDialog(); virtual MWGui::TradeWindow* getTradeWindow(); virtual MWGui::SpellBuyingWindow* getSpellBuyingWindow(); + virtual MWGui::TravelWindow* getTravelWindow(); virtual MWGui::SpellWindow* getSpellWindow(); virtual MWGui::Console* getConsole(); @@ -211,6 +215,10 @@ namespace MWGui virtual bool getPlayerSleeping(); virtual void wakeUpPlayer(); + virtual void startSpellMaking(MWWorld::Ptr actor); + virtual void startEnchanting(MWWorld::Ptr actor); + virtual void startTraining(MWWorld::Ptr actor); + private: OEngine::GUI::MyGUIManager *mGuiManager; HUD *mHud; @@ -230,6 +238,7 @@ namespace MWGui CountDialog* mCountDialog; TradeWindow* mTradeWindow; SpellBuyingWindow* mSpellBuyingWindow; + TravelWindow* mTravelWindow; SettingsWindow* mSettingsWindow; ConfirmationDialog* mConfirmationDialog; AlchemyWindow* mAlchemyWindow; @@ -238,6 +247,9 @@ namespace MWGui LoadingScreen* mLoadingScreen; LevelupDialog* mLevelupDialog; WaitDialog* mWaitDialog; + SpellCreationDialog* mSpellCreationDialog; + EnchantingDialog* mEnchantingDialog; + TrainingWindow* mTrainingWindow; CharacterCreation* mCharGen; @@ -249,7 +261,6 @@ namespace MWGui /// \todo get rid of this stuff. Move it to the respective UI element classes, if needed. // Various stats about player as needed by window manager - ESM::Class mPlayerClass; std::string mPlayerName; std::string mPlayerRaceId; std::map > mPlayerAttributes; diff --git a/apps/openmw/mwinput/inputmanagerimp.cpp b/apps/openmw/mwinput/inputmanagerimp.cpp index c3e131440..af30c9b04 100644 --- a/apps/openmw/mwinput/inputmanagerimp.cpp +++ b/apps/openmw/mwinput/inputmanagerimp.cpp @@ -9,7 +9,7 @@ #include -#include +#include #include #include diff --git a/apps/openmw/mwinput/inputmanagerimp.hpp b/apps/openmw/mwinput/inputmanagerimp.hpp index 5e6169f68..718d6b76f 100644 --- a/apps/openmw/mwinput/inputmanagerimp.hpp +++ b/apps/openmw/mwinput/inputmanagerimp.hpp @@ -42,8 +42,8 @@ namespace OIS class InputManager; } -#include -#include +#include +#include #include #include diff --git a/apps/openmw/mwmechanics/activespells.cpp b/apps/openmw/mwmechanics/activespells.cpp index df5ea7c3f..989bdedd7 100644 --- a/apps/openmw/mwmechanics/activespells.cpp +++ b/apps/openmw/mwmechanics/activespells.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -86,7 +86,7 @@ namespace MWMechanics if (effects.second) { const ESM::MagicEffect *magicEffect = - MWBase::Environment::get().getWorld()->getStore().magicEffects.find ( + MWBase::Environment::get().getWorld()->getStore().get().find ( iter->mEffectID); if (iter->mDuration==0) @@ -114,18 +114,18 @@ namespace MWMechanics std::pair ActiveSpells::getEffectList (const std::string& id) const { if (const ESM::Spell *spell = - MWBase::Environment::get().getWorld()->getStore().spells.search (id)) + MWBase::Environment::get().getWorld()->getStore().get().search (id)) return std::make_pair (spell->mEffects, false); if (const ESM::Potion *potion = - MWBase::Environment::get().getWorld()->getStore().potions.search (id)) + MWBase::Environment::get().getWorld()->getStore().get().search (id)) return std::make_pair (potion->mEffects, false); if (const ESM::Ingredient *ingredient = - MWBase::Environment::get().getWorld()->getStore().ingreds.search (id)) + MWBase::Environment::get().getWorld()->getStore().get().search (id)) { const ESM::MagicEffect *magicEffect = - MWBase::Environment::get().getWorld()->getStore().magicEffects.find ( + MWBase::Environment::get().getWorld()->getStore().get().find ( ingredient->mData.mEffectID[0]); ESM::ENAMstruct effect; diff --git a/apps/openmw/mwmechanics/actors.cpp b/apps/openmw/mwmechanics/actors.cpp index 87a058394..d541baea9 100644 --- a/apps/openmw/mwmechanics/actors.cpp +++ b/apps/openmw/mwmechanics/actors.cpp @@ -7,7 +7,7 @@ #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwworld/class.hpp" #include "../mwworld/inventorystore.hpp" @@ -24,8 +24,8 @@ namespace MWMechanics { // magic effects adjustMagicEffects (ptr); - calculateCreatureStatModifiers (ptr); calculateDynamicStats (ptr); + calculateCreatureStatModifiers (ptr); // AI CreatureStats& creatureStats = MWWorld::Class::get (ptr).getCreatureStats (ptr); @@ -73,13 +73,17 @@ namespace MWMechanics double magickaFactor = creatureStats.getMagicEffects().get (EffectKey (84)).mMagnitude * 0.1 + 0.5; - creatureStats.getHealth().setBase( - static_cast (0.5 * (strength + endurance)) + creatureStats.getLevelHealthBonus ()); + DynamicStat health = creatureStats.getHealth(); + health.setBase (static_cast (0.5 * (strength + endurance)) + creatureStats.getLevelHealthBonus ()); + creatureStats.setHealth (health); - creatureStats.getMagicka().setBase( - static_cast (intelligence + magickaFactor * intelligence)); - - creatureStats.getFatigue().setBase(strength+willpower+agility+endurance); + DynamicStat magicka = creatureStats.getMagicka(); + magicka.setBase (static_cast (intelligence + magickaFactor * intelligence)); + creatureStats.setMagicka (magicka); + + DynamicStat fatigue = creatureStats.getFatigue(); + fatigue.setBase (strength+willpower+agility+endurance); + creatureStats.setFatigue (fatigue); } void Actors::calculateRestoration (const MWWorld::Ptr& ptr, float duration) @@ -92,14 +96,16 @@ namespace MWMechanics bool stunted = stats.getMagicEffects ().get(MWMechanics::EffectKey(136)).mMagnitude > 0; int endurance = stats.getAttribute (ESM::Attribute::Endurance).getModified (); - stats.getHealth().setCurrent(stats.getHealth ().getCurrent () - + 0.1 * endurance); + + DynamicStat health = stats.getHealth(); + health.setCurrent (health.getCurrent() + 0.1 * endurance); + stats.setHealth (health); - const ESMS::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); + const MWWorld::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); - float fFatigueReturnBase = store.gameSettings.find("fFatigueReturnBase")->getFloat (); - float fFatigueReturnMult = store.gameSettings.find("fFatigueReturnMult")->getFloat (); - float fEndFatigueMult = store.gameSettings.find("fEndFatigueMult")->getFloat (); + float fFatigueReturnBase = store.get().find("fFatigueReturnBase")->getFloat (); + float fFatigueReturnMult = store.get().find("fFatigueReturnMult")->getFloat (); + float fEndFatigueMult = store.get().find("fEndFatigueMult")->getFloat (); float capacity = MWWorld::Class::get(ptr).getCapacity(ptr); float encumbrance = MWWorld::Class::get(ptr).getEncumbrance(ptr); @@ -109,27 +115,29 @@ namespace MWMechanics float x = fFatigueReturnBase + fFatigueReturnMult * (1 - normalizedEncumbrance); x *= fEndFatigueMult * endurance; - stats.getFatigue ().setCurrent (stats.getFatigue ().getCurrent () + 3600 * x); - + + DynamicStat fatigue = stats.getFatigue(); + fatigue.setCurrent (fatigue.getCurrent() + 3600 * x); + stats.setFatigue (fatigue); + if (!stunted) { - float fRestMagicMult = store.gameSettings.find("fRestMagicMult")->getFloat (); - stats.getMagicka().setCurrent (stats.getMagicka ().getCurrent () - + fRestMagicMult * stats.getAttribute(ESM::Attribute::Intelligence).getModified ()); + float fRestMagicMult = store.get().find("fRestMagicMult")->getFloat (); + + DynamicStat magicka = stats.getMagicka(); + magicka.setCurrent (magicka.getCurrent() + + fRestMagicMult * stats.getAttribute(ESM::Attribute::Intelligence).getModified()); + stats.setMagicka (magicka); } } - - - } - void Actors::calculateCreatureStatModifiers (const MWWorld::Ptr& ptr) { CreatureStats& creatureStats = MWWorld::Class::get (ptr).getCreatureStats (ptr); // attributes - for (int i=0; i<5; ++i) + for (int i=0; i<8; ++i) { int modifier = creatureStats.getMagicEffects().get (EffectKey (79, i)).mMagnitude; @@ -141,21 +149,26 @@ namespace MWMechanics // dynamic stats MagicEffects effects = creatureStats.getMagicEffects(); - creatureStats.getHealth().setModifier( - effects.get(EffectKey(80)).mMagnitude - effects.get(EffectKey(18)).mMagnitude); - - creatureStats.getMagicka().setModifier( - effects.get(EffectKey(81)).mMagnitude - effects.get(EffectKey(19)).mMagnitude); - - creatureStats.getFatigue().setModifier( - effects.get(EffectKey(82)).mMagnitude - effects.get(EffectKey(20)).mMagnitude); + + for (int i=0; i<3; ++i) + { + DynamicStat stat = creatureStats.getDynamic (i); + + stat.setModifier ( + effects.get (EffectKey(80+i)).mMagnitude - effects.get (EffectKey(18+i)).mMagnitude); + + creatureStats.setDynamic (i, stat); + } } Actors::Actors() : mDuration (0) {} void Actors::addActor (const MWWorld::Ptr& ptr) { - mActors.insert (ptr); + if (!MWWorld::Class::get (ptr).getCreatureStats (ptr).isDead()) + mActors.insert (ptr); + else + MWBase::Environment::get().getWorld()->playAnimationGroup (ptr, "death1", 2); } void Actors::removeActor (const MWWorld::Ptr& ptr) @@ -188,13 +201,51 @@ namespace MWMechanics { float totalDuration = mDuration; mDuration = 0; + + std::set::iterator iter (mActors.begin()); - for (std::set::iterator iter (mActors.begin()); iter!=mActors.end(); ++iter) + while (iter!=mActors.end()) { - updateActor (*iter, totalDuration); + if (!MWWorld::Class::get (*iter).getCreatureStats (*iter).isDead()) + { + updateActor (*iter, totalDuration); - if (iter->getTypeName()==typeid (ESM::NPC).name()) - updateNpc (*iter, totalDuration, paused); + if (iter->getTypeName()==typeid (ESM::NPC).name()) + updateNpc (*iter, totalDuration, paused); + } + + if (MWWorld::Class::get (*iter).getCreatureStats (*iter).isDead()) + { + // workaround: always keep player alive for now + // \todo remove workaround, once player death can be handled + if (iter->getRefData().getHandle()=="player") + { + MWMechanics::DynamicStat stat ( + MWWorld::Class::get (*iter).getCreatureStats (*iter).getHealth()); + + if (stat.getModified()<1) + { + stat.setModified (1, 0); + MWWorld::Class::get (*iter).getCreatureStats (*iter).setHealth (stat); + } + + MWWorld::Class::get (*iter).getCreatureStats (*iter).resurrect(); + ++iter; + continue; + } + + ++mDeathCount[MWWorld::Class::get (*iter).getId (*iter)]; + + MWBase::Environment::get().getWorld()->playAnimationGroup (*iter, "death1", 0); + + if (MWWorld::Class::get (*iter).isEssential (*iter)) + MWBase::Environment::get().getWindowManager()->messageBox ( + "#{sKilledEssential}", std::vector()); + + mActors.erase (iter++); + } + else + ++iter; } } @@ -215,4 +266,14 @@ namespace MWMechanics calculateRestoration (*iter, 3600); } } + + int Actors::countDeaths (const std::string& id) const + { + std::map::const_iterator iter = mDeathCount.find (id); + + if (iter!=mDeathCount.end()) + return iter->second; + + return 0; + } } diff --git a/apps/openmw/mwmechanics/actors.hpp b/apps/openmw/mwmechanics/actors.hpp index 7e5a0ac86..79ae16fc3 100644 --- a/apps/openmw/mwmechanics/actors.hpp +++ b/apps/openmw/mwmechanics/actors.hpp @@ -4,6 +4,7 @@ #include #include #include +#include namespace Ogre { @@ -22,6 +23,7 @@ namespace MWMechanics { std::set mActors; float mDuration; + std::map mDeathCount; void updateNpc (const MWWorld::Ptr& ptr, float duration, bool paused); @@ -40,6 +42,8 @@ namespace MWMechanics void addActor (const MWWorld::Ptr& ptr); ///< Register an actor for stats management + /// + /// \note Dead actors are ignored. void removeActor (const MWWorld::Ptr& ptr); ///< Deregister an actor for stats management @@ -59,6 +63,9 @@ namespace MWMechanics void restoreDynamicStats(); ///< If the player is sleeping, this should be called every hour. + + int countDeaths (const std::string& id) const; + ///< Return the number of deaths for actors with the given ID. }; } diff --git a/apps/openmw/mwmechanics/aiactivate.cpp b/apps/openmw/mwmechanics/aiactivate.cpp new file mode 100644 index 000000000..b94c8c259 --- /dev/null +++ b/apps/openmw/mwmechanics/aiactivate.cpp @@ -0,0 +1,21 @@ +#include "aiactivate.hpp" +#include + +MWMechanics::AiActivate::AiActivate(const std::string &objectId) +: mObjectId(objectId) +{ +} +MWMechanics::AiActivate *MWMechanics::AiActivate::clone() const +{ + return new AiActivate(*this); +} +bool MWMechanics::AiActivate::execute (const MWWorld::Ptr& actor) +{ + std::cout << "AiActivate completed.\n"; + return true; +} + +int MWMechanics::AiActivate::getTypeId() const +{ + return 4; +} diff --git a/apps/openmw/mwmechanics/aiactivate.hpp b/apps/openmw/mwmechanics/aiactivate.hpp new file mode 100644 index 000000000..7f3d4016d --- /dev/null +++ b/apps/openmw/mwmechanics/aiactivate.hpp @@ -0,0 +1,23 @@ +#ifndef GAME_MWMECHANICS_AIACTIVATE_H +#define GAME_MWMECHANICS_AIACTIVATE_H + +#include "aipackage.hpp" +#include + +namespace MWMechanics +{ + + class AiActivate : public AiPackage + { + public: + AiActivate(const std::string &objectId); + virtual AiActivate *clone() const; + virtual bool execute (const MWWorld::Ptr& actor); + ///< \return Package completed? + virtual int getTypeId() const; + + private: + std::string mObjectId; + }; +} +#endif // GAME_MWMECHANICS_AIACTIVATE_H diff --git a/apps/openmw/mwmechanics/aiescort.cpp b/apps/openmw/mwmechanics/aiescort.cpp new file mode 100644 index 000000000..27cd9095d --- /dev/null +++ b/apps/openmw/mwmechanics/aiescort.cpp @@ -0,0 +1,24 @@ +#include "aiescort.hpp" +#include + +MWMechanics::AiEscort::AiEscort(const std::string &actorId,int duration, float x, float y, float z) +: mActorId(actorId), mX(x), mY(y), mZ(z), mDuration(duration) +{ +} + +MWMechanics::AiEscort *MWMechanics::AiEscort::clone() const +{ + return new AiEscort(*this); +} + +bool MWMechanics::AiEscort::execute (const MWWorld::Ptr& actor) +{ + std::cout << "AiEscort completed. \n"; + return true; +} + +int MWMechanics::AiEscort::getTypeId() const +{ + return 2; +} + diff --git a/apps/openmw/mwmechanics/aiescort.hpp b/apps/openmw/mwmechanics/aiescort.hpp new file mode 100644 index 000000000..fef70f508 --- /dev/null +++ b/apps/openmw/mwmechanics/aiescort.hpp @@ -0,0 +1,29 @@ +#ifndef GAME_MWMECHANICS_AIESCORT_H +#define GAME_MWMECHANICS_AIESCORT_H + +#include "aipackage.hpp" +#include + +namespace MWMechanics +{ + class AiEscort : public AiPackage + { + public: + AiEscort(const std::string &actorId,int duration, float x, float y, float z); + virtual AiEscort *clone() const; + + virtual bool execute (const MWWorld::Ptr& actor); + ///< \return Package completed? + + virtual int getTypeId() const; + + private: + std::string mActorId; + float mX; + float mY; + float mZ; + int mDuration; + + }; +} +#endif diff --git a/apps/openmw/mwmechanics/aifollow.cpp b/apps/openmw/mwmechanics/aifollow.cpp new file mode 100644 index 000000000..3fee6d98c --- /dev/null +++ b/apps/openmw/mwmechanics/aifollow.cpp @@ -0,0 +1,22 @@ +#include "aifollow.hpp" +#include + +MWMechanics::AiFollow::AiFollow(const std::string &actorId,float duration, float x, float y, float z) +: mDuration(duration), mX(x), mY(y), mZ(z), mActorId(actorId) +{ +} +MWMechanics::AiFollow *MWMechanics::AiFollow::clone() const +{ + return new AiFollow(*this); +} + + bool MWMechanics::AiFollow::execute (const MWWorld::Ptr& actor) +{ + std::cout << "AiFollow completed.\n"; + return true; +} + + int MWMechanics::AiFollow::getTypeId() const +{ + return 3; +} diff --git a/apps/openmw/mwmechanics/aifollow.hpp b/apps/openmw/mwmechanics/aifollow.hpp new file mode 100644 index 000000000..ded13d780 --- /dev/null +++ b/apps/openmw/mwmechanics/aifollow.hpp @@ -0,0 +1,27 @@ +#ifndef GAME_MWMECHANICS_AIFALLOW_H +#define GAME_MWMECHANICS_AIFALLOW_H + +#include "aipackage.hpp" +#include + +namespace MWMechanics +{ + + class AiFollow : public AiPackage + { + public: + AiFollow(const std::string &ActorId,float duration, float X, float Y, float Z); + virtual AiFollow *clone() const; + virtual bool execute (const MWWorld::Ptr& actor); + ///< \return Package completed? + virtual int getTypeId() const; + + private: + float mDuration; + float mX; + float mY; + float mZ; + std::string mActorId; + }; +} +#endif diff --git a/apps/openmw/mwmechanics/aitravel.cpp b/apps/openmw/mwmechanics/aitravel.cpp new file mode 100644 index 000000000..897dd1748 --- /dev/null +++ b/apps/openmw/mwmechanics/aitravel.cpp @@ -0,0 +1,25 @@ +#include "aitravel.hpp" +#include + +MWMechanics::AiTravel::AiTravel(float x, float y, float z) +: mX(x),mY(y),mZ(z) +{ +} + +MWMechanics::AiTravel * MWMechanics::AiTravel::clone() const +{ + return new AiTravel(*this); +} + +bool MWMechanics::AiTravel::execute (const MWWorld::Ptr& actor) +{ + std::cout << "AiTravel completed.\n"; + return true; +} + +int MWMechanics::AiTravel::getTypeId() const +{ + return 1; +} + + diff --git a/apps/openmw/mwmechanics/aitravel.hpp b/apps/openmw/mwmechanics/aitravel.hpp new file mode 100644 index 000000000..1c6abbf27 --- /dev/null +++ b/apps/openmw/mwmechanics/aitravel.hpp @@ -0,0 +1,27 @@ +#ifndef GAME_MWMECHANICS_AITRAVEL_H +#define GAME_MWMECHANICS_AITRAVEL_H + +#include "aipackage.hpp" + +namespace MWMechanics +{ + class AiTravel : public AiPackage + { + public: + AiTravel(float x, float y, float z); + virtual AiTravel *clone() const; + + virtual bool execute (const MWWorld::Ptr& actor); + ///< \return Package completed? + + virtual int getTypeId() const; + + private: + float mX; + float mY; + float mZ; + + }; +} + +#endif diff --git a/apps/openmw/mwmechanics/aiwander.cpp b/apps/openmw/mwmechanics/aiwander.cpp new file mode 100644 index 000000000..e9db6d212 --- /dev/null +++ b/apps/openmw/mwmechanics/aiwander.cpp @@ -0,0 +1,23 @@ +#include "aiwander.hpp" +#include + +MWMechanics::AiWander::AiWander(int distance, int duration, int timeOfDay, const std::vector& idle): + mDistance(distance), mDuration(duration), mTimeOfDay(timeOfDay), mIdle(idle) +{ +} + +MWMechanics::AiPackage * MWMechanics::AiWander::clone() const +{ + return new AiWander(*this); +} + +bool MWMechanics::AiWander::execute (const MWWorld::Ptr& actor) +{ + std::cout << "AiWadner completed.\n"; + return true; +} + +int MWMechanics::AiWander::getTypeId() const +{ + return 0; +} diff --git a/apps/openmw/mwmechanics/aiwander.hpp b/apps/openmw/mwmechanics/aiwander.hpp new file mode 100644 index 000000000..a71858feb --- /dev/null +++ b/apps/openmw/mwmechanics/aiwander.hpp @@ -0,0 +1,29 @@ +#ifndef GAME_MWMECHANICS_AIWANDER_H +#define GAME_MWMECHANICS_AIWANDER_H + +#include "aipackage.hpp" +#include + +namespace MWMechanics +{ + + class AiWander : public AiPackage + { + public: + + AiWander(int distance, int duration, int timeOfDay, const std::vector& idle); + virtual AiPackage *clone() const; + virtual bool execute (const MWWorld::Ptr& actor); + ///< \return Package completed? + virtual int getTypeId() const; + ///< 0: Wander + + private: + int mDistance; + int mDuration; + int mTimeOfDay; + std::vector mIdle; + }; + } + +#endif diff --git a/apps/openmw/mwmechanics/alchemy.cpp b/apps/openmw/mwmechanics/alchemy.cpp new file mode 100644 index 000000000..c07c60209 --- /dev/null +++ b/apps/openmw/mwmechanics/alchemy.cpp @@ -0,0 +1,458 @@ + +#include "alchemy.hpp" + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + + +#include "../mwbase/environment.hpp" +#include "../mwbase/world.hpp" + +#include "../mwworld/esmstore.hpp" +#include "../mwworld/containerstore.hpp" +#include "../mwworld/class.hpp" +#include "../mwworld/cellstore.hpp" +#include "../mwworld/manualref.hpp" + +#include "magiceffects.hpp" +#include "creaturestats.hpp" +#include "npcstats.hpp" + +std::set MWMechanics::Alchemy::listEffects() const +{ + std::map effects; + + for (TIngredientsIterator iter (mIngredients.begin()); iter!=mIngredients.end(); ++iter) + { + if (!iter->isEmpty()) + { + const MWWorld::LiveCellRef *ingredient = iter->get(); + + for (int i=0; i<4; ++i) + if (ingredient->mBase->mData.mEffectID[i]!=-1) + { + EffectKey key ( + ingredient->mBase->mData.mEffectID[i], ingredient->mBase->mData.mSkills[i]!=-1 ? + ingredient->mBase->mData.mSkills[i] : ingredient->mBase->mData.mAttributes[i]); + + ++effects[key]; + } + } + } + + std::set effects2; + + for (std::map::const_iterator iter (effects.begin()); iter!=effects.end(); ++iter) + if (iter->second>1) + effects2.insert (iter->first); + + return effects2; +} + +void MWMechanics::Alchemy::applyTools (int flags, float& value) const +{ + bool magnitude = !(flags & ESM::MagicEffect::NoMagnitude); + bool duration = !(flags & ESM::MagicEffect::NoDuration); + bool negative = flags & (ESM::MagicEffect::Negative | ESM::MagicEffect::Harmful); + + int tool = negative ? ESM::Apparatus::Retort : ESM::Apparatus::Albemic; + + int setup = 0; + + if (!mTools[tool].isEmpty() && !mTools[ESM::Apparatus::Calcinator].isEmpty()) + setup = 1; + else if (!mTools[tool].isEmpty()) + setup = 2; + else if (!mTools[ESM::Apparatus::Calcinator].isEmpty()) + setup = 3; + else + return; + + float toolQuality = setup==1 || setup==2 ? mTools[tool].get()->mBase->mData.mQuality : 0; + float calcinatorQuality = setup==1 || setup==3 ? + mTools[ESM::Apparatus::Calcinator].get()->mBase->mData.mQuality : 0; + + float quality = 1; + + switch (setup) + { + case 1: + + quality = negative ? 2 * toolQuality + 3 * calcinatorQuality : + (magnitude && duration ? + 2 * toolQuality + calcinatorQuality : 2/3.0 * (toolQuality + calcinatorQuality) + 0.5); + break; + + case 2: + + quality = negative ? 1+toolQuality : (magnitude && duration ? toolQuality : toolQuality + 0.5); + break; + + case 3: + + quality = magnitude && duration ? calcinatorQuality : calcinatorQuality + 0.5; + break; + } + + if (setup==3 || !negative) + { + value += quality; + } + else + { + if (quality==0) + throw std::runtime_error ("invalid derived alchemy apparatus quality"); + + value /= quality; + } +} + +void MWMechanics::Alchemy::updateEffects() +{ + mEffects.clear(); + mValue = 0; + + if (countIngredients()<2 || mAlchemist.isEmpty() || mTools[ESM::Apparatus::MortarPestle].isEmpty()) + return; + + // find effects + std::set effects (listEffects()); + + // general alchemy factor + float x = getChance(); + + x *= mTools[ESM::Apparatus::MortarPestle].get()->mBase->mData.mQuality; + x *= MWBase::Environment::get().getWorld()->getStore().get().find ("fPotionStrengthMult")->getFloat(); + + // value + mValue = static_cast ( + x * MWBase::Environment::get().getWorld()->getStore().get().find ("iAlchemyMod")->getFloat()); + + // build quantified effect list + for (std::set::const_iterator iter (effects.begin()); iter!=effects.end(); ++iter) + { + const ESM::MagicEffect *magicEffect = + MWBase::Environment::get().getWorld()->getStore().get().find (iter->mId); + + if (magicEffect->mData.mBaseCost<=0) + throw std::runtime_error ("invalid base cost for magic effect " + iter->mId); + + float fPotionT1MagMul = + MWBase::Environment::get().getWorld()->getStore().get().find ("fPotionT1MagMult")->getFloat(); + + if (fPotionT1MagMul<=0) + throw std::runtime_error ("invalid gmst: fPotionT1MagMul"); + + float fPotionT1DurMult = + MWBase::Environment::get().getWorld()->getStore().get().find ("fPotionT1DurMult")->getFloat(); + + if (fPotionT1DurMult<=0) + throw std::runtime_error ("invalid gmst: fPotionT1DurMult"); + + float magnitude = magicEffect->mData.mFlags & ESM::MagicEffect::NoMagnitude ? + 1 : (x / fPotionT1MagMul) / magicEffect->mData.mBaseCost; + float duration = magicEffect->mData.mFlags & ESM::MagicEffect::NoDuration ? + 1 : (x / fPotionT1DurMult) / magicEffect->mData.mBaseCost; + + if (!(magicEffect->mData.mFlags & ESM::MagicEffect::NoMagnitude)) + applyTools (magicEffect->mData.mFlags, magnitude); + + if (!(magicEffect->mData.mFlags & ESM::MagicEffect::NoDuration)) + applyTools (magicEffect->mData.mFlags, duration); + + duration = static_cast (duration+0.5); + magnitude = static_cast (magnitude+0.5); + + if (magnitude>0 && duration>0) + { + ESM::ENAMstruct effect; + effect.mEffectID = iter->mId; + + effect.mSkill = effect.mAttribute = iter->mArg; // somewhat hack-ish, but should work + + effect.mRange = 0; + effect.mArea = 0; + + effect.mDuration = duration; + effect.mMagnMin = effect.mMagnMax = magnitude; + + mEffects.push_back (effect); + } + } +} + +const ESM::Potion *MWMechanics::Alchemy::getRecord() const +{ + const MWWorld::Store &potions = + MWBase::Environment::get().getWorld()->getStore().get(); + + MWWorld::Store::iterator iter = potions.begin(); + for (; iter != potions.end(); ++iter) + { + if (iter->mEffects.mList.size() != mEffects.size()) + continue; + + bool mismatch = false; + + for (int i=0; i (iter->mEffects.mList.size()); ++iter) + { + const ESM::ENAMstruct& first = iter->mEffects.mList[i]; + const ESM::ENAMstruct& second = mEffects[i]; + + if (first.mEffectID!=second.mEffectID || + first.mArea!=second.mArea || + first.mRange!=second.mRange || + first.mSkill!=second.mSkill || + first.mAttribute!=second.mAttribute || + first.mMagnMin!=second.mMagnMin || + first.mMagnMax!=second.mMagnMax || + first.mDuration!=second.mDuration) + { + mismatch = true; + break; + } + } + + if (!mismatch) + return &(*iter); + } + + return 0; +} + +void MWMechanics::Alchemy::removeIngredients() +{ + bool needsUpdate = false; + + for (TIngredientsContainer::iterator iter (mIngredients.begin()); iter!=mIngredients.end(); ++iter) + if (!iter->isEmpty()) + { + iter->getRefData().setCount (iter->getRefData().getCount()-1); + if (iter->getRefData().getCount()<1) + { + needsUpdate = true; + *iter = MWWorld::Ptr(); + } + } + + if (needsUpdate) + updateEffects(); +} + +void MWMechanics::Alchemy::addPotion (const std::string& name) +{ + const ESM::Potion *record = getRecord(); + + if (!record) + { + ESM::Potion newRecord; + + newRecord.mData.mWeight = 0; + + for (TIngredientsIterator iter (beginIngredients()); iter!=endIngredients(); ++iter) + if (!iter->isEmpty()) + newRecord.mData.mWeight += iter->get()->mBase->mData.mWeight; + + newRecord.mData.mWeight /= countIngredients(); + + newRecord.mData.mValue = mValue; + newRecord.mData.mAutoCalc = 0; + + newRecord.mName = name; + + int index = static_cast (std::rand()/static_cast (RAND_MAX)*6); + assert (index>=0 && index<6); + + static const char *name[] = { "standard", "bargain", "cheap", "fresh", "exclusive", "quality" }; + + newRecord.mModel = "m\\misc_potion_" + std::string (name[index]) + "_01.nif"; + newRecord.mIcon = "m\\tx_potion_" + std::string (name[index]) + "_01.dds"; + + newRecord.mEffects.mList = mEffects; + + record = MWBase::Environment::get().getWorld()->createRecord (newRecord); + } + + MWWorld::ManualRef ref (MWBase::Environment::get().getWorld()->getStore(), record->mId); + MWWorld::Class::get (mAlchemist).getContainerStore (mAlchemist).add (ref.getPtr()); +} + +void MWMechanics::Alchemy::increaseSkill() +{ + MWWorld::Class::get (mAlchemist).skillUsageSucceeded (mAlchemist, ESM::Skill::Alchemy, 0); +} + +float MWMechanics::Alchemy::getChance() const +{ + const CreatureStats& creatureStats = MWWorld::Class::get (mAlchemist).getCreatureStats (mAlchemist); + const NpcStats& npcStats = MWWorld::Class::get (mAlchemist).getNpcStats (mAlchemist); + + return + (npcStats.getSkill (ESM::Skill::Alchemy).getModified() + + 0.1 * creatureStats.getAttribute (1).getModified() + + 0.1 * creatureStats.getAttribute (7).getModified()); +} + +int MWMechanics::Alchemy::countIngredients() const +{ + int ingredients = 0; + + for (TIngredientsIterator iter (beginIngredients()); iter!=endIngredients(); ++iter) + if (!iter->isEmpty()) + ++ingredients; + + return ingredients; +} + +void MWMechanics::Alchemy::setAlchemist (const MWWorld::Ptr& npc) +{ + mAlchemist = npc; + + mIngredients.resize (4); + + std::fill (mIngredients.begin(), mIngredients.end(), MWWorld::Ptr()); + + mTools.resize (4); + + std::fill (mTools.begin(), mTools.end(), MWWorld::Ptr()); + + mEffects.clear(); + + MWWorld::ContainerStore& store = MWWorld::Class::get (npc).getContainerStore (npc); + + for (MWWorld::ContainerStoreIterator iter (store.begin (MWWorld::ContainerStore::Type_Apparatus)); + iter!=store.end(); ++iter) + { + MWWorld::LiveCellRef* ref = iter->get(); + + int type = ref->mBase->mData.mType; + + if (type<0 || type>=static_cast (mTools.size())) + throw std::runtime_error ("invalid apparatus type"); + + if (!mTools[type].isEmpty()) + if (ref->mBase->mData.mQuality<=mTools[type].get()->mBase->mData.mQuality) + continue; + + mTools[type] = *iter; + } +} + +MWMechanics::Alchemy::TToolsIterator MWMechanics::Alchemy::beginTools() const +{ + return mTools.begin(); +} + +MWMechanics::Alchemy::TToolsIterator MWMechanics::Alchemy::endTools() const +{ + return mTools.end(); +} + +MWMechanics::Alchemy::TIngredientsIterator MWMechanics::Alchemy::beginIngredients() const +{ + return mIngredients.begin(); +} + +MWMechanics::Alchemy::TIngredientsIterator MWMechanics::Alchemy::endIngredients() const +{ + return mIngredients.end(); +} + +void MWMechanics::Alchemy::clear() +{ + mAlchemist = MWWorld::Ptr(); + mTools.clear(); + mIngredients.clear(); + mEffects.clear(); +} + +int MWMechanics::Alchemy::addIngredient (const MWWorld::Ptr& ingredient) +{ + // find a free slot + int slot = -1; + + for (int i=0; i (mIngredients.size()); ++i) + if (mIngredients[i].isEmpty()) + { + slot = i; + break; + } + + if (slot==-1) + return -1; + + for (TIngredientsIterator iter (mIngredients.begin()); iter!=mIngredients.end(); ++iter) + if (!iter->isEmpty() && ingredient.get()==iter->get()) + return -1; + + mIngredients[slot] = ingredient; + + updateEffects(); + + return slot; +} + +void MWMechanics::Alchemy::removeIngredient (int index) +{ + if (index>=0 && index (mIngredients.size())) + { + mIngredients[index] = MWWorld::Ptr(); + updateEffects(); + } +} + +MWMechanics::Alchemy::TEffectsIterator MWMechanics::Alchemy::beginEffects() const +{ + return mEffects.begin(); +} + +MWMechanics::Alchemy::TEffectsIterator MWMechanics::Alchemy::endEffects() const +{ + return mEffects.end(); +} + +std::string MWMechanics::Alchemy::getPotionName() const +{ + if (const ESM::Potion *potion = getRecord()) + return potion->mName; + + return ""; +} + +MWMechanics::Alchemy::Result MWMechanics::Alchemy::create (const std::string& name) +{ + if (mTools[ESM::Apparatus::MortarPestle].isEmpty()) + return Result_NoMortarAndPestle; + + if (countIngredients()<2) + return Result_LessThanTwoIngredients; + + if (name.empty() && getPotionName().empty()) + return Result_NoName; + + if (beginEffects()==endEffects()) + return Result_NoEffects; + + if (getChance() (RAND_MAX)*100) + { + removeIngredients(); + return Result_RandomFailure; + } + + addPotion (name); + + removeIngredients(); + + increaseSkill(); + + return Result_Success; +} diff --git a/apps/openmw/mwmechanics/alchemy.hpp b/apps/openmw/mwmechanics/alchemy.hpp new file mode 100644 index 000000000..957e3122c --- /dev/null +++ b/apps/openmw/mwmechanics/alchemy.hpp @@ -0,0 +1,118 @@ +#ifndef GAME_MWMECHANICS_ALCHEMY_H +#define GAME_MWMECHANICS_ALCHEMY_H + +#include +#include + +#include + +#include "../mwworld/ptr.hpp" + +namespace MWMechanics +{ + struct EffectKey; + + /// \brief Potion creation via alchemy skill + class Alchemy + { + public: + + typedef std::vector TToolsContainer; + typedef TToolsContainer::const_iterator TToolsIterator; + + typedef std::vector TIngredientsContainer; + typedef TIngredientsContainer::const_iterator TIngredientsIterator; + + typedef std::vector TEffectsContainer; + typedef TEffectsContainer::const_iterator TEffectsIterator; + + enum Result + { + Result_Success, + + Result_NoMortarAndPestle, + Result_LessThanTwoIngredients, + Result_NoName, + Result_NoEffects, + Result_RandomFailure + }; + + private: + + MWWorld::Ptr mAlchemist; + TToolsContainer mTools; + TIngredientsContainer mIngredients; + TEffectsContainer mEffects; + int mValue; + + std::set listEffects() const; + ///< List all effects shared by at least two ingredients. + + void applyTools (int flags, float& value) const; + + void updateEffects(); + + const ESM::Potion *getRecord() const; + ///< Return existing recrod for created potion (may return 0) + + void removeIngredients(); + ///< Remove selected ingredients from alchemist's inventory, cleanup selected ingredients and + /// update effect list accordingly. + + void addPotion (const std::string& name); + ///< Add a potion to the alchemist's inventory. + + void increaseSkill(); + ///< Increase alchemist's skill. + + float getChance() const; + ///< Return chance of success. + + int countIngredients() const; + + public: + + void setAlchemist (const MWWorld::Ptr& npc); + ///< Set alchemist and configure alchemy setup accordingly. \a npc may be empty to indicate that + /// there is no alchemist (alchemy session has ended). + + TToolsIterator beginTools() const; + ///< \attention Iterates over tool slots, not over tools. Some of the slots may be empty. + + TToolsIterator endTools() const; + + TIngredientsIterator beginIngredients() const; + ///< \attention Iterates over ingredient slots, not over ingredients. Some of the slots may be empty. + + TIngredientsIterator endIngredients() const; + + void clear(); + ///< Remove alchemist, tools and ingredients. + + int addIngredient (const MWWorld::Ptr& ingredient); + ///< Add ingredient into the next free slot. + /// + /// \return Slot index or -1, if adding failed because of no free slot or the ingredient type being + /// listed already. + + void removeIngredient (int index); + ///< Remove ingredient from slot (calling this function on an empty slot is a no-op). + + TEffectsIterator beginEffects() const; + + TEffectsIterator endEffects() const; + + std::string getPotionName() const; + ///< Return the name of the potion that would be created when calling create (if a record for such + /// a potion already exists) or return an empty string. + + Result create (const std::string& name); + ///< Try to create a potion from the ingredients, place it in the inventory of the alchemist and + /// adjust the skills of the alchemist accordingly. + /// \param name must not be an empty string, unless there is already a potion record ( + /// getPotionName() does not return an empty string). + }; +} + +#endif + diff --git a/apps/openmw/mwmechanics/creaturestats.cpp b/apps/openmw/mwmechanics/creaturestats.cpp index fc0523141..4be5d55b2 100644 --- a/apps/openmw/mwmechanics/creaturestats.cpp +++ b/apps/openmw/mwmechanics/creaturestats.cpp @@ -2,16 +2,19 @@ #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" namespace MWMechanics -{ +{ CreatureStats::CreatureStats() - : mLevelHealthBonus(0.f) + : mLevel (0), mLevelHealthBonus(0.f), mDead (false), mFriendlyHits (0), mTalkedTo (false), mAlarmed (false), + mAttacked (false), mHostile (false) { + for (int i=0; i<4; ++i) + mAiSettings[i] = 0; } void CreatureStats::increaseLevelHealthBonus (float value) @@ -28,25 +31,26 @@ namespace MWMechanics { return mAiSequence; } - + AiSequence& CreatureStats::getAiSequence() { - return mAiSequence; + return mAiSequence; } - - float CreatureStats::getFatigueTerm() const + + float CreatureStats::getFatigueTerm() const { int max = getFatigue().getModified(); int current = getFatigue().getCurrent(); - + float normalised = max==0 ? 1 : std::max (0.0f, static_cast (current)/max); - const ESMS::ESMStore& store = MWBase::Environment::get().getWorld()->getStore(); - - return store.gameSettings.find ("fFatigueBase")->getFloat() - - store.gameSettings.find ("fFatigueMult")->getFloat() * (1-normalised); + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); + + return gmst.find ("fFatigueBase")->getFloat() + - gmst.find ("fFatigueMult")->getFloat() * (1-normalised); } - + const Stat &CreatureStats::getAttribute(int index) const { if (index < 0 || index > 7) { @@ -89,25 +93,11 @@ namespace MWMechanics { return mLevel; } - - int CreatureStats::getHello() const - { - return mHello; - } - int CreatureStats::getFight() const + int CreatureStats::getAiSetting (int index) const { - return mFight; - } - - int CreatureStats::getFlee() const - { - return mFlee; - } - - int CreatureStats::getAlarm() const - { - return mAlarm; + assert (index>=0 && index<4); + return mAiSettings[index]; } Stat &CreatureStats::getAttribute(int index) @@ -118,22 +108,7 @@ namespace MWMechanics return mAttributes[index]; } - DynamicStat &CreatureStats::getHealth() - { - return mDynamic[0]; - } - - DynamicStat &CreatureStats::getMagicka() - { - return mDynamic[1]; - } - - DynamicStat &CreatureStats::getFatigue() - { - return mDynamic[2]; - } - - DynamicStat &CreatureStats::getDynamic(int index) + const DynamicStat &CreatureStats::getDynamic(int index) const { if (index < 0 || index > 2) { throw std::runtime_error("dynamic stat index is out of range"); @@ -171,17 +146,28 @@ namespace MWMechanics void CreatureStats::setHealth(const DynamicStat &value) { - mDynamic[0] = value; + setDynamic (0, value); } void CreatureStats::setMagicka(const DynamicStat &value) { - mDynamic[1] = value; + setDynamic (1, value); } void CreatureStats::setFatigue(const DynamicStat &value) { - mDynamic[2] = value; + setDynamic (2, value); + } + + void CreatureStats::setDynamic (int index, const DynamicStat &value) + { + if (index < 0 || index > 2) + throw std::runtime_error("dynamic stat index is out of range"); + + mDynamic[index] = value; + + if (index==0 && mDynamic[index].getCurrent()<1) + mDead = true; } void CreatureStats::setLevel(int level) @@ -199,23 +185,91 @@ namespace MWMechanics mMagicEffects = effects; } - void CreatureStats::setHello(int value) + void CreatureStats::setAiSetting (int index, int value) { - mHello = value; + assert (index>=0 && index<4); + mAiSettings[index] = value; } - void CreatureStats::setFight(int value) + bool CreatureStats::isDead() const { - mFight = value; + return mDead; } - void CreatureStats::setFlee(int value) + void CreatureStats::resurrect() { - mFlee = value; + if (mDead) + { + if (mDynamic[0].getCurrent()<1) + mDynamic[0].setCurrent (1); + + if (mDynamic[0].getCurrent()>=1) + mDead = false; + } } - void CreatureStats::setAlarm(int value) + bool CreatureStats::hasCommonDisease() const { - mAlarm = value; - } + return mSpells.hasCommonDisease(); + } + + bool CreatureStats::hasBlightDisease() const + { + return mSpells.hasBlightDisease(); + } + + int CreatureStats::getFriendlyHits() const + { + return mFriendlyHits; + } + + void CreatureStats::friendlyHit() + { + ++mFriendlyHits; + } + + bool CreatureStats::hasTalkedToPlayer() const + { + return mTalkedTo; + } + + void CreatureStats::talkedToPlayer() + { + mTalkedTo = true; + } + + bool CreatureStats::isAlarmed() const + { + return mAlarmed; + } + + void CreatureStats::setAlarmed (bool alarmed) + { + mAlarmed = alarmed; + } + + bool CreatureStats::getAttacked() const + { + return mAttacked; + } + + void CreatureStats::setAttacked (bool attacked) + { + mAttacked = attacked; + } + + bool CreatureStats::isHostile() const + { + return mHostile; + } + + void CreatureStats::setHostile (bool hostile) + { + mHostile = hostile; + } + + bool CreatureStats::getCreatureTargetted() const + { + return false; + } } diff --git a/apps/openmw/mwmechanics/creaturestats.hpp b/apps/openmw/mwmechanics/creaturestats.hpp index 7a1e46f56..3375c1af8 100644 --- a/apps/openmw/mwmechanics/creaturestats.hpp +++ b/apps/openmw/mwmechanics/creaturestats.hpp @@ -24,13 +24,15 @@ namespace MWMechanics Spells mSpells; ActiveSpells mActiveSpells; MagicEffects mMagicEffects; - int mHello; - int mFight; - int mFlee; - int mAlarm; + int mAiSettings[4]; AiSequence mAiSequence; - float mLevelHealthBonus; + bool mDead; + int mFriendlyHits; + bool mTalkedTo; + bool mAlarmed; + bool mAttacked; + bool mHostile; public: CreatureStats(); @@ -43,6 +45,8 @@ namespace MWMechanics const DynamicStat & getFatigue() const; + const DynamicStat & getDynamic (int index) const; + const Spells & getSpells() const; const ActiveSpells & getActiveSpells() const; @@ -51,32 +55,17 @@ namespace MWMechanics int getLevel() const; - int getHello() const; - - int getFight() const; - - int getFlee() const; - - int getAlarm() const; - + int getAiSetting (int index) const; + ///< 0: hello, 1 fight, 2 flee, 3 alarm Stat & getAttribute(int index); - DynamicStat & getHealth(); - - DynamicStat & getMagicka(); - - DynamicStat & getFatigue(); - - DynamicStat & getDynamic(int index); - Spells & getSpells(); ActiveSpells & getActiveSpells(); MagicEffects & getMagicEffects(); - void setAttribute(int index, const Stat &value); void setHealth(const DynamicStat &value); @@ -85,6 +74,8 @@ namespace MWMechanics void setFatigue(const DynamicStat &value); + void setDynamic (int index, const DynamicStat &value); + void setSpells(const Spells &spells); void setActiveSpells(const ActiveSpells &active); @@ -93,24 +84,52 @@ namespace MWMechanics void setLevel(int level); - void setHello(int value); + void setAiSetting (int index, int value); + ///< 0: hello, 1 fight, 2 flee, 3 alarm - void setFight(int value); - - void setFlee(int value); - - void setAlarm(int value); - const AiSequence& getAiSequence() const; - + AiSequence& getAiSequence(); - + float getFatigueTerm() const; ///< Return effective fatigue // small hack to allow the fact that Health permanently increases by 10% of endurance on each level up void increaseLevelHealthBonus(float value); float getLevelHealthBonus() const; + + bool isDead() const; + + void resurrect(); + + bool hasCommonDisease() const; + + bool hasBlightDisease() const; + + int getFriendlyHits() const; + ///< Number of friendly hits received. + + void friendlyHit(); + ///< Increase number of friendly hits by one. + + bool hasTalkedToPlayer() const; + ///< Has this creature talked with the player before? + + void talkedToPlayer(); + + bool isAlarmed() const; + + void setAlarmed (bool alarmed); + + bool getAttacked() const; + + void setAttacked (bool attacked); + + bool isHostile() const; + + void setHostile (bool hostile); + + bool getCreatureTargetted() const; }; } diff --git a/apps/openmw/mwmechanics/drawstate.hpp b/apps/openmw/mwmechanics/drawstate.hpp index 112b6e4f9..5be00505c 100644 --- a/apps/openmw/mwmechanics/drawstate.hpp +++ b/apps/openmw/mwmechanics/drawstate.hpp @@ -8,7 +8,7 @@ namespace MWMechanics { DrawState_Weapon = 0, DrawState_Spell = 1, - DrawState_Nothing = 2, + DrawState_Nothing = 2 }; } diff --git a/apps/openmw/mwmechanics/mechanicsmanagerimp.cpp b/apps/openmw/mwmechanics/mechanicsmanagerimp.cpp index 364e65321..1b6e4b9f3 100644 --- a/apps/openmw/mwmechanics/mechanicsmanagerimp.cpp +++ b/apps/openmw/mwmechanics/mechanicsmanagerimp.cpp @@ -1,11 +1,12 @@ #include "mechanicsmanagerimp.hpp" -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwbase/windowmanager.hpp" +#include "../mwbase/dialoguemanager.hpp" #include "../mwworld/class.hpp" #include "../mwworld/player.hpp" @@ -19,7 +20,7 @@ namespace MWMechanics MWMechanics::CreatureStats& creatureStats = MWWorld::Class::get (ptr).getCreatureStats (ptr); MWMechanics::NpcStats& npcStats = MWWorld::Class::get (ptr).getNpcStats (ptr); - const ESM::NPC *player = ptr.get()->base; + const ESM::NPC *player = ptr.get()->mBase; // reset creatureStats.setLevel(player->mNpdt52.mLevel); @@ -37,15 +38,17 @@ namespace MWMechanics creatureStats.getAttribute(5).setBase (player->mNpdt52.mEndurance); creatureStats.getAttribute(6).setBase (player->mNpdt52.mPersonality); creatureStats.getAttribute(7).setBase (player->mNpdt52.mLuck); + + const MWWorld::ESMStore &esmStore = + MWBase::Environment::get().getWorld()->getStore(); // race if (mRaceSelected) { const ESM::Race *race = - MWBase::Environment::get().getWorld()->getStore().races.find ( - MWBase::Environment::get().getWorld()->getPlayer().getRace()); + esmStore.get().find(player->mRace); - bool male = MWBase::Environment::get().getWorld()->getPlayer().isMale(); + bool male = (player->mFlags & ESM::NPC::Female) == 0; for (int i=0; i<8; ++i) { @@ -88,11 +91,13 @@ namespace MWMechanics } // birthsign - if (!MWBase::Environment::get().getWorld()->getPlayer().getBirthsign().empty()) + const std::string &signId = + MWBase::Environment::get().getWorld()->getPlayer().getBirthSign(); + + if (!signId.empty()) { const ESM::BirthSign *sign = - MWBase::Environment::get().getWorld()->getStore().birthSigns.find ( - MWBase::Environment::get().getWorld()->getPlayer().getBirthsign()); + esmStore.get().find(signId); for (std::vector::const_iterator iter (sign->mPowers.mList.begin()); iter!=sign->mPowers.mList.end(); ++iter) @@ -104,11 +109,12 @@ namespace MWMechanics // class if (mClassSelected) { - const ESM::Class& class_ = MWBase::Environment::get().getWorld()->getPlayer().getClass(); + const ESM::Class *class_ = + esmStore.get().find(player->mClass); for (int i=0; i<2; ++i) { - int attribute = class_.mData.mAttribute[i]; + int attribute = class_->mData.mAttribute[i]; if (attribute>=0 && attribute<8) { creatureStats.getAttribute(attribute).setBase ( @@ -122,7 +128,7 @@ namespace MWMechanics for (int i2=0; i2<5; ++i2) { - int index = class_.mData.mSkills[i2][i]; + int index = class_->mData.mSkills[i2][i]; if (index>=0 && index<27) { @@ -132,14 +138,15 @@ namespace MWMechanics } } - typedef ESMS::IndexListT::MapType ContainerType; - const ContainerType& skills = MWBase::Environment::get().getWorld()->getStore().skills.list; + const MWWorld::Store &skills = + esmStore.get(); - for (ContainerType::const_iterator iter (skills.begin()); iter!=skills.end(); ++iter) + MWWorld::Store::iterator iter = skills.begin(); + for (; iter != skills.end(); ++iter) { - if (iter->second.mData.mSpecialization==class_.mData.mSpecialization) + if (iter->mData.mSpecialization==class_->mData.mSpecialization) { - int index = iter->first; + int index = iter->mIndex; if (index>=0 && index<27) { @@ -153,12 +160,14 @@ namespace MWMechanics // forced update and current value adjustments mActors.updateActor (ptr, 0); - creatureStats.getHealth().setCurrent(creatureStats.getHealth().getModified()); - creatureStats.getMagicka().setCurrent(creatureStats.getMagicka().getModified()); - creatureStats.getFatigue().setCurrent(creatureStats.getFatigue().getModified()); + for (int i=0; i<2; ++i) + { + DynamicStat stat = creatureStats.getDynamic (i); + stat.setCurrent (stat.getModified()); + creatureStats.setDynamic (i, stat); + } } - MechanicsManager::MechanicsManager() : mUpdatePlayer (true), mClassSelected (false), mRaceSelected (false) @@ -259,12 +268,22 @@ namespace MWMechanics if (mUpdatePlayer) { // basic player profile; should not change anymore after the creation phase is finished. - MWBase::Environment::get().getWindowManager()->setValue ("name", MWBase::Environment::get().getWorld()->getPlayer().getName()); - MWBase::Environment::get().getWindowManager()->setValue ("race", - MWBase::Environment::get().getWorld()->getStore().races.find (MWBase::Environment::get().getWorld()->getPlayer(). - getRace())->mName); - MWBase::Environment::get().getWindowManager()->setValue ("class", - MWBase::Environment::get().getWorld()->getPlayer().getClass().mName); + MWBase::WindowManager *winMgr = + MWBase::Environment::get().getWindowManager(); + + MWBase::World *world = MWBase::Environment::get().getWorld(); + const ESM::NPC *player = + world->getPlayer().getPlayer().get()->mBase; + + const ESM::Race *race = + world->getStore().get().find(player->mRace); + const ESM::Class *cls = + world->getStore().get().find(player->mClass); + + winMgr->setValue ("name", player->mName); + winMgr->setValue ("race", race->mName); + winMgr->setValue ("class", cls->mName); + mUpdatePlayer = false; MWBase::WindowManager::SkillList majorSkills (5); @@ -272,11 +291,11 @@ namespace MWMechanics for (int i=0; i<5; ++i) { - minorSkills[i] = MWBase::Environment::get().getWorld()->getPlayer().getClass().mData.mSkills[i][0]; - majorSkills[i] = MWBase::Environment::get().getWorld()->getPlayer().getClass().mData.mSkills[i][1]; + minorSkills[i] = cls->mData.mSkills[i][0]; + majorSkills[i] = cls->mData.mSkills[i][1]; } - MWBase::Environment::get().getWindowManager()->configureSkills (majorSkills, minorSkills); + winMgr->configureSkills (majorSkills, minorSkills); } mActors.update (movement, duration, paused); @@ -289,14 +308,31 @@ namespace MWMechanics void MechanicsManager::setPlayerName (const std::string& name) { - MWBase::Environment::get().getWorld()->getPlayer().setName (name); + MWBase::World *world = MWBase::Environment::get().getWorld(); + + ESM::NPC player = + *world->getPlayer().getPlayer().get()->mBase; + player.mName = name; + + world->createRecord(player); + mUpdatePlayer = true; } - void MechanicsManager::setPlayerRace (const std::string& race, bool male) + void MechanicsManager::setPlayerRace (const std::string& race, bool male, const std::string &head, const std::string &hair) { - MWBase::Environment::get().getWorld()->getPlayer().setGender (male); - MWBase::Environment::get().getWorld()->getPlayer().setRace (race); + MWBase::World *world = MWBase::Environment::get().getWorld(); + + ESM::NPC player = + *world->getPlayer().getPlayer().get()->mBase; + + player.mRace = race; + player.mHead = head; + player.mHair = hair; + player.setIsMale(male); + + world->createRecord(player); + mRaceSelected = true; buildPlayer(); mUpdatePlayer = true; @@ -304,24 +340,303 @@ namespace MWMechanics void MechanicsManager::setPlayerBirthsign (const std::string& id) { - MWBase::Environment::get().getWorld()->getPlayer().setBirthsign (id); + MWBase::Environment::get().getWorld()->getPlayer().setBirthSign(id); buildPlayer(); mUpdatePlayer = true; } void MechanicsManager::setPlayerClass (const std::string& id) { - MWBase::Environment::get().getWorld()->getPlayer().setClass (*MWBase::Environment::get().getWorld()->getStore().classes.find (id)); + MWBase::World *world = MWBase::Environment::get().getWorld(); + + ESM::NPC player = + *world->getPlayer().getPlayer().get()->mBase; + player.mClass = id; + + world->createRecord(player); + mClassSelected = true; buildPlayer(); mUpdatePlayer = true; } - void MechanicsManager::setPlayerClass (const ESM::Class& class_) + void MechanicsManager::setPlayerClass (const ESM::Class &cls) { - MWBase::Environment::get().getWorld()->getPlayer().setClass (class_); + MWBase::World *world = MWBase::Environment::get().getWorld(); + + const ESM::Class *ptr = world->createRecord(cls); + + ESM::NPC player = + *world->getPlayer().getPlayer().get()->mBase; + player.mClass = ptr->mId; + + world->createRecord(player); + mClassSelected = true; buildPlayer(); mUpdatePlayer = true; } + + std::string toLower (const std::string& name) + { + std::string lowerCase; + + std::transform (name.begin(), name.end(), std::back_inserter (lowerCase), + (int(*)(int)) std::tolower); + + return lowerCase; + } + + int MechanicsManager::getDerivedDisposition(const MWWorld::Ptr& ptr) + { + MWMechanics::NpcStats npcSkill = MWWorld::Class::get(ptr).getNpcStats(ptr); + float x = npcSkill.getBaseDisposition(); + + MWWorld::LiveCellRef* npc = ptr.get(); + MWWorld::Ptr playerPtr = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + MWWorld::LiveCellRef* player = playerPtr.get(); + MWMechanics::CreatureStats playerStats = MWWorld::Class::get(playerPtr).getCreatureStats(playerPtr); + MWMechanics::NpcStats playerNpcStats = MWWorld::Class::get(playerPtr).getNpcStats(playerPtr); + + if (toLower(npc->mBase->mRace) == toLower(player->mBase->mRace)) x += MWBase::Environment::get().getWorld()->getStore().get().find("fDispRaceMod")->getFloat(); + + x += MWBase::Environment::get().getWorld()->getStore().get().find("fDispPersonalityMult")->getFloat() + * (playerStats.getAttribute(ESM::Attribute::Personality).getModified() - MWBase::Environment::get().getWorld()->getStore().get().find("fDispPersonalityBase")->getFloat()); + + float reaction = 0; + int rank = 0; + std::string npcFaction = ""; + if(!npcSkill.getFactionRanks().empty()) npcFaction = npcSkill.getFactionRanks().begin()->first; + + if (playerNpcStats.getFactionRanks().find(toLower(npcFaction)) != playerNpcStats.getFactionRanks().end()) + { + for(std::vector::const_iterator it = MWBase::Environment::get().getWorld()->getStore().get().find(toLower(npcFaction))->mReactions.begin(); + it != MWBase::Environment::get().getWorld()->getStore().get().find(toLower(npcFaction))->mReactions.end(); it++) + { + if(toLower(it->mFaction) == toLower(npcFaction)) reaction = it->mReaction; + } + rank = playerNpcStats.getFactionRanks().find(toLower(npcFaction))->second; + } + else if (npcFaction != "") + { + for(std::vector::const_iterator it = MWBase::Environment::get().getWorld()->getStore().get().find(toLower(npcFaction))->mReactions.begin(); + it != MWBase::Environment::get().getWorld()->getStore().get().find(toLower(npcFaction))->mReactions.end();it++) + { + if(playerNpcStats.getFactionRanks().find(toLower(it->mFaction)) != playerNpcStats.getFactionRanks().end() ) + { + if(it->mReactionmReaction; + } + } + rank = 0; + } + else + { + reaction = 0; + rank = 0; + } + x += (MWBase::Environment::get().getWorld()->getStore().get().find("fDispFactionRankMult")->getFloat() * rank + + MWBase::Environment::get().getWorld()->getStore().get().find("fDispFactionRankBase")->getFloat()) + * MWBase::Environment::get().getWorld()->getStore().get().find("fDispFactionMod")->getFloat() * reaction; + + x -= MWBase::Environment::get().getWorld()->getStore().get().find("fDispCrimeMod")->getFloat() * playerNpcStats.getBounty(); + if (playerStats.hasCommonDisease() || playerStats.hasBlightDisease()) + x += MWBase::Environment::get().getWorld()->getStore().get().find("fDispDiseaseMod")->getFloat(); + + if (playerNpcStats.getDrawState() == MWMechanics::DrawState_::DrawState_Weapon) + x += MWBase::Environment::get().getWorld()->getStore().get().find("fDispWeaponDrawn")->getFloat(); + + int effective_disposition = std::max(0,std::min(int(x),100));//, normally clamped to [0..100] when used + return effective_disposition; + } + + int MechanicsManager::getBarterOffer(const MWWorld::Ptr& ptr,int basePrice, bool buying) + { + if (ptr.getTypeName() == typeid(ESM::Creature).name()) + return basePrice; + + MWMechanics::NpcStats sellerSkill = MWWorld::Class::get(ptr).getNpcStats(ptr); + MWMechanics::CreatureStats sellerStats = MWWorld::Class::get(ptr).getCreatureStats(ptr); + + MWWorld::Ptr playerPtr = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + MWMechanics::NpcStats playerSkill = MWWorld::Class::get(playerPtr).getNpcStats(playerPtr); + MWMechanics::CreatureStats playerStats = MWWorld::Class::get(playerPtr).getCreatureStats(playerPtr); + + // I suppose the temporary disposition change _has_ to be considered here, + // otherwise one would get different prices when exiting and re-entering the dialogue window... + int clampedDisposition = std::max(0, std::min(getDerivedDisposition(ptr) + + MWBase::Environment::get().getDialogueManager()->getTemporaryDispositionChange(),100)); + float a = std::min(playerSkill.getSkill(ESM::Skill::Mercantile).getModified(), 100.f); + float b = std::min(0.1f * playerStats.getAttribute(ESM::Attribute::Luck).getModified(), 10.f); + float c = std::min(0.2f * playerStats.getAttribute(ESM::Attribute::Personality).getModified(), 10.f); + float d = std::min(sellerSkill.getSkill(ESM::Skill::Mercantile).getModified(), 100.f); + float e = std::min(0.1f * sellerStats.getAttribute(ESM::Attribute::Luck).getModified(), 10.f); + float f = std::min(0.2f * sellerStats.getAttribute(ESM::Attribute::Personality).getModified(), 10.f); + + float pcTerm = (clampedDisposition - 50 + a + b + c) * playerStats.getFatigueTerm(); + float npcTerm = (d + e + f) * sellerStats.getFatigueTerm(); + float buyTerm = 0.01 * (100 - 0.5 * (pcTerm - npcTerm)); + float sellTerm = 0.01 * (50 - 0.5 * (npcTerm - pcTerm)); + + float x; + if(buying) x = buyTerm; + else x = std::min(buyTerm, sellTerm); + int offerPrice; + if (x < 1) offerPrice = int(x * basePrice); + if (x >= 1) offerPrice = basePrice + int((x - 1) * basePrice); + offerPrice = std::max(1, offerPrice); + return offerPrice; + } + + int MechanicsManager::countDeaths (const std::string& id) const + { + return mActors.countDeaths (id); + } + + + void MechanicsManager::getPersuasionDispositionChange (const MWWorld::Ptr& npc, PersuasionType type, + float currentTemporaryDispositionDelta, bool& success, float& tempChange, float& permChange) + { + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); + + MWWorld::Ptr playerPtr = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + MWMechanics::NpcStats playerSkill = MWWorld::Class::get(playerPtr).getNpcStats(playerPtr); + MWMechanics::CreatureStats playerStats = MWWorld::Class::get(playerPtr).getCreatureStats(playerPtr); + + MWMechanics::NpcStats npcSkill = MWWorld::Class::get(npc).getNpcStats(npc); + MWMechanics::CreatureStats npcStats = MWWorld::Class::get(npc).getCreatureStats(npc); + + + float persTerm = playerStats.getAttribute(ESM::Attribute::Personality).getModified() + / gmst.find("fPersonalityMod")->getFloat(); + + float luckTerm = playerStats.getAttribute(ESM::Attribute::Luck).getModified() + / gmst.find("fLuckMod")->getFloat(); + + float repTerm = playerSkill.getReputation() * gmst.find("fReputationMod")->getFloat(); + + float levelTerm = playerStats.getLevel() * gmst.find("fLevelMod")->getFloat(); + + float fatigueTerm = playerStats.getFatigueTerm(); + + float playerRating1 = (repTerm + luckTerm + persTerm + playerSkill.getSkill(ESM::Skill::Speechcraft).getModified()) * fatigueTerm; + float playerRating2 = playerRating1 + levelTerm; + float playerRating3 = (playerSkill.getSkill(ESM::Skill::Mercantile).getModified() + luckTerm + persTerm) * fatigueTerm; + + float npcRating1 = (repTerm + luckTerm + persTerm + playerSkill.getSkill(ESM::Skill::Speechcraft).getModified()) * fatigueTerm; + float npcRating2 = (levelTerm + repTerm + luckTerm + persTerm + npcSkill.getSkill(ESM::Skill::Speechcraft).getModified()) * fatigueTerm; + float npcRating3 = (playerSkill.getSkill(ESM::Skill::Mercantile).getModified() + repTerm + luckTerm + persTerm) * fatigueTerm; + + int currentDisposition = std::min(100, std::max(0, int(getDerivedDisposition(npc) + currentTemporaryDispositionDelta))); + + float d = 1 - 0.02 * abs(currentDisposition - 50); + float target1 = d * (playerRating1 - npcRating1 + 50); + float target2 = d * (playerRating2 - npcRating2 + 50); + + float bribeMod; + if (type == PT_Bribe10) bribeMod = gmst.find("fBribe10Mod")->getFloat(); + if (type == PT_Bribe100) bribeMod = gmst.find("fBribe100Mod")->getFloat(); + else bribeMod = gmst.find("fBribe1000Mod")->getFloat(); + + float target3 = d * (playerRating3 - npcRating3 + 50) + bribeMod; + + float iPerMinChance = gmst.find("iPerMinChance")->getInt(); + float iPerMinChange = gmst.find("iPerMinChange")->getInt(); + float fPerDieRollMult = gmst.find("fPerDieRollMult")->getFloat(); + float fPerTempMult = gmst.find("fPerTempMult")->getFloat(); + + float x,y; + + float roll = static_cast (std::rand()) / RAND_MAX * 100; + + if (type == PT_Admire) + { + target1 = std::max(iPerMinChance, target1); + success = (roll <= target1); + float c = int(fPerDieRollMult * (target1 - roll)); + x = success ? std::max(iPerMinChange, c) : c; + } + else if (type == PT_Intimidate) + { + target2 = std::max(iPerMinChance, target2); + + success = (roll <= target2); + + float r; + if (roll != target2) + r = int(target2 - roll); + else + r = 1; + + if (roll <= target2) + { + float s = int(r * fPerDieRollMult * fPerTempMult); + + npcStats.setAiSetting (2, std::max(0, std::min(100, npcStats.getAiSetting (2) + int(std::max(iPerMinChange, s))))); + npcStats.setAiSetting (1, std::max(0, std::min(100, npcStats.getAiSetting (1) + int(std::min(-iPerMinChange, -s))))); + } + + float c = -std::abs(int(r * fPerDieRollMult)); + if (success) + { + if (std::abs(c) < iPerMinChange) + { + x = 0; + y = -iPerMinChange; + } + else + { + x = -int(c * fPerTempMult); + y = c; + } + } + else + { + x = int(c * fPerTempMult); + y = c; + } + } + else if (type == PT_Taunt) + { + target1 = std::max(iPerMinChance, target1); + success = (roll <= target1); + + float c = std::abs(int(target1 - roll)); + + if (roll <= target1) + { + float s = c * fPerDieRollMult * fPerTempMult; + + npcStats.setAiSetting (2, std::max(0, std::min(100, npcStats.getAiSetting (2) + std::min(-int(iPerMinChange), int(-s))))); + npcStats.setAiSetting (1, std::max(0, std::min(100, npcStats.getAiSetting (1) + std::max(int(iPerMinChange), int(s))))); + } + x = int(-c * fPerDieRollMult); + + if (success && std::abs(x) < iPerMinChange) + x = -iPerMinChange; + } + else // Bribe + { + target3 = std::max(iPerMinChance, target3); + success = (roll <= target3); + float c = int((target3 - roll) * fPerDieRollMult); + + x = success ? std::max(iPerMinChange, c) : c; + } + + tempChange = type == PT_Intimidate ? x : int(x * fPerTempMult); + + + float cappedDispositionChange = tempChange; + if (currentDisposition + tempChange > 100.f) + cappedDispositionChange = 100 - currentDisposition; + if (currentDisposition + tempChange < 0.f) + cappedDispositionChange = -currentDisposition; + + permChange = int(cappedDispositionChange / fPerTempMult); + if (type == PT_Intimidate) + { + permChange = success ? -int(cappedDispositionChange/ fPerTempMult) : y; + } + } } diff --git a/apps/openmw/mwmechanics/mechanicsmanagerimp.hpp b/apps/openmw/mwmechanics/mechanicsmanagerimp.hpp index 3a41e8fa6..f8d470a4e 100644 --- a/apps/openmw/mwmechanics/mechanicsmanagerimp.hpp +++ b/apps/openmw/mwmechanics/mechanicsmanagerimp.hpp @@ -41,6 +41,8 @@ namespace MWMechanics virtual void addActor (const MWWorld::Ptr& ptr); ///< Register an actor for stats management + /// + /// \note Dead actors are ignored. virtual void removeActor (const MWWorld::Ptr& ptr); ///< Deregister an actor for stats management @@ -62,7 +64,7 @@ namespace MWMechanics virtual void setPlayerName (const std::string& name); ///< Set player name. - virtual void setPlayerRace (const std::string& id, bool male); + virtual void setPlayerRace (const std::string& id, bool male, const std::string &head, const std::string &hair); ///< Set player race. virtual void setPlayerBirthsign (const std::string& id); @@ -76,6 +78,19 @@ namespace MWMechanics virtual void restoreDynamicStats(); ///< If the player is sleeping, this should be called every hour. + + virtual int getBarterOffer(const MWWorld::Ptr& ptr,int basePrice, bool buying); + ///< This is used by every service to determine the price of objects given the trading skills of the player and NPC. + + virtual int getDerivedDisposition(const MWWorld::Ptr& ptr); + ///< Calculate the diposition of an NPC toward the player. + + virtual int countDeaths (const std::string& id) const; + ///< Return the number of deaths for actors with the given ID. + + virtual void getPersuasionDispositionChange (const MWWorld::Ptr& npc, PersuasionType type, + float currentTemporaryDispositionDelta, bool& success, float& tempChange, float& permChange); + ///< Perform a persuasion action on NPC }; } diff --git a/apps/openmw/mwmechanics/npcstats.cpp b/apps/openmw/mwmechanics/npcstats.cpp index bbd42c147..20a0360e7 100644 --- a/apps/openmw/mwmechanics/npcstats.cpp +++ b/apps/openmw/mwmechanics/npcstats.cpp @@ -3,14 +3,17 @@ #include #include +#include +#include #include #include #include #include +#include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -18,8 +21,8 @@ #include "../mwbase/soundmanager.hpp" MWMechanics::NpcStats::NpcStats() -: mMovementFlags (0), mDrawState (DrawState_Nothing) -, mLevelProgress(0) +: mMovementFlags (0), mDrawState (DrawState_Nothing), mBounty (0) +, mLevelProgress(0), mDisposition(0), mVampire (0), mReputation(0), mWerewolf (false), mWerewolfKills (0) { mSkillIncreases.resize (ESM::Attribute::Length); for (int i=0; i& MWMechanics::NpcStats::getFactionRanks() return mFactionRank; } +std::set& MWMechanics::NpcStats::getExpelled() +{ + return mExpelled; +} + const std::map& MWMechanics::NpcStats::getFactionRanks() const { return mFactionRank; } +bool MWMechanics::NpcStats::isSameFaction (const NpcStats& npcStats) const +{ + for (std::map::const_iterator iter (mFactionRank.begin()); iter!=mFactionRank.end(); + ++iter) + if (npcStats.mFactionRank.find (iter->first)!=npcStats.mFactionRank.end()) + return true; + + return false; +} + float MWMechanics::NpcStats::getSkillGain (int skillIndex, const ESM::Class& class_, int usageType, int level) const { if (level<0) level = static_cast (getSkill (skillIndex).getBase()); - const ESM::Skill *skill = MWBase::Environment::get().getWorld()->getStore().skills.find (skillIndex); + const ESM::Skill *skill = + MWBase::Environment::get().getWorld()->getStore().get().find (skillIndex); float skillFactor = 1; @@ -96,14 +125,15 @@ float MWMechanics::NpcStats::getSkillGain (int skillIndex, const ESM::Class& cla throw std::runtime_error ("invalid skill gain factor"); } - float typeFactor = - MWBase::Environment::get().getWorld()->getStore().gameSettings.find ("fMiscSkillBonus")->getFloat(); + const MWWorld::Store &gmst = + MWBase::Environment::get().getWorld()->getStore().get(); + + float typeFactor = gmst.find ("fMiscSkillBonus")->getFloat(); for (int i=0; i<5; ++i) if (class_.mData.mSkills[i][0]==skillIndex) { - typeFactor = - MWBase::Environment::get().getWorld()->getStore().gameSettings.find ("fMinorSkillBonus")->getFloat(); + typeFactor = gmst.find ("fMinorSkillBonus")->getFloat(); break; } @@ -111,8 +141,7 @@ float MWMechanics::NpcStats::getSkillGain (int skillIndex, const ESM::Class& cla for (int i=0; i<5; ++i) if (class_.mData.mSkills[i][1]==skillIndex) { - typeFactor = - MWBase::Environment::get().getWorld()->getStore().gameSettings.find ("fMajorSkillBonus")->getFloat(); + typeFactor = gmst.find ("fMajorSkillBonus")->getFloat(); break; } @@ -124,8 +153,7 @@ float MWMechanics::NpcStats::getSkillGain (int skillIndex, const ESM::Class& cla if (skill->mData.mSpecialization==class_.mData.mSpecialization) { - specialisationFactor = - MWBase::Environment::get().getWorld()->getStore().gameSettings.find ("fSpecialSkillBonus")->getFloat(); + specialisationFactor = gmst.find ("fSpecialSkillBonus")->getFloat(); if (specialisationFactor<=0) throw std::runtime_error ("invalid skill specialisation factor"); @@ -178,7 +206,8 @@ void MWMechanics::NpcStats::increaseSkill(int skillIndex, const ESM::Class &clas mLevelProgress += levelProgress; // check the attribute this skill belongs to - const ESM::Skill* skill = MWBase::Environment::get().getWorld ()->getStore ().skills.find(skillIndex); + const ESM::Skill* skill = + MWBase::Environment::get().getWorld ()->getStore ().get().find(skillIndex); ++mSkillIncreases[skill->mData.mAttribute]; // Play sound & skill progress notification @@ -237,3 +266,88 @@ bool MWMechanics::NpcStats::hasBeenUsed (const std::string& id) const { return mUsedIds.find (id)!=mUsedIds.end(); } + +int MWMechanics::NpcStats::getBounty() const +{ + return mBounty; +} + +void MWMechanics::NpcStats::setBounty (int bounty) +{ + mBounty = bounty; +} + +int MWMechanics::NpcStats::getFactionReputation (const std::string& faction) const +{ + std::map::const_iterator iter = mFactionReputation.find (faction); + + if (iter==mFactionReputation.end()) + return 0; + + return iter->second; +} + +void MWMechanics::NpcStats::setFactionReputation (const std::string& faction, int value) +{ + mFactionReputation[faction] = value; +} + +bool MWMechanics::NpcStats::isVampire() const +{ + return mVampire; +} + +void MWMechanics::NpcStats::setVampire (bool set) +{ + mVampire = set; +} + +int MWMechanics::NpcStats::getReputation() const +{ + return mReputation; +} + +void MWMechanics::NpcStats::setReputation(int reputation) +{ + mReputation = reputation; +} + +bool MWMechanics::NpcStats::hasSkillsForRank (const std::string& factionId, int rank) const +{ + if (rank<0 || rank>=10) + throw std::runtime_error ("rank index out of range"); + + const ESM::Faction& faction = + *MWBase::Environment::get().getWorld()->getStore().get().find (factionId); + + std::vector skills; + + for (int i=0; i<6; ++i) + skills.push_back (static_cast (getSkill (faction.mData.mSkillID[i]).getModified())); + + std::sort (skills.begin(), skills.end()); + + std::vector::const_reverse_iterator iter = skills.rbegin(); + + const ESM::RankData& rankData = faction.mData.mRankData[rank]; + + if (*iter=rankData.mSkill2; +} + +bool MWMechanics::NpcStats::isWerewolf() const +{ + return mWerewolf; +} + +void MWMechanics::NpcStats::setWerewolf (bool set) +{ + mWerewolf = set; +} + +int MWMechanics::NpcStats::getWerewolfKills() const +{ + return mWerewolfKills; +} \ No newline at end of file diff --git a/apps/openmw/mwmechanics/npcstats.hpp b/apps/openmw/mwmechanics/npcstats.hpp index 48e63d7b6..af32bd294 100644 --- a/apps/openmw/mwmechanics/npcstats.hpp +++ b/apps/openmw/mwmechanics/npcstats.hpp @@ -43,8 +43,16 @@ namespace MWMechanics std::map mFactionRank; DrawState_ mDrawState; + int mDisposition; unsigned int mMovementFlags; Stat mSkill[27]; + int mBounty; + std::set mExpelled; + std::map mFactionReputation; + bool mVampire; + int mReputation; + bool mWerewolf; + int mWerewolfKills; int mLevelProgress; // 0-10 @@ -60,6 +68,14 @@ namespace MWMechanics void setDrawState (DrawState_ state); + int getBaseDisposition() const; + + void setBaseDisposition(int disposition); + + int getReputation() const; + + void setReputation(int reputation); + bool getMovementFlag (Flag flag) const; void setMovementFlag (Flag flag, bool state); @@ -70,6 +86,11 @@ namespace MWMechanics std::map& getFactionRanks(); + std::set& getExpelled(); + + bool isSameFaction (const NpcStats& npcStats) const; + ///< Do *this and \a npcStats share a faction? + const std::map& getFactionRanks() const; float getSkillGain (int skillIndex, const ESM::Class& class_, int usageType = -1, @@ -88,10 +109,30 @@ namespace MWMechanics int getLevelupAttributeMultiplier(int attribute) const; void levelUp(); - + void flagAsUsed (const std::string& id); - + bool hasBeenUsed (const std::string& id) const; + + int getBounty() const; + + void setBounty (int bounty); + + int getFactionReputation (const std::string& faction) const; + + void setFactionReputation (const std::string& faction, int value); + + bool isVampire() const; + + void setVampire (bool set); + + bool hasSkillsForRank (const std::string& factionId, int rank) const; + + bool isWerewolf() const; + + void setWerewolf (bool set); + + int getWerewolfKills() const; }; } diff --git a/apps/openmw/mwmechanics/spells.cpp b/apps/openmw/mwmechanics/spells.cpp index adfb35cd9..ef084f479 100644 --- a/apps/openmw/mwmechanics/spells.cpp +++ b/apps/openmw/mwmechanics/spells.cpp @@ -1,7 +1,7 @@ #include "spells.hpp" -#include +#include "../mwworld/esmstore.hpp" #include @@ -50,7 +50,8 @@ namespace MWMechanics for (TIterator iter = mSpells.begin(); iter!=mSpells.end(); ++iter) { - const ESM::Spell *spell = MWBase::Environment::get().getWorld()->getStore().spells.find (*iter); + const ESM::Spell *spell = + MWBase::Environment::get().getWorld()->getStore().get().find (*iter); if (spell->mData.mType==ESM::Spell::ST_Ability || spell->mData.mType==ESM::Spell::ST_Blight || spell->mData.mType==ESM::Spell::ST_Disease || spell->mData.mType==ESM::Spell::ST_Curse) @@ -74,4 +75,32 @@ namespace MWMechanics { return mSelectedSpell; } + + bool Spells::hasCommonDisease() const + { + for (TIterator iter = mSpells.begin(); iter!=mSpells.end(); ++iter) + { + const ESM::Spell *spell = + MWBase::Environment::get().getWorld()->getStore().get().find (*iter); + + if (spell->mData.mFlags & ESM::Spell::ST_Disease) + return true; + } + + return false; + } + + bool Spells::hasBlightDisease() const + { + for (TIterator iter = mSpells.begin(); iter!=mSpells.end(); ++iter) + { + const ESM::Spell *spell = + MWBase::Environment::get().getWorld()->getStore().get().find (*iter); + + if (spell->mData.mFlags & ESM::Spell::ST_Blight) + return true; + } + + return false; + } } diff --git a/apps/openmw/mwmechanics/spells.hpp b/apps/openmw/mwmechanics/spells.hpp index d90f5b502..12308661b 100644 --- a/apps/openmw/mwmechanics/spells.hpp +++ b/apps/openmw/mwmechanics/spells.hpp @@ -55,6 +55,10 @@ namespace MWMechanics const std::string getSelectedSpell() const; ///< May return an empty string. + + bool hasCommonDisease() const; + + bool hasBlightDisease() const; }; } diff --git a/apps/openmw/mwmechanics/spellsuccess.hpp b/apps/openmw/mwmechanics/spellsuccess.hpp index 43db42aab..57c600df5 100644 --- a/apps/openmw/mwmechanics/spellsuccess.hpp +++ b/apps/openmw/mwmechanics/spellsuccess.hpp @@ -8,7 +8,7 @@ #include "../mwworld/class.hpp" #include "../mwmechanics/creaturestats.hpp" -#include +#include "../mwworld/esmstore.hpp" #include "npcstats.hpp" @@ -27,9 +27,8 @@ namespace MWMechanics return schoolSkillMap[school]; } - inline int getSpellSchool(const std::string& spellId, const MWWorld::Ptr& actor) + inline int getSpellSchool(const ESM::Spell* spell, const MWWorld::Ptr& actor) { - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(spellId); NpcStats& stats = MWWorld::Class::get(actor).getNpcStats(actor); // determine the spell's school @@ -41,7 +40,8 @@ namespace MWMechanics for (std::vector::const_iterator it = effects.begin(); it != effects.end(); ++it) { - const ESM::MagicEffect* effect = MWBase::Environment::get().getWorld()->getStore().magicEffects.find(it->mEffectID); + const ESM::MagicEffect* effect = + MWBase::Environment::get().getWorld()->getStore().get().find(it->mEffectID); int _school = effect->mData.mSchool; int _skillLevel = stats.getSkill (spellSchoolToSkill(_school)).getModified(); @@ -60,27 +60,35 @@ namespace MWMechanics return school; } + inline int getSpellSchool(const std::string& spellId, const MWWorld::Ptr& actor) + { + const ESM::Spell* spell = + MWBase::Environment::get().getWorld()->getStore().get().find(spellId); + return getSpellSchool(spell, actor); + } + // UESP wiki / Morrowind/Spells: // Chance of success is (Spell's skill * 2 + Willpower / 5 + Luck / 10 - Spell cost - Sound magnitude) * (Current fatigue + Maximum Fatigue * 1.5) / Maximum fatigue * 2 /** - * @param spellId ID of spell + * @param spell spell to cast * @param actor calculate spell success chance for this actor (depends on actor's skills) * @attention actor has to be an NPC and not a creature! * @return success chance from 0 to 100 (in percent) */ - inline float getSpellSuccessChance (const std::string& spellId, const MWWorld::Ptr& actor) + inline float getSpellSuccessChance (const ESM::Spell* spell, const MWWorld::Ptr& actor) { - const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().spells.find(spellId); - if (spell->mData.mFlags & ESM::Spell::F_Always // spells with this flag always succeed (usually birthsign spells) || spell->mData.mType == ESM::Spell::ST_Power) // powers always succeed, but can be cast only once per day return 100.0; + if (spell->mEffects.mList.size() == 0) + return 0.0; + NpcStats& stats = MWWorld::Class::get(actor).getNpcStats(actor); CreatureStats& creatureStats = MWWorld::Class::get(actor).getCreatureStats(actor); - int skillLevel = stats.getSkill (getSpellSchool(spellId, actor)).getModified(); + int skillLevel = stats.getSkill (getSpellSchool(spell, actor)).getModified(); // Sound magic effect (reduces spell casting chance) int soundMagnitude = creatureStats.getMagicEffects().get (MWMechanics::EffectKey (48)).mMagnitude; @@ -98,6 +106,13 @@ namespace MWMechanics return chance; } + + inline float getSpellSuccessChance (const std::string& spellId, const MWWorld::Ptr& actor) + { + const ESM::Spell* spell = + MWBase::Environment::get().getWorld()->getStore().get().find(spellId); + return getSpellSuccessChance(spell, actor); + } } #endif diff --git a/apps/openmw/mwrender/animation.cpp b/apps/openmw/mwrender/animation.cpp index ef92497e5..2a3b8cf43 100644 --- a/apps/openmw/mwrender/animation.cpp +++ b/apps/openmw/mwrender/animation.cpp @@ -7,7 +7,6 @@ #include #include - namespace MWRender { diff --git a/apps/openmw/mwrender/characterpreview.cpp b/apps/openmw/mwrender/characterpreview.cpp index 017062baa..0a11dc281 100644 --- a/apps/openmw/mwrender/characterpreview.cpp +++ b/apps/openmw/mwrender/characterpreview.cpp @@ -48,8 +48,9 @@ namespace MWRender mNode->setVisible (false); - mCamera->setPosition(mPosition); - mCamera->lookAt(mLookAt); + Ogre::Vector3 scale = mNode->getScale(); + mCamera->setPosition(mPosition * scale); + mCamera->lookAt(mLookAt * scale); mCamera->setNearClipDistance (0.01); mCamera->setFarClipDistance (1000); @@ -80,6 +81,22 @@ namespace MWRender delete mAnimation; } + void CharacterPreview::rebuild() + { + assert(mAnimation); + delete mAnimation; + + mAnimation = new NpcAnimation(mCharacter, mNode, + MWWorld::Class::get(mCharacter).getInventoryStore (mCharacter), RV_PlayerPreview); + + mNode->setVisible (false); + + Ogre::Vector3 scale = mNode->getScale(); + mCamera->setPosition(mPosition * scale); + mCamera->lookAt(mLookAt * scale); + + onSetup(); + } // -------------------------------------------------------------------------------------------------- @@ -128,8 +145,10 @@ namespace MWRender RaceSelectionPreview::RaceSelectionPreview() : CharacterPreview(MWBase::Environment::get().getWorld()->getPlayer().getPlayer(), 512, 512, "CharacterHeadPreview", Ogre::Vector3(0, 120, -35), Ogre::Vector3(0,125,0)) + , mRef(&mBase) { - + mBase = *mCharacter.get()->mBase; + mCharacter = MWWorld::Ptr(&mRef, mCharacter.getCell()); } void RaceSelectionPreview::update(float angle) @@ -141,4 +160,11 @@ namespace MWRender mNode->setVisible (false); } + void RaceSelectionPreview::setPrototype(const ESM::NPC &proto) + { + mBase = proto; + mBase.mId = "player"; + rebuild(); + update(0); + } } diff --git a/apps/openmw/mwrender/characterpreview.hpp b/apps/openmw/mwrender/characterpreview.hpp index 2a6b12b9e..18362d1db 100644 --- a/apps/openmw/mwrender/characterpreview.hpp +++ b/apps/openmw/mwrender/characterpreview.hpp @@ -4,6 +4,7 @@ #include #include +#include #include "externalrendering.hpp" @@ -32,6 +33,7 @@ namespace MWRender virtual void setup (Ogre::SceneManager *sceneManager); virtual void onSetup(); + virtual void rebuild(); protected: Ogre::TexturePtr mTexture; @@ -77,10 +79,19 @@ namespace MWRender class RaceSelectionPreview : public CharacterPreview { + ESM::NPC mBase; + MWWorld::LiveCellRef mRef; + public: RaceSelectionPreview(); void update(float angle); + + const ESM::NPC &getPrototype() const { + return mBase; + } + + void setPrototype(const ESM::NPC &proto); }; } diff --git a/apps/openmw/mwrender/creatureanimation.cpp b/apps/openmw/mwrender/creatureanimation.cpp index afd114972..7ee361a6f 100644 --- a/apps/openmw/mwrender/creatureanimation.cpp +++ b/apps/openmw/mwrender/creatureanimation.cpp @@ -21,10 +21,10 @@ CreatureAnimation::CreatureAnimation(const MWWorld::Ptr& ptr): Animation() mInsert = ptr.getRefData().getBaseNode(); MWWorld::LiveCellRef *ref = ptr.get(); - assert (ref->base != NULL); - if(!ref->base->mModel.empty()) + assert (ref->mBase != NULL); + if(!ref->mBase->mModel.empty()) { - std::string mesh = "meshes\\" + ref->base->mModel; + std::string mesh = "meshes\\" + ref->mBase->mModel; mEntityList = NifOgre::NIFLoader::createEntities(mInsert, &mTextKeys, mesh); for(size_t i = 0;i < mEntityList.mEntities.size();i++) diff --git a/apps/openmw/mwrender/debugging.cpp b/apps/openmw/mwrender/debugging.cpp index 4f7150754..1548cc1b0 100644 --- a/apps/openmw/mwrender/debugging.cpp +++ b/apps/openmw/mwrender/debugging.cpp @@ -11,7 +11,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/world.hpp" // these includes can be removed once the static-hack is gone #include "../mwbase/environment.hpp" @@ -228,22 +228,23 @@ void Debugging::togglePathgrid() void Debugging::enableCellPathgrid(MWWorld::Ptr::CellStore *store) { - ESM::Pathgrid *pathgrid = MWBase::Environment::get().getWorld()->getStore().pathgrids.search(*store->cell); + const ESM::Pathgrid *pathgrid = + MWBase::Environment::get().getWorld()->getStore().get().search(*store->mCell); if (!pathgrid) return; Vector3 cellPathGridPos(0, 0, 0); - if (store->cell->isExterior()) + if (store->mCell->isExterior()) { - cellPathGridPos.x = store->cell->mData.mX * ESM::Land::REAL_SIZE; - cellPathGridPos.y = store->cell->mData.mY * ESM::Land::REAL_SIZE; + cellPathGridPos.x = store->mCell->mData.mX * ESM::Land::REAL_SIZE; + cellPathGridPos.y = store->mCell->mData.mY * ESM::Land::REAL_SIZE; } SceneNode *cellPathGrid = mPathGridRoot->createChildSceneNode(cellPathGridPos); cellPathGrid->attachObject(createPathgridLines(pathgrid)); cellPathGrid->attachObject(createPathgridPoints(pathgrid)); - if (store->cell->isExterior()) + if (store->mCell->isExterior()) { - mExteriorPathgridNodes[std::make_pair(store->cell->mData.mX, store->cell->mData.mY)] = cellPathGrid; + mExteriorPathgridNodes[std::make_pair(store->mCell->getGridX(), store->mCell->getGridY())] = cellPathGrid; } else { @@ -254,10 +255,10 @@ void Debugging::enableCellPathgrid(MWWorld::Ptr::CellStore *store) void Debugging::disableCellPathgrid(MWWorld::Ptr::CellStore *store) { - if (store->cell->isExterior()) + if (store->mCell->isExterior()) { ExteriorPathgridNodes::iterator it = - mExteriorPathgridNodes.find(std::make_pair(store->cell->mData.mX, store->cell->mData.mY)); + mExteriorPathgridNodes.find(std::make_pair(store->mCell->getGridX(), store->mCell->getGridY())); if (it != mExteriorPathgridNodes.end()) { destroyCellPathgridNode(it->second); diff --git a/apps/openmw/mwrender/globalmap.cpp b/apps/openmw/mwrender/globalmap.cpp index c23fdc1a3..072015f9a 100644 --- a/apps/openmw/mwrender/globalmap.cpp +++ b/apps/openmw/mwrender/globalmap.cpp @@ -1,18 +1,19 @@ #include "globalmap.hpp" #include +#include #include #include #include #include #include +#include #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" -#include -#include +#include "../mwworld/esmstore.hpp" namespace MWRender { @@ -29,37 +30,41 @@ namespace MWRender { Ogre::TexturePtr tex; + const MWWorld::ESMStore &esmStore = + MWBase::Environment::get().getWorld()->getStore(); + // get the size of the world - const ESMS::CellList::ExtCells& extCells = MWBase::Environment::get().getWorld ()->getStore ().cells.extCells; - for (ESMS::CellList::ExtCells::const_iterator it = extCells.begin(); it != extCells.end(); ++it) + MWWorld::Store::iterator it = esmStore.get().extBegin(); + for (; it != esmStore.get().extEnd(); ++it) { - if (it->first.first < mMinX) - mMinX = it->first.first; - if (it->first.first > mMaxX) - mMaxX = it->first.first; - if (it->first.second < mMinY) - mMinY = it->first.second; - if (it->first.second > mMaxY) - mMaxY = it->first.second; + if (it->getGridX() < mMinX) + mMinX = it->getGridX(); + if (it->getGridX() > mMaxX) + mMaxX = it->getGridX(); + if (it->getGridY() < mMinY) + mMinY = it->getGridY(); + if (it->getGridY() > mMaxY) + mMaxY = it->getGridY(); } int cellSize = 24; mWidth = cellSize*(mMaxX-mMinX+1); mHeight = cellSize*(mMaxY-mMinY+1); + mExploredBuffer.resize((mMaxX-mMinX+1) * (mMaxY-mMinY+1) * 4); //if (!boost::filesystem::exists(mCacheDir + "/GlobalMap.png")) if (1) { Ogre::Image image; - Ogre::uchar data[mWidth * mHeight * 3]; + std::vector data (mWidth * mHeight * 3); for (int x = mMinX; x <= mMaxX; ++x) { for (int y = mMinY; y <= mMaxY; ++y) { - ESM::Land* land = MWBase::Environment::get().getWorld ()->getStore ().lands.search (x,y); + ESM::Land* land = esmStore.get().search (x,y); if (land) { @@ -150,18 +155,35 @@ namespace MWRender } } - image.loadDynamicImage (data, mWidth, mHeight, Ogre::PF_B8G8R8); + image.loadDynamicImage (&data[0], mWidth, mHeight, Ogre::PF_B8G8R8); //image.save (mCacheDir + "/GlobalMap.png"); tex = Ogre::TextureManager::getSingleton ().createManual ("GlobalMap.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Ogre::TEX_TYPE_2D, mWidth, mHeight, 0, Ogre::PF_B8G8R8, Ogre::TU_DEFAULT); + Ogre::TEX_TYPE_2D, mWidth, mHeight, 0, Ogre::PF_B8G8R8, Ogre::TU_STATIC); tex->loadImage(image); } else tex = Ogre::TextureManager::getSingleton ().getByName ("GlobalMap.png"); tex->load(); + + + + + mOverlayTexture = Ogre::TextureManager::getSingleton().createManual("GlobalMapOverlay", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, + Ogre::TEX_TYPE_2D, mWidth, mHeight, 0, Ogre::PF_A8B8G8R8, Ogre::TU_DYNAMIC_WRITE_ONLY); + + + std::vector buffer; + buffer.resize(mWidth * mHeight); + + // initialize to (0, 0, 0, 0) + for (int p=0; pgetBuffer()->lock(Ogre::HardwareBuffer::HBL_DISCARD), &buffer[0], mWidth*mHeight*4); + mOverlayTexture->getBuffer()->unlock(); } void GlobalMap::worldPosToImageSpace(float x, float z, float& imageX, float& imageY) @@ -179,5 +201,32 @@ namespace MWRender imageY = 1.f-float(y - mMinY + 1) / (mMaxY - mMinY + 1); } + void GlobalMap::exploreCell(int cellX, int cellY) + { + float originX = (cellX - mMinX) * 24; + // NB y + 1, because we want the top left corner, not bottom left where the origin of the cell is + float originY = mHeight - (cellY+1 - mMinY) * 24; + if (cellX > mMaxX || cellX < mMinX || cellY > mMaxY || cellY < mMinY) + return; + + Ogre::TexturePtr localMapTexture = Ogre::TextureManager::getSingleton().getByName("Cell_" + + boost::lexical_cast(cellX) + "_" + boost::lexical_cast(cellY)); + + // mipmap version - can't get ogre to generate automips.. + /*if (!localMapTexture.isNull()) + { + assert(localMapTexture->getBuffer(0, 4)->getWidth() == 64); // 1024 / 2^4 + + mOverlayTexture->getBuffer()->blit(localMapTexture->getBuffer(0, 4), Ogre::Image::Box(0,0,64, 64), + Ogre::Image::Box(originX,originY,originX+24,originY+24)); + }*/ + + if (!localMapTexture.isNull()) + { + + mOverlayTexture->getBuffer()->blit(localMapTexture->getBuffer(), Ogre::Image::Box(0,0,512,512), + Ogre::Image::Box(originX,originY,originX+24,originY+24)); + } + } } diff --git a/apps/openmw/mwrender/globalmap.hpp b/apps/openmw/mwrender/globalmap.hpp index 01f5fdb9e..c01182c5b 100644 --- a/apps/openmw/mwrender/globalmap.hpp +++ b/apps/openmw/mwrender/globalmap.hpp @@ -3,6 +3,8 @@ #include +#include + namespace MWRender { @@ -22,9 +24,16 @@ namespace MWRender void cellTopLeftCornerToImageSpace(int x, int y, float& imageX, float& imageY); + void exploreCell (int cellX, int cellY); + private: std::string mCacheDir; + std::vector< std::pair > mExploredCells; + + Ogre::TexturePtr mOverlayTexture; + std::vector mExploredBuffer; + int mWidth; int mHeight; diff --git a/apps/openmw/mwrender/localmap.cpp b/apps/openmw/mwrender/localmap.cpp index 1bdbce6d9..d878cb86e 100644 --- a/apps/openmw/mwrender/localmap.cpp +++ b/apps/openmw/mwrender/localmap.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -108,10 +108,10 @@ void LocalMap::requestMap(MWWorld::Ptr::CellStore* cell) mCameraRotNode->setOrientation(Quaternion::IDENTITY); - std::string name = "Cell_"+coordStr(cell->cell->mData.mX, cell->cell->mData.mY); + int x = cell->mCell->getGridX(); + int y = cell->mCell->getGridY(); - int x = cell->cell->mData.mX; - int y = cell->cell->mData.mY; + std::string name = "Cell_"+coordStr(x, y); mCameraPosNode->setPosition(Vector3(0,0,0)); @@ -163,7 +163,7 @@ void LocalMap::requestMap(MWWorld::Ptr::CellStore* cell, const int segsX = std::ceil( length.x / sSize ); const int segsY = std::ceil( length.y / sSize ); - mInteriorName = cell->cell->mName; + mInteriorName = cell->mCell->mName; for (int x=0; xcell->mName + "_" + coordStr(x,y)); + cell->mCell->mName + "_" + coordStr(x,y)); } } } diff --git a/apps/openmw/mwrender/localmap.hpp b/apps/openmw/mwrender/localmap.hpp index 056d2498a..1aedf1325 100644 --- a/apps/openmw/mwrender/localmap.hpp +++ b/apps/openmw/mwrender/localmap.hpp @@ -58,7 +58,6 @@ namespace MWRender */ void saveFogOfWar(MWWorld::CellStore* cell); - /** * Get the interior map texture index and normalized position * on this texture, given a world position (in ogre coordinates) @@ -75,7 +74,7 @@ namespace MWRender MWRender::RenderingManager* mRenderingManager; // 1024*1024 pixels for a cell - static const int sMapResolution = 1024; + static const int sMapResolution = 512; // the dynamic texture is a bottleneck, so don't set this too high static const int sFogOfWarResolution = 32; diff --git a/apps/openmw/mwrender/npcanimation.cpp b/apps/openmw/mwrender/npcanimation.cpp index 5c2b05aca..e6a8006e2 100644 --- a/apps/openmw/mwrender/npcanimation.cpp +++ b/apps/openmw/mwrender/npcanimation.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -17,44 +17,54 @@ using namespace NifOgre; namespace MWRender{ NpcAnimation::~NpcAnimation() { - removeEntities(head); - removeEntities(hair); - removeEntities(neck); - removeEntities(chest); - removeEntities(groin); - removeEntities(skirt); - removeEntities(rHand); - removeEntities(lHand); - removeEntities(rWrist); - removeEntities(lWrist); - removeEntities(rForearm); - removeEntities(lForearm); - removeEntities(rupperArm); - removeEntities(lupperArm); - removeEntities(rfoot); - removeEntities(lfoot); - removeEntities(rAnkle); - removeEntities(lAnkle); - removeEntities(rKnee); - removeEntities(lKnee); - removeEntities(rUpperLeg); - removeEntities(lUpperLeg); - removeEntities(rclavicle); - removeEntities(lclavicle); - removeEntities(tail); + removeEntities(mHead); + removeEntities(mHair); + removeEntities(mNeck); + removeEntities(mChest); + removeEntities(mGroin); + removeEntities(mSkirt); + removeEntities(mHandL); + removeEntities(mHandR); + removeEntities(mWristL); + removeEntities(mWristR); + removeEntities(mForearmL); + removeEntities(mForearmR); + removeEntities(mUpperArmL); + removeEntities(mUpperArmR); + removeEntities(mFootL); + removeEntities(mFootR); + removeEntities(mAnkleL); + removeEntities(mAnkleR); + removeEntities(mKneeL); + removeEntities(mKneeR); + removeEntities(mUpperLegL); + removeEntities(mUpperLegR); + removeEntities(mClavicleL); + removeEntities(mClavicleR); + removeEntities(mTail); } -NpcAnimation::NpcAnimation(const MWWorld::Ptr& ptr, Ogre::SceneNode* node, MWWorld::InventoryStore& _inv, int visibilityFlags) - : Animation(), mStateID(-1), mInv(_inv), timeToChange(0), mVisibilityFlags(visibilityFlags), - robe(mInv.end()), helmet(mInv.end()), shirt(mInv.end()), - cuirass(mInv.end()), greaves(mInv.end()), - leftpauldron(mInv.end()), rightpauldron(mInv.end()), - boots(mInv.end()), - leftglove(mInv.end()), rightglove(mInv.end()), skirtiter(mInv.end()), - pants(mInv.end()) +NpcAnimation::NpcAnimation(const MWWorld::Ptr& ptr, Ogre::SceneNode* node, MWWorld::InventoryStore& inv, int visibilityFlags) + : Animation(), + mStateID(-1), + mInv(inv), + mTimeToChange(0), + mVisibilityFlags(visibilityFlags), + mRobe(mInv.end()), + mHelmet(mInv.end()), + mShirt(mInv.end()), + mCuirass(mInv.end()), + mGreaves(mInv.end()), + mPauldronL(mInv.end()), + mPauldronR(mInv.end()), + mBoots(mInv.end()), + mPants(mInv.end()), + mGloveL(mInv.end()), + mGloveR(mInv.end()), + mSkirtIter(mInv.end()) { - MWWorld::LiveCellRef *ref = ptr.get(); + mNpc = ptr.get()->mBase; for (int init = 0; init < 27; init++) { @@ -62,25 +72,20 @@ NpcAnimation::NpcAnimation(const MWWorld::Ptr& ptr, Ogre::SceneNode* node, MWWor mPartPriorities[init] = 0; } - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); - const ESM::Race *race = store.races.find(ref->base->mRace); + const MWWorld::ESMStore &store = + MWBase::Environment::get().getWorld()->getStore(); + const ESM::Race *race = store.get().find(mNpc->mRace); - std::string hairID = ref->base->mHair; - std::string headID = ref->base->mHead; - headModel = "meshes\\" + store.bodyParts.find(headID)->mModel; - hairModel = "meshes\\" + store.bodyParts.find(hairID)->mModel; - npcName = ref->base->mName; - - isFemale = !!(ref->base->mFlags&ESM::NPC::Female); - isBeast = !!(race->mData.mFlags&ESM::Race::Beast); - - bodyRaceID = "b_n_"+ref->base->mRace; - std::transform(bodyRaceID.begin(), bodyRaceID.end(), bodyRaceID.begin(), ::tolower); + mHeadModel = "meshes\\" + store.get().find(mNpc->mHead)->mModel; + mHairModel = "meshes\\" + store.get().find(mNpc->mHair)->mModel; + mBodyPrefix = "b_n_" + mNpc->mRace; + std::transform(mBodyPrefix.begin(), mBodyPrefix.end(), mBodyPrefix.begin(), ::tolower); mInsert = node; assert(mInsert); + bool isBeast = (race->mData.mFlags & ESM::Race::Beast) != 0; std::string smodel = (!isBeast ? "meshes\\base_anim.nif" : "meshes\\base_animkna.nif"); mEntityList = NifOgre::NIFLoader::createEntities(mInsert, &mTextKeys, smodel); @@ -124,7 +129,7 @@ NpcAnimation::NpcAnimation(const MWWorld::Ptr& ptr, Ogre::SceneNode* node, MWWor } float scale = race->mData.mHeight.mMale; - if (isFemale) { + if (!mNpc->isMale()) { scale = race->mData.mHeight.mFemale; } mInsert->scale(scale, scale, scale); @@ -140,18 +145,18 @@ void NpcAnimation::updateParts() MWWorld::ContainerStoreIterator *iter; int slot; } slotlist[] = { - { &robe, MWWorld::InventoryStore::Slot_Robe }, - { &skirtiter, MWWorld::InventoryStore::Slot_Skirt }, - { &helmet, MWWorld::InventoryStore::Slot_Helmet }, - { &cuirass, MWWorld::InventoryStore::Slot_Cuirass }, - { &greaves, MWWorld::InventoryStore::Slot_Greaves }, - { &leftpauldron, MWWorld::InventoryStore::Slot_LeftPauldron }, - { &rightpauldron, MWWorld::InventoryStore::Slot_RightPauldron }, - { &boots, MWWorld::InventoryStore::Slot_Boots }, - { &leftglove, MWWorld::InventoryStore::Slot_LeftGauntlet }, - { &rightglove, MWWorld::InventoryStore::Slot_RightGauntlet }, - { &shirt, MWWorld::InventoryStore::Slot_Shirt }, - { &pants, MWWorld::InventoryStore::Slot_Pants }, + { &mRobe, MWWorld::InventoryStore::Slot_Robe }, + { &mSkirtIter, MWWorld::InventoryStore::Slot_Skirt }, + { &mHelmet, MWWorld::InventoryStore::Slot_Helmet }, + { &mCuirass, MWWorld::InventoryStore::Slot_Cuirass }, + { &mGreaves, MWWorld::InventoryStore::Slot_Greaves }, + { &mPauldronL, MWWorld::InventoryStore::Slot_LeftPauldron }, + { &mPauldronR, MWWorld::InventoryStore::Slot_RightPauldron }, + { &mBoots, MWWorld::InventoryStore::Slot_Boots }, + { &mGloveL, MWWorld::InventoryStore::Slot_LeftGauntlet }, + { &mGloveR, MWWorld::InventoryStore::Slot_RightGauntlet }, + { &mShirt, MWWorld::InventoryStore::Slot_Shirt }, + { &mPants, MWWorld::InventoryStore::Slot_Pants }, }; for(size_t i = 0;i < sizeof(slotlist)/sizeof(slotlist[0]);i++) { @@ -166,11 +171,11 @@ void NpcAnimation::updateParts() if(apparelChanged) { - if(robe != mInv.end()) + if(mRobe != mInv.end()) { - MWWorld::Ptr ptr = *robe; + MWWorld::Ptr ptr = *mRobe; - const ESM::Clothing *clothes = (ptr.get())->base; + const ESM::Clothing *clothes = (ptr.get())->mBase; std::vector parts = clothes->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_Robe, 5, parts); reserveIndividualPart(ESM::PRT_Groin, MWWorld::InventoryStore::Slot_Robe, 5); @@ -186,11 +191,11 @@ void NpcAnimation::updateParts() reserveIndividualPart(ESM::PRT_RPauldron, MWWorld::InventoryStore::Slot_Robe, 5); reserveIndividualPart(ESM::PRT_LPauldron, MWWorld::InventoryStore::Slot_Robe, 5); } - if(skirtiter != mInv.end()) + if(mSkirtIter != mInv.end()) { - MWWorld::Ptr ptr = *skirtiter; + MWWorld::Ptr ptr = *mSkirtIter; - const ESM::Clothing *clothes = (ptr.get())->base; + const ESM::Clothing *clothes = (ptr.get())->mBase; std::vector parts = clothes->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_Skirt, 4, parts); reserveIndividualPart(ESM::PRT_Groin, MWWorld::InventoryStore::Slot_Skirt, 4); @@ -198,103 +203,103 @@ void NpcAnimation::updateParts() reserveIndividualPart(ESM::PRT_LLeg, MWWorld::InventoryStore::Slot_Skirt, 4); } - if(helmet != mInv.end()) + if(mHelmet != mInv.end()) { removeIndividualPart(ESM::PRT_Hair); - const ESM::Armor *armor = (helmet->get())->base; + const ESM::Armor *armor = (mHelmet->get())->mBase; std::vector parts = armor->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_Helmet, 3, parts); } - if(cuirass != mInv.end()) + if(mCuirass != mInv.end()) { - const ESM::Armor *armor = (cuirass->get())->base; + const ESM::Armor *armor = (mCuirass->get())->mBase; std::vector parts = armor->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_Cuirass, 3, parts); } - if(greaves != mInv.end()) + if(mGreaves != mInv.end()) { - const ESM::Armor *armor = (greaves->get())->base; + const ESM::Armor *armor = (mGreaves->get())->mBase; std::vector parts = armor->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_Greaves, 3, parts); } - if(leftpauldron != mInv.end()) + if(mPauldronL != mInv.end()) { - const ESM::Armor *armor = (leftpauldron->get())->base; + const ESM::Armor *armor = (mPauldronL->get())->mBase; std::vector parts = armor->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_LeftPauldron, 3, parts); } - if(rightpauldron != mInv.end()) + if(mPauldronR != mInv.end()) { - const ESM::Armor *armor = (rightpauldron->get())->base; + const ESM::Armor *armor = (mPauldronR->get())->mBase; std::vector parts = armor->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_RightPauldron, 3, parts); } - if(boots != mInv.end()) + if(mBoots != mInv.end()) { - if(boots->getTypeName() == typeid(ESM::Clothing).name()) + if(mBoots->getTypeName() == typeid(ESM::Clothing).name()) { - const ESM::Clothing *clothes = (boots->get())->base; + const ESM::Clothing *clothes = (mBoots->get())->mBase; std::vector parts = clothes->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_Boots, 2, parts); } - else if(boots->getTypeName() == typeid(ESM::Armor).name()) + else if(mBoots->getTypeName() == typeid(ESM::Armor).name()) { - const ESM::Armor *armor = (boots->get())->base; + const ESM::Armor *armor = (mBoots->get())->mBase; std::vector parts = armor->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_Boots, 3, parts); } } - if(leftglove != mInv.end()) + if(mGloveL != mInv.end()) { - if(leftglove->getTypeName() == typeid(ESM::Clothing).name()) + if(mGloveL->getTypeName() == typeid(ESM::Clothing).name()) { - const ESM::Clothing *clothes = (leftglove->get())->base; + const ESM::Clothing *clothes = (mGloveL->get())->mBase; std::vector parts = clothes->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_LeftGauntlet, 2, parts); } else { - const ESM::Armor *armor = (leftglove->get())->base; + const ESM::Armor *armor = (mGloveL->get())->mBase; std::vector parts = armor->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_LeftGauntlet, 3, parts); } } - if(rightglove != mInv.end()) + if(mGloveR != mInv.end()) { - if(rightglove->getTypeName() == typeid(ESM::Clothing).name()) + if(mGloveR->getTypeName() == typeid(ESM::Clothing).name()) { - const ESM::Clothing *clothes = (rightglove->get())->base; + const ESM::Clothing *clothes = (mGloveR->get())->mBase; std::vector parts = clothes->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_RightGauntlet, 2, parts); } else { - const ESM::Armor *armor = (rightglove->get())->base; + const ESM::Armor *armor = (mGloveR->get())->mBase; std::vector parts = armor->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_RightGauntlet, 3, parts); } } - if(shirt != mInv.end()) + if(mShirt != mInv.end()) { - const ESM::Clothing *clothes = (shirt->get())->base; + const ESM::Clothing *clothes = (mShirt->get())->mBase; std::vector parts = clothes->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_Shirt, 2, parts); } - if(pants != mInv.end()) + if(mPants != mInv.end()) { - const ESM::Clothing *clothes = (pants->get())->base; + const ESM::Clothing *clothes = (mPants->get())->mBase; std::vector parts = clothes->mParts.mParts; addPartGroup(MWWorld::InventoryStore::Slot_Pants, 2, parts); } } if(mPartPriorities[ESM::PRT_Head] < 1) - addOrReplaceIndividualPart(ESM::PRT_Head, -1,1, headModel); + addOrReplaceIndividualPart(ESM::PRT_Head, -1,1, mHeadModel); if(mPartPriorities[ESM::PRT_Hair] < 1 && mPartPriorities[ESM::PRT_Head] <= 1) - addOrReplaceIndividualPart(ESM::PRT_Hair, -1,1, hairModel); + addOrReplaceIndividualPart(ESM::PRT_Hair, -1,1, mHairModel); static const struct { ESM::PartReferenceType type; @@ -322,26 +327,27 @@ void NpcAnimation::updateParts() { ESM::PRT_Tail, { "tail", "" } } }; - const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); + const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore(); for(size_t i = 0;i < sizeof(PartTypeList)/sizeof(PartTypeList[0]);i++) { if(mPartPriorities[PartTypeList[i].type] < 1) { const ESM::BodyPart *part = NULL; - bool tryfemale = isFemale; - int ni = 0; - do { - part = store.bodyParts.search(bodyRaceID+(tryfemale?"_f_":"_m_")+PartTypeList[i].name[ni]); - if(part) break; + const MWWorld::Store &partStore = + store.get(); - ni ^= 1; - if(ni == 0) - { - if(!tryfemale) - break; - tryfemale = false; + if (!mNpc->isMale()) { + part = partStore.search(mBodyPrefix + "_f_" + PartTypeList[i].name[0]); + if (part == 0) { + part = partStore.search(mBodyPrefix + "_f_" + PartTypeList[i].name[1]); } - } while(1); + } + if (part == 0) { + part = partStore.search(mBodyPrefix + "_m_" + PartTypeList[i].name[0]); + } + if (part == 0) { + part = partStore.search(mBodyPrefix + "_m_" + PartTypeList[i].name[1]); + } if(part) addOrReplaceIndividualPart(PartTypeList[i].type, -1,1, "meshes\\"+part->mModel); @@ -364,12 +370,12 @@ NifOgre::EntityList NpcAnimation::insertBoundedPart(const std::string &mesh, int void NpcAnimation::runAnimation(float timepassed) { - if(timeToChange > .2) + if(mTimeToChange > .2) { - timeToChange = 0; + mTimeToChange = 0; updateParts(); } - timeToChange += timepassed; + mTimeToChange += timepassed; Animation::runAnimation(timepassed); } @@ -394,61 +400,61 @@ void NpcAnimation::removeIndividualPart(int type) mPartslots[type] = -1; if(type == ESM::PRT_Head) //0 - removeEntities(head); + removeEntities(mHead); else if(type == ESM::PRT_Hair) //1 - removeEntities(hair); + removeEntities(mHair); else if(type == ESM::PRT_Neck) //2 - removeEntities(neck); + removeEntities(mNeck); else if(type == ESM::PRT_Cuirass)//3 - removeEntities(chest); + removeEntities(mChest); else if(type == ESM::PRT_Groin)//4 - removeEntities(groin); + removeEntities(mGroin); else if(type == ESM::PRT_Skirt)//5 - removeEntities(skirt); + removeEntities(mSkirt); else if(type == ESM::PRT_RHand)//6 - removeEntities(rHand); + removeEntities(mHandR); else if(type == ESM::PRT_LHand)//7 - removeEntities(lHand); + removeEntities(mHandL); else if(type == ESM::PRT_RWrist)//8 - removeEntities(rWrist); + removeEntities(mWristR); else if(type == ESM::PRT_LWrist) //9 - removeEntities(lWrist); + removeEntities(mWristL); else if(type == ESM::PRT_Shield) //10 { } else if(type == ESM::PRT_RForearm) //11 - removeEntities(rForearm); + removeEntities(mForearmR); else if(type == ESM::PRT_LForearm) //12 - removeEntities(lForearm); + removeEntities(mForearmL); else if(type == ESM::PRT_RUpperarm) //13 - removeEntities(rupperArm); + removeEntities(mUpperArmR); else if(type == ESM::PRT_LUpperarm) //14 - removeEntities(lupperArm); + removeEntities(mUpperArmL); else if(type == ESM::PRT_RFoot) //15 - removeEntities(rfoot); + removeEntities(mFootR); else if(type == ESM::PRT_LFoot) //16 - removeEntities(lfoot); + removeEntities(mFootL); else if(type == ESM::PRT_RAnkle) //17 - removeEntities(rAnkle); + removeEntities(mAnkleR); else if(type == ESM::PRT_LAnkle) //18 - removeEntities(lAnkle); + removeEntities(mAnkleL); else if(type == ESM::PRT_RKnee) //19 - removeEntities(rKnee); + removeEntities(mKneeR); else if(type == ESM::PRT_LKnee) //20 - removeEntities(lKnee); + removeEntities(mKneeL); else if(type == ESM::PRT_RLeg) //21 - removeEntities(rUpperLeg); + removeEntities(mUpperLegR); else if(type == ESM::PRT_LLeg) //22 - removeEntities(lUpperLeg); + removeEntities(mUpperLegL); else if(type == ESM::PRT_RPauldron) //23 - removeEntities(rclavicle); + removeEntities(mClavicleR); else if(type == ESM::PRT_LPauldron) //24 - removeEntities(lclavicle); + removeEntities(mClavicleL); else if(type == ESM::PRT_Weapon) //25 { } else if(type == ESM::PRT_Tail) //26 - removeEntities(tail); + removeEntities(mTail); } void NpcAnimation::reserveIndividualPart(int type, int group, int priority) @@ -481,83 +487,83 @@ bool NpcAnimation::addOrReplaceIndividualPart(int type, int group, int priority, switch(type) { case ESM::PRT_Head: //0 - head = insertBoundedPart(mesh, group, "Head"); + mHead = insertBoundedPart(mesh, group, "Head"); break; case ESM::PRT_Hair: //1 - hair = insertBoundedPart(mesh, group, "Head"); + mHair = insertBoundedPart(mesh, group, "Head"); break; case ESM::PRT_Neck: //2 - neck = insertBoundedPart(mesh, group, "Neck"); + mNeck = insertBoundedPart(mesh, group, "Neck"); break; case ESM::PRT_Cuirass: //3 - chest = insertBoundedPart(mesh, group, "Chest"); + mChest = insertBoundedPart(mesh, group, "Chest"); break; case ESM::PRT_Groin: //4 - groin = insertBoundedPart(mesh, group, "Groin"); + mGroin = insertBoundedPart(mesh, group, "Groin"); break; case ESM::PRT_Skirt: //5 - skirt = insertBoundedPart(mesh, group, "Groin"); + mSkirt = insertBoundedPart(mesh, group, "Groin"); break; case ESM::PRT_RHand: //6 - rHand = insertBoundedPart(mesh, group, "Right Hand"); + mHandR = insertBoundedPart(mesh, group, "Right Hand"); break; case ESM::PRT_LHand: //7 - lHand = insertBoundedPart(mesh, group, "Left Hand"); + mHandL = insertBoundedPart(mesh, group, "Left Hand"); break; case ESM::PRT_RWrist: //8 - rWrist = insertBoundedPart(mesh, group, "Right Wrist"); + mWristR = insertBoundedPart(mesh, group, "Right Wrist"); break; case ESM::PRT_LWrist: //9 - lWrist = insertBoundedPart(mesh, group, "Left Wrist"); + mWristL = insertBoundedPart(mesh, group, "Left Wrist"); break; case ESM::PRT_Shield: //10 break; case ESM::PRT_RForearm: //11 - rForearm = insertBoundedPart(mesh, group, "Right Forearm"); + mForearmR = insertBoundedPart(mesh, group, "Right Forearm"); break; case ESM::PRT_LForearm: //12 - lForearm = insertBoundedPart(mesh, group, "Left Forearm"); + mForearmL = insertBoundedPart(mesh, group, "Left Forearm"); break; case ESM::PRT_RUpperarm: //13 - rupperArm = insertBoundedPart(mesh, group, "Right Upper Arm"); + mUpperArmR = insertBoundedPart(mesh, group, "Right Upper Arm"); break; case ESM::PRT_LUpperarm: //14 - lupperArm = insertBoundedPart(mesh, group, "Left Upper Arm"); + mUpperArmL = insertBoundedPart(mesh, group, "Left Upper Arm"); break; case ESM::PRT_RFoot: //15 - rfoot = insertBoundedPart(mesh, group, "Right Foot"); + mFootR = insertBoundedPart(mesh, group, "Right Foot"); break; case ESM::PRT_LFoot: //16 - lfoot = insertBoundedPart(mesh, group, "Left Foot"); + mFootL = insertBoundedPart(mesh, group, "Left Foot"); break; case ESM::PRT_RAnkle: //17 - rAnkle = insertBoundedPart(mesh, group, "Right Ankle"); + mAnkleR = insertBoundedPart(mesh, group, "Right Ankle"); break; case ESM::PRT_LAnkle: //18 - lAnkle = insertBoundedPart(mesh, group, "Left Ankle"); + mAnkleL = insertBoundedPart(mesh, group, "Left Ankle"); break; case ESM::PRT_RKnee: //19 - rKnee = insertBoundedPart(mesh, group, "Right Knee"); + mKneeR = insertBoundedPart(mesh, group, "Right Knee"); break; case ESM::PRT_LKnee: //20 - lKnee = insertBoundedPart(mesh, group, "Left Knee"); + mKneeL = insertBoundedPart(mesh, group, "Left Knee"); break; case ESM::PRT_RLeg: //21 - rUpperLeg = insertBoundedPart(mesh, group, "Right Upper Leg"); + mUpperLegR = insertBoundedPart(mesh, group, "Right Upper Leg"); break; case ESM::PRT_LLeg: //22 - lUpperLeg = insertBoundedPart(mesh, group, "Left Upper Leg"); + mUpperLegL = insertBoundedPart(mesh, group, "Left Upper Leg"); break; case ESM::PRT_RPauldron: //23 - rclavicle = insertBoundedPart(mesh , group, "Right Clavicle"); + mClavicleR = insertBoundedPart(mesh , group, "Right Clavicle"); break; case ESM::PRT_LPauldron: //24 - lclavicle = insertBoundedPart(mesh, group, "Left Clavicle"); + mClavicleL = insertBoundedPart(mesh, group, "Left Clavicle"); break; case ESM::PRT_Weapon: //25 break; case ESM::PRT_Tail: //26 - tail = insertBoundedPart(mesh, group, "Tail"); + mTail = insertBoundedPart(mesh, group, "Tail"); break; } return true; @@ -569,11 +575,14 @@ void NpcAnimation::addPartGroup(int group, int priority, std::vector &partStore = + MWBase::Environment::get().getWorld()->getStore().get(); + const ESM::BodyPart *bodypart = 0; - if(isFemale) - bodypart = MWBase::Environment::get().getWorld()->getStore().bodyParts.search(part.mFemale); + if(!mNpc->isMale()) + bodypart = partStore.search(part.mFemale); if(!bodypart) - bodypart = MWBase::Environment::get().getWorld()->getStore().bodyParts.search(part.mMale); + bodypart = partStore.search(part.mMale); if(bodypart) addOrReplaceIndividualPart(part.mPart, group, priority,"meshes\\" + bodypart->mModel); diff --git a/apps/openmw/mwrender/npcanimation.hpp b/apps/openmw/mwrender/npcanimation.hpp index 21edb3be4..ca76dcc22 100644 --- a/apps/openmw/mwrender/npcanimation.hpp +++ b/apps/openmw/mwrender/npcanimation.hpp @@ -8,6 +8,11 @@ #include "../mwclass/npc.hpp" #include "../mwworld/containerstore.hpp" +namespace ESM +{ + struct NPC; +} + namespace MWRender{ class NpcAnimation: public Animation{ @@ -19,57 +24,57 @@ private: int mPartPriorities[27]; //Bounded Parts - NifOgre::EntityList lclavicle; - NifOgre::EntityList rclavicle; - NifOgre::EntityList rupperArm; - NifOgre::EntityList lupperArm; - NifOgre::EntityList rUpperLeg; - NifOgre::EntityList lUpperLeg; - NifOgre::EntityList lForearm; - NifOgre::EntityList rForearm; - NifOgre::EntityList lWrist; - NifOgre::EntityList rWrist; - NifOgre::EntityList rKnee; - NifOgre::EntityList lKnee; - NifOgre::EntityList neck; - NifOgre::EntityList rAnkle; - NifOgre::EntityList lAnkle; - NifOgre::EntityList groin; - NifOgre::EntityList skirt; - NifOgre::EntityList lfoot; - NifOgre::EntityList rfoot; - NifOgre::EntityList hair; - NifOgre::EntityList rHand; - NifOgre::EntityList lHand; - NifOgre::EntityList head; - NifOgre::EntityList chest; - NifOgre::EntityList tail; + NifOgre::EntityList mClavicleL; + NifOgre::EntityList mClavicleR; + NifOgre::EntityList mUpperArmL; + NifOgre::EntityList mUpperArmR; + NifOgre::EntityList mUpperLegL; + NifOgre::EntityList mUpperLegR; + NifOgre::EntityList mForearmL; + NifOgre::EntityList mForearmR; + NifOgre::EntityList mWristL; + NifOgre::EntityList mWristR; + NifOgre::EntityList mKneeR; + NifOgre::EntityList mKneeL; + NifOgre::EntityList mNeck; + NifOgre::EntityList mAnkleL; + NifOgre::EntityList mAnkleR; + NifOgre::EntityList mGroin; + NifOgre::EntityList mSkirt; + NifOgre::EntityList mFootL; + NifOgre::EntityList mFootR; + NifOgre::EntityList mHair; + NifOgre::EntityList mHandL; + NifOgre::EntityList mHandR; + NifOgre::EntityList mHead; + NifOgre::EntityList mChest; + NifOgre::EntityList mTail; - bool isBeast; - bool isFemale; - std::string headModel; - std::string hairModel; - std::string npcName; - std::string bodyRaceID; - float timeToChange; - MWWorld::ContainerStoreIterator robe; - MWWorld::ContainerStoreIterator helmet; - MWWorld::ContainerStoreIterator shirt; - MWWorld::ContainerStoreIterator cuirass; - MWWorld::ContainerStoreIterator greaves; - MWWorld::ContainerStoreIterator leftpauldron; - MWWorld::ContainerStoreIterator rightpauldron; - MWWorld::ContainerStoreIterator boots; - MWWorld::ContainerStoreIterator pants; - MWWorld::ContainerStoreIterator leftglove; - MWWorld::ContainerStoreIterator rightglove; - MWWorld::ContainerStoreIterator skirtiter; + const ESM::NPC *mNpc; + std::string mHeadModel; + std::string mHairModel; + std::string mBodyPrefix; + + + float mTimeToChange; + MWWorld::ContainerStoreIterator mRobe; + MWWorld::ContainerStoreIterator mHelmet; + MWWorld::ContainerStoreIterator mShirt; + MWWorld::ContainerStoreIterator mCuirass; + MWWorld::ContainerStoreIterator mGreaves; + MWWorld::ContainerStoreIterator mPauldronL; + MWWorld::ContainerStoreIterator mPauldronR; + MWWorld::ContainerStoreIterator mBoots; + MWWorld::ContainerStoreIterator mPants; + MWWorld::ContainerStoreIterator mGloveL; + MWWorld::ContainerStoreIterator mGloveR; + MWWorld::ContainerStoreIterator mSkirtIter; int mVisibilityFlags; public: NpcAnimation(const MWWorld::Ptr& ptr, Ogre::SceneNode* node, - MWWorld::InventoryStore& _inv, int visibilityFlags); + MWWorld::InventoryStore& inv, int visibilityFlags); virtual ~NpcAnimation(); NifOgre::EntityList insertBoundedPart(const std::string &mesh, int group, const std::string &bonename); virtual void runAnimation(float timepassed); diff --git a/apps/openmw/mwrender/objects.cpp b/apps/openmw/mwrender/objects.cpp index 69c853d86..36f09e6d9 100644 --- a/apps/openmw/mwrender/objects.cpp +++ b/apps/openmw/mwrender/objects.cpp @@ -219,18 +219,18 @@ void Objects::insertLight (const MWWorld::Ptr& ptr, float r, float g, float b, f info.radius = radius; info.colour = Ogre::ColourValue(r, g, b); - if (ref->base->mData.mFlags & ESM::Light::Negative) + if (ref->mBase->mData.mFlags & ESM::Light::Negative) info.colour *= -1; - info.interior = (ptr.getCell()->cell->mData.mFlags & ESM::Cell::Interior); + info.interior = !ptr.getCell()->mCell->isExterior(); - if (ref->base->mData.mFlags & ESM::Light::Flicker) + if (ref->mBase->mData.mFlags & ESM::Light::Flicker) info.type = LT_Flicker; - else if (ref->base->mData.mFlags & ESM::Light::FlickerSlow) + else if (ref->mBase->mData.mFlags & ESM::Light::FlickerSlow) info.type = LT_FlickerSlow; - else if (ref->base->mData.mFlags & ESM::Light::Pulse) + else if (ref->mBase->mData.mFlags & ESM::Light::Pulse) info.type = LT_Pulse; - else if (ref->base->mData.mFlags & ESM::Light::PulseSlow) + else if (ref->mBase->mData.mFlags & ESM::Light::PulseSlow) info.type = LT_PulseSlow; else info.type = LT_Normal; diff --git a/apps/openmw/mwrender/player.cpp b/apps/openmw/mwrender/player.cpp index bbc75cade..0e4c76b0e 100644 --- a/apps/openmw/mwrender/player.cpp +++ b/apps/openmw/mwrender/player.cpp @@ -23,7 +23,8 @@ namespace MWRender mFreeLook(true), mHeight(128.f), mCameraDistance(300.f), - mDistanceAdjusted(false) + mDistanceAdjusted(false), + mAnimation(NULL) { mVanity.enabled = false; mVanity.allowed = true; @@ -309,7 +310,13 @@ namespace MWRender void Player::setAnimation(NpcAnimation *anim) { + delete mAnimation; mAnimation = anim; + + mPlayerNode->setVisible( + mVanity.enabled || mPreviewMode || !mFirstPersonView, + false + ); } void Player::setHeight(float height) diff --git a/apps/openmw/mwrender/player.hpp b/apps/openmw/mwrender/player.hpp index b4d8983e4..29a68ca69 100644 --- a/apps/openmw/mwrender/player.hpp +++ b/apps/openmw/mwrender/player.hpp @@ -48,16 +48,6 @@ namespace MWRender /// Updates sound manager listener data void updateListener(); - void rotateCamera(const Ogre::Vector3 &rot, bool adjust); - - float getYaw(); - void setYaw(float angle); - - float getPitch(); - void setPitch(float angle); - - void compensateYaw(float diff); - void setLowHeight(bool low = true); public: @@ -69,7 +59,17 @@ namespace MWRender /// \param rot Rotation angles in radians /// \return true if player object needs to bo rotated physically bool rotate(const Ogre::Vector3 &rot, bool adjust); + + void rotateCamera(const Ogre::Vector3 &rot, bool adjust); + float getYaw(); + void setYaw(float angle); + + float getPitch(); + void setPitch(float angle); + + void compensateYaw(float diff); + std::string getHandle() const; /// Attach camera to object diff --git a/apps/openmw/mwrender/renderingmanager.cpp b/apps/openmw/mwrender/renderingmanager.cpp index fe74fe545..14392fc49 100644 --- a/apps/openmw/mwrender/renderingmanager.cpp +++ b/apps/openmw/mwrender/renderingmanager.cpp @@ -13,12 +13,13 @@ #include #include #include +#include #include #include #include -#include +#include "../mwworld/esmstore.hpp" #include #include "../mwbase/world.hpp" // these includes can be removed once the static-hack is gone @@ -68,7 +69,7 @@ RenderingManager::RenderingManager (OEngine::Render::OgreRenderer& _rend, const // material system sh::OgrePlatform* platform = new sh::OgrePlatform("General", (resDir / "materials").string()); if (!boost::filesystem::exists (cacheDir)) - boost::filesystem::create_directory (cacheDir); + boost::filesystem::create_directories (cacheDir); platform->setCacheFolder (cacheDir.string()); mFactory = new sh::Factory(platform); @@ -184,6 +185,7 @@ RenderingManager::~RenderingManager () delete mCompositors; delete mWater; delete mVideoPlayer; + delete mFactory; } MWRender::SkyManager* RenderingManager::getSkyManager() @@ -208,7 +210,7 @@ void RenderingManager::removeCell (MWWorld::Ptr::CellStore *store) mObjects.removeCell(store); mActors.removeCell(store); mDebugging->cellRemoved(store); - if (store->cell->isExterior()) + if (store->mCell->isExterior()) mTerrainManager->cellRemoved(store); } @@ -229,7 +231,7 @@ void RenderingManager::cellAdded (MWWorld::Ptr::CellStore *store) { mObjects.buildStaticGeometry (*store); mDebugging->cellAdded(store); - if (store->cell->isExterior()) + if (store->mCell->isExterior()) mTerrainManager->cellAdded(store); waterAdded(store); } @@ -238,18 +240,12 @@ void RenderingManager::addObject (const MWWorld::Ptr& ptr){ const MWWorld::Class& class_ = MWWorld::Class::get (ptr); class_.insertObjectRendering(ptr, *this); - } + void RenderingManager::removeObject (const MWWorld::Ptr& ptr) { if (!mObjects.deleteObject (ptr)) - { - /// \todo delete non-object MW-references - } - if (!mActors.deleteObject (ptr)) - { - /// \todo delete non-object MW-references - } + mActors.deleteObject (ptr); } void RenderingManager::moveObject (const MWWorld::Ptr& ptr, const Ogre::Vector3& position) @@ -259,39 +255,46 @@ void RenderingManager::moveObject (const MWWorld::Ptr& ptr, const Ogre::Vector3& setPosition (position); } -void RenderingManager::scaleObject (const MWWorld::Ptr& ptr, const Ogre::Vector3& scale){ - +void RenderingManager::scaleObject (const MWWorld::Ptr& ptr, const Ogre::Vector3& scale) +{ + ptr.getRefData().getBaseNode()->setScale(scale); } -bool -RenderingManager::rotateObject( - const MWWorld::Ptr &ptr, - Ogre::Vector3 &rot, - bool adjust) +bool RenderingManager::rotateObject( const MWWorld::Ptr &ptr, Ogre::Vector3 &rot, bool adjust) { bool isActive = ptr.getRefData().getBaseNode() != 0; bool isPlayer = isActive && ptr.getRefData().getHandle() == "player"; bool force = true; - if (isPlayer) { + if (isPlayer) force = mPlayer->rotate(rot, adjust); - } + MWWorld::Class::get(ptr).adjustRotation(ptr, rot.x, rot.y, rot.z); - if (adjust) { - /// \note Stored and passed in radians - float *f = ptr.getRefData().getPosition().rot; - rot.x += f[0], rot.y += f[1], rot.z += f[2]; - } - - if (!isPlayer && isActive) { + if (!isPlayer && isActive) + { Ogre::Quaternion xr(Ogre::Radian(rot.x), Ogre::Vector3::UNIT_X); Ogre::Quaternion yr(Ogre::Radian(rot.y), Ogre::Vector3::UNIT_Y); Ogre::Quaternion zr(Ogre::Radian(rot.z), Ogre::Vector3::UNIT_Z); - - ptr.getRefData().getBaseNode()->setOrientation(xr * yr * zr); + Ogre::Quaternion newo = adjust ? (xr * yr * zr) * ptr.getRefData().getBaseNode()->getOrientation() : xr * yr * zr; + rot.x = newo.x; + rot.y = newo.y; + rot.z = newo.z; + ptr.getRefData().getBaseNode()->setOrientation(newo); + } + else if(isPlayer) + { + rot.x = mPlayer->getPitch(); + rot.z = mPlayer->getYaw(); + } + else if (adjust) + { + // Stored and passed in radians + float *f = ptr.getRefData().getPosition().rot; + rot.x += f[0]; + rot.y += f[1]; + rot.z += f[2]; } - return force; } @@ -315,7 +318,7 @@ RenderingManager::moveObjectToCell( child->setPosition(pos); } -void RenderingManager::update (float duration) +void RenderingManager::update (float duration, bool paused) { Ogre::Vector3 orig, dest; mPlayer->setCameraDistance(); @@ -330,12 +333,23 @@ void RenderingManager::update (float duration) mPlayer->setCameraDistance(test.second * orig.distance(dest), false, false); } } + mOcclusionQuery->update(duration); + + mVideoPlayer->update (); + + if(paused) + { + Ogre::ControllerManager::getSingleton().setTimeFactor(0.f); + return; + } + Ogre::ControllerManager::getSingleton().setTimeFactor( + MWBase::Environment::get().getWorld()->getTimeScaleFactor()/30.f); + mPlayer->update(duration); mActors.update (duration); mObjects.update (duration); - mOcclusionQuery->update(duration); mSkyManager->update(duration); @@ -343,8 +357,6 @@ void RenderingManager::update (float duration) mRendering.update(duration); - mVideoPlayer->update (); - MWWorld::RefData &data = MWBase::Environment::get() .getWorld() @@ -354,7 +366,7 @@ void RenderingManager::update (float duration) float *fpos = data.getPosition().pos; - /// \note only for LocalMap::updatePlayer() + // only for LocalMap::updatePlayer() Ogre::Vector3 pos(fpos[0], -fpos[2], -fpos[1]); Ogre::SceneNode *node = data.getBaseNode(); @@ -370,22 +382,26 @@ void RenderingManager::update (float duration) mWater->updateUnderwater( world->isUnderwater( - *world->getPlayer().getPlayer().getCell()->cell, + *world->getPlayer().getPlayer().getCell()->mCell, Ogre::Vector3(cam.x, -cam.z, cam.y)) ); mWater->update(duration); } } -void RenderingManager::waterAdded (MWWorld::Ptr::CellStore *store){ - if(store->cell->mData.mFlags & store->cell->HasWater - || ((!(store->cell->mData.mFlags & ESM::Cell::Interior)) - && !MWBase::Environment::get().getWorld()->getStore().lands.search(store->cell->mData.mX,store->cell->mData.mY) )) // always use water, if the cell does not have land. +void RenderingManager::waterAdded (MWWorld::Ptr::CellStore *store) +{ + const MWWorld::Store &lands = + MWBase::Environment::get().getWorld()->getStore().get(); + + if(store->mCell->mData.mFlags & ESM::Cell::HasWater + || ((store->mCell->isExterior()) + && !lands.search(store->mCell->getGridX(),store->mCell->getGridY()) )) // always use water, if the cell does not have land. { if(mWater == 0) - mWater = new MWRender::Water(mRendering.getCamera(), this, store->cell); + mWater = new MWRender::Water(mRendering.getCamera(), this, store->mCell); else - mWater->changeCell(store->cell); + mWater->changeCell(store->mCell); mWater->setActive(true); } else @@ -462,7 +478,13 @@ bool RenderingManager::toggleRenderMode(int mode) return false; } } - else //if (mode == MWWorld::World::Render_Compositors) + else if (mode == MWBase::World::Render_BoundingBoxes) + { + bool show = !mRendering.getScene()->getShowBoundingBoxes(); + mRendering.getScene()->showBoundingBoxes(show); + return show; + } + else //if (mode == MWBase::World::Render_Compositors) { return mCompositors->toggle(); } @@ -471,9 +493,9 @@ bool RenderingManager::toggleRenderMode(int mode) void RenderingManager::configureFog(MWWorld::Ptr::CellStore &mCell) { Ogre::ColourValue color; - color.setAsABGR (mCell.cell->mAmbi.mFog); + color.setAsABGR (mCell.mCell->mAmbi.mFog); - configureFog(mCell.cell->mAmbi.mFogDensity, color); + configureFog(mCell.mCell->mAmbi.mFogDensity, color); if (mWater) mWater->setViewportBackground (Ogre::ColourValue(0.8f, 0.9f, 1.0f)); @@ -523,7 +545,7 @@ void RenderingManager::setAmbientMode() void RenderingManager::configureAmbient(MWWorld::Ptr::CellStore &mCell) { - mAmbientColor.setAsABGR (mCell.cell->mAmbi.mAmbient); + mAmbientColor.setAsABGR (mCell.mCell->mAmbi.mAmbient); setAmbientMode(); // Create a "sun" that shines light downwards. It doesn't look @@ -533,7 +555,7 @@ void RenderingManager::configureAmbient(MWWorld::Ptr::CellStore &mCell) mSun = mRendering.getScene()->createLight(); } Ogre::ColourValue colour; - colour.setAsABGR (mCell.cell->mAmbi.mSunlight); + colour.setAsABGR (mCell.mCell->mAmbi.mSunlight); mSun->setDiffuseColour (colour); mSun->setType(Ogre::Light::LT_DIRECTIONAL); mSun->setDirection(0,-1,0); @@ -617,7 +639,7 @@ void RenderingManager::setGlare(bool glare) void RenderingManager::requestMap(MWWorld::Ptr::CellStore* cell) { - if (!(cell->cell->mData.mFlags & ESM::Cell::Interior)) + if (cell->mCell->isExterior()) mLocalMap->requestMap(cell); else mLocalMap->requestMap(cell, mObjects.getDimensions(cell)); diff --git a/apps/openmw/mwrender/renderingmanager.hpp b/apps/openmw/mwrender/renderingmanager.hpp index d0ef3f593..ee64a371e 100644 --- a/apps/openmw/mwrender/renderingmanager.hpp +++ b/apps/openmw/mwrender/renderingmanager.hpp @@ -126,7 +126,7 @@ class RenderingManager: private RenderingInterface, public Ogre::WindowEventList /// \param store Cell the object was in previously (\a ptr has already been updated to the new cell). void moveObjectToCell (const MWWorld::Ptr& ptr, const Ogre::Vector3& position, MWWorld::CellStore *store); - void update (float duration); + void update (float duration, bool paused); void setAmbientColour(const Ogre::ColourValue& colour); void setSunColour(const Ogre::ColourValue& colour); diff --git a/apps/openmw/mwrender/terrain.cpp b/apps/openmw/mwrender/terrain.cpp index 114a9bc37..e5a1362d7 100644 --- a/apps/openmw/mwrender/terrain.cpp +++ b/apps/openmw/mwrender/terrain.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include @@ -92,10 +92,11 @@ namespace MWRender void TerrainManager::cellAdded(MWWorld::Ptr::CellStore *store) { - const int cellX = store->cell->getGridX(); - const int cellY = store->cell->getGridY(); + const int cellX = store->mCell->getGridX(); + const int cellY = store->mCell->getGridY(); - ESM::Land* land = MWBase::Environment::get().getWorld()->getStore().lands.search(cellX, cellY); + ESM::Land* land = + MWBase::Environment::get().getWorld()->getStore().get().search(cellX, cellY); if (land == NULL) // no land data means we're not going to create any terrain. return; @@ -188,8 +189,8 @@ namespace MWRender { for ( int y = 0; y < 2; y++ ) { - int terrainX = store->cell->getGridX() * 2 + x; - int terrainY = store->cell->getGridY() * 2 + y; + int terrainX = store->mCell->getGridX() * 2 + x; + int terrainY = store->mCell->getGridY() * 2 + y; if (mTerrainGroup.getTerrain(terrainX, terrainY) != NULL) mTerrainGroup.unloadTerrain(terrainX, terrainY); } @@ -245,7 +246,10 @@ namespace MWRender { //NB: All vtex ids are +1 compared to the ltex ids - assert( (int)MWBase::Environment::get().getWorld()->getStore().landTexts.getSize() >= (int)ltexIndex - 1 && + const MWWorld::Store <exStore = + MWBase::Environment::get().getWorld()->getStore().get(); + + assert( (int)ltexStore.getSize() >= (int)ltexIndex - 1 && "LAND.VTEX must be within the bounds of the LTEX array"); std::string texture; @@ -255,7 +259,7 @@ namespace MWRender } else { - texture = MWBase::Environment::get().getWorld()->getStore().landTexts.search(ltexIndex-1)->mTexture; + texture = ltexStore.search(ltexIndex-1)->mTexture; //TODO this is needed due to MWs messed up texture handling texture = texture.substr(0, texture.rfind(".")) + ".dds"; } @@ -411,7 +415,8 @@ namespace MWRender } - ESM::Land* land = MWBase::Environment::get().getWorld()->getStore().lands.search(cellX, cellY); + ESM::Land* land = + MWBase::Environment::get().getWorld()->getStore().get().search(cellX, cellY); if ( land != NULL ) { if (!land->isDataLoaded(ESM::Land::DATA_VTEX)) diff --git a/apps/openmw/mwrender/videoplayer.cpp b/apps/openmw/mwrender/videoplayer.cpp index 195369a2d..4679104d8 100644 --- a/apps/openmw/mwrender/videoplayer.cpp +++ b/apps/openmw/mwrender/videoplayer.cpp @@ -233,7 +233,17 @@ namespace MWRender mVideoCodecContext->width, mVideoCodecContext->height, 0, Ogre::PF_BYTE_RGBA, - Ogre::TU_DEFAULT); + Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE); + + // initialize to (0, 0, 0, 1) + std::vector buffer; + buffer.resize(mVideoCodecContext->width * mVideoCodecContext->height); + for (int p=0; pwidth * mVideoCodecContext->height; ++p) + { + buffer[p] = (255 << 24); + } + memcpy(mVideoTexture->getBuffer()->lock(Ogre::HardwareBuffer::HBL_DISCARD), &buffer[0], mVideoCodecContext->width*mVideoCodecContext->height*4); + mVideoTexture->getBuffer()->unlock(); mTextureUnit->setTextureName ("VideoTexture"); diff --git a/apps/openmw/mwrender/water.hpp b/apps/openmw/mwrender/water.hpp index dcb76533b..f1e3d7a3b 100644 --- a/apps/openmw/mwrender/water.hpp +++ b/apps/openmw/mwrender/water.hpp @@ -23,7 +23,7 @@ namespace Ogre class Entity; class Vector3; struct RenderTargetEvent; -}; +} namespace MWRender { diff --git a/apps/openmw/mwscript/aiextensions.cpp b/apps/openmw/mwscript/aiextensions.cpp index 9d70c28bd..787962ad1 100644 --- a/apps/openmw/mwscript/aiextensions.cpp +++ b/apps/openmw/mwscript/aiextensions.cpp @@ -130,7 +130,7 @@ namespace MWScript Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); - MWWorld::Class::get (ptr).getCreatureStats (ptr).setHello(value); + MWWorld::Class::get (ptr).getCreatureStats (ptr).setAiSetting (0, value); } }; @@ -146,7 +146,7 @@ namespace MWScript Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); - MWWorld::Class::get (ptr).getCreatureStats (ptr).setFight(value); + MWWorld::Class::get (ptr).getCreatureStats (ptr).setAiSetting (1, value); } }; @@ -162,7 +162,7 @@ namespace MWScript Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); - MWWorld::Class::get (ptr).getCreatureStats (ptr).setFlee(value); + MWWorld::Class::get (ptr).getCreatureStats (ptr).setAiSetting (2, value); } }; @@ -178,7 +178,7 @@ namespace MWScript Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); - MWWorld::Class::get (ptr).getCreatureStats (ptr).setAlarm(value); + MWWorld::Class::get (ptr).getCreatureStats (ptr).setAiSetting (3, value); } }; diff --git a/apps/openmw/mwscript/cellextensions.cpp b/apps/openmw/mwscript/cellextensions.cpp index 57dd7962b..a4a738ca7 100644 --- a/apps/openmw/mwscript/cellextensions.cpp +++ b/apps/openmw/mwscript/cellextensions.cpp @@ -1,7 +1,7 @@ #include "cellextensions.hpp" -#include +#include "../mwworld/esmstore.hpp" #include @@ -87,8 +87,7 @@ namespace MWScript virtual void execute (Interpreter::Runtime& runtime) { bool interior = - MWBase::Environment::get().getWorld()->getPlayer().getPlayer().getCell()->cell->mData.mFlags & - ESM::Cell::Interior; + !MWBase::Environment::get().getWorld()->getPlayer().getPlayer().getCell()->mCell->isExterior(); runtime.push (interior ? 1 : 0); } @@ -103,14 +102,14 @@ namespace MWScript std::string name = runtime.getStringLiteral (runtime[0].mInteger); runtime.pop(); - const ESM::Cell *cell = MWBase::Environment::get().getWorld()->getPlayer().getPlayer().getCell()->cell; + const ESM::Cell *cell = MWBase::Environment::get().getWorld()->getPlayer().getPlayer().getCell()->mCell; std::string current = cell->mName; if (!(cell->mData.mFlags & ESM::Cell::Interior) && current.empty()) { const ESM::Region *region = - MWBase::Environment::get().getWorld()->getStore().regions.find (cell->mRegion); + MWBase::Environment::get().getWorld()->getStore().get().find (cell->mRegion); current = region->mName; } @@ -143,7 +142,7 @@ namespace MWScript MWWorld::Ptr::CellStore *cell = MWBase::Environment::get().getWorld()->getPlayer().getPlayer().getCell(); - if (!(cell->cell->mData.mFlags & ESM::Cell::Interior)) + if (cell->mCell->isExterior()) throw std::runtime_error("Can't set water level in exterior cell"); cell->mWaterLevel = level; @@ -161,7 +160,7 @@ namespace MWScript MWWorld::Ptr::CellStore *cell = MWBase::Environment::get().getWorld()->getPlayer().getPlayer().getCell(); - if (!(cell->cell->mData.mFlags & ESM::Cell::Interior)) + if (cell->mCell->isExterior()) throw std::runtime_error("Can't set water level in exterior cell"); cell->mWaterLevel +=level; diff --git a/apps/openmw/mwscript/compilercontext.cpp b/apps/openmw/mwscript/compilercontext.cpp index 139a5cc6c..57d93512f 100644 --- a/apps/openmw/mwscript/compilercontext.cpp +++ b/apps/openmw/mwscript/compilercontext.cpp @@ -1,7 +1,7 @@ #include "compilercontext.hpp" -#include +#include "../mwworld/esmstore.hpp" #include @@ -42,26 +42,29 @@ namespace MWScript bool CompilerContext::isId (const std::string& name) const { + const MWWorld::ESMStore &store = + MWBase::Environment::get().getWorld()->getStore(); + return - MWBase::Environment::get().getWorld()->getStore().activators.search (name) || - MWBase::Environment::get().getWorld()->getStore().potions.search (name) || - MWBase::Environment::get().getWorld()->getStore().appas.search (name) || - MWBase::Environment::get().getWorld()->getStore().armors.search (name) || - MWBase::Environment::get().getWorld()->getStore().books.search (name) || - MWBase::Environment::get().getWorld()->getStore().clothes.search (name) || - MWBase::Environment::get().getWorld()->getStore().containers.search (name) || - MWBase::Environment::get().getWorld()->getStore().creatures.search (name) || - MWBase::Environment::get().getWorld()->getStore().doors.search (name) || - MWBase::Environment::get().getWorld()->getStore().ingreds.search (name) || - MWBase::Environment::get().getWorld()->getStore().creatureLists.search (name) || - MWBase::Environment::get().getWorld()->getStore().itemLists.search (name) || - MWBase::Environment::get().getWorld()->getStore().lights.search (name) || - MWBase::Environment::get().getWorld()->getStore().lockpicks.search (name) || - MWBase::Environment::get().getWorld()->getStore().miscItems.search (name) || - MWBase::Environment::get().getWorld()->getStore().npcs.search (name) || - MWBase::Environment::get().getWorld()->getStore().probes.search (name) || - MWBase::Environment::get().getWorld()->getStore().repairs.search (name) || - MWBase::Environment::get().getWorld()->getStore().statics.search (name) || - MWBase::Environment::get().getWorld()->getStore().weapons.search (name); + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name) || + store.get().search (name); } } diff --git a/apps/openmw/mwscript/docs/vmformat.txt b/apps/openmw/mwscript/docs/vmformat.txt index 584a29926..fdc4f4974 100644 --- a/apps/openmw/mwscript/docs/vmformat.txt +++ b/apps/openmw/mwscript/docs/vmformat.txt @@ -31,7 +31,13 @@ op 0x2000e: PCGetRank implicit op 0x2000f: PCGetRank explicit op 0x20010: AiWander op 0x20011: AiWander, explicit reference -op s 0x20012-0x3ffff unused +op 0x20012: GetPCFacRep +op 0x20013: GetPCFacRep, explicit reference +op 0x20014: SetPCFacRep +op 0x20015: SetPCFacRep, explicit reference +op 0x20016: ModPCFacRep +op 0x20017: ModPCFacRep, explicit reference +op s 0x20018-0x3ffff unused Segment 4: (not implemented yet) @@ -198,13 +204,23 @@ op 0x2000197: Position Explicit op 0x2000198: PositionCell op 0x2000199: PositionCell Explicit op 0x200019a: PlaceItemCell -op 0x200019b: PlaceItem +op 0x200019b: PlaceItem op 0x200019c: PlaceAtPc -op 0x200019d: PlaceAtMe +op 0x200019d: PlaceAtMe op 0x200019e: PlaceAtMe Explicit op 0x200019f: GetPcSleep op 0x20001a0: ShowMap op 0x20001a1: FillMap op 0x20001a2: WakeUpPc -opcodes 0x20001a3-0x3ffffff unused +op 0x20001a3: GetDeadCount +op 0x20001a4: SetDisposition +op 0x20001a5: SetDisposition, Explicit +op 0x20001a6: GetDisposition +op 0x20001a7: GetDisposition, Explicit +op 0x20001a8: CommonDisease +op 0x20001a9: CommonDisease, explicit reference +op 0x20001aa: BlightDisease +op 0x20001ab: BlightDisease, explicit reference +op 0x20001ac: ToggleCollisionBoxes +opcodes 0x20001ac-0x3ffffff unused diff --git a/apps/openmw/mwscript/globalscripts.cpp b/apps/openmw/mwscript/globalscripts.cpp index 37cf34127..3ef138432 100644 --- a/apps/openmw/mwscript/globalscripts.cpp +++ b/apps/openmw/mwscript/globalscripts.cpp @@ -3,8 +3,7 @@ #include -#include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/scriptmanager.hpp" @@ -13,21 +12,23 @@ namespace MWScript { - GlobalScripts::GlobalScripts (const ESMS::ESMStore& store) + GlobalScripts::GlobalScripts (const MWWorld::ESMStore& store) : mStore (store) { addScript ("Main"); - for (ESMS::RecListT::MapType::const_iterator iter - (store.startScripts.list.begin()); - iter != store.startScripts.list.end(); ++iter) - addScript (iter->second.mScript); + MWWorld::Store::iterator iter = + store.get().begin(); + + for (; iter != store.get().end(); ++iter) { + addScript (iter->mScript); + } } void GlobalScripts::addScript (const std::string& name) { if (mScripts.find (name)==mScripts.end()) - if (const ESM::Script *script = mStore.scripts.find (name)) + if (const ESM::Script *script = mStore.get().find (name)) { Locals locals; diff --git a/apps/openmw/mwscript/globalscripts.hpp b/apps/openmw/mwscript/globalscripts.hpp index cc2f7ffdd..f9f9b7ae3 100644 --- a/apps/openmw/mwscript/globalscripts.hpp +++ b/apps/openmw/mwscript/globalscripts.hpp @@ -6,7 +6,7 @@ #include "locals.hpp" -namespace ESMS +namespace MWWorld { struct ESMStore; } @@ -15,12 +15,12 @@ namespace MWScript { class GlobalScripts { - const ESMS::ESMStore& mStore; + const MWWorld::ESMStore& mStore; std::map > mScripts; // running, local variables public: - GlobalScripts (const ESMS::ESMStore& store); + GlobalScripts (const MWWorld::ESMStore& store); void addScript (const std::string& name); diff --git a/apps/openmw/mwscript/guiextensions.cpp b/apps/openmw/mwscript/guiextensions.cpp index 66bb4e043..72c2db164 100644 --- a/apps/openmw/mwscript/guiextensions.cpp +++ b/apps/openmw/mwscript/guiextensions.cpp @@ -9,8 +9,7 @@ #include #include -#include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/windowmanager.hpp" @@ -109,13 +108,20 @@ namespace MWScript // "Will match complete or partial cells, so ShowMap, "Vivec" will show cells Vivec and Vivec, Fred's House as well." // http://www.uesp.net/wiki/Tes3Mod:ShowMap - const ESMS::CellList::ExtCells& extCells = MWBase::Environment::get().getWorld ()->getStore ().cells.extCells; - for (ESMS::CellList::ExtCells::const_iterator it = extCells.begin(); it != extCells.end(); ++it) + const MWWorld::Store &cells = + MWBase::Environment::get().getWorld()->getStore().get(); + + MWWorld::Store::iterator it = cells.extBegin(); + for (; it != cells.extEnd(); ++it) { - std::string name = it->second->mName; + std::string name = it->mName; boost::algorithm::to_lower(name); if (name.find(cell) != std::string::npos) - MWBase::Environment::get().getWindowManager()->addVisitedLocation (it->second->mName, it->first.first, it->first.second); + MWBase::Environment::get().getWindowManager()->addVisitedLocation ( + it->mName, + it->getGridX(), + it->getGridY() + ); } } }; @@ -126,12 +132,19 @@ namespace MWScript virtual void execute (Interpreter::Runtime& runtime) { - const ESMS::CellList::ExtCells& extCells = MWBase::Environment::get().getWorld ()->getStore ().cells.extCells; - for (ESMS::CellList::ExtCells::const_iterator it = extCells.begin(); it != extCells.end(); ++it) + const MWWorld::Store &cells = + MWBase::Environment::get().getWorld ()->getStore().get(); + + MWWorld::Store::iterator it = cells.extBegin(); + for (; it != cells.extEnd(); ++it) { - std::string name = it->second->mName; + std::string name = it->mName; if (name != "") - MWBase::Environment::get().getWindowManager()->addVisitedLocation (name, it->first.first, it->first.second); + MWBase::Environment::get().getWindowManager()->addVisitedLocation ( + name, + it->getGridX(), + it->getGridY() + ); } } }; diff --git a/apps/openmw/mwscript/interpretercontext.cpp b/apps/openmw/mwscript/interpretercontext.cpp index 075ac5646..577ad008f 100644 --- a/apps/openmw/mwscript/interpretercontext.cpp +++ b/apps/openmw/mwscript/interpretercontext.cpp @@ -5,7 +5,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -278,7 +278,7 @@ namespace MWScript int index = MWBase::Environment::get().getScriptManager()->getLocalIndex (scriptId, name, 's'); ptr.getRefData().setLocals ( - *MWBase::Environment::get().getWorld()->getStore().scripts.find (scriptId)); + *MWBase::Environment::get().getWorld()->getStore().get().find (scriptId)); return ptr.getRefData().getLocals().mShorts[index]; } @@ -291,7 +291,7 @@ namespace MWScript int index = MWBase::Environment::get().getScriptManager()->getLocalIndex (scriptId, name, 'l'); ptr.getRefData().setLocals ( - *MWBase::Environment::get().getWorld()->getStore().scripts.find (scriptId)); + *MWBase::Environment::get().getWorld()->getStore().get().find (scriptId)); return ptr.getRefData().getLocals().mLongs[index]; } @@ -304,7 +304,7 @@ namespace MWScript int index = MWBase::Environment::get().getScriptManager()->getLocalIndex (scriptId, name, 'f'); ptr.getRefData().setLocals ( - *MWBase::Environment::get().getWorld()->getStore().scripts.find (scriptId)); + *MWBase::Environment::get().getWorld()->getStore().get().find (scriptId)); return ptr.getRefData().getLocals().mFloats[index]; } @@ -317,7 +317,7 @@ namespace MWScript int index = MWBase::Environment::get().getScriptManager()->getLocalIndex (scriptId, name, 's'); ptr.getRefData().setLocals ( - *MWBase::Environment::get().getWorld()->getStore().scripts.find (scriptId)); + *MWBase::Environment::get().getWorld()->getStore().get().find (scriptId)); ptr.getRefData().getLocals().mShorts[index] = value; } @@ -330,7 +330,7 @@ namespace MWScript int index = MWBase::Environment::get().getScriptManager()->getLocalIndex (scriptId, name, 'l'); ptr.getRefData().setLocals ( - *MWBase::Environment::get().getWorld()->getStore().scripts.find (scriptId)); + *MWBase::Environment::get().getWorld()->getStore().get().find (scriptId)); ptr.getRefData().getLocals().mLongs[index] = value; } @@ -343,7 +343,7 @@ namespace MWScript int index = MWBase::Environment::get().getScriptManager()->getLocalIndex (scriptId, name, 'f'); ptr.getRefData().setLocals ( - *MWBase::Environment::get().getWorld()->getStore().scripts.find (scriptId)); + *MWBase::Environment::get().getWorld()->getStore().get().find (scriptId)); ptr.getRefData().getLocals().mFloats[index] = value; } diff --git a/apps/openmw/mwscript/miscextensions.cpp b/apps/openmw/mwscript/miscextensions.cpp index 885db6458..a775be13c 100644 --- a/apps/openmw/mwscript/miscextensions.cpp +++ b/apps/openmw/mwscript/miscextensions.cpp @@ -145,6 +145,24 @@ namespace MWScript } }; + + class OpToggleCollisionBoxes : public Interpreter::Opcode0 + { + public: + + virtual void execute (Interpreter::Runtime& runtime) + { + InterpreterContext& context = + static_cast (runtime.getContext()); + + bool enabled = + MWBase::Environment::get().getWorld()->toggleRenderMode (MWBase::World::Render_BoundingBoxes); + + context.report (enabled ? + "Bounding Box Rendering -> On" : "Bounding Box Rendering -> Off"); + } + }; + class OpToggleWireframe : public Interpreter::Opcode0 { public: @@ -275,6 +293,7 @@ namespace MWScript const int opcodeUnlock = 0x200008c; const int opcodeUnlockExplicit = 0x200008d; const int opcodeToggleCollisionDebug = 0x2000132; + const int opcodeToggleCollisionBoxes = 0x20001ac; const int opcodeToggleWireframe = 0x200013b; const int opcodeFadeIn = 0x200013c; const int opcodeFadeOut = 0x200013d; @@ -295,9 +314,9 @@ namespace MWScript extensions.registerInstruction ("activate", "", opcodeActivate); extensions.registerInstruction ("lock", "/l", opcodeLock, opcodeLockExplicit); extensions.registerInstruction ("unlock", "", opcodeUnlock, opcodeUnlockExplicit); - extensions.registerInstruction ("togglecollisionboxes", "", opcodeToggleCollisionDebug); + extensions.registerInstruction ("togglecollisionboxes", "", opcodeToggleCollisionBoxes); extensions.registerInstruction ("togglecollisiongrid", "", opcodeToggleCollisionDebug); - extensions.registerInstruction ("tcb", "", opcodeToggleCollisionDebug); + extensions.registerInstruction ("tcb", "", opcodeToggleCollisionBoxes); extensions.registerInstruction ("tcg", "", opcodeToggleCollisionDebug); extensions.registerInstruction ("twf", "", opcodeToggleWireframe); extensions.registerInstruction ("togglewireframe", "", opcodeToggleWireframe); @@ -327,6 +346,7 @@ namespace MWScript interpreter.installSegment5 (opcodeUnlock, new OpUnlock); interpreter.installSegment5 (opcodeUnlockExplicit, new OpUnlock); interpreter.installSegment5 (opcodeToggleCollisionDebug, new OpToggleCollisionDebug); + interpreter.installSegment5 (opcodeToggleCollisionBoxes, new OpToggleCollisionBoxes); interpreter.installSegment5 (opcodeToggleWireframe, new OpToggleWireframe); interpreter.installSegment5 (opcodeFadeIn, new OpFadeIn); interpreter.installSegment5 (opcodeFadeOut, new OpFadeOut); diff --git a/apps/openmw/mwscript/scriptmanagerimp.cpp b/apps/openmw/mwscript/scriptmanagerimp.cpp index 883d3dfd3..1f338edbd 100644 --- a/apps/openmw/mwscript/scriptmanagerimp.cpp +++ b/apps/openmw/mwscript/scriptmanagerimp.cpp @@ -7,7 +7,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include #include @@ -17,7 +17,7 @@ namespace MWScript { - ScriptManager::ScriptManager (const ESMS::ESMStore& store, bool verbose, + ScriptManager::ScriptManager (const MWWorld::ESMStore& store, bool verbose, Compiler::Context& compilerContext) : mErrorHandler (std::cerr), mStore (store), mVerbose (verbose), mCompilerContext (compilerContext), mParser (mErrorHandler, mCompilerContext), @@ -31,7 +31,7 @@ namespace MWScript bool Success = true; - if (const ESM::Script *script = mStore.scripts.find (name)) + if (const ESM::Script *script = mStore.get().find (name)) { if (mVerbose) std::cout << "compiling script: " << name << std::endl; @@ -125,15 +125,14 @@ namespace MWScript std::pair ScriptManager::compileAll() { - typedef ESMS::ScriptListT::MapType Container; - - const Container& scripts = mStore.scripts.list; - int count = 0; int success = 0; - for (Container::const_iterator iter (scripts.begin()); iter!=scripts.end(); ++iter, ++count) - if (compile (iter->first)) + const MWWorld::Store& scripts = mStore.get(); + MWWorld::Store::iterator it = scripts.begin(); + + for (; it != scripts.end(); ++it, ++count) + if (compile (it->mId)) ++success; return std::make_pair (count, success); @@ -170,7 +169,7 @@ namespace MWScript int ScriptManager::getLocalIndex (const std::string& scriptId, const std::string& variable, char type) { - const ESM::Script *script = mStore.scripts.find (scriptId); + const ESM::Script *script = mStore.get().find (scriptId); int offset = 0; int size = 0; diff --git a/apps/openmw/mwscript/scriptmanagerimp.hpp b/apps/openmw/mwscript/scriptmanagerimp.hpp index bacc232b2..c4a016eb7 100644 --- a/apps/openmw/mwscript/scriptmanagerimp.hpp +++ b/apps/openmw/mwscript/scriptmanagerimp.hpp @@ -14,7 +14,7 @@ #include "globalscripts.hpp" -namespace ESMS +namespace MWWorld { struct ESMStore; } @@ -35,7 +35,7 @@ namespace MWScript class ScriptManager : public MWBase::ScriptManager { Compiler::StreamErrorHandler mErrorHandler; - const ESMS::ESMStore& mStore; + const MWWorld::ESMStore& mStore; bool mVerbose; Compiler::Context& mCompilerContext; Compiler::FileParser mParser; @@ -50,7 +50,7 @@ namespace MWScript public: - ScriptManager (const ESMS::ESMStore& store, bool verbose, + ScriptManager (const MWWorld::ESMStore& store, bool verbose, Compiler::Context& compilerContext); virtual void run (const std::string& name, Interpreter::Context& interpreterContext); @@ -74,6 +74,6 @@ namespace MWScript ///< Return index of the variable of the given name and type in the given script. Will /// throw an exception, if there is no such script or variable or the type does not match. }; -}; +} #endif diff --git a/apps/openmw/mwscript/statsextensions.cpp b/apps/openmw/mwscript/statsextensions.cpp index 66a5acae0..f6a31dd7f 100644 --- a/apps/openmw/mwscript/statsextensions.cpp +++ b/apps/openmw/mwscript/statsextensions.cpp @@ -7,7 +7,7 @@ #include -#include +#include "../mwworld/esmstore.hpp" #include @@ -17,6 +17,7 @@ #include "../mwbase/environment.hpp" #include "../mwbase/dialoguemanager.hpp" +#include "../mwbase/mechanicsmanager.hpp" #include "../mwworld/class.hpp" #include "../mwworld/player.hpp" @@ -27,6 +28,21 @@ #include "interpretercontext.hpp" #include "ref.hpp" +namespace +{ + std::string getDialogueActorFaction() + { + MWWorld::Ptr actor = MWBase::Environment::get().getDialogueManager()->getActor(); + + MWMechanics::NpcStats stats = MWWorld::Class::get (actor).getNpcStats (actor); + + if (stats.getFactionRanks().empty()) + throw std::runtime_error ( + "failed to determine dialogue actors faction (because actor is factionless)"); + + return stats.getFactionRanks().begin()->first; + } +} namespace MWScript { @@ -155,7 +171,7 @@ namespace MWScript virtual void execute (Interpreter::Runtime& runtime) { MWWorld::Ptr ptr = R()(runtime); - Interpreter::Type_Integer value; + Interpreter::Type_Float value; if (mIndex==0 && MWWorld::Class::get (ptr).hasItemHealth (ptr)) { @@ -185,13 +201,15 @@ namespace MWScript { MWWorld::Ptr ptr = R()(runtime); - Interpreter::Type_Integer value = runtime[0].mInteger; + Interpreter::Type_Float value = runtime[0].mFloat; runtime.pop(); - MWWorld::Class::get(ptr) - .getCreatureStats(ptr) - .getDynamic(mIndex) - .setModified(value, 0); + MWMechanics::DynamicStat stat (MWWorld::Class::get (ptr).getCreatureStats (ptr) + .getDynamic (mIndex)); + + stat.setModified (value, 0); + + MWWorld::Class::get (ptr).getCreatureStats (ptr).setDynamic (mIndex, stat); } }; @@ -208,17 +226,21 @@ namespace MWScript { MWWorld::Ptr ptr = R()(runtime); - Interpreter::Type_Integer diff = runtime[0].mInteger; + Interpreter::Type_Float diff = runtime[0].mFloat; runtime.pop(); MWMechanics::CreatureStats& stats = MWWorld::Class::get (ptr).getCreatureStats (ptr); - Interpreter::Type_Integer current = stats.getDynamic(mIndex).getCurrent(); + Interpreter::Type_Float current = stats.getDynamic(mIndex).getCurrent(); - stats.getDynamic(mIndex).setModified( - diff + stats.getDynamic(mIndex).getModified(), 0); + MWMechanics::DynamicStat stat (MWWorld::Class::get (ptr).getCreatureStats (ptr) + .getDynamic (mIndex)); - stats.getDynamic(mIndex).setCurrent(diff + current); + stat.setModified (diff + stat.getModified(), 0); + + stat.setCurrent (diff + current); + + MWWorld::Class::get (ptr).getCreatureStats (ptr).setDynamic (mIndex, stat); } }; @@ -235,14 +257,19 @@ namespace MWScript { MWWorld::Ptr ptr = R()(runtime); - Interpreter::Type_Integer diff = runtime[0].mInteger; + Interpreter::Type_Float diff = runtime[0].mFloat; runtime.pop(); MWMechanics::CreatureStats& stats = MWWorld::Class::get (ptr).getCreatureStats (ptr); - Interpreter::Type_Integer current = stats.getDynamic(mIndex).getCurrent(); + Interpreter::Type_Float current = stats.getDynamic(mIndex).getCurrent(); - stats.getDynamic(mIndex).setCurrent (diff + current); + MWMechanics::DynamicStat stat (MWWorld::Class::get (ptr).getCreatureStats (ptr) + .getDynamic (mIndex)); + + stat.setCurrent (diff + current); + + MWWorld::Class::get (ptr).getCreatureStats (ptr).setDynamic (mIndex, stat); } }; @@ -316,7 +343,7 @@ namespace MWScript assert (ref); const ESM::Class& class_ = - *MWBase::Environment::get().getWorld()->getStore().classes.find (ref->base->mClass); + *MWBase::Environment::get().getWorld()->getStore().get().find (ref->mBase->mClass); float level = 0; float progress = std::modf (stats.getSkill (mIndex).getBase(), &level); @@ -378,7 +405,7 @@ namespace MWScript runtime.pop(); // make sure a spell with this ID actually exists. - MWBase::Environment::get().getWorld()->getStore().spells.find (id); + MWBase::Environment::get().getWorld()->getStore().get().find (id); MWWorld::Class::get (ptr).getCreatureStats (ptr).getSpells().add (id); } @@ -438,7 +465,7 @@ namespace MWScript if(arg0==0) { - factionID = MWBase::Environment::get().getDialogueManager()->getFaction(); + factionID = getDialogueActorFaction(); } else { @@ -467,7 +494,7 @@ namespace MWScript if(arg0==0) { - factionID = MWBase::Environment::get().getDialogueManager()->getFaction(); + factionID = getDialogueActorFaction(); } else { @@ -500,7 +527,7 @@ namespace MWScript if(arg0==0) { - factionID = MWBase::Environment::get().getDialogueManager()->getFaction(); + factionID = getDialogueActorFaction(); } else { @@ -538,7 +565,7 @@ namespace MWScript { if(MWWorld::Class::get(ptr).getNpcStats(ptr).getFactionRanks().empty()) { - //throw exception? + factionID = ""; } else { @@ -574,10 +601,182 @@ namespace MWScript { MWWorld::Ptr ptr = R()(runtime); -// Interpreter::Type_Integer value = runtime[0].mInteger; + Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); - /// \todo modify disposition towards the player + MWWorld::Class::get (ptr).getNpcStats (ptr).setBaseDisposition + (MWWorld::Class::get (ptr).getNpcStats (ptr).getBaseDisposition() + value); + } + }; + + template + class OpSetDisposition : public Interpreter::Opcode0 + { + public: + + virtual void execute (Interpreter::Runtime& runtime) + { + MWWorld::Ptr ptr = R()(runtime); + + Interpreter::Type_Integer value = runtime[0].mInteger; + runtime.pop(); + + MWWorld::Class::get (ptr).getNpcStats (ptr).setBaseDisposition (value); + } + }; + + template + class OpGetDisposition : public Interpreter::Opcode0 + { + public: + + virtual void execute (Interpreter::Runtime& runtime) + { + MWWorld::Ptr ptr = R()(runtime); + + runtime.push (MWWorld::Class::get (ptr).getNpcStats (ptr).getBaseDisposition()); + } + }; + + class OpGetDeadCount : public Interpreter::Opcode0 + { + public: + + virtual void execute (Interpreter::Runtime& runtime) + { + std::string id = runtime.getStringLiteral (runtime[0].mInteger); + runtime[0].mInteger = MWBase::Environment::get().getMechanicsManager()->countDeaths (id); + } + }; + + template + class OpGetPCFacRep : public Interpreter::Opcode1 + { + public: + + virtual void execute (Interpreter::Runtime& runtime, unsigned int arg0) + { + std::string factionId; + + if (arg0==1) + { + factionId = runtime.getStringLiteral (runtime[0].mInteger); + runtime.pop(); + } + else + { + MWWorld::Ptr ptr = R()(runtime); + + if (!MWWorld::Class::get (ptr).getNpcStats (ptr).getFactionRanks().empty()) + factionId = MWWorld::Class::get (ptr).getNpcStats (ptr).getFactionRanks().begin()->first; + } + + if (factionId.empty()) + throw std::runtime_error ("failed to determine faction"); + + boost::algorithm::to_lower (factionId); + + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + runtime.push ( + MWWorld::Class::get (player).getNpcStats (player).getFactionReputation (factionId)); + } + }; + + template + class OpSetPCFacRep : public Interpreter::Opcode1 + { + public: + + virtual void execute (Interpreter::Runtime& runtime, unsigned int arg0) + { + Interpreter::Type_Integer value = runtime[0].mInteger; + runtime.pop(); + + std::string factionId; + + if (arg0==1) + { + factionId = runtime.getStringLiteral (runtime[0].mInteger); + runtime.pop(); + } + else + { + MWWorld::Ptr ptr = R()(runtime); + + if (!MWWorld::Class::get (ptr).getNpcStats (ptr).getFactionRanks().empty()) + factionId = MWWorld::Class::get (ptr).getNpcStats (ptr).getFactionRanks().begin()->first; + } + + if (factionId.empty()) + throw std::runtime_error ("failed to determine faction"); + + boost::algorithm::to_lower (factionId); + + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + MWWorld::Class::get (player).getNpcStats (player).setFactionReputation (factionId, value); + } + }; + + template + class OpModPCFacRep : public Interpreter::Opcode1 + { + public: + + virtual void execute (Interpreter::Runtime& runtime, unsigned int arg0) + { + Interpreter::Type_Integer value = runtime[0].mInteger; + runtime.pop(); + + std::string factionId; + + if (arg0==1) + { + factionId = runtime.getStringLiteral (runtime[0].mInteger); + runtime.pop(); + } + else + { + MWWorld::Ptr ptr = R()(runtime); + + if (!MWWorld::Class::get (ptr).getNpcStats (ptr).getFactionRanks().empty()) + factionId = MWWorld::Class::get (ptr).getNpcStats (ptr).getFactionRanks().begin()->first; + } + + if (factionId.empty()) + throw std::runtime_error ("failed to determine faction"); + + boost::algorithm::to_lower (factionId); + + MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); + MWWorld::Class::get (player).getNpcStats (player).setFactionReputation (factionId, + MWWorld::Class::get (player).getNpcStats (player).getFactionReputation (factionId)+ + value); + } + }; + + template + class OpGetCommonDisease : public Interpreter::Opcode0 + { + public: + + virtual void execute (Interpreter::Runtime& runtime) + { + MWWorld::Ptr ptr = R()(runtime); + + runtime.push (MWWorld::Class::get (ptr).getCreatureStats (ptr).hasCommonDisease()); + } + }; + + template + class OpGetBlightDisease : public Interpreter::Opcode0 + { + public: + + virtual void execute (Interpreter::Runtime& runtime) + { + MWWorld::Ptr ptr = R()(runtime); + + runtime.push (MWWorld::Class::get (ptr).getCreatureStats (ptr).hasBlightDisease()); } }; @@ -627,12 +826,30 @@ namespace MWScript const int opcodeGetPCRankExplicit = 0x2000f; const int opcodeModDisposition = 0x200014d; const int opcodeModDispositionExplicit = 0x200014e; + const int opcodeSetDisposition = 0x20001a4; + const int opcodeSetDispositionExplicit = 0x20001a5; + const int opcodeGetDisposition = 0x20001a6; + const int opcodeGetDispositionExplicit = 0x20001a7; const int opcodeGetLevel = 0x200018c; const int opcodeGetLevelExplicit = 0x200018d; const int opcodeSetLevel = 0x200018e; const int opcodeSetLevelExplicit = 0x200018f; + const int opcodeGetDeadCount = 0x20001a3; + + const int opcodeGetPCFacRep = 0x20012; + const int opcodeGetPCFacRepExplicit = 0x20013; + const int opcodeSetPCFacRep = 0x20014; + const int opcodeSetPCFacRepExplicit = 0x20015; + const int opcodeModPCFacRep = 0x20016; + const int opcodeModPCFacRepExplicit = 0x20017; + + const int opcodeGetCommonDisease = 0x20001a8; + const int opcodeGetCommonDiseaseExplicit = 0x20001a9; + const int opcodeGetBlightDisease = 0x20001aa; + const int opcodeGetBlightDiseaseExplicit = 0x20001ab; + void registerExtensions (Compiler::Extensions& extensions) { static const char *attributes[numberOfAttributes] = @@ -676,16 +893,16 @@ namespace MWScript for (int i=0; i); - interpreter.installSegment5(opcodeModDispositionExplicit,new OpModDisposition); interpreter.installSegment3(opcodeGetPCRank,new OpGetPCRank); interpreter.installSegment3(opcodeGetPCRankExplicit,new OpGetPCRank); + interpreter.installSegment5(opcodeModDisposition,new OpModDisposition); + interpreter.installSegment5(opcodeModDispositionExplicit,new OpModDisposition); + interpreter.installSegment5(opcodeSetDisposition,new OpSetDisposition); + interpreter.installSegment5(opcodeSetDispositionExplicit,new OpSetDisposition); + interpreter.installSegment5(opcodeGetDisposition,new OpGetDisposition); + interpreter.installSegment5(opcodeGetDispositionExplicit,new OpGetDisposition); + interpreter.installSegment5 (opcodeGetLevel, new OpGetLevel); interpreter.installSegment5 (opcodeGetLevelExplicit, new OpGetLevel); interpreter.installSegment5 (opcodeSetLevel, new OpSetLevel); interpreter.installSegment5 (opcodeSetLevelExplicit, new OpSetLevel); + interpreter.installSegment5 (opcodeGetDeadCount, new OpGetDeadCount); + + interpreter.installSegment3 (opcodeGetPCFacRep, new OpGetPCFacRep); + interpreter.installSegment3 (opcodeGetPCFacRepExplicit, new OpGetPCFacRep); + interpreter.installSegment3 (opcodeSetPCFacRep, new OpSetPCFacRep); + interpreter.installSegment3 (opcodeSetPCFacRepExplicit, new OpSetPCFacRep); + interpreter.installSegment3 (opcodeModPCFacRep, new OpModPCFacRep); + interpreter.installSegment3 (opcodeModPCFacRepExplicit, new OpModPCFacRep); + + interpreter.installSegment5 (opcodeGetCommonDisease, new OpGetCommonDisease); + interpreter.installSegment5 (opcodeGetCommonDiseaseExplicit, new OpGetCommonDisease); + interpreter.installSegment5 (opcodeGetBlightDisease, new OpGetBlightDisease); + interpreter.installSegment5 (opcodeGetBlightDiseaseExplicit, new OpGetBlightDisease); } } } diff --git a/apps/openmw/mwscript/transformationextensions.cpp b/apps/openmw/mwscript/transformationextensions.cpp index 6e70f588e..a64651a97 100644 --- a/apps/openmw/mwscript/transformationextensions.cpp +++ b/apps/openmw/mwscript/transformationextensions.cpp @@ -3,7 +3,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include #include diff --git a/apps/openmw/mwsound/ffmpeg_decoder.cpp b/apps/openmw/mwsound/ffmpeg_decoder.cpp index 9298bf848..a2cccfd13 100644 --- a/apps/openmw/mwsound/ffmpeg_decoder.cpp +++ b/apps/openmw/mwsound/ffmpeg_decoder.cpp @@ -1,7 +1,12 @@ #ifdef OPENMW_USE_FFMPEG + #include "ffmpeg_decoder.hpp" +// auto_ptr +#include + +#include namespace MWSound { diff --git a/apps/openmw/mwsound/ffmpeg_decoder.hpp b/apps/openmw/mwsound/ffmpeg_decoder.hpp index 4344397c7..7b028e1d0 100644 --- a/apps/openmw/mwsound/ffmpeg_decoder.hpp +++ b/apps/openmw/mwsound/ffmpeg_decoder.hpp @@ -54,6 +54,6 @@ namespace MWSound #ifndef DEFAULT_DECODER #define DEFAULT_DECODER (::MWSound::FFmpeg_Decoder) #endif -}; +} #endif diff --git a/apps/openmw/mwsound/mpgsnd_decoder.hpp b/apps/openmw/mwsound/mpgsnd_decoder.hpp index 870773edc..09082c2f4 100644 --- a/apps/openmw/mwsound/mpgsnd_decoder.hpp +++ b/apps/openmw/mwsound/mpgsnd_decoder.hpp @@ -52,6 +52,6 @@ namespace MWSound #ifndef DEFAULT_DECODER #define DEFAULT_DECODER (::MWSound::MpgSnd_Decoder) #endif -}; +} #endif diff --git a/apps/openmw/mwsound/openal_output.hpp b/apps/openmw/mwsound/openal_output.hpp index 90917c53c..fecffa575 100644 --- a/apps/openmw/mwsound/openal_output.hpp +++ b/apps/openmw/mwsound/openal_output.hpp @@ -66,6 +66,6 @@ namespace MWSound #ifndef DEFAULT_OUTPUT #define DEFAULT_OUTPUT (::MWSound::OpenAL_Output) #endif -}; +} #endif diff --git a/apps/openmw/mwsound/soundmanagerimp.cpp b/apps/openmw/mwsound/soundmanagerimp.cpp index 5d5ef3d1d..8c4798c9d 100644 --- a/apps/openmw/mwsound/soundmanagerimp.cpp +++ b/apps/openmw/mwsound/soundmanagerimp.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -116,9 +116,8 @@ namespace MWSound std::string SoundManager::lookup(const std::string &soundId, float &volume, float &min, float &max) { - const ESM::Sound *snd = MWBase::Environment::get().getWorld()->getStore().sounds.search(soundId); - if(snd == NULL) - throw std::runtime_error(std::string("Failed to lookup sound ")+soundId); + const ESM::Sound *snd = + MWBase::Environment::get().getWorld()->getStore().get().find(soundId); volume *= pow(10.0, (snd->mData.mVolume/255.0*3348.0 - 3348.0) / 2000.0); @@ -414,17 +413,19 @@ namespace MWSound //If the region has changed timePassed += duration; - if((current->cell->mData.mFlags & current->cell->Interior) || timePassed < 10) + if(!current->mCell->isExterior() || timePassed < 10) return; timePassed = 0; - if(regionName != current->cell->mRegion) + if(regionName != current->mCell->mRegion) { - regionName = current->cell->mRegion; + regionName = current->mCell->mRegion; total = 0; } - const ESM::Region *regn = MWBase::Environment::get().getWorld()->getStore().regions.search(regionName); + const ESM::Region *regn = + MWBase::Environment::get().getWorld()->getStore().get().search(regionName); + if (regn == NULL) return; @@ -477,7 +478,7 @@ namespace MWSound MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayer().getPlayer(); - const ESM::Cell *cell = player.getCell()->cell; + const ESM::Cell *cell = player.getCell()->mCell; Environment env = Env_Normal; if((cell->mData.mFlags&cell->HasWater) && mListenerPos.z < cell->mWater) diff --git a/apps/openmw/mwsound/soundmanagerimp.hpp b/apps/openmw/mwsound/soundmanagerimp.hpp index f91e291ef..a84aa3b9a 100644 --- a/apps/openmw/mwsound/soundmanagerimp.hpp +++ b/apps/openmw/mwsound/soundmanagerimp.hpp @@ -26,7 +26,7 @@ namespace MWSound enum Environment { Env_Normal, - Env_Underwater, + Env_Underwater }; class SoundManager : public MWBase::SoundManager diff --git a/apps/openmw/mwworld/actioneat.cpp b/apps/openmw/mwworld/actioneat.cpp index abd1ac4b9..63efff738 100644 --- a/apps/openmw/mwworld/actioneat.cpp +++ b/apps/openmw/mwworld/actioneat.cpp @@ -5,14 +5,13 @@ #include -#include - #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwmechanics/creaturestats.hpp" #include "../mwmechanics/npcstats.hpp" +#include "esmstore.hpp" #include "class.hpp" namespace MWWorld diff --git a/apps/openmw/mwworld/actionread.cpp b/apps/openmw/mwworld/actionread.cpp index 4ac613df7..6d5d9d8fd 100644 --- a/apps/openmw/mwworld/actionread.cpp +++ b/apps/openmw/mwworld/actionread.cpp @@ -4,15 +4,14 @@ #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" -#include "../mwworld/player.hpp" -#include "../mwworld/class.hpp" - #include "../mwmechanics/npcstats.hpp" #include "../mwgui/bookwindow.hpp" #include "../mwgui/scrollwindow.hpp" -#include +#include "player.hpp" +#include "class.hpp" +#include "esmstore.hpp" namespace MWWorld { @@ -24,7 +23,7 @@ namespace MWWorld { LiveCellRef *ref = getTarget().get(); - if (ref->base->mData.mIsScroll) + if (ref->mBase->mData.mIsScroll) { MWBase::Environment::get().getWindowManager()->pushGuiMode(MWGui::GM_Scroll); MWBase::Environment::get().getWindowManager()->getScrollWindow()->open(getTarget()); @@ -39,16 +38,19 @@ namespace MWWorld MWMechanics::NpcStats& npcStats = MWWorld::Class::get(player).getNpcStats (player); // Skill gain from books - if (ref->base->mData.mSkillID >= 0 && ref->base->mData.mSkillID < ESM::Skill::Length - && !npcStats.hasBeenUsed (ref->base->mId)) + if (ref->mBase->mData.mSkillID >= 0 && ref->mBase->mData.mSkillID < ESM::Skill::Length + && !npcStats.hasBeenUsed (ref->mBase->mId)) { MWWorld::LiveCellRef *playerRef = player.get(); - const ESM::Class *class_ = MWBase::Environment::get().getWorld()->getStore().classes.find ( - playerRef->base->mClass); - npcStats.increaseSkill (ref->base->mData.mSkillID, *class_, true); + const ESM::Class *class_ = + MWBase::Environment::get().getWorld()->getStore().get().find ( + playerRef->mBase->mClass + ); - npcStats.flagAsUsed (ref->base->mId); + npcStats.increaseSkill (ref->mBase->mData.mSkillID, *class_, true); + + npcStats.flagAsUsed (ref->mBase->mId); } } diff --git a/apps/openmw/mwworld/cells.cpp b/apps/openmw/mwworld/cells.cpp index e5a38d4be..696a469f7 100644 --- a/apps/openmw/mwworld/cells.cpp +++ b/apps/openmw/mwworld/cells.cpp @@ -1,11 +1,10 @@ #include "cells.hpp" -#include - #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "class.hpp" +#include "esmstore.hpp" #include "containerstore.hpp" MWWorld::Ptr::CellStore *MWWorld::Cells::getCellStore (const ESM::Cell *cell) @@ -24,12 +23,12 @@ MWWorld::Ptr::CellStore *MWWorld::Cells::getCellStore (const ESM::Cell *cell) else { std::map, Ptr::CellStore>::iterator result = - mExteriors.find (std::make_pair (cell->mData.mX, cell->mData.mY)); + mExteriors.find (std::make_pair (cell->getGridX(), cell->getGridY())); if (result==mExteriors.end()) { result = mExteriors.insert (std::make_pair ( - std::make_pair (cell->mData.mX, cell->mData.mY), Ptr::CellStore (cell))).first; + std::make_pair (cell->getGridX(), cell->getGridY()), Ptr::CellStore (cell))).first; } @@ -40,33 +39,33 @@ MWWorld::Ptr::CellStore *MWWorld::Cells::getCellStore (const ESM::Cell *cell) void MWWorld::Cells::fillContainers (Ptr::CellStore& cellStore) { for (CellRefList::List::iterator iter ( - cellStore.containers.list.begin()); - iter!=cellStore.containers.list.end(); ++iter) + cellStore.mContainers.mList.begin()); + iter!=cellStore.mContainers.mList.end(); ++iter) { Ptr container (&*iter, &cellStore); Class::get (container).getContainerStore (container).fill ( - iter->base->mInventory, mStore); + iter->mBase->mInventory, mStore); } for (CellRefList::List::iterator iter ( - cellStore.creatures.list.begin()); - iter!=cellStore.creatures.list.end(); ++iter) + cellStore.mCreatures.mList.begin()); + iter!=cellStore.mCreatures.mList.end(); ++iter) { Ptr container (&*iter, &cellStore); Class::get (container).getContainerStore (container).fill ( - iter->base->mInventory, mStore); + iter->mBase->mInventory, mStore); } for (CellRefList::List::iterator iter ( - cellStore.npcs.list.begin()); - iter!=cellStore.npcs.list.end(); ++iter) + cellStore.mNpcs.mList.begin()); + iter!=cellStore.mNpcs.mList.end(); ++iter) { Ptr container (&*iter, &cellStore); Class::get (container).getContainerStore (container).fill ( - iter->base->mInventory, mStore); + iter->mBase->mInventory, mStore); } } @@ -85,7 +84,7 @@ MWWorld::Ptr MWWorld::Cells::getPtrAndCache (const std::string& name, Ptr::CellS return ptr; } -MWWorld::Cells::Cells (const ESMS::ESMStore& store, ESM::ESMReader& reader) +MWWorld::Cells::Cells (const MWWorld::ESMStore& store, ESM::ESMReader& reader) : mStore (store), mReader (reader), mIdCache (20, std::pair ("", (Ptr::CellStore*)0)), /// \todo make cache size configurable mIdCacheIndex (0) @@ -98,7 +97,7 @@ MWWorld::Ptr::CellStore *MWWorld::Cells::getExterior (int x, int y) if (result==mExteriors.end()) { - const ESM::Cell *cell = mStore.cells.searchExt (x, y); + const ESM::Cell *cell = mStore.get().search(x, y); if (!cell) { @@ -133,7 +132,7 @@ MWWorld::Ptr::CellStore *MWWorld::Cells::getInterior (const std::string& name) if (result==mInteriors.end()) { - const ESM::Cell *cell = mStore.cells.findInt (name); + const ESM::Cell *cell = mStore.get().find(name); result = mInteriors.insert (std::make_pair (name, Ptr::CellStore (cell))).first; } @@ -169,64 +168,64 @@ MWWorld::Ptr MWWorld::Cells::getPtr (const std::string& name, Ptr::CellStore& ce } MWWorld::Ptr ptr; - if (MWWorld::LiveCellRef *ref = cell.activators.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mActivators.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.potions.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mPotions.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.appas.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mAppas.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.armors.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mArmors.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.books.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mBooks.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.clothes.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mClothes.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.containers.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mContainers.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.creatures.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mCreatures.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.doors.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mDoors.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.ingreds.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mIngreds.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.creatureLists.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mCreatureLists.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.itemLists.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mItemLists.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.lights.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mLights.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.lockpicks.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mLockpicks.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.miscItems.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mMiscItems.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.npcs.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mNpcs.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.probes.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mProbes.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.repairs.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mRepairs.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.statics.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mStatics.find (name)) ptr = Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = cell.weapons.find (name)) + if (MWWorld::LiveCellRef *ref = cell.mWeapons.find (name)) ptr = Ptr (ref, &cell); if (!ptr.isEmpty() && ptr.getRefData().getCount() > 0) { @@ -265,10 +264,12 @@ MWWorld::Ptr MWWorld::Cells::getPtr (const std::string& name) } // Now try the other cells - for (ESMS::CellList::IntCells::const_iterator iter = mStore.cells.intCells.begin(); - iter!=mStore.cells.intCells.end(); ++iter) + const MWWorld::Store &cells = mStore.get(); + MWWorld::Store::iterator iter; + + for (iter = cells.intBegin(); iter != cells.intEnd(); ++iter) { - Ptr::CellStore *cellStore = getCellStore (iter->second); + Ptr::CellStore *cellStore = getCellStore (&(*iter)); Ptr ptr = getPtrAndCache (name, *cellStore); @@ -276,10 +277,9 @@ MWWorld::Ptr MWWorld::Cells::getPtr (const std::string& name) return ptr; } - for (ESMS::CellList::ExtCells::const_iterator iter = mStore.cells.extCells.begin(); - iter!=mStore.cells.extCells.end(); ++iter) + for (iter = cells.extBegin(); iter != cells.extEnd(); ++iter) { - Ptr::CellStore *cellStore = getCellStore (iter->second); + Ptr::CellStore *cellStore = getCellStore (&(*iter)); Ptr ptr = getPtrAndCache (name, *cellStore); diff --git a/apps/openmw/mwworld/cells.hpp b/apps/openmw/mwworld/cells.hpp index 3e1383166..edaf70055 100644 --- a/apps/openmw/mwworld/cells.hpp +++ b/apps/openmw/mwworld/cells.hpp @@ -11,17 +11,14 @@ namespace ESM class ESMReader; } -namespace ESM -{ - class ESMStore; -} - namespace MWWorld { + class ESMStore; + /// \brief Cell container class Cells { - const ESMS::ESMStore& mStore; + const MWWorld::ESMStore& mStore; ESM::ESMReader& mReader; std::map mInteriors; std::map, CellStore> mExteriors; @@ -39,7 +36,7 @@ namespace MWWorld public: - Cells (const ESMS::ESMStore& store, ESM::ESMReader& reader); + Cells (const MWWorld::ESMStore& store, ESM::ESMReader& reader); ///< \todo pass the dynamic part of the ESMStore isntead (once it is written) of the whole /// world diff --git a/apps/openmw/mwworld/cellstore.cpp b/apps/openmw/mwworld/cellstore.cpp index fcdec1e7f..1ef2d36a2 100644 --- a/apps/openmw/mwworld/cellstore.cpp +++ b/apps/openmw/mwworld/cellstore.cpp @@ -2,28 +2,28 @@ #include -#include - #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "ptr.hpp" +#include "esmstore.hpp" namespace MWWorld { - CellStore::CellStore (const ESM::Cell *cell_) : cell (cell_), mState (State_Unloaded) + CellStore::CellStore (const ESM::Cell *cell) + : mCell (cell), mState (State_Unloaded) { mWaterLevel = cell->mWater; } - void CellStore::load (const ESMS::ESMStore &store, ESM::ESMReader &esm) + void CellStore::load (const MWWorld::ESMStore &store, ESM::ESMReader &esm) { if (mState!=State_Loaded) { if (mState==State_Preloaded) mIds.clear(); - std::cout << "loading cell " << cell->getDescription() << std::endl; + std::cout << "loading cell " << mCell->getDescription() << std::endl; loadRefs (store, esm); @@ -31,7 +31,7 @@ namespace MWWorld } } - void CellStore::preload (const ESMS::ESMStore &store, ESM::ESMReader &esm) + void CellStore::preload (const MWWorld::ESMStore &store, ESM::ESMReader &esm) { if (mState==State_Unloaded) { @@ -41,20 +41,20 @@ namespace MWWorld } } - void CellStore::listRefs(const ESMS::ESMStore &store, ESM::ESMReader &esm) + void CellStore::listRefs(const MWWorld::ESMStore &store, ESM::ESMReader &esm) { - assert (cell); + assert (mCell); - if (cell->mContext.filename.empty()) + if (mCell->mContext.filename.empty()) return; // this is a dynamically generated cell -> skipping. // Reopen the ESM reader and seek to the right position. - cell->restore (esm); + mCell->restore (esm); ESM::CellRef ref; // Get each reference in turn - while (cell->getNextRef (esm, ref)) + while (mCell->getNextRef (esm, ref)) { std::string lowerCase; @@ -67,20 +67,20 @@ namespace MWWorld std::sort (mIds.begin(), mIds.end()); } - void CellStore::loadRefs(const ESMS::ESMStore &store, ESM::ESMReader &esm) + void CellStore::loadRefs(const MWWorld::ESMStore &store, ESM::ESMReader &esm) { - assert (cell); + assert (mCell); - if (cell->mContext.filename.empty()) + if (mCell->mContext.filename.empty()) return; // this is a dynamically generated cell -> skipping. // Reopen the ESM reader and seek to the right position. - cell->restore(esm); + mCell->restore(esm); ESM::CellRef ref; // Get each reference in turn - while(cell->getNextRef(esm, ref)) + while(mCell->getNextRef(esm, ref)) { std::string lowerCase; @@ -98,26 +98,26 @@ namespace MWWorld */ switch(rec) { - case ESM::REC_ACTI: activators.find(ref, store.activators); break; - case ESM::REC_ALCH: potions.find(ref, store.potions); break; - case ESM::REC_APPA: appas.find(ref, store.appas); break; - case ESM::REC_ARMO: armors.find(ref, store.armors); break; - case ESM::REC_BOOK: books.find(ref, store.books); break; - case ESM::REC_CLOT: clothes.find(ref, store.clothes); break; - case ESM::REC_CONT: containers.find(ref, store.containers); break; - case ESM::REC_CREA: creatures.find(ref, store.creatures); break; - case ESM::REC_DOOR: doors.find(ref, store.doors); break; - case ESM::REC_INGR: ingreds.find(ref, store.ingreds); break; - case ESM::REC_LEVC: creatureLists.find(ref, store.creatureLists); break; - case ESM::REC_LEVI: itemLists.find(ref, store.itemLists); break; - case ESM::REC_LIGH: lights.find(ref, store.lights); break; - case ESM::REC_LOCK: lockpicks.find(ref, store.lockpicks); break; - case ESM::REC_MISC: miscItems.find(ref, store.miscItems); break; - case ESM::REC_NPC_: npcs.find(ref, store.npcs); break; - case ESM::REC_PROB: probes.find(ref, store.probes); break; - case ESM::REC_REPA: repairs.find(ref, store.repairs); break; - case ESM::REC_STAT: statics.find(ref, store.statics); break; - case ESM::REC_WEAP: weapons.find(ref, store.weapons); break; + case ESM::REC_ACTI: mActivators.load(ref, store); break; + case ESM::REC_ALCH: mPotions.load(ref, store); break; + case ESM::REC_APPA: mAppas.load(ref, store); break; + case ESM::REC_ARMO: mArmors.load(ref, store); break; + case ESM::REC_BOOK: mBooks.load(ref, store); break; + case ESM::REC_CLOT: mClothes.load(ref, store); break; + case ESM::REC_CONT: mContainers.load(ref, store); break; + case ESM::REC_CREA: mCreatures.load(ref, store); break; + case ESM::REC_DOOR: mDoors.load(ref, store); break; + case ESM::REC_INGR: mIngreds.load(ref, store); break; + case ESM::REC_LEVC: mCreatureLists.load(ref, store); break; + case ESM::REC_LEVI: mItemLists.load(ref, store); break; + case ESM::REC_LIGH: mLights.load(ref, store); break; + case ESM::REC_LOCK: mLockpicks.load(ref, store); break; + case ESM::REC_MISC: mMiscItems.load(ref, store); break; + case ESM::REC_NPC_: mNpcs.load(ref, store); break; + case ESM::REC_PROB: mProbes.load(ref, store); break; + case ESM::REC_REPA: mRepairs.load(ref, store); break; + case ESM::REC_STAT: mStatics.load(ref, store); break; + case ESM::REC_WEAP: mWeapons.load(ref, store); break; case 0: std::cout << "Cell reference " + ref.mRefID + " not found!\n"; break; default: diff --git a/apps/openmw/mwworld/cellstore.hpp b/apps/openmw/mwworld/cellstore.hpp index 32ab6e07b..ba3d24d7e 100644 --- a/apps/openmw/mwworld/cellstore.hpp +++ b/apps/openmw/mwworld/cellstore.hpp @@ -7,15 +7,12 @@ #include #include "refdata.hpp" - -namespace ESMS -{ - struct ESMStore; -} +#include "esmstore.hpp" namespace MWWorld { class Ptr; + class ESMStore; /// A reference to one object (of any type) in a cell. /// @@ -26,19 +23,21 @@ namespace MWWorld template struct LiveCellRef { - LiveCellRef(const ESM::CellRef& cref, const X* b = NULL) : base(b), ref(cref), - mData(ref) {} + LiveCellRef(const ESM::CellRef& cref, const X* b = NULL) + : mBase(b), mRef(cref), mData(mRef) + {} - - LiveCellRef(const X* b = NULL) : base(b), mData(ref) {} + LiveCellRef(const X* b = NULL) + : mBase(b), mData(mRef) + {} // The object that this instance is based on. - const X* base; + const X* mBase; /* Information about this instance, such as 3D location and rotation and individual type-dependent data. */ - ESM::CellRef ref; + ESM::CellRef mRef; /// runtime-data RefData mData; @@ -50,26 +49,29 @@ namespace MWWorld { typedef LiveCellRef LiveRef; typedef std::list List; - List list; + List mList; - // Search for the given reference in the given reclist from - // ESMStore. Insert the reference into the list if a match is - // found. If not, throw an exception. - template - void find(ESM::CellRef &ref, const Y& recList) + /// Searches for reference of appropriate type in given ESMStore. + /// If reference exists, loads it into container, throws an exception + /// on miss + void load(ESM::CellRef &ref, const MWWorld::ESMStore &esmStore) { - const X* obj = recList.find(ref.mRefID); - if(obj == NULL) - throw std::runtime_error("Error resolving cell reference " + ref.mRefID); + // for throwing exception on unhandled record type + const MWWorld::Store &store = esmStore.get(); + const X *ptr = store.find(ref.mRefID); - list.push_back(LiveRef(ref, obj)); + /// \note redundant because Store::find() throws exception on miss + if (ptr == NULL) { + throw std::runtime_error("Error resolving cell reference " + ref.mRefID); + } + mList.push_back(LiveRef(ref, ptr)); } LiveRef *find (const std::string& name) { - for (typename std::list::iterator iter (list.begin()); iter!=list.end(); ++iter) + for (typename std::list::iterator iter (mList.begin()); iter!=mList.end(); ++iter) { - if (iter->mData.getCount() > 0 && iter->ref.mRefID == name) + if (iter->mData.getCount() > 0 && iter->mRef.mRefID == name) return &*iter; } @@ -77,8 +79,8 @@ namespace MWWorld } LiveRef &insert(const LiveRef &item) { - list.push_back(item); - return list.back(); + mList.push_back(item); + return mList.back(); } }; @@ -94,37 +96,37 @@ namespace MWWorld CellStore (const ESM::Cell *cell_); - const ESM::Cell *cell; + const ESM::Cell *mCell; State mState; std::vector mIds; float mWaterLevel; // Lists for each individual object type - CellRefList activators; - CellRefList potions; - CellRefList appas; - CellRefList armors; - CellRefList books; - CellRefList clothes; - CellRefList containers; - CellRefList creatures; - CellRefList doors; - CellRefList ingreds; - CellRefList creatureLists; - CellRefList itemLists; - CellRefList lights; - CellRefList lockpicks; - CellRefList miscItems; - CellRefList npcs; - CellRefList probes; - CellRefList repairs; - CellRefList statics; - CellRefList weapons; + CellRefList mActivators; + CellRefList mPotions; + CellRefList mAppas; + CellRefList mArmors; + CellRefList mBooks; + CellRefList mClothes; + CellRefList mContainers; + CellRefList mCreatures; + CellRefList mDoors; + CellRefList mIngreds; + CellRefList mCreatureLists; + CellRefList mItemLists; + CellRefList mLights; + CellRefList mLockpicks; + CellRefList mMiscItems; + CellRefList mNpcs; + CellRefList mProbes; + CellRefList mRepairs; + CellRefList mStatics; + CellRefList mWeapons; - void load (const ESMS::ESMStore &store, ESM::ESMReader &esm); + void load (const MWWorld::ESMStore &store, ESM::ESMReader &esm); - void preload (const ESMS::ESMStore &store, ESM::ESMReader &esm); + void preload (const MWWorld::ESMStore &store, ESM::ESMReader &esm); /// Call functor (ref) for each reference. functor must return a bool. Returning /// false will abort the iteration. @@ -133,32 +135,32 @@ namespace MWWorld bool forEach (Functor& functor) { return - forEachImp (functor, activators) && - forEachImp (functor, potions) && - forEachImp (functor, appas) && - forEachImp (functor, armors) && - forEachImp (functor, books) && - forEachImp (functor, clothes) && - forEachImp (functor, containers) && - forEachImp (functor, creatures) && - forEachImp (functor, doors) && - forEachImp (functor, ingreds) && - forEachImp (functor, creatureLists) && - forEachImp (functor, itemLists) && - forEachImp (functor, lights) && - forEachImp (functor, lockpicks) && - forEachImp (functor, miscItems) && - forEachImp (functor, npcs) && - forEachImp (functor, probes) && - forEachImp (functor, repairs) && - forEachImp (functor, statics) && - forEachImp (functor, weapons); + forEachImp (functor, mActivators) && + forEachImp (functor, mPotions) && + forEachImp (functor, mAppas) && + forEachImp (functor, mArmors) && + forEachImp (functor, mBooks) && + forEachImp (functor, mClothes) && + forEachImp (functor, mContainers) && + forEachImp (functor, mCreatures) && + forEachImp (functor, mDoors) && + forEachImp (functor, mIngreds) && + forEachImp (functor, mCreatureLists) && + forEachImp (functor, mItemLists) && + forEachImp (functor, mLights) && + forEachImp (functor, mLockpicks) && + forEachImp (functor, mMiscItems) && + forEachImp (functor, mNpcs) && + forEachImp (functor, mProbes) && + forEachImp (functor, mRepairs) && + forEachImp (functor, mStatics) && + forEachImp (functor, mWeapons); } bool operator==(const CellStore &cell) { - return this->cell->mName == cell.cell->mName && - this->cell->mData.mX == cell.cell->mData.mX && - this->cell->mData.mY == cell.cell->mData.mY; + return mCell->mName == cell.mCell->mName && + mCell->mData.mX == cell.mCell->mData.mX && + mCell->mData.mY == cell.mCell->mData.mY; } bool operator!=(const CellStore &cell) { @@ -166,7 +168,7 @@ namespace MWWorld } bool isExterior() const { - return cell->isExterior(); + return mCell->isExterior(); } private: @@ -174,18 +176,18 @@ namespace MWWorld template bool forEachImp (Functor& functor, List& list) { - for (typename List::List::iterator iter (list.list.begin()); iter!=list.list.end(); + for (typename List::List::iterator iter (list.mList.begin()); iter!=list.mList.end(); ++iter) - if (!functor (iter->ref, iter->mData)) + if (!functor (iter->mRef, iter->mData)) return false; return true; } /// Run through references and store IDs - void listRefs(const ESMS::ESMStore &store, ESM::ESMReader &esm); + void listRefs(const MWWorld::ESMStore &store, ESM::ESMReader &esm); - void loadRefs(const ESMS::ESMStore &store, ESM::ESMReader &esm); + void loadRefs(const MWWorld::ESMStore &store, ESM::ESMReader &esm); }; } diff --git a/apps/openmw/mwworld/class.cpp b/apps/openmw/mwworld/class.cpp index 5267e368d..c76019149 100644 --- a/apps/openmw/mwworld/class.cpp +++ b/apps/openmw/mwworld/class.cpp @@ -157,6 +157,16 @@ namespace MWWorld throw std::runtime_error ("encumbrance not supported by class"); } + bool Class::isEssential (const MWWorld::Ptr& ptr) const + { + return false; + } + + bool Class::hasDetected (const MWWorld::Ptr& ptr, const MWWorld::Ptr& ptr2) const + { + return false; + } + const Class& Class::get (const std::string& key) { std::map >::const_iterator iter = sClasses.find (key); diff --git a/apps/openmw/mwworld/class.hpp b/apps/openmw/mwworld/class.hpp index 3c3b0e34b..07dcb8fe0 100644 --- a/apps/openmw/mwworld/class.hpp +++ b/apps/openmw/mwworld/class.hpp @@ -186,6 +186,16 @@ namespace MWWorld /// /// (default implementations: throws an exception) + virtual bool isEssential (const MWWorld::Ptr& ptr) const; + ///< Is \a ptr essential? (i.e. may losing \a ptr make the game unwinnable) + /// + /// (default implementation: return false) + + virtual bool hasDetected (const MWWorld::Ptr& ptr, const MWWorld::Ptr& ptr2) const; + ///< Has \æ ptr detected \a ptr2? + /// + /// (default implementation: return false) + static const Class& get (const std::string& key); ///< If there is no class for this \a key, an exception is thrown. diff --git a/apps/openmw/mwworld/containerstore.cpp b/apps/openmw/mwworld/containerstore.cpp index 3bc06b581..e47f2191a 100644 --- a/apps/openmw/mwworld/containerstore.cpp +++ b/apps/openmw/mwworld/containerstore.cpp @@ -24,12 +24,12 @@ namespace float sum = 0; for (typename MWWorld::CellRefList::List::const_iterator iter ( - cellRefList.list.begin()); - iter!=cellRefList.list.end(); + cellRefList.mList.begin()); + iter!=cellRefList.mList.end(); ++iter) { if (iter->mData.getCount()>0) - sum += iter->mData.getCount()*iter->base->mData.mWeight; + sum += iter->mData.getCount()*iter->mBase->mData.mWeight; } return sum; @@ -74,26 +74,29 @@ MWWorld::ContainerStoreIterator MWWorld::ContainerStore::add (const Ptr& ptr) { int type = getType(ptr); + const MWWorld::ESMStore &esmStore = + MWBase::Environment::get().getWorld()->getStore(); + // gold needs special handling: when it is inserted into a container, the base object automatically becomes Gold_001 // this ensures that gold piles of different sizes stack with each other (also, several scripts rely on Gold_001 for detecting player gold) - if (MWWorld::Class::get(ptr).getName(ptr) == MWBase::Environment::get().getWorld()->getStore().gameSettings.find("sGold")->getString()) + if (MWWorld::Class::get(ptr).getName(ptr) == esmStore.get().find("sGold")->getString()) { MWWorld::LiveCellRef *gold = ptr.get(); - if (compare_string_ci(gold->ref.mRefID, "gold_001") - || compare_string_ci(gold->ref.mRefID, "gold_005") - || compare_string_ci(gold->ref.mRefID, "gold_010") - || compare_string_ci(gold->ref.mRefID, "gold_025") - || compare_string_ci(gold->ref.mRefID, "gold_100")) + if (compare_string_ci(gold->mRef.mRefID, "gold_001") + || compare_string_ci(gold->mRef.mRefID, "gold_005") + || compare_string_ci(gold->mRef.mRefID, "gold_010") + || compare_string_ci(gold->mRef.mRefID, "gold_025") + || compare_string_ci(gold->mRef.mRefID, "gold_100")) { - MWWorld::ManualRef ref(MWBase::Environment::get().getWorld()->getStore(), "Gold_001"); + MWWorld::ManualRef ref(esmStore, "Gold_001"); - int count = (ptr.getRefData().getCount() == 1) ? gold->base->mData.mValue : ptr.getRefData().getCount(); + int count = (ptr.getRefData().getCount() == 1) ? gold->mBase->mData.mValue : ptr.getRefData().getCount(); ref.getPtr().getRefData().setCount(count); for (MWWorld::ContainerStoreIterator iter (begin(type)); iter!=end(); ++iter) { - if (compare_string_ci((*iter).get()->ref.mRefID, "gold_001")) + if (compare_string_ci((*iter).get()->mRef.mRefID, "gold_001")) { (*iter).getRefData().setCount( (*iter).getRefData().getCount() + count); flagAsModified(); @@ -127,25 +130,25 @@ MWWorld::ContainerStoreIterator MWWorld::ContainerStore::addImpl (const Ptr& ptr switch (getType(ptr)) { - case Type_Potion: potions.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --potions.list.end()); break; - case Type_Apparatus: appas.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --appas.list.end()); break; - case Type_Armor: armors.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --armors.list.end()); break; - case Type_Book: books.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --books.list.end()); break; - case Type_Clothing: clothes.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --clothes.list.end()); break; - case Type_Ingredient: ingreds.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --ingreds.list.end()); break; - case Type_Light: lights.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --lights.list.end()); break; - case Type_Lockpick: lockpicks.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --lockpicks.list.end()); break; - case Type_Miscellaneous: miscItems.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --miscItems.list.end()); break; - case Type_Probe: probes.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --probes.list.end()); break; - case Type_Repair: repairs.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --repairs.list.end()); break; - case Type_Weapon: weapons.list.push_back (*ptr.get()); it = ContainerStoreIterator(this, --weapons.list.end()); break; + case Type_Potion: potions.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --potions.mList.end()); break; + case Type_Apparatus: appas.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --appas.mList.end()); break; + case Type_Armor: armors.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --armors.mList.end()); break; + case Type_Book: books.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --books.mList.end()); break; + case Type_Clothing: clothes.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --clothes.mList.end()); break; + case Type_Ingredient: ingreds.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --ingreds.mList.end()); break; + case Type_Light: lights.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --lights.mList.end()); break; + case Type_Lockpick: lockpicks.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --lockpicks.mList.end()); break; + case Type_Miscellaneous: miscItems.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --miscItems.mList.end()); break; + case Type_Probe: probes.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --probes.mList.end()); break; + case Type_Repair: repairs.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --repairs.mList.end()); break; + case Type_Weapon: weapons.mList.push_back (*ptr.get()); it = ContainerStoreIterator(this, --weapons.mList.end()); break; } flagAsModified(); return it; } -void MWWorld::ContainerStore::fill (const ESM::InventoryList& items, const ESMS::ESMStore& store) +void MWWorld::ContainerStore::fill (const ESM::InventoryList& items, const MWWorld::ESMStore& store) { for (std::vector::const_iterator iter (items.mList.begin()); iter!=items.mList.end(); ++iter) @@ -167,18 +170,8 @@ void MWWorld::ContainerStore::fill (const ESM::InventoryList& items, const ESMS: void MWWorld::ContainerStore::clear() { - potions.list.clear(); - appas.list.clear(); - armors.list.clear(); - books.list.clear(); - clothes.list.clear(); - ingreds.list.clear(); - lights.list.clear(); - lockpicks.list.clear(); - miscItems.list.clear(); - probes.list.clear(); - repairs.list.clear(); - weapons.list.clear(); + for (ContainerStoreIterator iter (begin()); iter!=end(); ++iter) + iter->getRefData().setCount (0); flagAsModified(); } @@ -336,63 +329,63 @@ bool MWWorld::ContainerStoreIterator::resetIterator() { case ContainerStore::Type_Potion: - mPotion = mContainer->potions.list.begin(); - return mPotion!=mContainer->potions.list.end(); + mPotion = mContainer->potions.mList.begin(); + return mPotion!=mContainer->potions.mList.end(); case ContainerStore::Type_Apparatus: - mApparatus = mContainer->appas.list.begin(); - return mApparatus!=mContainer->appas.list.end(); + mApparatus = mContainer->appas.mList.begin(); + return mApparatus!=mContainer->appas.mList.end(); case ContainerStore::Type_Armor: - mArmor = mContainer->armors.list.begin(); - return mArmor!=mContainer->armors.list.end(); + mArmor = mContainer->armors.mList.begin(); + return mArmor!=mContainer->armors.mList.end(); case ContainerStore::Type_Book: - mBook = mContainer->books.list.begin(); - return mBook!=mContainer->books.list.end(); + mBook = mContainer->books.mList.begin(); + return mBook!=mContainer->books.mList.end(); case ContainerStore::Type_Clothing: - mClothing = mContainer->clothes.list.begin(); - return mClothing!=mContainer->clothes.list.end(); + mClothing = mContainer->clothes.mList.begin(); + return mClothing!=mContainer->clothes.mList.end(); case ContainerStore::Type_Ingredient: - mIngredient = mContainer->ingreds.list.begin(); - return mIngredient!=mContainer->ingreds.list.end(); + mIngredient = mContainer->ingreds.mList.begin(); + return mIngredient!=mContainer->ingreds.mList.end(); case ContainerStore::Type_Light: - mLight = mContainer->lights.list.begin(); - return mLight!=mContainer->lights.list.end(); + mLight = mContainer->lights.mList.begin(); + return mLight!=mContainer->lights.mList.end(); case ContainerStore::Type_Lockpick: - mLockpick = mContainer->lockpicks.list.begin(); - return mLockpick!=mContainer->lockpicks.list.end(); + mLockpick = mContainer->lockpicks.mList.begin(); + return mLockpick!=mContainer->lockpicks.mList.end(); case ContainerStore::Type_Miscellaneous: - mMiscellaneous = mContainer->miscItems.list.begin(); - return mMiscellaneous!=mContainer->miscItems.list.end(); + mMiscellaneous = mContainer->miscItems.mList.begin(); + return mMiscellaneous!=mContainer->miscItems.mList.end(); case ContainerStore::Type_Probe: - mProbe = mContainer->probes.list.begin(); - return mProbe!=mContainer->probes.list.end(); + mProbe = mContainer->probes.mList.begin(); + return mProbe!=mContainer->probes.mList.end(); case ContainerStore::Type_Repair: - mRepair = mContainer->repairs.list.begin(); - return mRepair!=mContainer->repairs.list.end(); + mRepair = mContainer->repairs.mList.begin(); + return mRepair!=mContainer->repairs.mList.end(); case ContainerStore::Type_Weapon: - mWeapon = mContainer->weapons.list.begin(); - return mWeapon!=mContainer->weapons.list.end(); + mWeapon = mContainer->weapons.mList.begin(); + return mWeapon!=mContainer->weapons.mList.end(); } return false; @@ -405,62 +398,62 @@ bool MWWorld::ContainerStoreIterator::incIterator() case ContainerStore::Type_Potion: ++mPotion; - return mPotion==mContainer->potions.list.end(); + return mPotion==mContainer->potions.mList.end(); case ContainerStore::Type_Apparatus: ++mApparatus; - return mApparatus==mContainer->appas.list.end(); + return mApparatus==mContainer->appas.mList.end(); case ContainerStore::Type_Armor: ++mArmor; - return mArmor==mContainer->armors.list.end(); + return mArmor==mContainer->armors.mList.end(); case ContainerStore::Type_Book: ++mBook; - return mBook==mContainer->books.list.end(); + return mBook==mContainer->books.mList.end(); case ContainerStore::Type_Clothing: ++mClothing; - return mClothing==mContainer->clothes.list.end(); + return mClothing==mContainer->clothes.mList.end(); case ContainerStore::Type_Ingredient: ++mIngredient; - return mIngredient==mContainer->ingreds.list.end(); + return mIngredient==mContainer->ingreds.mList.end(); case ContainerStore::Type_Light: ++mLight; - return mLight==mContainer->lights.list.end(); + return mLight==mContainer->lights.mList.end(); case ContainerStore::Type_Lockpick: ++mLockpick; - return mLockpick==mContainer->lockpicks.list.end(); + return mLockpick==mContainer->lockpicks.mList.end(); case ContainerStore::Type_Miscellaneous: ++mMiscellaneous; - return mMiscellaneous==mContainer->miscItems.list.end(); + return mMiscellaneous==mContainer->miscItems.mList.end(); case ContainerStore::Type_Probe: ++mProbe; - return mProbe==mContainer->probes.list.end(); + return mProbe==mContainer->probes.mList.end(); case ContainerStore::Type_Repair: ++mRepair; - return mRepair==mContainer->repairs.list.end(); + return mRepair==mContainer->repairs.mList.end(); case ContainerStore::Type_Weapon: ++mWeapon; - return mWeapon==mContainer->weapons.list.end(); + return mWeapon==mContainer->weapons.mList.end(); } return true; diff --git a/apps/openmw/mwworld/containerstore.hpp b/apps/openmw/mwworld/containerstore.hpp index ae27fad3d..1297fc53c 100644 --- a/apps/openmw/mwworld/containerstore.hpp +++ b/apps/openmw/mwworld/containerstore.hpp @@ -83,7 +83,7 @@ namespace MWWorld public: - void fill (const ESM::InventoryList& items, const ESMS::ESMStore& store); + void fill (const ESM::InventoryList& items, const MWWorld::ESMStore& store); ///< Insert items into *this. void clear(); diff --git a/apps/openmw/mwworld/esmstore.cpp b/apps/openmw/mwworld/esmstore.cpp new file mode 100644 index 000000000..73f5185c9 --- /dev/null +++ b/apps/openmw/mwworld/esmstore.cpp @@ -0,0 +1,111 @@ +#include "esmstore.hpp" + +#include +#include + +namespace MWWorld +{ + +static bool isCacheableRecord(int id) +{ + if (id == ESM::REC_ACTI || id == ESM::REC_ALCH || id == ESM::REC_APPA || id == ESM::REC_ARMO || + id == ESM::REC_BOOK || id == ESM::REC_CLOT || id == ESM::REC_CONT || id == ESM::REC_CREA || + id == ESM::REC_DOOR || id == ESM::REC_INGR || id == ESM::REC_LEVC || id == ESM::REC_LEVI || + id == ESM::REC_LIGH || id == ESM::REC_LOCK || id == ESM::REC_MISC || id == ESM::REC_NPC_ || + id == ESM::REC_PROB || id == ESM::REC_REPA || id == ESM::REC_STAT || id == ESM::REC_WEAP) + { + return true; + } + return false; +} + +void ESMStore::load(ESM::ESMReader &esm) +{ + std::set missing; + + ESM::Dialogue *dialogue = 0; + + // Loop through all records + while(esm.hasMoreRecs()) + { + ESM::NAME n = esm.getRecName(); + esm.getRecHeader(); + + // Look up the record type. + std::map::iterator it = mStores.find(n.val); + + if (it == mStores.end()) { + if (n.val == ESM::REC_INFO) { + if (dialogue) { + dialogue->mInfo.push_back(ESM::DialInfo()); + dialogue->mInfo.back().load(esm); + } else { + std::cerr << "error: info record without dialog" << std::endl; + esm.skipRecord(); + } + } else if (n.val == ESM::REC_MGEF) { + mMagicEffects.load (esm); + } else if (n.val == ESM::REC_SKIL) { + mSkills.load (esm); + } else { + // Not found (this would be an error later) + esm.skipRecord(); + missing.insert(n.toString()); + } + } else { + // Load it + std::string id = esm.getHNOString("NAME"); + it->second->load(esm, id); + + if (n.val==ESM::REC_DIAL) { + // dirty hack, but it is better than non-const search() + // or friends + dialogue = &mDialogs.mStatic.back(); + assert (dialogue->mId == id); + } else { + dialogue = 0; + } + // Insert the reference into the global lookup + if (!id.empty() && isCacheableRecord(n.val)) { + mIds[id] = n.val; + } + } + } + + /* This information isn't needed on screen. But keep the code around + for debugging purposes later. + + cout << "\n" << mStores.size() << " record types:\n"; + for(RecListList::iterator it = mStores.begin(); it != mStores.end(); it++) + cout << " " << toStr(it->first) << ": " << it->second->getSize() << endl; + cout << "\nNot implemented yet: "; + for(set::iterator it = missing.begin(); + it != missing.end(); it++ ) + cout << *it << " "; + cout << endl; + */ + setUp(); +} + +void ESMStore::setUp() +{ + std::map::iterator it = mStores.begin(); + for (; it != mStores.end(); ++it) { + it->second->setUp(); + } + mSkills.setUp(); + mMagicEffects.setUp(); + mAttributes.setUp(); + + ESM::NPC item; + item.mId = "player"; + + std::vector::iterator pIt = + std::lower_bound(mNpcs.mStatic.begin(), mNpcs.mStatic.end(), item, RecordCmp()); + assert(pIt != mNpcs.mStatic.end() && pIt->mId == "player"); + + mNpcs.insert(*pIt); + mNpcs.mStatic.erase(pIt); +} + +} // end namespace diff --git a/apps/openmw/mwworld/esmstore.hpp b/apps/openmw/mwworld/esmstore.hpp new file mode 100644 index 000000000..9917254ee --- /dev/null +++ b/apps/openmw/mwworld/esmstore.hpp @@ -0,0 +1,426 @@ +#ifndef OPENMW_MWWORLD_ESMSTORE_H +#define OPENMW_MWWORLD_ESMSTORE_H + +#include + +#include +#include "store.hpp" + +namespace MWWorld +{ + class ESMStore + { + Store mActivators; + Store mPotions; + Store mAppas; + Store mArmors; + Store mBodyParts; + Store mBooks; + Store mBirthSigns; + Store mClasses; + Store mClothes; + Store mContChange; + Store mContainers; + Store mCreatures; + Store mCreaChange; + Store mDialogs; + Store mDoors; + Store mEnchants; + Store mFactions; + Store mGlobals; + Store mIngreds; + Store mCreatureLists; + Store mItemLists; + Store mLights; + Store mLockpicks; + Store mMiscItems; + Store mNpcs; + Store mNpcChange; + Store mProbes; + Store mRaces; + Store mRegions; + Store mRepairs; + Store mSoundGens; + Store mSounds; + Store mSpells; + Store mStartScripts; + Store mStatics; + Store mWeapons; + + Store mGameSettings; + Store mScripts; + + // Lists that need special rules + Store mCells; + Store mLands; + Store mLandTextures; + Store mPathgrids; + + Store mMagicEffects; + Store mSkills; + + // Special entry which is hardcoded and not loaded from an ESM + Store mAttributes; + + // Lookup of all IDs. Makes looking up references faster. Just + // maps the id name to the record type. + std::map mIds; + std::map mStores; + + unsigned int mDynamicCount; + + public: + /// \todo replace with SharedIterator + typedef std::map::const_iterator iterator; + + iterator begin() const { + return mStores.begin(); + } + + iterator end() const { + return mStores.end(); + } + + // Look up the given ID in 'all'. Returns 0 if not found. + int find(const std::string &id) const + { + std::map::const_iterator it = mIds.find(id); + if (it == mIds.end()) { + return 0; + } + return it->second; + } + + ESMStore() + : mDynamicCount(0) + { + mStores[ESM::REC_ACTI] = &mActivators; + mStores[ESM::REC_ALCH] = &mPotions; + mStores[ESM::REC_APPA] = &mAppas; + mStores[ESM::REC_ARMO] = &mArmors; + mStores[ESM::REC_BODY] = &mBodyParts; + mStores[ESM::REC_BOOK] = &mBooks; + mStores[ESM::REC_BSGN] = &mBirthSigns; + mStores[ESM::REC_CELL] = &mCells; + mStores[ESM::REC_CLAS] = &mClasses; + mStores[ESM::REC_CLOT] = &mClothes; + mStores[ESM::REC_CNTC] = &mContChange; + mStores[ESM::REC_CONT] = &mContainers; + mStores[ESM::REC_CREA] = &mCreatures; + mStores[ESM::REC_CREC] = &mCreaChange; + mStores[ESM::REC_DIAL] = &mDialogs; + mStores[ESM::REC_DOOR] = &mDoors; + mStores[ESM::REC_ENCH] = &mEnchants; + mStores[ESM::REC_FACT] = &mFactions; + mStores[ESM::REC_GLOB] = &mGlobals; + mStores[ESM::REC_GMST] = &mGameSettings; + mStores[ESM::REC_INGR] = &mIngreds; + mStores[ESM::REC_LAND] = &mLands; + mStores[ESM::REC_LEVC] = &mCreatureLists; + mStores[ESM::REC_LEVI] = &mItemLists; + mStores[ESM::REC_LIGH] = &mLights; + mStores[ESM::REC_LOCK] = &mLockpicks; + mStores[ESM::REC_LTEX] = &mLandTextures; + mStores[ESM::REC_MISC] = &mMiscItems; + mStores[ESM::REC_NPC_] = &mNpcs; + mStores[ESM::REC_NPCC] = &mNpcChange; + mStores[ESM::REC_PGRD] = &mPathgrids; + mStores[ESM::REC_PROB] = &mProbes; + mStores[ESM::REC_RACE] = &mRaces; + mStores[ESM::REC_REGN] = &mRegions; + mStores[ESM::REC_REPA] = &mRepairs; + mStores[ESM::REC_SCPT] = &mScripts; + mStores[ESM::REC_SNDG] = &mSoundGens; + mStores[ESM::REC_SOUN] = &mSounds; + mStores[ESM::REC_SPEL] = &mSpells; + mStores[ESM::REC_SSCR] = &mStartScripts; + mStores[ESM::REC_STAT] = &mStatics; + mStores[ESM::REC_WEAP] = &mWeapons; + } + + void load(ESM::ESMReader &esm); + + template + const Store &get() const { + throw std::runtime_error("Storage for this type not exist"); + } + + template + const T *insert(const T &x) { + Store &store = const_cast &>(get()); + if (store.search(x.mId) != 0) { + std::ostringstream msg; + msg << "Try to override existing record '" << x.mId << "'"; + throw std::runtime_error(msg.str()); + } + T record = x; + + std::ostringstream id; + id << "$dynamic" << mDynamicCount++; + record.mId = id.str(); + + T *ptr = store.insert(record); + for (iterator it = mStores.begin(); it != mStores.end(); ++it) { + if (it->second == &store) { + mIds[ptr->mId] = it->first; + } + } + return ptr; + } + + private: + void setUp(); + }; + + template <> + inline const ESM::Cell *ESMStore::insert(const ESM::Cell &cell) { + return mCells.insert(cell); + } + + template <> + inline const ESM::NPC *ESMStore::insert(const ESM::NPC &npc) { + if (StringUtils::ciEqual(npc.mId, "player")) { + return mNpcs.insert(npc); + } else if (mNpcs.search(npc.mId) != 0) { + std::ostringstream msg; + msg << "Try to override existing record '" << npc.mId << "'"; + throw std::runtime_error(msg.str()); + } + ESM::NPC record = npc; + + std::ostringstream id; + id << "$dynamic" << mDynamicCount++; + record.mId = id.str(); + + ESM::NPC *ptr = mNpcs.insert(record); + mIds[ptr->mId] = ESM::REC_NPC_; + return ptr; + } + + template <> + inline const Store &ESMStore::get() const { + return mActivators; + } + + template <> + inline const Store &ESMStore::get() const { + return mPotions; + } + + template <> + inline const Store &ESMStore::get() const { + return mAppas; + } + + template <> + inline const Store &ESMStore::get() const { + return mArmors; + } + + template <> + inline const Store &ESMStore::get() const { + return mBodyParts; + } + + template <> + inline const Store &ESMStore::get() const { + return mBooks; + } + + template <> + inline const Store &ESMStore::get() const { + return mBirthSigns; + } + + template <> + inline const Store &ESMStore::get() const { + return mClasses; + } + + template <> + inline const Store &ESMStore::get() const { + return mClothes; + } + + template <> + inline const Store &ESMStore::get() const { + return mContChange; + } + + template <> + inline const Store &ESMStore::get() const { + return mContainers; + } + + template <> + inline const Store &ESMStore::get() const { + return mCreatures; + } + + template <> + inline const Store &ESMStore::get() const { + return mCreaChange; + } + + template <> + inline const Store &ESMStore::get() const { + return mDialogs; + } + + template <> + inline const Store &ESMStore::get() const { + return mDoors; + } + + template <> + inline const Store &ESMStore::get() const { + return mEnchants; + } + + template <> + inline const Store &ESMStore::get() const { + return mFactions; + } + + template <> + inline const Store &ESMStore::get() const { + return mGlobals; + } + + template <> + inline const Store &ESMStore::get() const { + return mIngreds; + } + + template <> + inline const Store &ESMStore::get() const { + return mCreatureLists; + } + + template <> + inline const Store &ESMStore::get() const { + return mItemLists; + } + + template <> + inline const Store &ESMStore::get() const { + return mLights; + } + + template <> + inline const Store &ESMStore::get() const { + return mLockpicks; + } + + template <> + inline const Store &ESMStore::get() const { + return mMiscItems; + } + + template <> + inline const Store &ESMStore::get() const { + return mNpcs; + } + + template <> + inline const Store &ESMStore::get() const { + return mNpcChange; + } + + template <> + inline const Store &ESMStore::get() const { + return mProbes; + } + + template <> + inline const Store &ESMStore::get() const { + return mRaces; + } + + template <> + inline const Store &ESMStore::get() const { + return mRegions; + } + + template <> + inline const Store &ESMStore::get() const { + return mRepairs; + } + + template <> + inline const Store &ESMStore::get() const { + return mSoundGens; + } + + template <> + inline const Store &ESMStore::get() const { + return mSounds; + } + + template <> + inline const Store &ESMStore::get() const { + return mSpells; + } + + template <> + inline const Store &ESMStore::get() const { + return mStartScripts; + } + + template <> + inline const Store &ESMStore::get() const { + return mStatics; + } + + template <> + inline const Store &ESMStore::get() const { + return mWeapons; + } + + template <> + inline const Store &ESMStore::get() const { + return mGameSettings; + } + + template <> + inline const Store &ESMStore::get() const { + return mScripts; + } + + template <> + inline const Store &ESMStore::get() const { + return mCells; + } + + template <> + inline const Store &ESMStore::get() const { + return mLands; + } + + template <> + inline const Store &ESMStore::get() const { + return mLandTextures; + } + + template <> + inline const Store &ESMStore::get() const { + return mPathgrids; + } + + template <> + inline const Store &ESMStore::get() const { + return mMagicEffects; + } + + template <> + inline const Store &ESMStore::get() const { + return mSkills; + } + + template <> + inline const Store &ESMStore::get() const { + return mAttributes; + } +} + +#endif diff --git a/apps/openmw/mwworld/failedaction.cpp b/apps/openmw/mwworld/failedaction.cpp new file mode 100644 index 000000000..ec763dba0 --- /dev/null +++ b/apps/openmw/mwworld/failedaction.cpp @@ -0,0 +1,21 @@ +#include "failedaction.hpp" +#include "../mwbase/world.hpp" + +#include "../mwbase/environment.hpp" +#include "../mwbase/windowmanager.hpp" + + +namespace MWWorld +{ + FailedAction::FailedAction (const std::string& msg) : Action (false), message(msg) + { } + + + void FailedAction::executeImp (const Ptr& actor) + { + if ( actor.getRefData().getHandle()=="player" && !(message.empty())) + { + MWBase::Environment::get().getWindowManager() ->messageBox(message, std::vector()); + } + } +} diff --git a/apps/openmw/mwworld/failedaction.hpp b/apps/openmw/mwworld/failedaction.hpp new file mode 100644 index 000000000..e736bfb63 --- /dev/null +++ b/apps/openmw/mwworld/failedaction.hpp @@ -0,0 +1,20 @@ +#ifndef GAME_MWWORLD_FAILEDACTION_H +#define GAME_MWWORLD_FAILEDACTION_H + +#include "action.hpp" +#include "ptr.hpp" + +namespace MWWorld +{ + class FailedAction : public Action + { + std::string message; + + virtual void executeImp (const Ptr& actor); + + public: + FailedAction (const std::string& message = std::string()); + }; +} + +#endif \ No newline at end of file diff --git a/apps/openmw/mwworld/globals.cpp b/apps/openmw/mwworld/globals.cpp index 1430219d9..76dede5a3 100644 --- a/apps/openmw/mwworld/globals.cpp +++ b/apps/openmw/mwworld/globals.cpp @@ -3,7 +3,7 @@ #include -#include +#include "esmstore.hpp" namespace MWWorld { @@ -27,35 +27,36 @@ namespace MWWorld return iter; } - Globals::Globals (const ESMS::ESMStore& store) + Globals::Globals (const MWWorld::ESMStore& store) { - for (ESMS::RecListT::MapType::const_iterator iter - (store.globals.list.begin()); iter != store.globals.list.end(); ++iter) + const MWWorld::Store &globals = store.get(); + MWWorld::Store::iterator iter = globals.begin(); + for (; iter != globals.end(); ++iter) { char type = ' '; Data value; - switch (iter->second.mType) + switch (iter->mType) { case ESM::VT_Short: type = 's'; value.mShort = *reinterpret_cast ( - &iter->second.mValue); + &iter->mValue); break; case ESM::VT_Int: type = 'l'; value.mLong = *reinterpret_cast ( - &iter->second.mValue); + &iter->mValue); break; case ESM::VT_Float: type = 'f'; value.mFloat = *reinterpret_cast ( - &iter->second.mValue); + &iter->mValue); break; default: @@ -63,7 +64,7 @@ namespace MWWorld throw std::runtime_error ("unsupported global variable type"); } - mVariables.insert (std::make_pair (iter->first, std::make_pair (type, value))); + mVariables.insert (std::make_pair (iter->mId, std::make_pair (type, value))); } if (mVariables.find ("dayspassed")==mVariables.end()) diff --git a/apps/openmw/mwworld/globals.hpp b/apps/openmw/mwworld/globals.hpp index 6aa54ade2..c7aee5f93 100644 --- a/apps/openmw/mwworld/globals.hpp +++ b/apps/openmw/mwworld/globals.hpp @@ -6,13 +6,10 @@ #include -namespace ESMS -{ - struct ESMStore; -} - namespace MWWorld { + class ESMStore; + class Globals { public: @@ -36,7 +33,7 @@ namespace MWWorld public: - Globals (const ESMS::ESMStore& store); + Globals (const MWWorld::ESMStore& store); const Data& operator[] (const std::string& name) const; diff --git a/apps/openmw/mwworld/inventorystore.cpp b/apps/openmw/mwworld/inventorystore.cpp index 179a484e9..dd518ff6a 100644 --- a/apps/openmw/mwworld/inventorystore.cpp +++ b/apps/openmw/mwworld/inventorystore.cpp @@ -6,13 +6,12 @@ #include -#include - #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwmechanics/npcstats.hpp" +#include "esmstore.hpp" #include "class.hpp" void MWWorld::InventoryStore::copySlots (const InventoryStore& store) @@ -231,7 +230,7 @@ const MWMechanics::MagicEffects& MWWorld::InventoryStore::getMagicEffects() if (!enchantmentId.empty()) { const ESM::Enchantment& enchantment = - *MWBase::Environment::get().getWorld()->getStore().enchants.find (enchantmentId); + *MWBase::Environment::get().getWorld()->getStore().get().find (enchantmentId); if (enchantment.mData.mType==ESM::Enchantment::ConstantEffect) mMagicEffects.add (enchantment.mEffects); diff --git a/apps/openmw/mwworld/localscripts.cpp b/apps/openmw/mwworld/localscripts.cpp index d0d698feb..a821ad486 100644 --- a/apps/openmw/mwworld/localscripts.cpp +++ b/apps/openmw/mwworld/localscripts.cpp @@ -1,8 +1,6 @@ - #include "localscripts.hpp" -#include - +#include "esmstore.hpp" #include "cellstore.hpp" namespace @@ -12,18 +10,18 @@ namespace MWWorld::CellRefList& cellRefList, MWWorld::Ptr::CellStore *cell) { for (typename MWWorld::CellRefList::List::iterator iter ( - cellRefList.list.begin()); - iter!=cellRefList.list.end(); ++iter) + cellRefList.mList.begin()); + iter!=cellRefList.mList.end(); ++iter) { - if (!iter->base->mScript.empty() && iter->mData.getCount()) + if (!iter->mBase->mScript.empty() && iter->mData.getCount()) { - localScripts.add (iter->base->mScript, MWWorld::Ptr (&*iter, cell)); + localScripts.add (iter->mBase->mScript, MWWorld::Ptr (&*iter, cell)); } } } } -MWWorld::LocalScripts::LocalScripts (const ESMS::ESMStore& store) : mStore (store) {} +MWWorld::LocalScripts::LocalScripts (const MWWorld::ESMStore& store) : mStore (store) {} void MWWorld::LocalScripts::setIgnore (const Ptr& ptr) { @@ -63,7 +61,7 @@ std::pair MWWorld::LocalScripts::getNext() void MWWorld::LocalScripts::add (const std::string& scriptName, const Ptr& ptr) { - if (const ESM::Script *script = mStore.scripts.find (scriptName)) + if (const ESM::Script *script = mStore.get().find (scriptName)) { ptr.getRefData().setLocals (*script); @@ -73,23 +71,23 @@ void MWWorld::LocalScripts::add (const std::string& scriptName, const Ptr& ptr) void MWWorld::LocalScripts::addCell (Ptr::CellStore *cell) { - listCellScripts (*this, cell->activators, cell); - listCellScripts (*this, cell->potions, cell); - listCellScripts (*this, cell->appas, cell); - listCellScripts (*this, cell->armors, cell); - listCellScripts (*this, cell->books, cell); - listCellScripts (*this, cell->clothes, cell); - listCellScripts (*this, cell->containers, cell); - listCellScripts (*this, cell->creatures, cell); - listCellScripts (*this, cell->doors, cell); - listCellScripts (*this, cell->ingreds, cell); - listCellScripts (*this, cell->lights, cell); - listCellScripts (*this, cell->lockpicks, cell); - listCellScripts (*this, cell->miscItems, cell); - listCellScripts (*this, cell->npcs, cell); - listCellScripts (*this, cell->probes, cell); - listCellScripts (*this, cell->repairs, cell); - listCellScripts (*this, cell->weapons, cell); + listCellScripts (*this, cell->mActivators, cell); + listCellScripts (*this, cell->mPotions, cell); + listCellScripts (*this, cell->mAppas, cell); + listCellScripts (*this, cell->mArmors, cell); + listCellScripts (*this, cell->mBooks, cell); + listCellScripts (*this, cell->mClothes, cell); + listCellScripts (*this, cell->mContainers, cell); + listCellScripts (*this, cell->mCreatures, cell); + listCellScripts (*this, cell->mDoors, cell); + listCellScripts (*this, cell->mIngreds, cell); + listCellScripts (*this, cell->mLights, cell); + listCellScripts (*this, cell->mLockpicks, cell); + listCellScripts (*this, cell->mMiscItems, cell); + listCellScripts (*this, cell->mNpcs, cell); + listCellScripts (*this, cell->mProbes, cell); + listCellScripts (*this, cell->mRepairs, cell); + listCellScripts (*this, cell->mWeapons, cell); } void MWWorld::LocalScripts::clear() diff --git a/apps/openmw/mwworld/localscripts.hpp b/apps/openmw/mwworld/localscripts.hpp index 78f65e356..028dcdeda 100644 --- a/apps/openmw/mwworld/localscripts.hpp +++ b/apps/openmw/mwworld/localscripts.hpp @@ -6,13 +6,9 @@ #include "ptr.hpp" -namespace ESMS -{ - struct ESMStore; -} - namespace MWWorld { + struct ESMStore; class CellStore; /// \brief List of active local scripts @@ -21,11 +17,11 @@ namespace MWWorld std::list > mScripts; std::list >::iterator mIter; MWWorld::Ptr mIgnore; - const ESMS::ESMStore& mStore; + const MWWorld::ESMStore& mStore; public: - LocalScripts (const ESMS::ESMStore& store); + LocalScripts (const MWWorld::ESMStore& store); void setIgnore (const Ptr& ptr); ///< Mark a single reference for ignoring during iteration over local scripts (will revoke diff --git a/apps/openmw/mwworld/manualref.hpp b/apps/openmw/mwworld/manualref.hpp index 6570761ab..91b8cf8cd 100644 --- a/apps/openmw/mwworld/manualref.hpp +++ b/apps/openmw/mwworld/manualref.hpp @@ -3,8 +3,7 @@ #include -#include - +#include "esmstore.hpp" #include "ptr.hpp" #include "cellstore.hpp" @@ -20,29 +19,12 @@ namespace MWWorld ManualRef& operator= (const ManualRef&); template - bool create (const ESMS::RecListT& list, const std::string& name) + bool create (const MWWorld::Store& list, const std::string& name) { if (const T *instance = list.search (name)) { LiveCellRef ref; - ref.base = instance; - - mRef = ref; - mPtr = Ptr (&boost::any_cast&> (mRef), 0); - - return true; - } - - return false; - } - - template - bool create (const ESMS::RecListWithIDT& list, const std::string& name) - { - if (const T *instance = list.search (name)) - { - LiveCellRef ref; - ref.base = instance; + ref.mBase = instance; mRef = ref; mPtr = Ptr (&boost::any_cast&> (mRef), 0); @@ -55,29 +37,29 @@ namespace MWWorld public: - ManualRef (const ESMS::ESMStore& store, const std::string& name) + ManualRef (const MWWorld::ESMStore& store, const std::string& name) { // create - if (!create (store.activators, name) && - !create (store.potions, name) && - !create (store.appas, name) && - !create (store.armors, name) && - !create (store.books, name) && - !create (store.clothes, name) && - !create (store.containers, name) && - !create (store.creatures, name) && - !create (store.doors, name) && - !create (store.ingreds, name) && - !create (store.creatureLists, name) && - !create (store.itemLists, name) && - !create (store.lights, name) && - !create (store.lockpicks, name) && - !create (store.miscItems, name) && - !create (store.npcs, name) && - !create (store.probes, name) && - !create (store.repairs, name) && - !create (store.statics, name) && - !create (store.weapons, name)) + if (!create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name) && + !create (store.get(), name)) throw std::logic_error ("failed to create manual cell ref for " + name); // initialise diff --git a/apps/openmw/mwworld/physicssystem.cpp b/apps/openmw/mwworld/physicssystem.cpp index 8fa1976ac..5359c4eb2 100644 --- a/apps/openmw/mwworld/physicssystem.cpp +++ b/apps/openmw/mwworld/physicssystem.cpp @@ -12,6 +12,7 @@ #include //#include "../mwbase/world.hpp" // FIXME +#include "../mwbase/environment.hpp" #include "ptr.hpp" #include "class.hpp" @@ -249,31 +250,36 @@ namespace MWWorld mEngine->removeHeightField(x, y); } - void PhysicsSystem::addObject (const std::string& handle, const std::string& mesh, - const Ogre::Quaternion& rotation, float scale, const Ogre::Vector3& position) + void PhysicsSystem::addObject (const Ptr& ptr) { - handleToMesh[handle] = mesh; - OEngine::Physic::RigidBody* body = mEngine->createAndAdjustRigidBody(mesh,handle,scale, position, rotation); + std::string mesh = MWWorld::Class::get(ptr).getModel(ptr); + Ogre::SceneNode* node = ptr.getRefData().getBaseNode(); + handleToMesh[node->getName()] = mesh; + OEngine::Physic::RigidBody* body = mEngine->createAndAdjustRigidBody(mesh, node->getName(), node->getScale().x, node->getPosition(), node->getOrientation()); mEngine->addRigidBody(body); } - void PhysicsSystem::addActor (const std::string& handle, const std::string& mesh, - const Ogre::Vector3& position, float scale, const Ogre::Quaternion& rotation) + void PhysicsSystem::addActor (const Ptr& ptr) { + std::string mesh = MWWorld::Class::get(ptr).getModel(ptr); + Ogre::SceneNode* node = ptr.getRefData().getBaseNode(); //TODO:optimize this. Searching the std::map isn't very efficient i think. - mEngine->addCharacter(handle, mesh, position, scale, rotation); + mEngine->addCharacter(node->getName(), mesh, node->getPosition(), node->getScale().x, node->getOrientation()); } void PhysicsSystem::removeObject (const std::string& handle) { //TODO:check if actor??? + mEngine->removeCharacter(handle); mEngine->removeRigidBody(handle); mEngine->deleteRigidBody(handle); } - void PhysicsSystem::moveObject (const std::string& handle, Ogre::SceneNode* node) + void PhysicsSystem::moveObject (const Ptr& ptr) { + Ogre::SceneNode* node = ptr.getRefData().getBaseNode(); + std::string handle = node->getName(); Ogre::Vector3 position = node->getPosition(); if (OEngine::Physic::RigidBody* body = mEngine->getRigidBody(handle)) { @@ -307,8 +313,10 @@ namespace MWWorld } } - void PhysicsSystem::rotateObject (const std::string& handle, Ogre::SceneNode* node) + void PhysicsSystem::rotateObject (const Ptr& ptr) { + Ogre::SceneNode* node = ptr.getRefData().getBaseNode(); + std::string handle = node->getName(); Ogre::Quaternion rotation = node->getOrientation(); if (OEngine::Physic::PhysicActor* act = mEngine->getCharacter(handle)) { @@ -324,32 +332,23 @@ namespace MWWorld } } - void PhysicsSystem::scaleObject (const std::string& handle, Ogre::SceneNode* node) + void PhysicsSystem::scaleObject (const Ptr& ptr) { + Ogre::SceneNode* node = ptr.getRefData().getBaseNode(); + std::string handle = node->getName(); if(handleToMesh.find(handle) != handleToMesh.end()) { removeObject(handle); - - float scale = node->getScale().x; - Ogre::Quaternion quat = node->getOrientation(); - Ogre::Vector3 vec = node->getPosition(); - addObject(handle, handleToMesh[handle], quat, scale, vec); + addObject(ptr); } if (OEngine::Physic::PhysicActor* act = mEngine->getCharacter(handle)) - { - float scale = node->getScale().x; - act->setScale(scale); - } + act->setScale(node->getScale().x); } bool PhysicsSystem::toggleCollisionMode() { - if(playerphysics->ps.move_type==PM_NOCLIP) - playerphysics->ps.move_type=PM_NORMAL; - - else - playerphysics->ps.move_type=PM_NOCLIP; + playerphysics->ps.move_type = (playerphysics->ps.move_type == PM_NOCLIP ? PM_NORMAL : PM_NOCLIP); for(std::map::iterator it = mEngine->PhysicActorMap.begin(); it != mEngine->PhysicActorMap.end();it++) { if (it->first=="player") @@ -375,23 +374,6 @@ namespace MWWorld throw std::logic_error ("can't find player"); } - void PhysicsSystem::insertObjectPhysics(const MWWorld::Ptr& ptr, const std::string model){ - - Ogre::SceneNode* node = ptr.getRefData().getBaseNode(); - - addObject( - node->getName(), - model, - node->getOrientation(), - node->getScale().x, - node->getPosition()); - } - - void PhysicsSystem::insertActorPhysics(const MWWorld::Ptr& ptr, const std::string model){ - Ogre::SceneNode* node = ptr.getRefData().getBaseNode(); - addActor (node->getName(), model, node->getPosition(), node->getScale().x, node->getOrientation()); - } - bool PhysicsSystem::getObjectAABB(const MWWorld::Ptr &ptr, Ogre::Vector3 &min, Ogre::Vector3 &max) { std::string model = MWWorld::Class::get(ptr).getModel(ptr); diff --git a/apps/openmw/mwworld/physicssystem.hpp b/apps/openmw/mwworld/physicssystem.hpp index 1427060f6..8bd73fd6c 100644 --- a/apps/openmw/mwworld/physicssystem.hpp +++ b/apps/openmw/mwworld/physicssystem.hpp @@ -20,11 +20,9 @@ namespace MWWorld std::vector< std::pair > doPhysicsFixed (const std::vector >& actors); ///< do physics with fixed timestep - Usage: first call doPhysics with frame dt, then call doPhysicsFixed as often as time steps have passed - void addObject (const std::string& handle, const std::string& mesh, - const Ogre::Quaternion& rotation, float scale, const Ogre::Vector3& position); + void addObject (const MWWorld::Ptr& ptr); - void addActor (const std::string& handle, const std::string& mesh, - const Ogre::Vector3& position, float scale, const Ogre::Quaternion& rotation); + void addActor (const MWWorld::Ptr& ptr); void addHeightField (float* heights, int x, int y, float yoffset, @@ -32,13 +30,14 @@ namespace MWWorld void removeHeightField (int x, int y); + // have to keep this as handle for now as unloadcell only knows scenenode names void removeObject (const std::string& handle); - void moveObject (const std::string& handle, Ogre::SceneNode* node); + void moveObject (const MWWorld::Ptr& ptr); - void rotateObject (const std::string& handle, Ogre::SceneNode* node); + void rotateObject (const MWWorld::Ptr& ptr); - void scaleObject (const std::string& handle, Ogre::SceneNode* node); + void scaleObject (const MWWorld::Ptr& ptr); bool toggleCollisionMode(); @@ -60,10 +59,6 @@ namespace MWWorld std::pair castRay(float mouseX, float mouseY); ///< cast ray from the mouse, return true if it hit something and the first result (in OGRE coordinates) - void insertObjectPhysics(const MWWorld::Ptr& ptr, std::string model); - - void insertActorPhysics(const MWWorld::Ptr&, std::string model); - OEngine::Physic::PhysicEngine* getEngine(); void setCurrentWater(bool hasWater, int waterHeight); diff --git a/apps/openmw/mwworld/player.cpp b/apps/openmw/mwworld/player.cpp index e1eb02c32..3414ba448 100644 --- a/apps/openmw/mwworld/player.cpp +++ b/apps/openmw/mwworld/player.cpp @@ -1,7 +1,6 @@ #include "player.hpp" -#include #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" @@ -9,37 +8,21 @@ #include "../mwmechanics/movement.hpp" #include "../mwmechanics/npcstats.hpp" +#include "esmstore.hpp" #include "class.hpp" namespace MWWorld { - Player::Player (const ESM::NPC *player, const MWBase::World& world) : - mCellStore (0), mClass (0), - mAutoMove (false), mForwardBackward (0) + Player::Player (const ESM::NPC *player, const MWBase::World& world) + : mCellStore(0), + mAutoMove(false), + mForwardBackward (0) { - mPlayer.base = player; - mPlayer.ref.mRefID = "player"; - mName = player->mName; - mMale = !(player->mFlags & ESM::NPC::Female); - mRace = player->mRace; + mPlayer.mBase = player; + mPlayer.mRef.mRefID = "player"; float* playerPos = mPlayer.mData.getPosition().pos; playerPos[0] = playerPos[1] = playerPos[2] = 0; - - /// \todo Do not make a copy of classes defined in esm/p records. - mClass = new ESM::Class (*world.getStore().classes.find (player->mClass)); - } - - Player::~Player() - { - delete mClass; - } - - void Player::setClass (const ESM::Class& class_) - { - ESM::Class *new_class = new ESM::Class (class_); - delete mClass; - mClass = new_class; } void Player::setDrawState (MWMechanics::DrawState_ state) @@ -102,5 +85,4 @@ namespace MWWorld MWWorld::Ptr ptr = getPlayer(); return MWWorld::Class::get(ptr).getNpcStats(ptr).getDrawState(); } - } diff --git a/apps/openmw/mwworld/player.hpp b/apps/openmw/mwworld/player.hpp index 68df2ec6d..1c1ef76cf 100644 --- a/apps/openmw/mwworld/player.hpp +++ b/apps/openmw/mwworld/player.hpp @@ -1,8 +1,6 @@ #ifndef GAME_MWWORLD_PLAYER_H #define GAME_MWWORLD_PLAYER_H -#include "OgreCamera.h" - #include "../mwworld/cellstore.hpp" #include "../mwworld/refdata.hpp" #include "../mwworld/ptr.hpp" @@ -21,21 +19,17 @@ namespace MWWorld /// \brief NPC object representing the player and additional player data class Player { - LiveCellRef mPlayer; - MWWorld::CellStore *mCellStore; - std::string mName; - bool mMale; - std::string mRace; - std::string mBirthsign; - ESM::Class *mClass; - bool mAutoMove; - int mForwardBackward; + LiveCellRef mPlayer; + MWWorld::CellStore *mCellStore; + std::string mSign; + + bool mAutoMove; + int mForwardBackward; + public: Player(const ESM::NPC *player, const MWBase::World& world); - ~Player(); - void setCell (MWWorld::CellStore *cellStore) { mCellStore = cellStore; @@ -47,55 +41,16 @@ namespace MWWorld return ptr; } - void setName (const std::string& name) - { - mName = name; + void setBirthSign(const std::string &sign) { + mSign = sign; } - void setGender (bool male) - { - mMale = male; + const std::string &getBirthSign() const { + return mSign; } - void setRace (const std::string& race) - { - mRace = race; - } - - void setBirthsign (const std::string& birthsign) - { - mBirthsign = birthsign; - } - - void setClass (const ESM::Class& class_); - void setDrawState (MWMechanics::DrawState_ state); - std::string getName() const - { - return mName; - } - - bool isMale() const - { - return mMale; - } - - std::string getRace() const - { - return mRace; - } - - std::string getBirthsign() const - { - return mBirthsign; - } - - const ESM::Class& getClass() const - { - return *mClass; - } - bool getAutoMove() const { return mAutoMove; diff --git a/apps/openmw/mwworld/ptr.hpp b/apps/openmw/mwworld/ptr.hpp index f74fdd3ef..594ddef2d 100644 --- a/apps/openmw/mwworld/ptr.hpp +++ b/apps/openmw/mwworld/ptr.hpp @@ -50,7 +50,7 @@ namespace MWWorld : mContainerStore (0) { mPtr = liveCellRef; - mCellRef = &liveCellRef->ref; + mCellRef = &liveCellRef->mRef; mRefData = &liveCellRef->mData; mCell = cell; mTypeName = typeid (T).name(); diff --git a/apps/openmw/mwworld/recordcmp.hpp b/apps/openmw/mwworld/recordcmp.hpp new file mode 100644 index 000000000..0b1655100 --- /dev/null +++ b/apps/openmw/mwworld/recordcmp.hpp @@ -0,0 +1,84 @@ +#ifndef OPENMW_MWWORLD_RECORDCMP_H +#define OPENMW_MWWORLD_RECORDCMP_H + +#include +#include +#include + +#include + +namespace MWWorld +{ + /// \todo move this to another location + class StringUtils + { + struct ci + { + bool operator()(int x, int y) const { + return std::tolower(x) < std::tolower(y); + } + }; + + public: + static bool ciLess(const std::string &x, const std::string &y) { + return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end(), ci()); + } + + static bool ciEqual(const std::string &x, const std::string &y) { + if (x.size() != y.size()) { + return false; + } + std::string::const_iterator xit = x.begin(); + std::string::const_iterator yit = y.begin(); + for (; xit != x.end(); ++xit, ++yit) { + if (std::tolower(*xit) != std::tolower(*yit)) { + return false; + } + } + return true; + } + + /// Transforms input string to lower case w/o copy + static std::string &toLower(std::string &inout) { + std::transform( + inout.begin(), + inout.end(), + inout.begin(), + (int (*)(int)) std::tolower + ); + return inout; + } + + /// Returns lower case copy of input string + static std::string lowerCase(const std::string &in) + { + std::string out = in; + return toLower(out); + } + }; + + struct RecordCmp + { + template + bool operator()(const T &x, const T& y) const { + return x.mId < y.mId; + } + }; + + template <> + inline bool RecordCmp::operator()(const ESM::Dialogue &x, const ESM::Dialogue &y) const { + return StringUtils::ciLess(x.mId, y.mId); + } + + template <> + inline bool RecordCmp::operator()(const ESM::Cell &x, const ESM::Cell &y) const { + return StringUtils::ciLess(x.mName, y.mName); + } + + template <> + inline bool RecordCmp::operator()(const ESM::Pathgrid &x, const ESM::Pathgrid &y) const { + return StringUtils::ciLess(x.mCell, y.mCell); + } + +} // end namespace +#endif diff --git a/apps/openmw/mwworld/scene.cpp b/apps/openmw/mwworld/scene.cpp index f16077202..6b9abf508 100644 --- a/apps/openmw/mwworld/scene.cpp +++ b/apps/openmw/mwworld/scene.cpp @@ -1,6 +1,5 @@ #include "scene.hpp" -#include #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" /// FIXME @@ -10,6 +9,7 @@ #include "player.hpp" #include "localscripts.hpp" +#include "esmstore.hpp" #include "cellfunctors.hpp" @@ -20,15 +20,15 @@ namespace void insertCellRefList(MWRender::RenderingManager& rendering, T& cellRefList, MWWorld::CellStore &cell, MWWorld::PhysicsSystem& physics) { - if (!cellRefList.list.empty()) + if (!cellRefList.mList.empty()) { const MWWorld::Class& class_ = - MWWorld::Class::get (MWWorld::Ptr (&*cellRefList.list.begin(), &cell)); + MWWorld::Class::get (MWWorld::Ptr (&*cellRefList.mList.begin(), &cell)); - int numRefs = cellRefList.list.size(); + int numRefs = cellRefList.mList.size(); int current = 0; - for (typename T::List::iterator it = cellRefList.list.begin(); - it != cellRefList.list.end(); it++) + for (typename T::List::iterator it = cellRefList.mList.begin(); + it != cellRefList.mList.end(); it++) { MWBase::Environment::get().getWindowManager ()->setLoadingProgress ("Loading cells", 1, current, numRefs); ++current; @@ -41,6 +41,8 @@ namespace { rendering.addObject(ptr); class_.insertObject(ptr, physics); + MWBase::Environment::get().getWorld()->rotateObject(ptr, 0, 0, 0, true); + MWBase::Environment::get().getWorld()->scaleObject(ptr, ptr.getCellRef().mScale); } catch (const std::exception& e) { @@ -62,25 +64,17 @@ namespace namespace MWWorld { - void Scene::update (float duration){ - mRendering.update (duration); + void Scene::update (float duration, bool paused){ + mRendering.update (duration, paused); } void Scene::unloadCell (CellStoreCollection::iterator iter) { std::cout << "Unloading cell\n"; ListHandles functor; - - - - - - + (*iter)->forEach(functor); - { - - // silence annoying g++ warning for (std::vector::const_iterator iter2 (functor.mHandles.begin()); iter2!=functor.mHandles.end(); ++iter2){ @@ -88,35 +82,32 @@ namespace MWWorld mPhysics->removeObject (node->getName()); } - if (!((*iter)->cell->mData.mFlags & ESM::Cell::Interior)) + if ((*iter)->mCell->isExterior()) { - ESM::Land* land = MWBase::Environment::get().getWorld()->getStore().lands.search((*iter)->cell->mData.mX,(*iter)->cell->mData.mY); + ESM::Land* land = + MWBase::Environment::get().getWorld()->getStore().get().search( + (*iter)->mCell->getGridX(), + (*iter)->mCell->getGridY() + ); if (land) - mPhysics->removeHeightField( (*iter)->cell->mData.mX, (*iter)->cell->mData.mY ); + mPhysics->removeHeightField( (*iter)->mCell->getGridX(), (*iter)->mCell->getGridY() ); } } - mRendering.removeCell(*iter); - //mPhysics->removeObject("Unnamed_43"); + mRendering.removeCell(*iter); + //mPhysics->removeObject("Unnamed_43"); MWBase::Environment::get().getWorld()->getLocalScripts().clearCell (*iter); MWBase::Environment::get().getMechanicsManager()->dropActors (*iter); MWBase::Environment::get().getSoundManager()->stopSound (*iter); - mActiveCells.erase(*iter); - - - + mActiveCells.erase(*iter); } void Scene::loadCell (Ptr::CellStore *cell) { // register local scripts MWBase::Environment::get().getWorld()->getLocalScripts().addCell (cell); - - - - std::pair result = - mActiveCells.insert(cell); + std::pair result = mActiveCells.insert(cell); if(result.second) { @@ -126,31 +117,35 @@ namespace MWWorld float verts = ESM::Land::LAND_SIZE; float worldsize = ESM::Land::REAL_SIZE; - if (!(cell->cell->mData.mFlags & ESM::Cell::Interior)) + if (cell->mCell->isExterior()) { - ESM::Land* land = MWBase::Environment::get().getWorld()->getStore().lands.search(cell->cell->mData.mX,cell->cell->mData.mY); - if (land) - mPhysics->addHeightField (land->mLandData->mHeights, - cell->cell->mData.mX, cell->cell->mData.mY, - 0, ( worldsize/(verts-1) ), verts); + ESM::Land* land = + MWBase::Environment::get().getWorld()->getStore().get().search( + cell->mCell->getGridX(), + cell->mCell->getGridY() + ); + if (land) { + mPhysics->addHeightField ( + land->mLandData->mHeights, + cell->mCell->getGridX(), + cell->mCell->getGridY(), + 0, + worldsize / (verts-1), + verts) + ; + } } mRendering.configureAmbient(*cell); mRendering.requestMap(cell); mRendering.configureAmbient(*cell); - } - } - void - Scene::playerCellChange( - MWWorld::CellStore *cell, - const ESM::Position& pos, - bool adjustPlayerPos) + void Scene::playerCellChange(MWWorld::CellStore *cell, const ESM::Position& pos, bool adjustPlayerPos) { - bool hasWater = cell->cell->mData.mFlags & cell->cell->HasWater; - mPhysics->setCurrentWater(hasWater, cell->cell->mWater); + bool hasWater = cell->mCell->mData.mFlags & ESM::Cell::HasWater; + mPhysics->setCurrentWater(hasWater, cell->mCell->mWater); MWBase::World *world = MWBase::Environment::get().getWorld(); world->getPlayer().setCell(cell); @@ -188,10 +183,10 @@ namespace MWWorld int numUnload = 0; while (active!=mActiveCells.end()) { - if (!((*active)->cell->mData.mFlags & ESM::Cell::Interior)) + if ((*active)->mCell->isExterior()) { - if (std::abs (X-(*active)->cell->mData.mX)<=1 && - std::abs (Y-(*active)->cell->mData.mY)<=1) + if (std::abs (X-(*active)->mCell->getGridX())<=1 && + std::abs (Y-(*active)->mCell->getGridY())<=1) { // keep cells within the new 3x3 grid ++active; @@ -206,10 +201,10 @@ namespace MWWorld active = mActiveCells.begin(); while (active!=mActiveCells.end()) { - if (!((*active)->cell->mData.mFlags & ESM::Cell::Interior)) + if ((*active)->mCell->isExterior()) { - if (std::abs (X-(*active)->cell->mData.mX)<=1 && - std::abs (Y-(*active)->cell->mData.mY)<=1) + if (std::abs (X-(*active)->mCell->getGridX())<=1 && + std::abs (Y-(*active)->mCell->getGridY())<=1) { // keep cells within the new 3x3 grid ++active; @@ -231,10 +226,10 @@ namespace MWWorld while (iter!=mActiveCells.end()) { - assert (!((*iter)->cell->mData.mFlags & ESM::Cell::Interior)); + assert ((*iter)->mCell->isExterior()); - if (x==(*iter)->cell->mData.mX && - y==(*iter)->cell->mData.mY) + if (x==(*iter)->mCell->getGridX() && + y==(*iter)->mCell->getGridY()) break; ++iter; @@ -253,10 +248,10 @@ namespace MWWorld while (iter!=mActiveCells.end()) { - assert (!((*iter)->cell->mData.mFlags & ESM::Cell::Interior)); + assert ((*iter)->mCell->isExterior()); - if (x==(*iter)->cell->mData.mX && - y==(*iter)->cell->mData.mY) + if (x==(*iter)->mCell->getGridX() && + y==(*iter)->mCell->getGridY()) break; ++iter; @@ -277,10 +272,10 @@ namespace MWWorld while (iter!=mActiveCells.end()) { - assert (!((*iter)->cell->mData.mFlags & ESM::Cell::Interior)); + assert ((*iter)->mCell->isExterior()); - if (X==(*iter)->cell->mData.mX && - Y==(*iter)->cell->mData.mY) + if (X==(*iter)->mCell->getGridX() && + Y==(*iter)->mCell->getGridY()) break; ++iter; @@ -325,9 +320,24 @@ namespace MWWorld void Scene::changeToInteriorCell (const std::string& cellName, const ESM::Position& position) { - std::cout << "Changing to interior\n"; - CellStore *cell = MWBase::Environment::get().getWorld()->getInterior(cellName); + bool loadcell = (mCurrentCell == NULL); + if(!loadcell) + loadcell = *mCurrentCell != *cell; + + if(!loadcell) + { + MWBase::World *world = MWBase::Environment::get().getWorld(); + world->moveObject(world->getPlayer().getPlayer(), position.pos[0], position.pos[1], position.pos[2]); + + float x = Ogre::Radian(position.rot[0]).valueDegrees(); + float y = Ogre::Radian(position.rot[1]).valueDegrees(); + float z = Ogre::Radian(position.rot[2]).valueDegrees(); + world->rotateObject(world->getPlayer().getPlayer(), x, y, z); + return; + } + + std::cout << "Changing to interior\n"; // remove active CellStoreCollection::iterator active = mActiveCells.begin(); @@ -352,19 +362,19 @@ namespace MWWorld } // Load cell. - std::cout << "cellName:" << cellName << std::endl; - + std::cout << "cellName: " << cell->mCell->mName << std::endl; MWBase::Environment::get().getWindowManager ()->setLoadingProgress ("Loading cells", 0, 0, 1); loadCell (cell); - // adjust player mCurrentCell = cell; - playerCellChange (cell, position); // adjust fog mRendering.switchToInterior(); - mRendering.configureFog(*cell); + mRendering.configureFog(*mCurrentCell); + + // adjust player + playerCellChange (mCurrentCell, position); // Sky system MWBase::Environment::get().getWorld()->adjustSky(); @@ -397,32 +407,34 @@ namespace MWWorld void Scene::insertCell (Ptr::CellStore &cell) { // Loop through all references in the cell - insertCellRefList(mRendering, cell.activators, cell, *mPhysics); - insertCellRefList(mRendering, cell.potions, cell, *mPhysics); - insertCellRefList(mRendering, cell.appas, cell, *mPhysics); - insertCellRefList(mRendering, cell.armors, cell, *mPhysics); - insertCellRefList(mRendering, cell.books, cell, *mPhysics); - insertCellRefList(mRendering, cell.clothes, cell, *mPhysics); - insertCellRefList(mRendering, cell.containers, cell, *mPhysics); - insertCellRefList(mRendering, cell.creatures, cell, *mPhysics); - insertCellRefList(mRendering, cell.doors, cell, *mPhysics); - insertCellRefList(mRendering, cell.ingreds, cell, *mPhysics); - insertCellRefList(mRendering, cell.creatureLists, cell, *mPhysics); - insertCellRefList(mRendering, cell.itemLists, cell, *mPhysics); - insertCellRefList(mRendering, cell.lights, cell, *mPhysics); - insertCellRefList(mRendering, cell.lockpicks, cell, *mPhysics); - insertCellRefList(mRendering, cell.miscItems, cell, *mPhysics); - insertCellRefList(mRendering, cell.npcs, cell, *mPhysics); - insertCellRefList(mRendering, cell.probes, cell, *mPhysics); - insertCellRefList(mRendering, cell.repairs, cell, *mPhysics); - insertCellRefList(mRendering, cell.statics, cell, *mPhysics); - insertCellRefList(mRendering, cell.weapons, cell, *mPhysics); + insertCellRefList(mRendering, cell.mActivators, cell, *mPhysics); + insertCellRefList(mRendering, cell.mPotions, cell, *mPhysics); + insertCellRefList(mRendering, cell.mAppas, cell, *mPhysics); + insertCellRefList(mRendering, cell.mArmors, cell, *mPhysics); + insertCellRefList(mRendering, cell.mBooks, cell, *mPhysics); + insertCellRefList(mRendering, cell.mClothes, cell, *mPhysics); + insertCellRefList(mRendering, cell.mContainers, cell, *mPhysics); + insertCellRefList(mRendering, cell.mCreatures, cell, *mPhysics); + insertCellRefList(mRendering, cell.mDoors, cell, *mPhysics); + insertCellRefList(mRendering, cell.mIngreds, cell, *mPhysics); + insertCellRefList(mRendering, cell.mCreatureLists, cell, *mPhysics); + insertCellRefList(mRendering, cell.mItemLists, cell, *mPhysics); + insertCellRefList(mRendering, cell.mLights, cell, *mPhysics); + insertCellRefList(mRendering, cell.mLockpicks, cell, *mPhysics); + insertCellRefList(mRendering, cell.mMiscItems, cell, *mPhysics); + insertCellRefList(mRendering, cell.mNpcs, cell, *mPhysics); + insertCellRefList(mRendering, cell.mProbes, cell, *mPhysics); + insertCellRefList(mRendering, cell.mRepairs, cell, *mPhysics); + insertCellRefList(mRendering, cell.mStatics, cell, *mPhysics); + insertCellRefList(mRendering, cell.mWeapons, cell, *mPhysics); } void Scene::addObjectToScene (const Ptr& ptr) { mRendering.addObject(ptr); MWWorld::Class::get(ptr).insertObject(ptr, *mPhysics); + MWBase::Environment::get().getWorld()->rotateObject(ptr, 0, 0, 0, true); + MWBase::Environment::get().getWorld()->scaleObject(ptr, ptr.getCellRef().mScale); } void Scene::removeObjectFromScene (const Ptr& ptr) diff --git a/apps/openmw/mwworld/scene.hpp b/apps/openmw/mwworld/scene.hpp index 59e13dafe..ad6ad1559 100644 --- a/apps/openmw/mwworld/scene.hpp +++ b/apps/openmw/mwworld/scene.hpp @@ -88,7 +88,7 @@ namespace MWWorld void insertCell (Ptr::CellStore &cell); - void update (float duration); + void update (float duration, bool paused); void addObjectToScene (const Ptr& ptr); ///< Add an object that already exists in the world model to the scene. diff --git a/apps/openmw/mwworld/store.hpp b/apps/openmw/mwworld/store.hpp new file mode 100644 index 000000000..fd93f39f1 --- /dev/null +++ b/apps/openmw/mwworld/store.hpp @@ -0,0 +1,879 @@ +#ifndef OPENMW_MWWORLD_STORE_H +#define OPENMW_MWWORLD_STORE_H + +#include +#include +#include +#include + +#include "recordcmp.hpp" + +namespace MWWorld +{ + struct StoreBase + { + virtual ~StoreBase() {} + + virtual void setUp() {} + virtual void listIdentifier(std::vector &list) const {} + + virtual int getSize() const = 0; + virtual void load(ESM::ESMReader &esm, const std::string &id) = 0; + }; + + template + class SharedIterator + { + typedef typename std::vector::const_iterator Iter; + + Iter mIter; + + public: + SharedIterator() {} + + SharedIterator(const SharedIterator &orig) + : mIter(orig.mIter) + {} + + SharedIterator(const Iter &iter) + : mIter(iter) + {} + + SharedIterator &operator++() { + ++mIter; + return *this; + } + + SharedIterator operator++(int) { + SharedIterator iter = *this; + mIter++; + + return iter; + } + + SharedIterator &operator--() { + --mIter; + return *this; + } + + SharedIterator operator--(int) { + SharedIterator iter = *this; + mIter--; + + return iter; + } + + bool operator==(const SharedIterator &x) const { + return mIter == x.mIter; + } + + bool operator!=(const SharedIterator &x) const { + return !(*this == x); + } + + const T &operator*() const { + return **mIter; + } + + const T *operator->() const { + return &(**mIter); + } + }; + + class ESMStore; + + template + class Store : public StoreBase + { + std::vector mStatic; + std::vector mShared; + std::map mDynamic; + + typedef std::map Dynamic; + + friend class ESMStore; + + public: + Store() + {} + + Store(const Store &orig) + : mStatic(orig.mData) + {} + + typedef SharedIterator iterator; + + const T *search(const std::string &id) const { + T item; + item.mId = StringUtils::lowerCase(id); + + typename std::vector::const_iterator it = + std::lower_bound(mStatic.begin(), mStatic.end(), item, RecordCmp()); + + if (it != mStatic.end() && StringUtils::ciEqual(it->mId, id)) { + return &(*it); + } + + typename Dynamic::const_iterator dit = mDynamic.find(item.mId); + if (dit != mDynamic.end()) { + return &dit->second; + } + + return 0; + } + + const T *find(const std::string &id) const { + const T *ptr = search(id); + if (ptr == 0) { + std::ostringstream msg; + msg << "Object '" << id << "' not found (const)"; + throw std::runtime_error(msg.str()); + } + return ptr; + } + + void load(ESM::ESMReader &esm, const std::string &id) { + mStatic.push_back(T()); + mStatic.back().mId = StringUtils::lowerCase(id); + mStatic.back().load(esm); + } + + void setUp() { + std::sort(mStatic.begin(), mStatic.end(), RecordCmp()); + + mShared.reserve(mStatic.size()); + typename std::vector::iterator it = mStatic.begin(); + for (; it != mStatic.end(); ++it) { + mShared.push_back(&(*it)); + } + } + + iterator begin() const { + return mShared.begin(); + } + + iterator end() const { + return mShared.end(); + } + + int getSize() const { + return mShared.size(); + } + + void listIdentifier(std::vector &list) const { + list.reserve(list.size() + getSize()); + typename std::vector::const_iterator it = mShared.begin(); + for (; it != mShared.end(); ++it) { + list.push_back((*it)->mId); + } + } + + T *insert(const T &item) { + std::string id = StringUtils::lowerCase(item.mId); + std::pair result = + mDynamic.insert(std::pair(id, item)); + T *ptr = &result.first->second; + if (result.second) { + mShared.push_back(ptr); + } else { + *ptr = item; + } + return ptr; + } + + bool erase(const std::string &id) { + std::string key = StringUtils::lowerCase(id); + typename Dynamic::iterator it = mDynamic.find(key); + if (it == mDynamic.end()) { + return false; + } + mDynamic.erase(it); + + // have to reinit the whole shared part + mShared.erase(mShared.begin() + mStatic.size(), mShared.end()); + for (it = mDynamic.begin(); it != mDynamic.end(); ++it) { + mShared.push_back(&it->second); + } + return true; + } + + bool erase(const T &item) { + return erase(item.mId); + } + }; + + template <> + inline void Store::load(ESM::ESMReader &esm, const std::string &id) { + mStatic.push_back(ESM::Dialogue()); + mStatic.back().mId = id; + mStatic.back().load(esm); + } + + template <> + inline void Store::load(ESM::ESMReader &esm, const std::string &id) { + mStatic.push_back(ESM::Script()); + mStatic.back().load(esm); + StringUtils::toLower(mStatic.back().mId); + } + + template <> + class Store : public StoreBase + { + std::vector mStatic; + + public: + Store() { + mStatic.reserve(128); + } + + typedef std::vector::const_iterator iterator; + + const ESM::LandTexture *search(size_t index) const { + if (index < mStatic.size()) { + return &mStatic.at(index); + } + return 0; + } + + const ESM::LandTexture *find(size_t index) const { + const ESM::LandTexture *ptr = search(index); + if (ptr == 0) { + std::ostringstream msg; + msg << "Land texture with index " << index << " not found"; + throw std::runtime_error(msg.str()); + } + return ptr; + } + + int getSize() const { + return mStatic.size(); + } + + void load(ESM::ESMReader &esm, const std::string &id) { + ESM::LandTexture ltex; + ltex.load(esm); + + if (ltex.mIndex >= (int) mStatic.size()) { + mStatic.resize(ltex.mIndex + 1); + } + mStatic[ltex.mIndex] = ltex; + mStatic[ltex.mIndex].mId = id; + } + + iterator begin() const { + return mStatic.begin(); + } + + iterator end() const { + return mStatic.end(); + } + }; + + template <> + class Store : public StoreBase + { + std::vector mStatic; + + struct Compare + { + bool operator()(const ESM::Land *x, const ESM::Land *y) { + if (x->mX == y->mX) { + return x->mY < y->mY; + } + return x->mX < y->mX; + } + }; + + public: + typedef SharedIterator iterator; + + int getSize() const { + return mStatic.size(); + } + + iterator begin() const { + return iterator(mStatic.begin()); + } + + iterator end() const { + return iterator(mStatic.end()); + } + + ESM::Land *search(int x, int y) const { + ESM::Land land; + land.mX = x, land.mY = y; + + std::vector::const_iterator it = + std::lower_bound(mStatic.begin(), mStatic.end(), &land, Compare()); + + if (it != mStatic.end() && (*it)->mX == x && (*it)->mY == y) { + return const_cast(*it); + } + return 0; + } + + ESM::Land *find(int x, int y) const{ + ESM::Land *ptr = search(x, y); + if (ptr == 0) { + std::ostringstream msg; + msg << "Land at (" << x << ", " << y << ") not found"; + throw std::runtime_error(msg.str()); + } + return ptr; + } + + void load(ESM::ESMReader &esm, const std::string &id) { + ESM::Land *ptr = new ESM::Land(); + ptr->load(esm); + + mStatic.push_back(ptr); + } + + void setUp() { + std::sort(mStatic.begin(), mStatic.end(), Compare()); + } + }; + + template <> + class Store : public StoreBase + { + struct ExtCmp + { + bool operator()(const ESM::Cell &x, const ESM::Cell &y) { + if (x.mData.mX == y.mData.mX) { + return x.mData.mY < y.mData.mY; + } + return x.mData.mX < y.mData.mX; + } + }; + + std::vector mInt; + std::vector mExt; + + std::vector mSharedInt; + std::vector mSharedExt; + + typedef std::map DynamicInt; + typedef std::map, ESM::Cell> DynamicExt; + + DynamicInt mDynamicInt; + DynamicExt mDynamicExt; + + + const ESM::Cell *search(const ESM::Cell &cell) const { + if (cell.isExterior()) { + return search(cell.getGridX(), cell.getGridY()); + } + return search(cell.mName); + } + + public: + typedef SharedIterator iterator; + + Store() + {} + + const ESM::Cell *search(const std::string &id) const { + ESM::Cell cell; + cell.mName = StringUtils::lowerCase(id); + + std::vector::const_iterator it = + std::lower_bound(mInt.begin(), mInt.end(), cell, RecordCmp()); + + if (it != mInt.end() && StringUtils::ciEqual(it->mName, id)) { + return &(*it); + } + + DynamicInt::const_iterator dit = mDynamicInt.find(cell.mName); + if (dit != mDynamicInt.end()) { + return &dit->second; + } + + return 0; + } + + const ESM::Cell *search(int x, int y) const { + ESM::Cell cell; + cell.mData.mX = x, cell.mData.mY = y; + + std::vector::const_iterator it = + std::lower_bound(mExt.begin(), mExt.end(), cell, ExtCmp()); + + if (it != mExt.end() && it->mData.mX == x && it->mData.mY == y) { + return &(*it); + } + + std::pair key(x, y); + DynamicExt::const_iterator dit = mDynamicExt.find(key); + if (dit != mDynamicExt.end()) { + return &dit->second; + } + + return 0; + } + + const ESM::Cell *find(const std::string &id) const { + const ESM::Cell *ptr = search(id); + if (ptr == 0) { + std::ostringstream msg; + msg << "Interior cell '" << id << "' not found"; + throw std::runtime_error(msg.str()); + } + return ptr; + } + + const ESM::Cell *find(int x, int y) const { + const ESM::Cell *ptr = search(x, y); + if (ptr == 0) { + std::ostringstream msg; + msg << "Exterior at (" << x << ", " << y << ") not found"; + throw std::runtime_error(msg.str()); + } + return ptr; + } + + void setUp() { + typedef std::vector::iterator Iterator; + + std::sort(mInt.begin(), mInt.end(), RecordCmp()); + mSharedInt.reserve(mInt.size()); + for (Iterator it = mInt.begin(); it != mInt.end(); ++it) { + mSharedInt.push_back(&(*it)); + } + + std::sort(mExt.begin(), mExt.end(), ExtCmp()); + mSharedExt.reserve(mExt.size()); + for (Iterator it = mExt.begin(); it != mExt.end(); ++it) { + mSharedExt.push_back(&(*it)); + } + } + + void load(ESM::ESMReader &esm, const std::string &id) { + ESM::Cell cell; + cell.mName = id; + cell.load(esm); + + if (cell.isExterior()) { + mExt.push_back(cell); + } else { + mInt.push_back(cell); + } + } + + iterator intBegin() const { + return iterator(mSharedInt.begin()); + } + + iterator intEnd() const { + return iterator(mSharedInt.end()); + } + + iterator extBegin() const { + return iterator(mSharedExt.begin()); + } + + iterator extEnd() const { + return iterator(mSharedExt.end()); + } + + /// \todo implement appropriate index + const ESM::Cell *searchExtByName(const std::string &id) const { + std::vector::const_iterator it = mSharedExt.begin(); + for (; it != mSharedExt.end(); ++it) { + if (StringUtils::ciEqual((*it)->mName, id)) { + return *it; + } + } + return 0; + } + + /// \todo implement appropriate index + const ESM::Cell *searchExtByRegion(const std::string &id) const { + std::vector::const_iterator it = mSharedExt.begin(); + for (; it != mSharedExt.end(); ++it) { + if (StringUtils::ciEqual((*it)->mRegion, id)) { + return *it; + } + } + return 0; + } + + int getSize() const { + return mSharedInt.size() + mSharedExt.size(); + } + + void listIdentifier(std::vector &list) const { + list.reserve(list.size() + mSharedInt.size()); + + std::vector::const_iterator it = mSharedInt.begin(); + for (; it != mSharedInt.end(); ++it) { + list.push_back((*it)->mName); + } + } + + ESM::Cell *insert(const ESM::Cell &cell) { + if (search(cell) != 0) { + std::ostringstream msg; + msg << "Failed to create "; + msg << ((cell.isExterior()) ? "exterior" : "interior"); + msg << " cell"; + + throw std::runtime_error(msg.str()); + } + ESM::Cell *ptr; + if (cell.isExterior()) { + std::pair key(cell.getGridX(), cell.getGridY()); + + // duplicate insertions are avoided by search(ESM::Cell &) + std::pair result = + mDynamicExt.insert(std::make_pair(key, cell)); + + ptr = &result.first->second; + mSharedExt.push_back(ptr); + } else { + std::string key = StringUtils::lowerCase(cell.mName); + + // duplicate insertions are avoided by search(ESM::Cell &) + std::pair result = + mDynamicInt.insert(std::make_pair(key, cell)); + + ptr = &result.first->second; + mSharedInt.push_back(ptr); + } + return ptr; + } + + bool erase(const ESM::Cell &cell) { + if (cell.isExterior()) { + return erase(cell.getGridX(), cell.getGridY()); + } + return erase(cell.mName); + } + + bool erase(const std::string &id) { + std::string key = StringUtils::lowerCase(id); + DynamicInt::iterator it = mDynamicInt.find(key); + + if (it == mDynamicInt.end()) { + return false; + } + mDynamicInt.erase(it); + mSharedInt.erase( + mSharedInt.begin() + mSharedInt.size(), + mSharedInt.end() + ); + + for (it = mDynamicInt.begin(); it != mDynamicInt.end(); ++it) { + mSharedInt.push_back(&it->second); + } + + return true; + } + + bool erase(int x, int y) { + std::pair key(x, y); + DynamicExt::iterator it = mDynamicExt.find(key); + + if (it == mDynamicExt.end()) { + return false; + } + mDynamicExt.erase(it); + mSharedExt.erase( + mSharedExt.begin() + mSharedExt.size(), + mSharedExt.end() + ); + + for (it = mDynamicExt.begin(); it != mDynamicExt.end(); ++it) { + mSharedExt.push_back(&it->second); + } + + return true; + } + }; + + template <> + class Store : public StoreBase + { + public: + typedef std::vector::const_iterator iterator; + + private: + std::vector mStatic; + + std::vector::iterator mIntBegin, mIntEnd, mExtBegin, mExtEnd; + + struct IntExtOrdering + { + bool operator()(const ESM::Pathgrid &x, const ESM::Pathgrid &y) const { + // interior pathgrids precedes exterior ones (x < y) + if ((x.mData.mX == 0 && x.mData.mY == 0) && + (y.mData.mX != 0 || y.mData.mY != 0)) + { + return true; + } + return false; + } + }; + + struct ExtCompare + { + bool operator()(const ESM::Pathgrid &x, const ESM::Pathgrid &y) const { + if (x.mData.mX == y.mData.mX) { + return x.mData.mY < y.mData.mY; + } + return x.mData.mX < y.mData.mX; + } + }; + + public: + + void load(ESM::ESMReader &esm, const std::string &id) { + mStatic.push_back(ESM::Pathgrid()); + mStatic.back().load(esm); + } + + int getSize() const { + return mStatic.size(); + } + + void setUp() { + IntExtOrdering cmp; + std::sort(mStatic.begin(), mStatic.end(), cmp); + + ESM::Pathgrid pg; + pg.mData.mX = pg.mData.mY = 1; + mExtBegin = + std::lower_bound(mStatic.begin(), mStatic.end(), pg, cmp); + mExtEnd = mStatic.end(); + + mIntBegin = mStatic.begin(); + mIntEnd = mExtBegin; + + std::sort(mIntBegin, mIntEnd, RecordCmp()); + std::sort(mExtBegin, mExtEnd, ExtCompare()); + } + + const ESM::Pathgrid *search(int x, int y) const { + ESM::Pathgrid pg; + pg.mData.mX = x; + pg.mData.mY = y; + + iterator it = + std::lower_bound(mExtBegin, mExtEnd, pg, ExtCompare()); + if (it != mExtEnd && it->mData.mX == x && it->mData.mY == y) { + return &(*it); + } + return 0; + } + + const ESM::Pathgrid *find(int x, int y) const { + const ESM::Pathgrid *ptr = search(x, y); + if (ptr == 0) { + std::ostringstream msg; + msg << "Pathgrid at (" << x << ", " << y << ") not found"; + throw std::runtime_error(msg.str()); + } + return ptr; + } + + const ESM::Pathgrid *search(const std::string &name) const { + ESM::Pathgrid pg; + pg.mCell = name; + + iterator it = std::lower_bound(mIntBegin, mIntEnd, pg, RecordCmp()); + if (it != mIntEnd && StringUtils::ciEqual(it->mCell, name)) { + return &(*it); + } + return 0; + } + + const ESM::Pathgrid *find(const std::string &name) const { + const ESM::Pathgrid *ptr = search(name); + if (ptr == 0) { + std::ostringstream msg; + msg << "Pathgrid in cell '" << name << "' not found"; + throw std::runtime_error(msg.str()); + } + return ptr; + } + + const ESM::Pathgrid *search(const ESM::Cell &cell) const { + if (cell.mData.mFlags & ESM::Cell::Interior) { + return search(cell.mName); + } + return search(cell.mData.mX, cell.mData.mY); + } + + const ESM::Pathgrid *find(const ESM::Cell &cell) const { + if (cell.mData.mFlags & ESM::Cell::Interior) { + return find(cell.mName); + } + return find(cell.mData.mX, cell.mData.mY); + } + + iterator begin() const { + return mStatic.begin(); + } + + iterator end() const { + return mStatic.end(); + } + + iterator interiorPathsBegin() const { + return mIntBegin; + } + + iterator interiorPathsEnd() const { + return mIntEnd; + } + + iterator exteriorPathsBegin() const { + return mExtBegin; + } + + iterator exteriorPathsEnd() const { + return mExtEnd; + } + }; + + template + class IndexedStore + { + struct Compare + { + bool operator()(const T &x, const T &y) const { + return x.mIndex < y.mIndex; + } + }; + protected: + std::vector mStatic; + + public: + typedef typename std::vector::const_iterator iterator; + + IndexedStore() {} + + IndexedStore(unsigned int size) { + mStatic.reserve(size); + } + + iterator begin() const { + return mStatic.begin(); + } + + iterator end() const { + return mStatic.end(); + } + + /// \todo refine loading order + void load(ESM::ESMReader &esm) { + mStatic.push_back(T()); + mStatic.back().load(esm); + } + + int getSize() const { + return mStatic.size(); + } + + void setUp() { + std::sort(mStatic.begin(), mStatic.end(), Compare()); + } + + const T *search(int index) const { + T item; + item.mIndex = index; + + iterator it = + std::lower_bound(mStatic.begin(), mStatic.end(), item, Compare()); + if (it != mStatic.end() && it->mIndex == index) { + return &(*it); + } + return 0; + } + + const T *find(int index) const { + const T *ptr = search(index); + if (ptr == 0) { + std::ostringstream msg; + msg << "Object with index " << index << " not found"; + throw std::runtime_error(msg.str()); + } + return ptr; + } + }; + + template <> + struct Store : public IndexedStore + { + Store() {} + Store(unsigned int size) + : IndexedStore(size) + {} + }; + + template <> + struct Store : public IndexedStore + { + Store() {} + Store(unsigned int size) + : IndexedStore(size) + {} + }; + + template <> + class Store : public IndexedStore + { + std::vector mStatic; + + public: + typedef std::vector::const_iterator iterator; + + Store() { + mStatic.reserve(ESM::Attribute::Length); + } + + const ESM::Attribute *search(size_t index) const { + if (index >= mStatic.size()) { + return 0; + } + return &mStatic.at(index); + } + + const ESM::Attribute *find(size_t index) const { + const ESM::Attribute *ptr = search(index); + if (ptr == 0) { + std::ostringstream msg; + msg << "Attribute with index " << index << " not found"; + throw std::runtime_error(msg.str()); + } + return ptr; + } + + void setUp() { + for (int i = 0; i < ESM::Attribute::Length; ++i) { + mStatic.push_back( + ESM::Attribute( + ESM::Attribute::sAttributeIds[i], + ESM::Attribute::sGmstAttributeIds[i], + ESM::Attribute::sGmstAttributeDescIds[i] + ) + ); + } + } + + int getSize() const { + return mStatic.size(); + } + + iterator begin() const { + return mStatic.begin(); + } + + iterator end() const { + return mStatic.end(); + } + }; + +} //end namespace + +#endif diff --git a/apps/openmw/mwworld/weather.cpp b/apps/openmw/mwworld/weather.cpp index 391b34a84..009b325c0 100644 --- a/apps/openmw/mwworld/weather.cpp +++ b/apps/openmw/mwworld/weather.cpp @@ -5,8 +5,6 @@ #include -#include - #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwbase/soundmanager.hpp" @@ -14,6 +12,7 @@ #include "../mwrender/renderingmanager.hpp" #include "player.hpp" +#include "esmstore.hpp" using namespace Ogre; using namespace MWWorld; @@ -497,7 +496,7 @@ void WeatherManager::update(float duration) if (exterior) { - std::string regionstr = MWBase::Environment::get().getWorld()->getPlayer().getPlayer().getCell()->cell->mRegion; + std::string regionstr = MWBase::Environment::get().getWorld()->getPlayer().getPlayer().getCell()->mCell->mRegion; boost::algorithm::to_lower(regionstr); if (mWeatherUpdateTime <= 0 || regionstr != mCurrentRegion) @@ -512,7 +511,8 @@ void WeatherManager::update(float duration) else { // get weather probabilities for the current region - const ESM::Region *region = MWBase::Environment::get().getWorld()->getStore().regions.search (regionstr); + const ESM::Region *region = + MWBase::Environment::get().getWorld()->getStore().get().search (regionstr); if (region != 0) { diff --git a/apps/openmw/mwworld/worldimp.cpp b/apps/openmw/mwworld/worldimp.cpp index 595ccd0c8..0f9dd83d3 100644 --- a/apps/openmw/mwworld/worldimp.cpp +++ b/apps/openmw/mwworld/worldimp.cpp @@ -19,34 +19,37 @@ using namespace Ogre; namespace { +/* // NOTE this code is never instantiated (proper copy in localscripts.cpp), + // so this commented out to not produce syntactic errors + template - void listCellScripts (const ESMS::ESMStore& store, + void listCellScripts (const MWWorld::ESMStore& store, MWWorld::CellRefList& cellRefList, MWWorld::LocalScripts& localScripts, MWWorld::Ptr::CellStore *cell) { for (typename MWWorld::CellRefList::List::iterator iter ( - cellRefList.list.begin()); - iter!=cellRefList.list.end(); ++iter) + cellRefList.mList.begin()); + iter!=cellRefList.mList.end(); ++iter) { - if (!iter->base->script.empty() && iter->mData.getCount()) + if (!iter->mBase->mScript.empty() && iter->mData.getCount()) { - if (const ESM::Script *script = store.scripts.find (iter->base->script)) + if (const ESM::Script *script = store.get().find (iter->mBase->mScript)) { iter->mData.setLocals (*script); - localScripts.add (iter->base->script, MWWorld::Ptr (&*iter, cell)); + localScripts.add (iter->mBase->mScript, MWWorld::Ptr (&*iter, cell)); } } } } - +*/ template MWWorld::LiveCellRef *searchViaHandle (const std::string& handle, MWWorld::CellRefList& refList) { typedef typename MWWorld::CellRefList::List::iterator iterator; - for (iterator iter (refList.list.begin()); iter!=refList.list.end(); ++iter) + for (iterator iter (refList.mList.begin()); iter!=refList.mList.end(); ++iter) { if(iter->mData.getCount() > 0 && iter->mData.getBaseNode()){ if (iter->mData.getHandle()==handle) @@ -64,44 +67,44 @@ namespace MWWorld Ptr World::getPtrViaHandle (const std::string& handle, Ptr::CellStore& cell) { if (MWWorld::LiveCellRef *ref = - searchViaHandle (handle, cell.activators)) + searchViaHandle (handle, cell.mActivators)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.potions)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mPotions)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.appas)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mAppas)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.armors)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mArmors)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.books)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mBooks)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.clothes)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mClothes)) return Ptr (ref, &cell); if (MWWorld::LiveCellRef *ref = - searchViaHandle (handle, cell.containers)) + searchViaHandle (handle, cell.mContainers)) return Ptr (ref, &cell); if (MWWorld::LiveCellRef *ref = - searchViaHandle (handle, cell.creatures)) + searchViaHandle (handle, cell.mCreatures)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.doors)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mDoors)) return Ptr (ref, &cell); if (MWWorld::LiveCellRef *ref = - searchViaHandle (handle, cell.ingreds)) + searchViaHandle (handle, cell.mIngreds)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.lights)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mLights)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.lockpicks)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mLockpicks)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.miscItems)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mMiscItems)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.npcs)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mNpcs)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.probes)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mProbes)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.repairs)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mRepairs)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.statics)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mStatics)) return Ptr (ref, &cell); - if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.weapons)) + if (MWWorld::LiveCellRef *ref = searchViaHandle (handle, cell.mWeapons)) return Ptr (ref, &cell); return Ptr(); } @@ -167,7 +170,7 @@ namespace MWWorld const std::string& master, const boost::filesystem::path& resDir, const boost::filesystem::path& cacheDir, bool newGame, const std::string& encoding, std::map fallbackMap) : mPlayer (0), mLocalScripts (mStore), mGlobalVariables (0), - mSky (true), mNextDynamicRecord (0), mCells (mStore, mEsm), + mSky (true), mCells (mStore, mEsm), mNumFacing(0) { mPhysics = new PhysicsSystem(renderer); @@ -186,13 +189,11 @@ namespace MWWorld mEsm.open (masterPath.string()); mStore.load (mEsm); - mPlayer = new MWWorld::Player (mStore.npcs.find ("player"), *this); + mPlayer = new MWWorld::Player (mStore.get().find ("player"), *this); mRendering->attachCameraTo(mPlayer->getPlayer()); - std::string playerCollisionFile = "meshes\\base_anim.nif"; //This is used to make a collision shape for our player - //We will need to support the 1st person file too in the future - mPhysics->addActor (mPlayer->getPlayer().getRefData().getHandle(), playerCollisionFile, Ogre::Vector3 (0, 0, 0), 1, Ogre::Quaternion::ZERO); - + mPhysics->addActor(mPlayer->getPlayer()); + // global variables mGlobalVariables = new Globals (mStore); @@ -224,21 +225,19 @@ namespace MWWorld const ESM::Cell *World::getExterior (const std::string& cellName) const { // first try named cells - if (const ESM::Cell *cell = mStore.cells.searchExtByName (cellName)) + const ESM::Cell *cell = mStore.get().searchExtByName (cellName); + if (cell != 0) { return cell; + } // didn't work -> now check for regions - std::string cellName2 = ESMS::RecListT::toLower (cellName); - - for (ESMS::RecListT::MapType::const_iterator iter (mStore.regions.list.begin()); - iter!=mStore.regions.list.end(); ++iter) + const MWWorld::Store ®ions = mStore.get(); + MWWorld::Store::iterator it = regions.begin(); + for (; it != regions.end(); ++it) { - if (ESMS::RecListT::toLower (iter->second.mName)==cellName2) + if (MWWorld::StringUtils::ciEqual(cellName, it->mName)) { - if (const ESM::Cell *cell = mStore.cells.searchExtByRegion (iter->first)) - return cell; - - break; + return mStore.get().searchExtByRegion(it->mId); } } @@ -260,7 +259,7 @@ namespace MWWorld return *mPlayer; } - const ESMS::ESMStore& World::getStore() const + const MWWorld::ESMStore& World::getStore() const { return mStore; } @@ -326,6 +325,14 @@ namespace MWWorld } Ptr World::getPtrViaHandle (const std::string& handle) + { + Ptr res = searchPtrViaHandle (handle); + if (res.isEmpty ()) + throw std::runtime_error ("unknown Ogre handle: " + handle); + return res; + } + + Ptr World::searchPtrViaHandle (const std::string& handle) { if (mPlayer->getPlayer().getRefData().getHandle()==handle) return mPlayer->getPlayer(); @@ -339,7 +346,7 @@ namespace MWWorld return ptr; } - throw std::runtime_error ("unknown Ogre handle: " + handle); + return MWWorld::Ptr(); } void World::enable (const Ptr& reference) @@ -399,15 +406,15 @@ namespace MWWorld void World::setDay (int day) { - if (day<0) - day = 0; + if (day<1) + day = 1; int month = mGlobalVariables->getInt ("month"); while (true) { int days = getDaysPerMonth (month); - if (dayskySetDate (day, month); mWeatherManager->setDate (day, month); - - } void World::setMonth (int month) @@ -443,8 +448,8 @@ namespace MWWorld int days = getDaysPerMonth (month); - if (mGlobalVariables->getInt ("day")>=days) - mGlobalVariables->setInt ("day", days-1); + if (mGlobalVariables->getInt ("day")>days) + mGlobalVariables->setInt ("day", days); mGlobalVariables->setInt ("month", month); @@ -528,7 +533,7 @@ namespace MWWorld std::pair result = mPhysics->getFacedHandle (*this); if (result.first.empty() || - result.second>getStore().gameSettings.find ("iMaxActivateDist")->getInt()) + result.second>getStore().get().find ("iMaxActivateDist")->getInt()) return ""; return result.first; @@ -574,39 +579,49 @@ namespace MWWorld CellStore *currCell = ptr.getCell(); bool isPlayer = ptr == mPlayer->getPlayer(); bool haveToMove = mWorldScene->isCellActive(*currCell) || isPlayer; - if (*currCell != newCell) { - if (isPlayer) { - if (!newCell.isExterior()) { - changeToInteriorCell(toLower(newCell.cell->mName), pos); - } else { - int cellX = newCell.cell->mData.mX; - int cellY = newCell.cell->mData.mY; + + if (*currCell != newCell) + { + if (isPlayer) + if (!newCell.isExterior()) + changeToInteriorCell(toLower(newCell.mCell->mName), pos); + else + { + int cellX = newCell.mCell->getGridX(); + int cellY = newCell.mCell->getGridY(); mWorldScene->changeCell(cellX, cellY, pos, false); } - } else { - if (!mWorldScene->isCellActive(*currCell)) { + else { + if (!mWorldScene->isCellActive(*currCell)) copyObjectToCell(ptr, newCell, pos); - } else if (!mWorldScene->isCellActive(newCell)) { + else if (!mWorldScene->isCellActive(newCell)) + { MWWorld::Class::get(ptr).copyToCell(ptr, newCell); mWorldScene->removeObjectFromScene(ptr); mLocalScripts.remove(ptr); haveToMove = false; - } else { + } + else + { MWWorld::Ptr copy = MWWorld::Class::get(ptr).copyToCell(ptr, newCell); mRendering->moveObjectToCell(copy, vec, currCell); - if (MWWorld::Class::get(ptr).isActor()) { + if (MWWorld::Class::get(ptr).isActor()) + { MWBase::MechanicsManager *mechMgr = MWBase::Environment::get().getMechanicsManager(); mechMgr->removeActor(ptr); mechMgr->addActor(copy); - } else { + } + else + { std::string script = MWWorld::Class::get(ptr).getScript(ptr); - if (!script.empty()) { + if (!script.empty()) + { mLocalScripts.remove(ptr); mLocalScripts.add(script, copy); } @@ -615,9 +630,10 @@ namespace MWWorld ptr.getRefData().setCount(0); } } - if (haveToMove) { + if (haveToMove) + { mRendering->moveObject(ptr, vec); - mPhysics->moveObject (ptr.getRefData().getHandle(), ptr.getRefData().getBaseNode()); + mPhysics->moveObject (ptr); } } @@ -638,18 +654,17 @@ namespace MWWorld void World::moveObject (const Ptr& ptr, float x, float y, float z) { moveObjectImp(ptr, x, y, z); - - } void World::scaleObject (const Ptr& ptr, float scale) { MWWorld::Class::get(ptr).adjustScale(ptr,scale); - ptr.getCellRef().mScale = scale; - //scale = scale/ptr.getRefData().getBaseNode()->getScale().x; - ptr.getRefData().getBaseNode()->setScale(scale,scale,scale); - mPhysics->scaleObject( ptr.getRefData().getHandle(), ptr.getRefData().getBaseNode()); + + if(ptr.getRefData().getBaseNode() == 0) + return; + mRendering->scaleObject(ptr, Vector3(scale,scale,scale)); + mPhysics->scaleObject(ptr); } void World::rotateObject (const Ptr& ptr,float x,float y,float z, bool adjust) @@ -659,19 +674,16 @@ namespace MWWorld rot.y = Ogre::Degree(y).valueRadians(); rot.z = Ogre::Degree(z).valueRadians(); - if (mRendering->rotateObject(ptr, rot, adjust)) { - float *objRot = ptr.getRefData().getPosition().rot; - objRot[0] = rot.x, objRot[1] = rot.y, objRot[2] = rot.z; - - - if (ptr.getRefData().getBaseNode() != 0) { - mPhysics->rotateObject( - ptr.getRefData().getHandle(), - ptr.getRefData().getBaseNode() - ); - } - } + float *objRot = ptr.getRefData().getPosition().rot; + if(ptr.getRefData().getBaseNode() == 0 || !mRendering->rotateObject(ptr, rot, adjust)) + { + objRot[0] = (adjust ? objRot[0] + rot.x : rot.x), objRot[1] = (adjust ? objRot[1] + rot.y : rot.y), objRot[2] = (adjust ? objRot[2] + rot.z : rot.z); + return; + } + // do this after rendering rotated the object so it gets changed by Class->adjustRotation + objRot[0] = rot.x, objRot[1] = rot.y, objRot[2] = rot.z; + mPhysics->rotateObject(ptr); } void World::safePlaceObject(const MWWorld::Ptr& ptr,MWWorld::CellStore &Cell,ESM::Position pos) @@ -767,62 +779,43 @@ namespace MWWorld return mRendering->toggleRenderMode (mode); } - std::pair World::createRecord (const ESM::Potion& record) + const ESM::Potion *World::createRecord (const ESM::Potion& record) { - /// \todo Rewrite the ESMStore so that a dynamic 2nd ESMStore can be attached to it. - /// This function should then insert the record into the 2nd store (the code for this - /// should also be moved to the ESMStore class). It might be a good idea to review - /// the STL-container usage of the ESMStore before the rewrite. - - std::ostringstream stream; - stream << "$dynamic" << mNextDynamicRecord++; - - ESM::Potion record2 (record); - record2.mId = stream.str(); - - const ESM::Potion *created = - &mStore.potions.list.insert (std::make_pair (stream.str(), record2)).first->second; - - mStore.all.insert (std::make_pair (stream.str(), ESM::REC_ALCH)); - - return std::make_pair (stream.str(), created); + return mStore.insert(record); } - std::pair World::createRecord (const ESM::Class& record) + const ESM::Class *World::createRecord (const ESM::Class& record) { - /// \todo See function above. - std::ostringstream stream; - stream << "$dynamic" << mNextDynamicRecord++; + return mStore.insert(record); + } - const ESM::Class *created = - &mStore.classes.list.insert (std::make_pair (stream.str(), record)).first->second; - - mStore.all.insert (std::make_pair (stream.str(), ESM::REC_CLAS)); - - return std::make_pair (stream.str(), created); + const ESM::Spell *World::createRecord (const ESM::Spell& record) + { + return mStore.insert(record); } const ESM::Cell *World::createRecord (const ESM::Cell& record) { - if (record.mData.mFlags & ESM::Cell::Interior) - { - if (mStore.cells.searchInt (record.mName)) - throw std::runtime_error ("failed creating interior cell"); + return mStore.insert(record); + } - ESM::Cell *cell = new ESM::Cell (record); - mStore.cells.intCells.insert (std::make_pair (record.mName, cell)); - return cell; - } - else - { - if (mStore.cells.searchExt (record.mData.mX, record.mData.mY)) - throw std::runtime_error ("failed creating exterior cell"); + const ESM::NPC *World::createRecord(const ESM::NPC &record) + { + bool update = false; + if (StringUtils::ciEqual(record.mId, "player")) { + const ESM::NPC *player = + mPlayer->getPlayer().get()->mBase; - ESM::Cell *cell = new ESM::Cell (record); - mStore.cells.extCells.insert ( - std::make_pair (std::make_pair (record.mData.mX, record.mData.mY), cell)); - return cell; + update = record.isMale() != player->isMale() || + !StringUtils::ciEqual(record.mRace, player->mRace) || + !StringUtils::ciEqual(record.mHead, player->mHead) || + !StringUtils::ciEqual(record.mHair, player->mHair); } + const ESM::NPC *ret = mStore.insert(record); + if (update) { + mRendering->renderPlayer(mPlayer->getPlayer()); + } + return ret; } void World::playAnimationGroup (const MWWorld::Ptr& ptr, const std::string& groupName, int mode, @@ -836,11 +829,11 @@ namespace MWWorld mRendering->skipAnimation (ptr); } - void World::update (float duration) + void World::update (float duration, bool paused) { /// \todo split this function up into subfunctions - mWorldScene->update (duration); + mWorldScene->update (duration, paused); float pitch, yaw; Ogre::Vector3 eyepos; @@ -850,12 +843,13 @@ namespace MWWorld mWeatherManager->update (duration); // inform the GUI about focused object - try - { - MWWorld::Ptr object = getPtrViaHandle(mFacedHandle); - MWBase::Environment::get().getWindowManager()->setFocusObject(object); + MWWorld::Ptr object = searchPtrViaHandle(mFacedHandle); - // retrieve object dimensions so we know where to place the floating label + MWBase::Environment::get().getWindowManager()->setFocusObject(object); + + // retrieve object dimensions so we know where to place the floating label + if (!object.isEmpty ()) + { Ogre::SceneNode* node = object.getRefData().getBaseNode(); Ogre::AxisAlignedBox bounds; int i; @@ -871,11 +865,6 @@ namespace MWWorld screenCoords[0], screenCoords[1], screenCoords[2], screenCoords[3]); } } - catch (std::runtime_error&) - { - MWWorld::Ptr null; - MWBase::Environment::get().getWindowManager()->setFocusObject(null); - } if (!mRendering->occlusionQuerySupported()) { @@ -1015,10 +1004,7 @@ namespace MWWorld Ptr::CellStore *currentCell = mWorldScene->getCurrentCell(); if (currentCell) { - if (!(currentCell->cell->mData.mFlags & ESM::Cell::Interior)) - return true; - else - return false; + return currentCell->mCell->isExterior(); } return false; } @@ -1028,7 +1014,7 @@ namespace MWWorld Ptr::CellStore *currentCell = mWorldScene->getCurrentCell(); if (currentCell) { - if (!(currentCell->cell->mData.mFlags & ESM::Cell::QuasiEx)) + if (!(currentCell->mCell->mData.mFlags & ESM::Cell::QuasiEx)) return false; else return true; @@ -1053,7 +1039,7 @@ namespace MWWorld Ogre::Vector2 World::getNorthVector (CellStore* cell) { - MWWorld::CellRefList& statics = cell->statics; + MWWorld::CellRefList& statics = cell->mStatics; MWWorld::LiveCellRef* ref = statics.find("northmarker"); if (!ref) return Vector2(0, 1); @@ -1067,34 +1053,33 @@ namespace MWWorld { std::vector result; - MWWorld::CellRefList& doors = cell->doors; - std::list< MWWorld::LiveCellRef >& refList = doors.list; + MWWorld::CellRefList& doors = cell->mDoors; + std::list< MWWorld::LiveCellRef >& refList = doors.mList; for (std::list< MWWorld::LiveCellRef >::iterator it = refList.begin(); it != refList.end(); ++it) { MWWorld::LiveCellRef& ref = *it; - if (ref.ref.mTeleport) + if (ref.mRef.mTeleport) { World::DoorMarker newMarker; std::string dest; - if (ref.ref.mDestCell != "") + if (ref.mRef.mDestCell != "") { // door leads to an interior, use interior name - dest = ref.ref.mDestCell; + dest = ref.mRef.mDestCell; } else { // door leads to exterior, use cell name (if any), otherwise translated region name int x,y; - positionToIndex (ref.ref.mDoorDest.pos[0], ref.ref.mDoorDest.pos[1], x, y); - const ESM::Cell* cell = mStore.cells.findExt(x,y); + positionToIndex (ref.mRef.mDoorDest.pos[0], ref.mRef.mDoorDest.pos[1], x, y); + const ESM::Cell* cell = mStore.get().find(x,y); if (cell->mName != "") dest = cell->mName; else { - const ESM::Region* region = mStore.regions.search(cell->mRegion); - dest = region->mName; + dest = mStore.get().find(cell->mRegion)->mName; } } @@ -1238,7 +1223,7 @@ namespace MWWorld /// \fixme should rely on object height pos.z += 30; - return isUnderwater(*object.getCell()->cell, pos); + return isUnderwater(*object.getCell()->mCell, pos); } bool @@ -1274,10 +1259,10 @@ namespace MWWorld mPhysics->castRay(playerPos, Ogre::Vector3(0,0,-1), 50); bool isOnGround = (hit.first ? (hit.second.distance (playerPos) < 25) : false); - if (!isOnGround || isUnderwater (*currentCell->cell, playerPos)) + if (!isOnGround || isUnderwater (*currentCell->mCell, playerPos)) return 2; - if (currentCell->cell->mData.mFlags & ESM::Cell::NoSleep) + if (currentCell->mCell->mData.mFlags & ESM::Cell::NoSleep) return 1; return 0; diff --git a/apps/openmw/mwworld/worldimp.hpp b/apps/openmw/mwworld/worldimp.hpp index 5d8c689db..349fd163c 100644 --- a/apps/openmw/mwworld/worldimp.hpp +++ b/apps/openmw/mwworld/worldimp.hpp @@ -1,12 +1,11 @@ #ifndef GAME_MWWORLD_WORLDIMP_H #define GAME_MWWORLD_WORLDIMP_H -#include - #include "../mwrender/debugging.hpp" #include "ptr.hpp" #include "scene.hpp" +#include "esmstore.hpp" #include "physicssystem.hpp" #include "cells.hpp" #include "localscripts.hpp" @@ -56,12 +55,11 @@ namespace MWWorld MWWorld::Scene *mWorldScene; MWWorld::Player *mPlayer; ESM::ESMReader mEsm; - ESMS::ESMStore mStore; + MWWorld::ESMStore mStore; LocalScripts mLocalScripts; MWWorld::Globals *mGlobalVariables; MWWorld::PhysicsSystem *mPhysics; bool mSky; - int mNextDynamicRecord; Cells mCells; @@ -124,7 +122,7 @@ namespace MWWorld virtual Player& getPlayer(); - virtual const ESMS::ESMStore& getStore() const; + virtual const MWWorld::ESMStore& getStore() const; virtual ESM::ESMReader& getEsmReader(); @@ -163,6 +161,9 @@ namespace MWWorld virtual Ptr getPtrViaHandle (const std::string& handle); ///< Return a pointer to a liveCellRef with the given Ogre handle. + virtual Ptr searchPtrViaHandle (const std::string& handle); + ///< Return a pointer to a liveCellRef with the given Ogre handle or Ptr() if not found + virtual void enable (const Ptr& ptr); virtual void disable (const Ptr& ptr); @@ -249,17 +250,26 @@ namespace MWWorld ///< Toggle a render mode. ///< \return Resulting mode - virtual std::pair createRecord (const ESM::Potion& record); + virtual const ESM::Potion *createRecord (const ESM::Potion& record); ///< Create a new recrod (of type potion) in the ESM store. - /// \return ID, pointer to created record + /// \return pointer to created record - virtual std::pair createRecord (const ESM::Class& record); + virtual const ESM::Spell *createRecord (const ESM::Spell& record); + ///< Create a new recrod (of type spell) in the ESM store. + /// \return pointer to created record + + virtual const ESM::Class *createRecord (const ESM::Class& record); ///< Create a new recrod (of type class) in the ESM store. - /// \return ID, pointer to created record + /// \return pointer to created record virtual const ESM::Cell *createRecord (const ESM::Cell& record); ///< Create a new recrod (of type cell) in the ESM store. - /// \return ID, pointer to created record + /// \return pointer to created record + + virtual const ESM::NPC *createRecord(const ESM::NPC &record); + ///< Create a new recrod (of type npc) in the ESM store. + /// \return pointer to created record + virtual void playAnimationGroup (const MWWorld::Ptr& ptr, const std::string& groupName, int mode, int number = 1); @@ -273,7 +283,7 @@ namespace MWWorld ///< Skip the animation for the given MW-reference for one frame. Calls to this function for /// references that are currently not in the rendered scene should be ignored. - virtual void update (float duration); + virtual void update (float duration, bool paused); virtual bool placeObject (const Ptr& object, float cursorX, float cursorY); ///< place an object into the gameworld at the specified cursor position diff --git a/components/CMakeLists.txt b/components/CMakeLists.txt index c714693c3..29d6f46cd 100644 --- a/components/CMakeLists.txt +++ b/components/CMakeLists.txt @@ -34,10 +34,6 @@ add_component_dir (file_finder file_finder filename_less search ) -add_component_dir (esm_store - reclists store - ) - add_component_dir (esm attr defs esmcommon esmreader esmwriter loadacti loadalch loadappa loadarmo loadbody loadbook loadbsgn loadcell loadclas loadclot loadcont loadcrea loadcrec loaddial loaddoor loadench loadfact loadglob loadgmst diff --git a/components/bsa/bsa_archive.cpp b/components/bsa/bsa_archive.cpp index 081207b0c..8380b0838 100644 --- a/components/bsa/bsa_archive.cpp +++ b/components/bsa/bsa_archive.cpp @@ -375,7 +375,7 @@ void addBSA(const std::string& name, const std::string& group) { insertBSAFactory(); ResourceGroupManager::getSingleton(). - addResourceLocation(name, "BSA", group); + addResourceLocation(name, "BSA", group, true); } void addDir(const std::string& name, const bool& fs, const std::string& group) @@ -384,7 +384,7 @@ void addDir(const std::string& name, const bool& fs, const std::string& group) insertDirFactory(); ResourceGroupManager::getSingleton(). - addResourceLocation(name, "Dir", group); + addResourceLocation(name, "Dir", group, true); } } diff --git a/components/esm/aipackage.hpp b/components/esm/aipackage.hpp index 3046a6a98..3128fe0c6 100644 --- a/components/esm/aipackage.hpp +++ b/components/esm/aipackage.hpp @@ -18,8 +18,6 @@ namespace ESM { // These are probabilities char mHello, mU1, mFight, mFlee, mAlarm, mU2, mU3, mU4; - // The last u's might be the skills that this NPC can train you - // in? int mServices; // See the Services enum }; // 12 bytes @@ -60,7 +58,7 @@ namespace ESM AI_Travel = 0x545f4941, AI_Follow = 0x465f4941, AI_Escort = 0x455f4941, - AI_Activate = 0x415f4941, + AI_Activate = 0x415f4941 }; /// \note Used for storaging packages in a single container diff --git a/components/esm/esmwriter.cpp b/components/esm/esmwriter.cpp index 24658a40b..c1ae06490 100644 --- a/components/esm/esmwriter.cpp +++ b/components/esm/esmwriter.cpp @@ -138,11 +138,11 @@ void ESMWriter::writeHNString(const std::string& name, const std::string& data) void ESMWriter::writeHNString(const std::string& name, const std::string& data, int size) { - assert(data.size() <= size); + assert(static_cast (data.size()) <= size); startSubRecord(name); writeHString(data); - if (data.size() < size) + if (static_cast (data.size()) < size) { for (int i = data.size(); i < size; ++i) write("\0",1); diff --git a/components/esm/loadacti.hpp b/components/esm/loadacti.hpp index 86c2f44c4..8cb335feb 100644 --- a/components/esm/loadacti.hpp +++ b/components/esm/loadacti.hpp @@ -11,7 +11,7 @@ class ESMWriter; struct Activator { - std::string mName, mScript, mModel; + std::string mId, mName, mScript, mModel; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadappa.hpp b/components/esm/loadappa.hpp index 101c39f41..486a559f8 100644 --- a/components/esm/loadappa.hpp +++ b/components/esm/loadappa.hpp @@ -32,7 +32,7 @@ struct Apparatus }; AADTstruct mData; - std::string mModel, mIcon, mScript, mName; + std::string mId, mModel, mIcon, mScript, mName; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadarmo.hpp b/components/esm/loadarmo.hpp index 57c9ccf12..a94ae6735 100644 --- a/components/esm/loadarmo.hpp +++ b/components/esm/loadarmo.hpp @@ -84,7 +84,7 @@ struct Armor AODTstruct mData; PartReferenceList mParts; - std::string mName, mModel, mIcon, mScript, mEnchant; + std::string mId, mName, mModel, mIcon, mScript, mEnchant; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadbody.hpp b/components/esm/loadbody.hpp index 8a05d9924..c91bb40bf 100644 --- a/components/esm/loadbody.hpp +++ b/components/esm/loadbody.hpp @@ -52,7 +52,7 @@ struct BodyPart }; BYDTstruct mData; - std::string mModel, mName; + std::string mId, mModel, mName; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadbsgn.hpp b/components/esm/loadbsgn.hpp index ac4050878..b0bc28be4 100644 --- a/components/esm/loadbsgn.hpp +++ b/components/esm/loadbsgn.hpp @@ -13,7 +13,7 @@ class ESMWriter; struct BirthSign { - std::string mName, mDescription, mTexture; + std::string mId, mName, mDescription, mTexture; // List of powers and abilities that come with this birth sign. SpellList mPowers; diff --git a/components/esm/loadclas.hpp b/components/esm/loadclas.hpp index 0311002b8..264e342e6 100644 --- a/components/esm/loadclas.hpp +++ b/components/esm/loadclas.hpp @@ -60,7 +60,7 @@ struct Class int mCalc; }; // 60 bytes - std::string mName, mDescription; + std::string mId, mName, mDescription; CLDTstruct mData; void load(ESMReader &esm); diff --git a/components/esm/loadclot.hpp b/components/esm/loadclot.hpp index df64c87d3..623983ccf 100644 --- a/components/esm/loadclot.hpp +++ b/components/esm/loadclot.hpp @@ -42,7 +42,7 @@ struct Clothing PartReferenceList mParts; - std::string mName, mModel, mIcon, mEnchant, mScript; + std::string mId, mName, mModel, mIcon, mEnchant, mScript; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadcont.hpp b/components/esm/loadcont.hpp index eb1f64d6f..b66ca086d 100644 --- a/components/esm/loadcont.hpp +++ b/components/esm/loadcont.hpp @@ -39,7 +39,7 @@ struct Container Unknown = 8 }; - std::string mName, mModel, mScript; + std::string mId, mName, mModel, mScript; float mWeight; // Not sure, might be max total weight allowed? int mFlags; diff --git a/components/esm/loadcrec.hpp b/components/esm/loadcrec.hpp index a95656f63..6904df15a 100644 --- a/components/esm/loadcrec.hpp +++ b/components/esm/loadcrec.hpp @@ -1,6 +1,8 @@ #ifndef OPENMW_ESM_CREC_H #define OPENMW_ESM_CREC_H +#include + // TODO create implementation files and remove this one #include "esmreader.hpp" @@ -15,6 +17,8 @@ class ESMWriter; /// Changes a creature struct LoadCREC { + std::string mId; + void load(ESMReader &esm) { esm.skipRecord(); @@ -28,6 +32,8 @@ struct LoadCREC /// Changes an item list / container struct LoadCNTC { + std::string mId; + void load(ESMReader &esm) { esm.skipRecord(); diff --git a/components/esm/loaddoor.hpp b/components/esm/loaddoor.hpp index 5c0af52e4..e992a592f 100644 --- a/components/esm/loaddoor.hpp +++ b/components/esm/loaddoor.hpp @@ -11,7 +11,7 @@ class ESMWriter; struct Door { - std::string mName, mModel, mScript, mOpenSound, mCloseSound; + std::string mId, mName, mModel, mScript, mOpenSound, mCloseSound; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadench.hpp b/components/esm/loadench.hpp index d89549322..999f93ad9 100644 --- a/components/esm/loadench.hpp +++ b/components/esm/loadench.hpp @@ -1,6 +1,8 @@ #ifndef OPENMW_ESM_ENCH_H #define OPENMW_ESM_ENCH_H +#include + #include "effectlist.hpp" namespace ESM @@ -32,6 +34,7 @@ struct Enchantment // calculate }; + std::string mId; ENDTstruct mData; EffectList mEffects; diff --git a/components/esm/loadglob.hpp b/components/esm/loadglob.hpp index b85af74bc..302729d2e 100644 --- a/components/esm/loadglob.hpp +++ b/components/esm/loadglob.hpp @@ -1,6 +1,8 @@ #ifndef OPENMW_ESM_GLOB_H #define OPENMW_ESM_GLOB_H +#include + #include "defs.hpp" namespace ESM @@ -15,6 +17,7 @@ class ESMWriter; struct Global { + std::string mId; unsigned mValue; VarType mType; diff --git a/components/esm/loadgmst.cpp b/components/esm/loadgmst.cpp index dcc500125..14e29f4ae 100644 --- a/components/esm/loadgmst.cpp +++ b/components/esm/loadgmst.cpp @@ -2,6 +2,8 @@ #include +#include + #include "esmreader.hpp" #include "esmwriter.hpp" @@ -12,9 +14,9 @@ namespace ESM /// working properly in its current state and I doubt it can be fixed without breaking other stuff. // Some handy macros -#define cI(s,x) { if(mId == (s)) return (mI == (x)); } -#define cF(s,x) { if(mId == (s)) return (mF == (x)); } -#define cS(s,x) { if(mId == (s)) return (mStr == (x)); } +#define cI(s,x) { label = (s); boost::algorithm::to_lower(label); if (mId == label) return (mI == (x)); } +#define cF(s,x) { label = (s); boost::algorithm::to_lower(label); if (mId == label) return (mF == (x)); } +#define cS(s,x) { label = (s); boost::algorithm::to_lower(label); if (mId == label) return (mStr == (x)); } bool GameSetting::isDirtyTribunal() { @@ -28,6 +30,7 @@ bool GameSetting::isDirtyTribunal() from other mods. */ + std::string label; // Strings cS("sProfitValue", "Profit Value"); // 'Profit:' cS("sEditNote", "Edit Note"); // same @@ -51,13 +54,14 @@ bool GameSetting::isDirtyTribunal() // [The difference here is "Profit Value" -> "Profit"] // Strings that matches the mId - cS("sEffectSummonFabricant", mId);// 'Summon Fabricant' + cS("sEffectSummonFabricant", "sEffectSummonFabricant");// 'Summon Fabricant' return false; } // Bloodmoon variant bool GameSetting::isDirtyBloodmoon() { + std::string label; // Strings cS("sWerewolfPopup", "Werewolf"); // same cS("sWerewolfRestMessage", @@ -69,16 +73,16 @@ bool GameSetting::isDirtyBloodmoon() // 'You have been detected as a known werewolf.' // Strings that matches the mId - cS("sMagicCreature01ID", mId); // 'BM_wolf_grey_summon' - cS("sMagicCreature02ID", mId); // 'BM_bear_black_summon' - cS("sMagicCreature03ID", mId); // 'BM_wolf_bone_summon' - cS("sMagicCreature04ID", mId); // same - cS("sMagicCreature05ID", mId); // same - cS("sEffectSummonCreature01", mId); // 'Calf Wolf' - cS("sEffectSummonCreature02", mId); // 'Calf Bear' - cS("sEffectSummonCreature03", mId); // 'Summon Bonewolf' - cS("sEffectSummonCreature04", mId); // same - cS("sEffectSummonCreature05", mId); // same + cS("sMagicCreature01ID", "sMagicCreature01ID"); // 'BM_wolf_grey_summon' + cS("sMagicCreature02ID", "sMagicCreature02ID"); // 'BM_bear_black_summon' + cS("sMagicCreature03ID", "sMagicCreature03ID"); // 'BM_wolf_bone_summon' + cS("sMagicCreature04ID", "sMagicCreature04ID"); // same + cS("sMagicCreature05ID", "sMagicCreature05ID"); // same + cS("sEffectSummonCreature01", "sEffectSummonCreature01"); // 'Calf Wolf' + cS("sEffectSummonCreature02", "sEffectSummonCreature02"); // 'Calf Bear' + cS("sEffectSummonCreature03", "sEffectSummonCreature03"); // 'Summon Bonewolf' + cS("sEffectSummonCreature04", "sEffectSummonCreature04"); // same + cS("sEffectSummonCreature05", "sEffectSummonCreature05"); // same // Integers cI("iWereWolfBounty", 10000); // 1000 diff --git a/components/esm/loadinfo.hpp b/components/esm/loadinfo.hpp index f04fe862e..f1decb9c6 100644 --- a/components/esm/loadinfo.hpp +++ b/components/esm/loadinfo.hpp @@ -32,10 +32,10 @@ struct DialInfo { int mUnknown1; int mDisposition; - char mRank; // Rank of NPC - char mGender; // See Gender enum - char mPCrank; // Player rank - char mUnknown2; + signed char mRank; // Rank of NPC + signed char mGender; // See Gender enum + signed char mPCrank; // Player rank + signed char mUnknown2; }; // 12 bytes DATAstruct mData; diff --git a/components/esm/loadlevlist.hpp b/components/esm/loadlevlist.hpp index 72b4af92f..b7db5db36 100644 --- a/components/esm/loadlevlist.hpp +++ b/components/esm/loadlevlist.hpp @@ -33,6 +33,7 @@ struct LeveledListBase // list.) int mFlags; unsigned char mChanceNone; // Chance that none are selected (0-255?) + std::string mId; // Record name used to read references. Must be set before load() is // called. diff --git a/components/esm/loadligh.hpp b/components/esm/loadligh.hpp index c425af6b3..b3d703cc2 100644 --- a/components/esm/loadligh.hpp +++ b/components/esm/loadligh.hpp @@ -41,7 +41,7 @@ struct Light LHDTstruct mData; - std::string mSound, mScript, mModel, mIcon, mName; + std::string mSound, mScript, mModel, mIcon, mName, mId; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadlocks.hpp b/components/esm/loadlocks.hpp index 72d375cbb..8e88c548e 100644 --- a/components/esm/loadlocks.hpp +++ b/components/esm/loadlocks.hpp @@ -36,7 +36,7 @@ struct Tool Data mData; Type mType; - std::string mName, mModel, mIcon, mScript; + std::string mId, mName, mModel, mIcon, mScript; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadmgef.cpp b/components/esm/loadmgef.cpp index be588fbb0..4aef97838 100644 --- a/components/esm/loadmgef.cpp +++ b/components/esm/loadmgef.cpp @@ -1,5 +1,9 @@ #include "loadmgef.hpp" +#include + +#include + #include "esmreader.hpp" #include "esmwriter.hpp" @@ -79,4 +83,162 @@ void MagicEffect::save(ESMWriter &esm) esm.writeHNOString("DESC", mDescription); } +std::string MagicEffect::effectIdToString(short effectID) +{ + // Map effect ID to GMST name + // http://www.uesp.net/morrow/hints/mweffects.shtml + std::map names; + names[85] ="sEffectAbsorbAttribute"; + names[88] ="sEffectAbsorbFatigue"; + names[86] ="sEffectAbsorbHealth"; + names[87] ="sEffectAbsorbSpellPoints"; + names[89] ="sEffectAbsorbSkill"; + names[63] ="sEffectAlmsiviIntervention"; + names[47] ="sEffectBlind"; + names[123] ="sEffectBoundBattleAxe"; + names[129] ="sEffectBoundBoots"; + names[127] ="sEffectBoundCuirass"; + names[120] ="sEffectBoundDagger"; + names[131] ="sEffectBoundGloves"; + names[128] ="sEffectBoundHelm"; + names[125] ="sEffectBoundLongbow"; + names[121] ="sEffectBoundLongsword"; + names[122] ="sEffectBoundMace"; + names[130] ="sEffectBoundShield"; + names[124] ="sEffectBoundSpear"; + names[7] ="sEffectBurden"; + names[50] ="sEffectCalmCreature"; + names[49] ="sEffectCalmHumanoid"; + names[40] ="sEffectChameleon"; + names[44] ="sEffectCharm"; + names[118] ="sEffectCommandCreatures"; + names[119] ="sEffectCommandHumanoids"; + names[132] ="sEffectCorpus"; // NB this typo. (bethesda made it) + names[70] ="sEffectCureBlightDisease"; + names[69] ="sEffectCureCommonDisease"; + names[71] ="sEffectCureCorprusDisease"; + names[73] ="sEffectCureParalyzation"; + names[72] ="sEffectCurePoison"; + names[22] ="sEffectDamageAttribute"; + names[25] ="sEffectDamageFatigue"; + names[23] ="sEffectDamageHealth"; + names[24] ="sEffectDamageMagicka"; + names[26] ="sEffectDamageSkill"; + names[54] ="sEffectDemoralizeCreature"; + names[53] ="sEffectDemoralizeHumanoid"; + names[64] ="sEffectDetectAnimal"; + names[65] ="sEffectDetectEnchantment"; + names[66] ="sEffectDetectKey"; + names[38] ="sEffectDisintegrateArmor"; + names[37] ="sEffectDisintegrateWeapon"; + names[57] ="sEffectDispel"; + names[62] ="sEffectDivineIntervention"; + names[17] ="sEffectDrainAttribute"; + names[20] ="sEffectDrainFatigue"; + names[18] ="sEffectDrainHealth"; + names[19] ="sEffectDrainSpellpoints"; + names[21] ="sEffectDrainSkill"; + names[8] ="sEffectFeather"; + names[14] ="sEffectFireDamage"; + names[4] ="sEffectFireShield"; + names[117] ="sEffectFortifyAttackBonus"; + names[79] ="sEffectFortifyAttribute"; + names[82] ="sEffectFortifyFatigue"; + names[80] ="sEffectFortifyHealth"; + names[81] ="sEffectFortifySpellpoints"; + names[84] ="sEffectFortifyMagickaMultiplier"; + names[83] ="sEffectFortifySkill"; + names[52] ="sEffectFrenzyCreature"; + names[51] ="sEffectFrenzyHumanoid"; + names[16] ="sEffectFrostDamage"; + names[6] ="sEffectFrostShield"; + names[39] ="sEffectInvisibility"; + names[9] ="sEffectJump"; + names[10] ="sEffectLevitate"; + names[41] ="sEffectLight"; + names[5] ="sEffectLightningShield"; + names[12] ="sEffectLock"; + names[60] ="sEffectMark"; + names[43] ="sEffectNightEye"; + names[13] ="sEffectOpen"; + names[45] ="sEffectParalyze"; + names[27] ="sEffectPoison"; + names[56] ="sEffectRallyCreature"; + names[55] ="sEffectRallyHumanoid"; + names[61] ="sEffectRecall"; + names[68] ="sEffectReflect"; + names[100] ="sEffectRemoveCurse"; + names[95] ="sEffectResistBlightDisease"; + names[94] ="sEffectResistCommonDisease"; + names[96] ="sEffectResistCorprusDisease"; + names[90] ="sEffectResistFire"; + names[91] ="sEffectResistFrost"; + names[93] ="sEffectResistMagicka"; + names[98] ="sEffectResistNormalWeapons"; + names[99] ="sEffectResistParalysis"; + names[97] ="sEffectResistPoison"; + names[92] ="sEffectResistShock"; + names[74] ="sEffectRestoreAttribute"; + names[77] ="sEffectRestoreFatigue"; + names[75] ="sEffectRestoreHealth"; + names[76] ="sEffectRestoreSpellPoints"; + names[78] ="sEffectRestoreSkill"; + names[42] ="sEffectSanctuary"; + names[3] ="sEffectShield"; + names[15] ="sEffectShockDamage"; + names[46] ="sEffectSilence"; + names[11] ="sEffectSlowFall"; + names[58] ="sEffectSoultrap"; + names[48] ="sEffectSound"; + names[67] ="sEffectSpellAbsorption"; + names[136] ="sEffectStuntedMagicka"; + names[106] ="sEffectSummonAncestralGhost"; + names[110] ="sEffectSummonBonelord"; + names[108] ="sEffectSummonLeastBonewalker"; + names[134] ="sEffectSummonCenturionSphere"; + names[103] ="sEffectSummonClannfear"; + names[104] ="sEffectSummonDaedroth"; + names[105] ="sEffectSummonDremora"; + names[114] ="sEffectSummonFlameAtronach"; + names[115] ="sEffectSummonFrostAtronach"; + names[113] ="sEffectSummonGoldenSaint"; + names[109] ="sEffectSummonGreaterBonewalker"; + names[112] ="sEffectSummonHunger"; + names[102] ="sEffectSummonScamp"; + names[107] ="sEffectSummonSkeletalMinion"; + names[116] ="sEffectSummonStormAtronach"; + names[111] ="sEffectSummonWingedTwilight"; + names[135] ="sEffectSunDamage"; + names[1] ="sEffectSwiftSwim"; + names[59] ="sEffectTelekinesis"; + names[101] ="sEffectTurnUndead"; + names[133] ="sEffectVampirism"; + names[0] ="sEffectWaterBreathing"; + names[2] ="sEffectWaterWalking"; + names[33] ="sEffectWeaknesstoBlightDisease"; + names[32] ="sEffectWeaknesstoCommonDisease"; + names[34] ="sEffectWeaknesstoCorprusDisease"; + names[28] ="sEffectWeaknesstoFire"; + names[29] ="sEffectWeaknesstoFrost"; + names[31] ="sEffectWeaknesstoMagicka"; + names[36] ="sEffectWeaknesstoNormalWeapons"; + names[35] ="sEffectWeaknesstoPoison"; + names[30] ="sEffectWeaknesstoShock"; + + // bloodmoon + names[138] ="sEffectSummonCreature01"; + names[139] ="sEffectSummonCreature02"; + names[140] ="sEffectSummonCreature03"; + names[141] ="sEffectSummonCreature04"; + names[142] ="sEffectSummonCreature05"; + + // tribunal + names[137] ="sEffectSummonFabricant"; + + if (names.find(effectID) == names.end()) + throw std::runtime_error( std::string("Unimplemented effect ID ") + boost::lexical_cast(effectID)); + + return names[effectID]; +} + } diff --git a/components/esm/loadmgef.hpp b/components/esm/loadmgef.hpp index 861f66be0..93c59f9cb 100644 --- a/components/esm/loadmgef.hpp +++ b/components/esm/loadmgef.hpp @@ -13,11 +13,23 @@ struct MagicEffect { enum Flags { - NoDuration = 0x4, + TargetSkill = 0x1, // Affects a specific skill, which is specified elsewhere in the effect structure. + TargetAttribute = 0x2, // Affects a specific attribute, which is specified elsewhere in the effect structure. + NoDuration = 0x4, // Has no duration. Only runs effect once on cast. + NoMagnitude = 0x8, // Has no magnitude. + Harmful = 0x10, // Counts as a negative effect. Interpreted as useful for attack, and is treated as a bad effect in alchemy. + ContinuousVfx = 0x20, // The effect's hit particle VFX repeats for the full duration of the spell, rather than occuring once on hit. + CastSelf = 0x40, // Allows range - cast on self. + CastTouch = 0x80, // Allows range - cast on touch. + CastTarget = 0x100, // Allows range - cast on target. + UncappedDamage = 0x1000, // Negates multiple cap behaviours. Allows an effect to reduce an attribute below zero; removes the normal minimum effect duration of 1 second. + NonRecastable = 0x4000, // Does not land if parent spell is already affecting target. Shows "you cannot re-cast" message for self target. + Unreflectable = 0x10000, // Cannot be reflected, the effect always lands normally. + CasterLinked = 0x20000, // Must quench if caster is dead, or not an NPC/creature. Not allowed in containter/door trap spells. SpellMaking = 0x0200, Enchanting = 0x0400, Negative = 0x0800 // A harmful effect. Will determine whether - // eg. NPCs regard this spell as an attack. + // eg. NPCs regard this spell as an attack. (same as 0x10?) }; struct MEDTstruct @@ -30,6 +42,9 @@ struct MagicEffect float mSpeed, mSize, mSizeCap; }; // 36 bytes + static std::string effectIdToString(short effectID); + + MEDTstruct mData; std::string mIcon, mParticle; // Textures diff --git a/components/esm/loadmisc.hpp b/components/esm/loadmisc.hpp index 1a34e6504..26d25139c 100644 --- a/components/esm/loadmisc.hpp +++ b/components/esm/loadmisc.hpp @@ -26,7 +26,7 @@ struct Miscellaneous }; MCDTstruct mData; - std::string mName, mModel, mIcon, mScript; + std::string mId, mName, mModel, mIcon, mScript; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadnpc.hpp b/components/esm/loadnpc.hpp index ee9ef6b0b..46be29961 100644 --- a/components/esm/loadnpc.hpp +++ b/components/esm/loadnpc.hpp @@ -117,6 +117,17 @@ struct NPC // Implementation moved to load_impl.cpp void load(ESMReader &esm); void save(ESMWriter &esm); + + bool isMale() const { + return (mFlags & Female) == 0; + } + + void setIsMale(bool value) { + mFlags |= Female; + if (value) { + mFlags ^= Female; + } + } }; } #endif diff --git a/components/esm/loadnpcc.hpp b/components/esm/loadnpcc.hpp index 3da14655f..79d92397f 100644 --- a/components/esm/loadnpcc.hpp +++ b/components/esm/loadnpcc.hpp @@ -1,6 +1,8 @@ #ifndef OPENMW_ESM_NPCC_H #define OPENMW_ESM_NPCC_H +#include + // TODO: create implementation files to remove this #include "esmreader.hpp" @@ -76,6 +78,8 @@ class ESMWriter; struct LoadNPCC { + std::string mId; + void load(ESMReader &esm) { esm.skipRecord(); diff --git a/components/esm/loadrace.hpp b/components/esm/loadrace.hpp index 42b2c91a7..91a424c10 100644 --- a/components/esm/loadrace.hpp +++ b/components/esm/loadrace.hpp @@ -64,7 +64,7 @@ struct Race RADTstruct mData; - std::string mName, mDescription; + std::string mId, mName, mDescription; SpellList mPowers; void load(ESMReader &esm); diff --git a/components/esm/loadregn.hpp b/components/esm/loadregn.hpp index fd0863b5b..0496ef5af 100644 --- a/components/esm/loadregn.hpp +++ b/components/esm/loadregn.hpp @@ -42,7 +42,7 @@ struct Region // sleepList refers to a eveled list of creatures you can meet if // you sleep outside in this region. - std::string mName, mSleepList; + std::string mId, mName, mSleepList; std::vector mSoundList; diff --git a/components/esm/loadscpt.cpp b/components/esm/loadscpt.cpp index dc28166d4..d9b6497d9 100644 --- a/components/esm/loadscpt.cpp +++ b/components/esm/loadscpt.cpp @@ -6,9 +6,18 @@ namespace ESM { +struct SCHD +{ + NAME32 mName; + Script::SCHDstruct mData; +}; + void Script::load(ESMReader &esm) { - esm.getHNT(mData, "SCHD", 52); + SCHD data; + esm.getHNT(data, "SCHD", 52); + mData = data.mData; + mId = data.mName.toString(); // List of local variables if (esm.isNextSub("SCVR")) @@ -48,7 +57,13 @@ void Script::save(ESMWriter &esm) for (std::vector::iterator it = mVarNames.begin(); it != mVarNames.end(); ++it) varNameString.append(*it); - esm.writeHNT("SCHD", mData, 52); + SCHD data; + memset(&data, 0, sizeof(data)); + + data.mData = mData; + memcpy(data.mName.name, mId.c_str(), mId.size()); + + esm.writeHNT("SCHD", data, 52); if (!mVarNames.empty()) { diff --git a/components/esm/loadscpt.hpp b/components/esm/loadscpt.hpp index db8f85057..10a6d24b1 100644 --- a/components/esm/loadscpt.hpp +++ b/components/esm/loadscpt.hpp @@ -42,13 +42,13 @@ public: approach though. */ - NAME32 mName; - // These describe the sizes we need to allocate for the script // data. int mNumShorts, mNumLongs, mNumFloats, mScriptDataSize, mStringTableSize; }; // 52 bytes + std::string mId; + SCHDstruct mData; std::vector mVarNames; // Variable names diff --git a/components/esm/loadsndg.hpp b/components/esm/loadsndg.hpp index dadfbd239..a6226c154 100644 --- a/components/esm/loadsndg.hpp +++ b/components/esm/loadsndg.hpp @@ -30,7 +30,7 @@ struct SoundGenerator // Type int mType; - std::string mCreature, mSound; + std::string mId, mCreature, mSound; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadsoun.hpp b/components/esm/loadsoun.hpp index 5443c6cb9..8f59f690a 100644 --- a/components/esm/loadsoun.hpp +++ b/components/esm/loadsoun.hpp @@ -17,7 +17,7 @@ struct SOUNstruct struct Sound { SOUNstruct mData; - std::string mSound; + std::string mId, mSound; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadspel.hpp b/components/esm/loadspel.hpp index 5ad184126..0d5e0be52 100644 --- a/components/esm/loadspel.hpp +++ b/components/esm/loadspel.hpp @@ -38,7 +38,7 @@ struct Spell }; SPDTstruct mData; - std::string mName; + std::string mId, mName; EffectList mEffects; void load(ESMReader &esm); diff --git a/components/esm/loadsscr.hpp b/components/esm/loadsscr.hpp index d180bfcff..713fe96b5 100644 --- a/components/esm/loadsscr.hpp +++ b/components/esm/loadsscr.hpp @@ -20,7 +20,7 @@ class ESMWriter; struct StartScript { std::string mData; - std::string mScript; + std::string mId, mScript; // Load a record and add it to the list void load(ESMReader &esm); diff --git a/components/esm/loadstat.hpp b/components/esm/loadstat.hpp index ba35fa718..790a71147 100644 --- a/components/esm/loadstat.hpp +++ b/components/esm/loadstat.hpp @@ -22,7 +22,7 @@ class ESMWriter; struct Static { - std::string mModel; + std::string mId, mModel; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm/loadweap.hpp b/components/esm/loadweap.hpp index 341a2c86e..e482d3b10 100644 --- a/components/esm/loadweap.hpp +++ b/components/esm/loadweap.hpp @@ -56,7 +56,7 @@ struct Weapon WPDTstruct mData; - std::string mName, mModel, mIcon, mEnchant, mScript; + std::string mId, mName, mModel, mIcon, mEnchant, mScript; void load(ESMReader &esm); void save(ESMWriter &esm); diff --git a/components/esm_store/reclists.hpp b/components/esm_store/reclists.hpp deleted file mode 100644 index 24580a79c..000000000 --- a/components/esm_store/reclists.hpp +++ /dev/null @@ -1,683 +0,0 @@ -#ifndef _GAME_ESM_RECLISTS_H -#define _GAME_ESM_RECLISTS_H - -#include "components/esm/records.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include - - - -using namespace boost::algorithm; - -namespace ESMS -{ - using namespace ESM; - - struct RecList - { - virtual ~RecList() {} - - virtual void load(ESMReader &esm, const std::string &id) = 0; - virtual int getSize() = 0; - virtual void listIdentifier (std::vector& identifier) const = 0; - - static std::string toLower (const std::string& name) - { - std::string lowerCase; - - std::transform (name.begin(), name.end(), std::back_inserter (lowerCase), - (int(*)(int)) std::tolower); - - return lowerCase; - } - }; - - typedef std::map RecListList; - - template - struct RecListT : RecList - { - virtual ~RecListT() {} - - typedef std::map MapType; - - MapType list; - - // Load one object of this type - void load(ESMReader &esm, const std::string &id) - { - std::string id2 = toLower (id); - list[id2].load(esm); - } - - // Find the given object ID, or return NULL if not found. - const X* search(const std::string &id) const - { - std::string id2 = toLower (id); - - typename MapType::const_iterator iter = list.find (id2); - - if (iter == list.end()) - return NULL; - - return &iter->second; - } - - // Find the given object ID (throws an exception if not found) - const X* find(const std::string &id) const - { - const X *object = search (id); - - if (!object) - throw std::runtime_error ("object " + id + " not found"); - - return object; - } - - int getSize() { return list.size(); } - - virtual void listIdentifier (std::vector& identifier) const - { - for (typename MapType::const_iterator iter (list.begin()); iter!=list.end(); ++iter) - identifier.push_back (iter->first); - } - }; - - // Same as RecListT, but does not case-smash the IDs - // Note that lookups (search or find) are still case insensitive - template - struct RecListCaseT : RecList - { - virtual ~RecListCaseT() {} - - typedef std::map MapType; - - MapType list; - - // Load one object of this type - void load(ESMReader &esm, const std::string &id) - { - //std::string id2 = toLower (id); - - list[id].load(esm); - } - - // Find the given object ID, or return NULL if not found. - const X* search(const std::string &id) const - { - std::string id2 = toLower (id); - - for (typename MapType::const_iterator iter = list.begin(); - iter != list.end(); ++iter) - { - if (toLower(iter->first) == id2) - return &iter->second; - } - - return NULL; - } - - // non-const version - X* search(const std::string &id) - { - std::string id2 = toLower (id); - - for (typename MapType::iterator iter = list.begin(); - iter != list.end(); ++iter) - { - if (toLower(iter->first) == id2) - return &iter->second; - } - - return NULL; - } - - // Find the given object ID (throws an exception if not found) - const X* find(const std::string &id) const - { - const X *object = search (id); - - if (!object) - throw std::runtime_error ("object " + id + " not found"); - - return object; - } - - int getSize() { return list.size(); } - - virtual void listIdentifier (std::vector& identifier) const - { - for (typename MapType::const_iterator iter (list.begin()); iter!=list.end(); ++iter) - identifier.push_back (iter->first); - } - }; - - /// Modified version of RecListT for records, that need to store their own ID - template - struct RecListWithIDT : RecList - { - virtual ~RecListWithIDT() {} - - typedef std::map MapType; - - MapType list; - - // Load one object of this type - void load(ESMReader &esm, const std::string &id) - { - std::string id2 = toLower (id); - list[id2].mId = id2; - list[id2].load(esm); - } - - // Find the given object ID, or return NULL if not found. - const X* search(const std::string &id) const - { - std::string id2 = toLower (id); - - typename MapType::const_iterator iter = list.find (id2); - - if (iter == list.end()) - return NULL; - return &iter->second; - } - - // Find the given object ID (throws an exception if not found) - const X* find(const std::string &id) const - { - const X *object = search (id); - - if (!object) - throw std::runtime_error ("object " + id + " not found"); - - return object; - } - - int getSize() { return list.size(); } - - virtual void listIdentifier (std::vector& identifier) const - { - for (typename MapType::const_iterator iter (list.begin()); iter!=list.end(); ++iter) - identifier.push_back (iter->first); - } - }; - - // The only difference to the above is a slight change to the load() - // function. We might merge these together later, and store the id - // in all the structs. - template - struct RecIDListT : RecList - { - virtual ~RecIDListT() {} - - typedef std::map MapType; - - MapType list; - - void load(ESMReader &esm, const std::string &id) - { - std::string id2 = toLower (id); - X& ref = list[id2]; - - ref.mId = id; - ref.load(esm); - } - - // Find the given object ID, or return NULL if not found. - const X* search(const std::string &id) const - { - std::string id2 = toLower (id); - - typename MapType::const_iterator iter = list.find (id2); - - if (iter == list.end()) - return NULL; - - return &iter->second; - } - - // Find the given object ID (throws an exception if not found) - const X* find(const std::string &id) const - { - const X *object = search (id); - - if (!object) - throw std::runtime_error ("object " + id + " not found"); - - return object; - } - - int getSize() { return list.size(); } - - virtual void listIdentifier (std::vector& identifier) const - { - for (typename MapType::const_iterator iter (list.begin()); iter!=list.end(); ++iter) - identifier.push_back (iter->first); - } - }; - - /* Land textures are indexed by an integer number - */ - struct LTexList : RecList - { - virtual ~LTexList() {} - - // TODO: For multiple ESM/ESP files we need one list per file. - std::vector ltex; - - LTexList() - { - // More than enough to hold Morrowind.esm. - ltex.reserve(128); - } - - const LandTexture* search(size_t index) const - { - assert(index < ltex.size()); - return <ex.at(index); - } - - int getSize() { return ltex.size(); } - int getSize() const { return ltex.size(); } - - virtual void listIdentifier (std::vector& identifier) const {} - - void load(ESMReader &esm, const std::string &id) - { - LandTexture lt; - lt.load(esm); - lt.mId = id; - - // Make sure we have room for the structure - if(lt.mIndex + 1 > (int)ltex.size()) - ltex.resize(lt.mIndex+1); - - // Store it - ltex[lt.mIndex] = lt; - } - }; - - /* Landscapes are indexed by the X,Y coordinates of the exterior - cell they belong to. - */ - struct LandList : RecList - { - virtual ~LandList() - { - for ( LandMap::iterator itr = lands.begin(); itr != lands.end(); ++itr ) - { - delete itr->second; - } - } - - // Map containing all landscapes - typedef std::pair LandCoord; - typedef std::map LandMap; - LandMap lands; - - int count; - LandList() : count(0) {} - int getSize() { return count; } - - virtual void listIdentifier (std::vector& identifier) const {} - - // Find land for the given coordinates. Return null if no mData. - Land *search(int x, int y) const - { - LandMap::const_iterator itr = lands.find(std::make_pair(x, y)); - if ( itr == lands.end() ) - { - return NULL; - } - - return itr->second; - } - - void load(ESMReader &esm, const std::string &id) - { - count++; - - // Create the structure and load it. This actually skips the - // landscape data and remembers the file position for later. - Land *land = new Land(); - land->load(esm); - - // Store the structure - lands[std::make_pair(land->mX, land->mY)] = land; - } - }; - - struct ciLessBoost : std::binary_function -{ - bool operator() (const std::string & s1, const std::string & s2) const { - //case insensitive version of is_less - return lexicographical_compare(s1, s2, is_iless()); - } -}; - - - // Cells aren't simply indexed by name. Exterior cells are treated - // separately. - // TODO: case handling (cell names are case-insensitive, but they are also showen to the - // player, so we can't simply smash case. - struct CellList : RecList - { - // Total cell count. Used for statistics. - int count; - CellList() : count(0) {} - int getSize() { return count; } - - // List of interior cells. Indexed by cell name. - typedef std::map IntCells; - IntCells intCells; - - // List of exterior cells. Indexed as extCells[mX][mY]. - typedef std::map, ESM::Cell*> ExtCells; - ExtCells extCells; - - virtual void listIdentifier (std::vector& identifier) const - { - for (IntCells::const_iterator iter (intCells.begin()); iter!=intCells.end(); ++iter) - identifier.push_back (iter->first); - } - - virtual ~CellList() - { - for (IntCells::iterator it = intCells.begin(); it!=intCells.end(); ++it) - delete it->second; - - for (ExtCells::iterator it = extCells.begin(); it!=extCells.end(); ++it) - delete it->second; - } - - const ESM::Cell* searchInt(const std::string &id) const - { - IntCells::const_iterator iter = intCells.find(id); - - if (iter!=intCells.end()) - return iter->second; - - return 0; - } - - const ESM::Cell* findInt(const std::string &id) const - { - const ESM::Cell *cell = searchInt (id); - - if (!cell) - throw std::runtime_error ("Interior cell not found - " + id); - - return cell; - } - - const ESM::Cell *searchExt (int x, int y) const - { - ExtCells::const_iterator it = extCells.find (std::make_pair (x, y)); - - if (it==extCells.end()) - return 0; - - return it->second; - } - - const ESM::Cell *findExt (int x, int y) const - { - const ESM::Cell *cell = searchExt (x, y); - - if (!cell) - throw std::runtime_error ("Exterior cell not found"); - - return cell; - } - const ESM::Cell *searchExtByName (const std::string& id) const - { - for (ExtCells::const_iterator iter = extCells.begin(); iter!=extCells.end(); ++iter) - { - if (toLower (iter->second->mName) == toLower (id)) - return iter->second; - } - - return 0; - } - - const ESM::Cell *searchExtByRegion (const std::string& id) const - { - std::string id2 = toLower (id); - - for (ExtCells::const_iterator iter = extCells.begin(); iter!=extCells.end(); ++iter) - if (toLower (iter->second->mRegion)==id) - return iter->second; - - return 0; - } - - void load(ESMReader &esm, const std::string &id) - { - count++; - - // All cells have a name record, even nameless exterior cells. - ESM::Cell *cell = new ESM::Cell; - cell->mName = id; - - // The cell itself takes care of all the hairy details - cell->load(esm); - - if(cell->mData.mFlags & ESM::Cell::Interior) - { - // Store interior cell by name - intCells[id] = cell; - } - else - { - // Store exterior cells by grid position - extCells[std::make_pair (cell->mData.mX, cell->mData.mY)] = cell; - } - } - }; - - struct PathgridList : RecList - { - int count; - - // List of grids for interior cells. Indexed by cell name. - typedef std::map IntGrids; - IntGrids intGrids; - - // List of grids for exterior cells. Indexed as extCells[mX][mY]. - typedef std::map, ESM::Pathgrid*> ExtGrids; - ExtGrids extGrids; - - PathgridList() : count(0) {} - - virtual ~PathgridList() - { - for (IntGrids::iterator it = intGrids.begin(); it!=intGrids.end(); ++it) - delete it->second; - - for (ExtGrids::iterator it = extGrids.begin(); it!=extGrids.end(); ++it) - delete it->second; - } - - int getSize() { return count; } - - virtual void listIdentifier (std::vector& identifier) const - { - // do nothing - } - - void load(ESMReader &esm, const std::string &id) - { - count++; - ESM::Pathgrid *grid = new ESM::Pathgrid; - grid->load(esm); - if (grid->mData.mX == 0 && grid->mData.mY == 0) - { - intGrids[grid->mCell] = grid; - } - else - { - extGrids[std::make_pair(grid->mData.mX, grid->mData.mY)] = grid; - } - } - - Pathgrid *find(int cellX, int cellY, const std::string &cellName) const - { - Pathgrid *result = search(cellX, cellY, cellName); - if (!result) - { - throw std::runtime_error("no pathgrid found for cell " + cellName); - } - return result; - } - - Pathgrid *search(int cellX, int cellY, const std::string &cellName) const - { - Pathgrid *result = NULL; - if (cellX == 0 && cellY == 0) // possibly interior - { - IntGrids::const_iterator it = intGrids.find(cellName); - if (it != intGrids.end()) - result = it->second; - } - else - { - ExtGrids::const_iterator it = extGrids.find(std::make_pair(cellX, cellY)); - if (it != extGrids.end()) - result = it->second; - } - return result; - } - - Pathgrid *search(const ESM::Cell &cell) const - { - int cellX, cellY; - if (cell.mData.mFlags & ESM::Cell::Interior) - { - cellX = cellY = 0; - } - else - { - cellX = cell.mData.mX; - cellY = cell.mData.mY; - } - return search(cellX, cellY, cell.mName); - } - }; - - template - struct ScriptListT : RecList - { - virtual ~ScriptListT() {} - - typedef std::map MapType; - - MapType list; - - // Load one object of this type - void load(ESMReader &esm, const std::string &id) - { - X ref; - ref.load (esm); - - std::string realId = toLower (ref.mData.mName.toString()); - - std::swap (list[realId], ref); - } - - // Find the given object ID, or return NULL if not found. - const X* search(const std::string &id) const - { - std::string id2 = toLower (id); - - typename MapType::const_iterator iter = list.find (id2); - - if (iter == list.end()) - return NULL; - - return &iter->second; - } - - // Find the given object ID (throws an exception if not found) - const X* find(const std::string &id) const - { - const X *object = search (id); - - if (!object) - throw std::runtime_error ("object " + id + " not found"); - - return object; - } - - int getSize() { return list.size(); } - - virtual void listIdentifier (std::vector& identifier) const - { - for (typename MapType::const_iterator iter (list.begin()); iter!=list.end(); ++iter) - identifier.push_back (iter->first); - } - }; - - template - struct IndexListT - { - virtual ~IndexListT() {} - - typedef std::map MapType; - - MapType list; - - void load(ESMReader &esm) - { - X ref; - ref.load (esm); - int index = ref.mIndex; - list[index] = ref; - } - - int getSize() - { - return list.size(); - } - - virtual void listIdentifier (std::vector& identifier) const {} - - // Find the given object ID, or return NULL if not found. - const X* search (int id) const - { - typename MapType::const_iterator iter = list.find (id); - - if (iter == list.end()) - return NULL; - - return &iter->second; - } - - // Find the given object ID (throws an exception if not found) - const X* find (int id) const - { - const X *object = search (id); - - if (!object) - { - std::ostringstream error; - error << "object " << id << " not found"; - throw std::runtime_error (error.str()); - } - - return object; - } - }; - - /* We need special lists for: - - Path grids - */ -} -#endif diff --git a/components/esm_store/store.cpp b/components/esm_store/store.cpp deleted file mode 100644 index d1fe9b10b..000000000 --- a/components/esm_store/store.cpp +++ /dev/null @@ -1,115 +0,0 @@ -#include -#include -#include "store.hpp" - -using namespace std; -using namespace ESM; -using namespace ESMS; - -/* -static string toStr(int i) -{ - char name[5]; - *((int*)name) = i; - name[4] = 0; - return std::string(name); -} -*/ - -void ESMStore::load(ESMReader &esm) -{ - set missing; - - ESM::Dialogue *dialogue = 0; - - // Loop through all records - while(esm.hasMoreRecs()) - { - NAME n = esm.getRecName(); - esm.getRecHeader(); - - // Look up the record type. - RecListList::iterator it = recLists.find(n.val); - - if(it == recLists.end()) - { - if (n.val==ESM::REC_INFO) - { - if (dialogue) - { - ESM::DialInfo info; - info.load (esm); - - dialogue->mInfo.push_back (info); - } - else - { - std::cerr << "error: info record without dialog" << std::endl; - esm.skipRecord(); - } - } - else if (n.val==ESM::REC_MGEF) - { - magicEffects.load (esm); - } - else if (n.val==ESM::REC_SKIL) - { - skills.load (esm); - } - else - { - // Not found (this would be an error later) - esm.skipRecord(); - missing.insert(n.toString()); - } - } - else - { - // Load it - std::string id = esm.getHNOString("NAME"); - it->second->load(esm, id); - - if (n.val==ESM::REC_DIAL) - { - RecListCaseT& recList = static_cast& > (*it->second); - - ESM::Dialogue* d = recList.search (id); - - assert (d != NULL); - - dialogue = d; - } - else - dialogue = 0; - - // Insert the reference into the global lookup - if(!id.empty() && - (n.val==REC_ACTI || n.val==REC_ALCH || n.val==REC_APPA || n.val==REC_ARMO || - n.val==REC_BOOK || n.val==REC_CLOT || n.val==REC_CONT || n.val==REC_CREA || - n.val==REC_DOOR || n.val==REC_INGR || n.val==REC_LEVC || n.val==REC_LEVI || - n.val==REC_LIGH || n.val==REC_LOCK || n.val==REC_MISC || n.val==REC_NPC_ || - n.val==REC_PROB || n.val==REC_REPA || n.val==REC_STAT || n.val==REC_WEAP) - ) - all[id] = n.val; - } - } - - for (int i = 0; i < Attribute::Length; ++i) - { - Attribute::AttributeID id = Attribute::sAttributeIds[i]; - attributes.list.insert(std::make_pair(id, Attribute(id, Attribute::sGmstAttributeIds[i], Attribute::sGmstAttributeDescIds[i]))); - } - - /* This information isn't needed on screen. But keep the code around - for debugging purposes later. - - cout << "\n" << recLists.size() << " record types:\n"; - for(RecListList::iterator it = recLists.begin(); it != recLists.end(); it++) - cout << " " << toStr(it->first) << ": " << it->second->getSize() << endl; - cout << "\nNot implemented yet: "; - for(set::iterator it = missing.begin(); - it != missing.end(); it++ ) - cout << *it << " "; - cout << endl; - */ -} diff --git a/components/esm_store/store.hpp b/components/esm_store/store.hpp deleted file mode 100644 index 7329386d4..000000000 --- a/components/esm_store/store.hpp +++ /dev/null @@ -1,146 +0,0 @@ -#ifndef _GAME_ESM_STORE_H -#define _GAME_ESM_STORE_H - -/* - The ESM storage module. - - This is separate from the ESM loader module, located in esm/. It is - also unaware of the cell loading and storage module. - - The advantage of this, as with all other modularizations, is that - you can replace the storage method later without touching the - loading code. Cutting down dependencies also help on the general - maintainability. - */ - -#include "components/esm/records.hpp" -#include "reclists.hpp" - -namespace ESMS -{ - using namespace ESM; - - struct ESMStore - { - /* Lists all the list types. Mostly used for quick lookup on - loading. The key is the record name (4 chars) parsed as a 32 - bit int. See esm/records.hpp for the complete list. - */ - RecListList recLists; - - // Each individual list - RecListT activators; - RecListWithIDT potions; - RecListT appas; - RecListT armors; - RecListT bodyParts; - RecListWithIDT books; - RecListT birthSigns; - RecListT classes; - RecListT clothes; - RecListT contChange; - RecListT containers; - RecListWithIDT creatures; - RecListT creaChange; - RecListCaseT dialogs; - RecListT doors; - RecListT enchants; - RecListT factions; - RecListT globals; - RecListWithIDT ingreds; - RecListT creatureLists; - RecListT itemLists; - RecListT lights; - RecListT lockpicks; - RecListT miscItems; - RecListWithIDT npcs; - RecListT npcChange; - RecListT probes; - RecListT races; - RecListT regions; - RecListT repairs; - RecListT soundGens; - RecListT sounds; - RecListT spells; - RecListT startScripts; - RecListT statics; - RecListT weapons; - - // Lists that need special rules - CellList cells; - RecIDListT gameSettings; - LandList lands; - LTexList landTexts; - ScriptListT