Files
2026-10-27 19:45:33 +01:00

1426 lines
56 KiB
C++

#include "weather.hpp"
#include <components/esm/stringrefid.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/settings/values.hpp>
#include <components/misc/rng.hpp>
#include <components/esm3/esmreader.hpp>
#include <components/esm3/esmwriter.hpp>
#include <components/esm3/loadregn.hpp>
#include <components/esm3/weatherstate.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/soundmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwmechanics/actorutil.hpp"
#include "../mwsound/sound.hpp"
#include "../mwrender/renderingmanager.hpp"
#include "../mwrender/sky.hpp"
#include "cellstore.hpp"
#include "esmstore.hpp"
#include "player.hpp"
#include <algorithm>
#include <cmath>
#include <limits>
namespace MWWorld
{
namespace
{
// linear interpolate between x and y based on factor.
float lerp(float x, float y, float factor)
{
return x * (1 - factor) + y * factor;
}
// linear interpolate between x and y based on factor.
osg::Vec4f lerp(const osg::Vec4f& x, const osg::Vec4f& y, float factor)
{
return x * (1 - factor) + y * factor;
}
// Sign-safe and finite-safe division.
float safeDivide(float numerator, float divisor)
{
if (divisor != 0.0f)
return numerator / divisor;
float magnitude = numerator != 0.0f ? std::numeric_limits<float>::max() : 0.0f;
return std::signbit(numerator) != std::signbit(divisor) ? -magnitude : magnitude;
}
}
template <typename T>
T TimeOfDayInterpolator<T>::getValue(
const float gameHour, const TimeOfDaySettings& timeSettings, const std::string& prefix) const
{
WeatherSetting setting = timeSettings.getSetting(prefix);
float preSunriseTime = setting.mPreSunriseTime;
float postSunriseTime = setting.mPostSunriseTime;
float preSunsetTime = setting.mPreSunsetTime;
float postSunsetTime = setting.mPostSunsetTime;
// night
if (gameHour < timeSettings.mNightEnd - preSunriseTime || gameHour > timeSettings.mNightStart + postSunsetTime)
return mNightValue;
// sunrise
else if (gameHour >= timeSettings.mNightEnd - preSunriseTime
&& gameHour <= timeSettings.mDayStart + postSunriseTime)
{
float duration = timeSettings.mDayStart + postSunriseTime - timeSettings.mNightEnd + preSunriseTime;
float middle = timeSettings.mNightEnd - preSunriseTime + duration / 2.f;
if (gameHour <= middle)
{
// fade in
float advance = middle - gameHour;
float factor = 0.f;
if (duration > 0)
factor = advance / duration * 2;
return lerp(mSunriseValue, mNightValue, factor);
}
else
{
// fade out
float advance = gameHour - middle;
float factor = 1.f;
if (duration > 0)
factor = advance / duration * 2;
return lerp(mSunriseValue, mDayValue, factor);
}
}
// day
else if (gameHour > timeSettings.mDayStart + postSunriseTime && gameHour < timeSettings.mDayEnd - preSunsetTime)
return mDayValue;
// sunset
else if (gameHour >= timeSettings.mDayEnd - preSunsetTime
&& gameHour <= timeSettings.mNightStart + postSunsetTime)
{
float duration = timeSettings.mNightStart + postSunsetTime - timeSettings.mDayEnd + preSunsetTime;
float middle = timeSettings.mDayEnd - preSunsetTime + duration / 2.f;
if (gameHour <= middle)
{
// fade in
float advance = middle - gameHour;
float factor = 0.f;
if (duration > 0)
factor = advance / duration * 2;
return lerp(mSunsetValue, mDayValue, factor);
}
else
{
// fade out
float advance = gameHour - middle;
float factor = 1.f;
if (duration > 0)
factor = advance / duration * 2;
return lerp(mSunsetValue, mNightValue, factor);
}
}
// shut up compiler
return T();
}
template class MWWorld::TimeOfDayInterpolator<float>;
template class MWWorld::TimeOfDayInterpolator<osg::Vec4f>;
osg::Vec3f Weather::defaultDirection()
{
static const osg::Vec3f direction = osg::Vec3f(0.f, 1.f, 0.f);
return direction;
}
float Weather::transitionDelta() const
{
// Transition Delta describes how quickly transitioning to the weather in question will take, in Hz. Note that
// the measurement is in real time, not in-game time.
return mTransitionDelta;
}
float Weather::cloudBlendFactor(const float transitionRatio) const
{
// Clouds Maximum Percent affects how quickly the sky transitions from one sky texture to the next.
return transitionRatio / mCloudsMaximumPercent;
}
float Weather::calculateThunder(const float transitionRatio, const float elapsedSeconds, const bool isPaused)
{
// When paused, the flash brightness remains the same and no new strikes can occur.
if (!isPaused)
{
// Morrowind doesn't appear to do any calculations unless the transition ratio is higher than the Thunder
// Threshold.
if (transitionRatio >= mThunderThreshold && mThunderFrequency > 0.0f)
{
flashDecrement(elapsedSeconds);
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
if (Misc::Rng::rollProbability(prng) <= thunderChance(transitionRatio, elapsedSeconds))
{
lightningAndThunder();
}
}
else
{
mFlashBrightness = 0.0f;
}
}
return mFlashBrightness;
}
inline void Weather::flashDecrement(const float elapsedSeconds)
{
// The Flash Decrement is measured in whole units per second. This means that if the flash brightness was
// currently 1.0, then it should take approximately 0.25 seconds to decay to 0.0 (the minimum).
float decrement = mFlashDecrement * elapsedSeconds;
mFlashBrightness = decrement > mFlashBrightness ? 0.0f : mFlashBrightness - decrement;
}
inline float Weather::thunderChance(const float transitionRatio, const float elapsedSeconds) const
{
// This formula is reversed from the observation that with Thunder Frequency set to 1, there are roughly 10
// strikes per minute. It doesn't appear to be tied to in game time as Timescale doesn't affect it. Various
// values of Thunder Frequency seem to change the average number of strikes in a linear fashion.. During a
// transition, it appears to scaled based on how far past it is past the Thunder Threshold.
float scaleFactor = (transitionRatio - mThunderThreshold) / (1.0f - mThunderThreshold);
return ((mThunderFrequency * 10.0f) / 60.0f) * elapsedSeconds * scaleFactor;
}
inline void Weather::lightningAndThunder(void)
{
// Morrowind seems to vary the intensity of the brightness based on which of the four sound IDs it selects.
// They appear to go from 0 (brightest, closest) to 3 (faintest, farthest). The value of 0.25 per distance
// was derived by setting the Flash Decrement to 0.1 and measuring how long each value took to decay to 0.
// TODO: Determine the distribution of each distance to see if it's evenly weighted.
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
unsigned int distance = Misc::Rng::rollDice(4, prng);
// Flash brightness appears additive, since if multiple strikes occur, it takes longer for it to decay to 0.
mFlashBrightness += 1 - (distance * 0.25f);
MWBase::Environment::get().getSoundManager()->playSound(mThunderSoundID[distance], 1.0, 1.0);
}
void Weather::blank()
{
mName.clear();
mCloudTexture.clear();
mParticleEffect.clear();
mRainEffect.clear();
mAmbientLoopSoundID = {};
mRainLoopSoundID = {};
mThunderSoundID.fill({});
mSkyColor.blank();
mFogColor.blank();
mAmbientColor.blank();
mSunColor.blank();
mLandFogDepth.blank();
mSunDiscSunsetColor = {};
mStormDirection = defaultDirection();
mStormParticleRotation = defaultDirection();
mScriptId = {};
mWindSpeed = {};
mCloudSpeed = {};
mGlareView = {};
mDL.FogFactor = {};
mDL.FogOffset = {};
mRainSpeed = {};
mRainEntranceSpeed = 1.f;
mRainMaxRaindrops = {};
mRainDiameter = {};
mRainThreshold = {};
mRainMinHeight = {};
mRainMaxHeight = {};
mCloudsMaximumPercent = 1.f;
mTransitionDelta = {};
mThunderFrequency = {};
mThunderThreshold = {};
mFlashDecrement = {};
mFlashBrightness = {};
mIsStorm = {};
mRipplesEnabled = {};
mUseTorches = true;
mOcclusionEnabled = {};
}
RegionWeather::RegionWeather(const ESM::Region& region)
: mChances(region.mData.mProbabilities)
{
}
RegionWeather::RegionWeather(const ESM::RegionWeatherState& state)
: mWeather(state.mWeather)
, mChances(state.mChances)
{
}
RegionWeather::operator ESM::RegionWeatherState() const
{
ESM::RegionWeatherState state = { mWeather, mChances };
return state;
}
void RegionWeather::setChances(const std::map<ESM::RefId, uint8_t>& chances, const WeatherStore& store)
{
mChances = chances;
// Regional weather no longer supports the current type, select a new weather pattern.
if (getChance(mWeather) == 0)
{
chooseNewWeather(store);
}
}
uint8_t RegionWeather::getChance(ESM::RefId weather) const
{
const auto found = mChances.find(weather);
if (found != mChances.end())
return found->second;
return 0;
}
void RegionWeather::setWeather(ESM::RefId weatherID)
{
mWeather = weatherID;
}
ESM::RefId RegionWeather::getWeather(const WeatherStore& store)
{
// If the region weather was already set (by ChangeWeather, or by a previous call) then just return that value.
// Note that the region weather will be expired periodically when the weather update timer expires.
if (mWeather.empty())
{
chooseNewWeather(store);
}
return mWeather;
}
void RegionWeather::chooseNewWeather(const WeatherStore& store)
{
// All probabilities must add to 100 (responsibility of the user).
// If chances A and B has values 30 and 70 then by generating 100 numbers 1..100, 30% will be lesser or equal 30
// and 70% will be greater than 30 (in theory).
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
unsigned int chance = Misc::Rng::rollDice(100u, prng) + 1u; // 1..100
unsigned int sum = 0;
for (const Weather* weather : store)
{
sum += getChance(weather->mId);
if (chance <= sum)
{
mWeather = weather->mId;
return;
}
}
// if we hit this path then the chances don't add to 100, choose a default weather instead
if (store.getSize() > 0)
mWeather = store.at(0)->mId;
else
mWeather = {};
}
MoonModel::MoonModel(float fadeInStart, float fadeInFinish, float fadeOutStart, float fadeOutFinish,
float axisOffset, float speed, float dailyIncrement, float fadeStartAngle, float fadeEndAngle,
float moonShadowEarlyFadeAngle, float sunriseHour, float sunsetHour)
: mFadeInStart(fadeInStart)
, mFadeInFinish(fadeInFinish)
, mFadeOutStart(fadeOutStart)
, mFadeOutFinish(fadeOutFinish)
, mAxisOffset(axisOffset)
, mSpeed(speed)
, mDailyIncrement(dailyIncrement)
, mFadeStartAngle(fadeStartAngle)
, mFadeEndAngle(fadeEndAngle)
, mMoonShadowEarlyFadeAngle(moonShadowEarlyFadeAngle)
, mSunriseHour(sunriseHour)
, mSunsetHour(sunsetHour)
{
calculateSettings();
buildCycle();
}
MoonModel::MoonModel(const std::string& name)
: mFadeInStart(Fallback::Map::getFloat("Moons_" + name + "_Fade_In_Start"))
, mFadeInFinish(Fallback::Map::getFloat("Moons_" + name + "_Fade_In_Finish"))
, mFadeOutStart(Fallback::Map::getFloat("Moons_" + name + "_Fade_Out_Start"))
, mFadeOutFinish(Fallback::Map::getFloat("Moons_" + name + "_Fade_Out_Finish"))
, mAxisOffset(Fallback::Map::getFloat("Moons_" + name + "_Axis_Offset"))
, mSpeed(Fallback::Map::getFloat("Moons_" + name + "_Speed"))
, mDailyIncrement(Fallback::Map::getFloat("Moons_" + name + "_Daily_Increment"))
, mFadeStartAngle(Fallback::Map::getFloat("Moons_" + name + "_Fade_Start_Angle"))
, mFadeEndAngle(Fallback::Map::getFloat("Moons_" + name + "_Fade_End_Angle"))
, mMoonShadowEarlyFadeAngle(Fallback::Map::getFloat("Moons_" + name + "_Moon_Shadow_Early_Fade_Angle"))
, mSunriseHour(Fallback::Map::getFloat("Weather_Sunrise_Time"))
, mSunsetHour(Fallback::Map::getFloat("Weather_Sunset_Time"))
{
calculateSettings();
buildCycle();
}
void MoonModel::calculateSettings()
{
// Morrowind's moon speed is tied to day length. A shorter day means a faster sun and
// (weirdly) a faster moon too. The reverse-engineered formula is
// mSpeed * 180 degrees (a full hemisphere) / day length (vanilla is 12 hours).
float dayLength = mSunsetHour - mSunriseHour;
mDegreesPerHour = safeDivide(mSpeed * 180.0f, dayLength);
// Morrowind appears to have a minimum speed to avoid situations where the moon can't
// complete a full rotation in a single 24-hour period. The minimum is 1 rotation in 23 hours.
// Also weirdly, the minimum only applies to moon speeds that aren't literally signed negative.
if (!std::signbit(mDegreesPerHour))
mDegreesPerHour = std::max(mDegreesPerHour, 180.0f / 23.0f);
// Morrowind appears to reduce mDailyIncrement with mod 24.0f to avoid situations where
// the moon would increment more than an entire rotation in a single day.
mDailyIncrement = std::fmod(mDailyIncrement, 24.0f);
}
void MoonModel::buildCycle()
{
// The moon changes to the next day's rise hour when it's out of sight, so each day depends
// on the previous. We calculate an extra cycle to make the cached cycle accurate.
constexpr int firstDay = 1 - sDaysPerCycle;
float currentRiseHour = riseHour(firstDay);
for (int day = firstDay + 1; day <= sDaysPerCycle; ++day)
{
float nextRiseHour = riseHour(day);
float handover = handoverHour(currentRiseHour, nextRiseHour);
if (day >= 1)
mCycle[dayOfCycle(day)] = { currentRiseHour, handover };
if (handover < 24.0f)
currentRiseHour = nextRiseHour;
}
}
MWRender::MoonState MoonModel::calculateState(const TimeStamp& gameTime) const
{
const CycleDay& today = mCycle[dayOfCycle(gameTime.getDay())];
bool postHandover = gameTime.getHour() >= today.mHandoverHour;
float currentRiseHour = postHandover ? mCycle[dayOfCycle(gameTime.getDay() + 1)].mRiseHour : today.mRiseHour;
float rotationFromHorizon = angle(gameTime.getHour(), currentRiseHour);
return { rotationFromHorizon,
mAxisOffset, // Reverse engineered from Morrowind's scene graph rotation matrices.
phase(gameTime.getDay(), postHandover), shadowBlend(rotationFromHorizon),
earlyMoonShadowAlpha(rotationFromHorizon) * hourlyAlpha(gameTime.getHour()) };
}
inline float MoonModel::hoursUntilVisible() const
{
return safeDivide(mFadeEndAngle - mMoonShadowEarlyFadeAngle, rotation(1.0f));
}
inline float MoonModel::hoursUntilInvisible() const
{
return safeDivide(180.0f - mFadeEndAngle + mMoonShadowEarlyFadeAngle, rotation(1.0f));
}
inline float MoonModel::hourOfDay(float hours)
{
float hour = std::fmod(hours, 24.0f);
return hour < 0.0f ? hour + 24.0f : hour;
}
inline int MoonModel::dayOfCycle(int gameDay)
{
// Get the current day's placement in the cycle.
int day = (gameDay - 1) % sDaysPerCycle;
return day < 0 ? day + sDaysPerCycle : day;
}
float MoonModel::riseHour(int gameDay) const
{
if (mDailyIncrement == 0.0f)
return 0.0f;
// Skip enough increments that the rise hour maintains a 24-day cycle.
float skippedIncrements = (sDaysPerCycle - std::abs(sDaysPerCycle / mDailyIncrement))
* std::floor(static_cast<float>(gameDay + sStartIncrements - 1) / sDaysPerCycle);
float riseHour = mDailyIncrement * (gameDay + sStartIncrements - 1 - skippedIncrements);
// We need to wrap the moon's rise hour between about 0,24 or -24,0 depending on daily increment.
riseHour = std::fmod(riseHour, 24.0f);
if (mDailyIncrement < 0.0f && riseHour > sRiseHourEpsilon)
riseHour -= 24.0f;
if (mDailyIncrement >= 0.0f && riseHour <= sRiseHourEpsilon)
riseHour += 24.0f;
return riseHour;
}
float MoonModel::handoverHour(float prevRiseHour, float nextRiseHour) const
{
// The handover hour is the point where the moon's rise hour switches to the next day's.
// This makes the moon "jump" from one position to another, so Morrowind waits
// until the moon is invisible to make the transition.
// Whether the time elapsed since the rise hour places the moon in an invisible hour range.
auto isInvisibleHour = [&](float gameHour, float riseHour) {
float travelled = hourOfDay(gameHour - riseHour);
return travelled < hoursUntilVisible() || travelled >= hoursUntilInvisible() - sRiseHourEpsilon;
};
// Whether the moon is invisible by alpha or by fade angle at both the old and new positions.
auto isInvisible = [&](float gameHour) {
bool transparent = hourlyAlpha(gameHour) <= 0.0f;
return (transparent || isInvisibleHour(gameHour, prevRiseHour))
&& (isInvisibleHour(gameHour, nextRiseHour) || (transparent && gameHour < mSunriseHour));
};
// Midnight is the earliest possible invisible time.
if (isInvisible(0.0f))
return 0.0f;
// Get the moon fadeout point and both days' invisible times, then find the earliest.
// Moon settings can lead to no invisible times, which means no handover.
float daytimeFade = mFadeOutFinish - sOneMinute;
float prevRiseInvisibleHour = hourOfDay(prevRiseHour + hoursUntilInvisible());
float nextRiseInvisibleHour = hourOfDay(nextRiseHour + hoursUntilInvisible());
float handover = 999.0f; // No handover
if (daytimeFade >= 0.0f && isInvisible(daytimeFade))
handover = daytimeFade;
if (isInvisible(prevRiseInvisibleHour))
handover = std::min(handover, prevRiseInvisibleHour);
if (isInvisible(nextRiseInvisibleHour))
handover = std::min(handover, nextRiseInvisibleHour);
return handover;
}
inline float MoonModel::rotation(float hours) const
{
return mDegreesPerHour * hours;
}
inline float MoonModel::angle(float gameHour, float riseHour) const
{
// Morrowind's moons start travel on one side of the horizon (let's call it H-rise) and travel 180 degrees to
// the opposite horizon (let's call it H-set). Upon reaching H-set, they reset to H-rise until the next moon
// rise.
// A rise hour past this game hour means the moon rose the day before.
float travelled = gameHour - riseHour;
if (travelled < 0.0f)
travelled += 24.0f;
// Absolute value to account for negative non-zero speed moons
float rotationFromHorizon = rotation(travelled);
return std::abs(rotationFromHorizon) < 180.0f ? rotationFromHorizon : 0.0f;
}
inline MWRender::MoonState::Phase MoonModel::phase(int gameDay, bool postHandover)
{
// Morrowind starts with a full moon on 16 Last Seed and then begins to wane 17 Last Seed, working on a 3 day
// phase cycle.
// The phase changes when the active rise hour changes.
int phaseDay = postHandover ? gameDay + 1 : gameDay;
return static_cast<MWRender::MoonState::Phase>((phaseDay / sDaysPerPhase) % sPhasesPerCycle);
}
inline float MoonModel::shadowBlend(float angle) const
{
// The Fade End Angle and Fade Start Angle describe a region where the moon transitions from a solid disk
// that is roughly the color of the sky, to a textured surface.
// Depending on the current angle, the following values describe the ratio between the textured moon
// and the solid disk:
// 1. From Fade End Angle 1 to Fade Start Angle 1 (during moon rise): 0..1
// 2. From Fade Start Angle 1 to Fade Start Angle 2 (between moon rise and moon set): 1 (textured)
// 3. From Fade Start Angle 2 to Fade End Angle 2 (during moon set): 1..0
// 4. From Fade End Angle 2 to Fade End Angle 1 (between moon set and moon rise): 0 (solid disk)
float fadeAngle = mFadeStartAngle - mFadeEndAngle;
float fadeEndAngle2 = 180.0f - mFadeEndAngle;
float fadeStartAngle2 = 180.0f - mFadeStartAngle;
if ((angle >= mFadeEndAngle) && (angle < mFadeStartAngle))
return (angle - mFadeEndAngle) / fadeAngle;
else if ((angle >= mFadeStartAngle) && (angle < fadeStartAngle2))
return 1.0f;
else if ((angle >= fadeStartAngle2) && (angle < fadeEndAngle2))
return (fadeEndAngle2 - angle) / fadeAngle;
else
return 0.0f;
}
inline float MoonModel::hourlyAlpha(float gameHour) const
{
// Morrowind culls the moon one minute before mFadeOutFinish, but only when the moon has
// a transparent hour range. If #2 below is <= 0, the early minute is skipped.
float adjustedFadeOutFinish = mFadeInStart > mFadeOutFinish ? mFadeOutFinish - sOneMinute : mFadeOutFinish;
// The Fade Out Start / Finish and Fade In Start / Finish describe the hours at which the moon
// appears and disappears.
// Depending on the current hour, the following values describe how transparent the moon is.
// 1. From Fade Out Start to Fade Out Finish: 1..0
// 2. From Fade Out Finish to Fade In Start: 0 (transparent)
// 3. From Fade In Start to Fade In Finish: 0..1
// 4. From Fade In Finish to Fade Out Start: 1 (solid)
if ((gameHour >= mFadeOutStart) && (gameHour < adjustedFadeOutFinish))
return (adjustedFadeOutFinish - gameHour) / (adjustedFadeOutFinish - mFadeOutStart);
else if ((gameHour >= adjustedFadeOutFinish) && (gameHour < mFadeInStart))
return 0.0f;
else if ((gameHour >= mFadeInStart) && (gameHour < mFadeInFinish))
return (gameHour - mFadeInStart) / (mFadeInFinish - mFadeInStart);
else
return 1.0f;
}
inline float MoonModel::earlyMoonShadowAlpha(float angle) const
{
// A moon at the horizon has either not yet risen or has finished its arc.
// A negative moonShadowEarlyFadeAngle1 keeps the horizon permanently lit.
if (angle <= 0.0f && mFadeEndAngle >= mMoonShadowEarlyFadeAngle)
return 0.0f;
// The Moon Shadow Early Fade Angle describes an arc relative to Fade End Angle.
// Depending on the current angle, the following values describe how transparent the moon is.
// 1. From Moon Shadow Early Fade Angle 1 to Fade End Angle 1 (during moon rise): 0..1
// 2. From Fade End Angle 1 to Fade End Angle 2 (between moon rise and moon set): 1 (solid)
// 3. From Fade End Angle 2 to Moon Shadow Early Fade Angle 2 (during moon set): 1..0
// 4. From Moon Shadow Early Fade Angle 2 to Moon Shadow Early Fade Angle 1: 0 (transparent)
float moonShadowEarlyFadeAngle1 = mFadeEndAngle - mMoonShadowEarlyFadeAngle;
float fadeEndAngle2 = 180.0f - mFadeEndAngle;
float moonShadowEarlyFadeAngle2 = fadeEndAngle2 + mMoonShadowEarlyFadeAngle;
if ((angle >= moonShadowEarlyFadeAngle1) && (angle < mFadeEndAngle))
return (angle - moonShadowEarlyFadeAngle1) / mMoonShadowEarlyFadeAngle;
else if ((angle >= mFadeEndAngle) && (angle < fadeEndAngle2))
return 1.0f;
else if ((angle >= fadeEndAngle2) && (angle < moonShadowEarlyFadeAngle2))
return (moonShadowEarlyFadeAngle2 - angle) / mMoonShadowEarlyFadeAngle;
else
return 0.0f;
}
void WeatherStore::reset()
{
if (mInitial.empty())
{
for (const Weather* weather : mShared)
mInitial.push_back(*weather);
}
mShared.clear();
mStatic.clear();
for (const Weather& weather : mInitial)
insertStatic(weather);
}
const Weather* WeatherStore::search(ESM::RefId id) const
{
const auto it = mStatic.find(id);
if (it == mStatic.end())
return nullptr;
return &it->second;
}
const Weather* WeatherStore::find(ESM::RefId id) const
{
if (const Weather* weather = search(id))
return weather;
throw std::runtime_error("Weather " + id.toDebugString() + " not found");
}
Weather* WeatherStore::search(ESM::RefId id)
{
const auto* self = this;
return const_cast<Weather*>(self->search(id));
}
Weather* WeatherStore::insertStatic(const Weather& item)
{
const auto [it, inserted] = mStatic.insert_or_assign(item.mId, item);
Weather* ptr = &it->second;
if (inserted)
mShared.push_back(ptr);
return ptr;
}
void WeatherStore::eraseStatic(ESM::RefId id)
{
const auto found = mStatic.find(id);
if (found == mStatic.end())
return;
for (auto it = mShared.begin(); it != mShared.end(); ++it)
{
if ((*it)->mId == id)
{
mShared.erase(it);
break;
}
}
mStatic.erase(found);
}
std::vector<Moon> WeatherManager::getCurrentMoons(const TimeStamp& time) const
{
const auto makeMoon = [](std::string_view name, const MoonModel& model, const TimeStamp& timestamp) {
const MWRender::MoonState state = model.calculateState(timestamp);
return Moon{ name, state.mPhase, MWRender::MoonState::phaseToInt(state.mPhase), state.mMoonAlpha };
};
return { makeMoon("Masser", mMasser, time), makeMoon("Secunda", mSecunda, time) };
}
WeatherManager::WeatherManager(
MWRender::RenderingManager& rendering, MWWorld::ESMStore& store, MWWorld::WeatherStore& weatherStore)
: mStore(store)
, mRendering(rendering)
, mSunriseTime(Fallback::Map::getFloat("Weather_Sunrise_Time"))
, mSunsetTime(Fallback::Map::getFloat("Weather_Sunset_Time"))
, mSunriseDuration(Fallback::Map::getFloat("Weather_Sunrise_Duration"))
, mSunsetDuration(Fallback::Map::getFloat("Weather_Sunset_Duration"))
, mSunPreSunsetTime(Fallback::Map::getFloat("Weather_Sun_Pre-Sunset_Time"))
, mNightFade(0, 0, 0, 1)
, mHoursBetweenWeatherChanges(Fallback::Map::getFloat("Weather_Hours_Between_Weather_Changes"))
, mUnderwaterFog(Fallback::Map::getFloat("Water_UnderwaterSunriseFog"),
Fallback::Map::getFloat("Water_UnderwaterDayFog"), Fallback::Map::getFloat("Water_UnderwaterSunsetFog"),
Fallback::Map::getFloat("Water_UnderwaterNightFog"))
, mWeatherStore(&weatherStore)
, mMasser("Masser")
, mSecunda("Secunda")
, mWindSpeed(0.f)
, mCurrentWindSpeed(0.f)
, mNextWindSpeed(0.f)
, mIsStorm(false)
, mUseTorches(true)
, mCurrentRegion()
, mTimePassed(0)
, mFastForward(false)
, mWeatherUpdateTime(mHoursBetweenWeatherChanges)
, mTransitionFactor(0)
, mNightDayMode(Default)
, mRegions()
{
mTimeSettings.mNightStart = mSunsetTime + mSunsetDuration;
mTimeSettings.mNightEnd = mSunriseTime;
mTimeSettings.mDayStart = mSunriseTime + mSunriseDuration;
mTimeSettings.mDayEnd = mSunsetTime;
mTimeSettings.addSetting("Sky");
mTimeSettings.addSetting("Ambient");
mTimeSettings.addSetting("Fog");
mTimeSettings.addSetting("Sun");
// Morrowind handles stars settings differently for other ones
mTimeSettings.mStarsPostSunsetStart = Fallback::Map::getFloat("Weather_Stars_Post-Sunset_Start");
mTimeSettings.mStarsPreSunriseFinish = Fallback::Map::getFloat("Weather_Stars_Pre-Sunrise_Finish");
mTimeSettings.mStarsFadingDuration = Fallback::Map::getFloat("Weather_Stars_Fading_Duration");
WeatherSetting starSetting = { mTimeSettings.mStarsPreSunriseFinish,
mTimeSettings.mStarsFadingDuration - mTimeSettings.mStarsPreSunriseFinish,
mTimeSettings.mStarsPostSunsetStart,
mTimeSettings.mStarsFadingDuration - mTimeSettings.mStarsPostSunsetStart };
mTimeSettings.mSunriseTransitions["Stars"] = starSetting;
mWeatherStore->reset();
importRegions();
forceWeather(ESM::Weather::indexToRefId(0));
}
WeatherManager::~WeatherManager()
{
stopSounds();
}
void WeatherManager::changeWeather(ESM::RefId regionID, ESM::RefId weatherID)
{
// In Morrowind, this seems to have the following behavior, when applied to the current region:
// - When there is no transition in progress, start transitioning to the new weather.
// - If there is a transition in progress, queue up the transition and process it when the current one
// completes.
// - If there is a transition in progress, and a queued transition, overwrite the queued transition.
// - If multiple calls to ChangeWeather are made while paused (console up), only the last call will be used,
// meaning that if there was no transition in progress, only the last ChangeWeather will be processed.
// If the region isn't current, Morrowind will store the new weather for the region in question.
if (const Weather* weather = mWeatherStore->search(weatherID))
{
auto rIt = mRegions.find(regionID);
if (rIt != mRegions.end())
{
rIt->second.setWeather(weather->mId);
regionalWeatherChanged(rIt->first, rIt->second);
}
}
}
void WeatherManager::modRegion(ESM::RefId regionID, const std::map<ESM::RefId, uint8_t>& chances)
{
// Sets the region's probability for various weather patterns. Note that this appears to be saved permanently.
// In Morrowind, this seems to have the following behavior when applied to the current region:
// - If the region supports the current weather, no change in current weather occurs.
// - If the region no longer supports the current weather, and there is no transition in progress, begin to
// transition to a new supported weather type.
// - If the region no longer supports the current weather, and there is a transition in progress, queue a
// transition to a new supported weather type.
auto it = mRegions.find(regionID);
if (it != mRegions.end())
{
it->second.setChances(chances, *mWeatherStore);
regionalWeatherChanged(it->first, it->second);
}
}
const std::map<ESM::RefId, uint8_t>& WeatherManager::getRegionChances(ESM::RefId regionID) const
{
return mRegions.at(regionID).getChances();
}
void WeatherManager::playerTeleported(const ESM::RefId& playerRegion, bool isExterior)
{
// If the player teleports to an outdoors cell in a new region (for instance, by travelling), the weather needs
// to be changed immediately, and any transitions for the previous region discarded.
{
auto it = mRegions.find(playerRegion);
if (it != mRegions.end() && playerRegion != mCurrentRegion)
{
mCurrentRegion = playerRegion;
forceWeather(it->second.getWeather(*mWeatherStore));
}
}
}
float WeatherManager::calculateWindSpeed(const Weather& weather, float currentSpeed) const
{
float targetSpeed = std::min(8.0f * weather.mWindSpeed, 70.f);
if (currentSpeed == 0.f)
currentSpeed = targetSpeed;
float multiplier = weather.mRainEffect.empty() ? 1.f : 0.5f;
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
float updatedSpeed = (Misc::Rng::rollClosedProbability(prng) - 0.5f) * multiplier * targetSpeed + currentSpeed;
if (updatedSpeed > 0.5f * targetSpeed && updatedSpeed < 2.f * targetSpeed)
currentSpeed = updatedSpeed;
return currentSpeed;
}
void WeatherManager::update(float duration, bool paused, const TimeStamp& time, bool isExterior)
{
MWWorld::ConstPtr player = MWMechanics::getPlayer();
if (!paused || mFastForward)
{
// Add new transitions when either the player's current external region changes.
if (updateWeatherTime() || updateWeatherRegion(player.getCell()->getCell()->getRegion()))
{
auto it = mRegions.find(mCurrentRegion);
if (it != mRegions.end())
{
addWeatherTransition(it->second.getWeather(*mWeatherStore));
}
}
updateWeatherTransitions(duration);
}
bool isDay = time.getHour() >= mSunriseTime && time.getHour() <= mTimeSettings.mNightStart;
if (isExterior && !isDay)
mNightDayMode = ExteriorNight;
else if (!isExterior && isDay)
{
const Weather* current = mWeatherStore->search(mCurrentWeather);
if (current != nullptr && current->mGlareView >= 0.5f)
mNightDayMode = InteriorDay;
else
mNightDayMode = Default;
}
else
mNightDayMode = Default;
if (!isExterior)
{
mRendering.setSkyEnabled(false);
stopSounds();
mWindSpeed = 0.f;
mCurrentWindSpeed = 0.f;
mNextWindSpeed = 0.f;
return;
}
const MWRender::WeatherResult result = calculateWeatherResult(time.getHour(), duration, paused);
if (!paused)
{
mWindSpeed = result.mWindSpeed;
mCurrentWindSpeed = result.mCurrentWindSpeed;
mNextWindSpeed = result.mNextWindSpeed;
}
mIsStorm = result.getIsStorm();
mUseTorches = result.getUseTorches();
// disable sun during night
if (time.getHour() >= mTimeSettings.mNightStart || time.getHour() <= mSunriseTime)
mRendering.getSkyManager()->sunDisable();
else
mRendering.getSkyManager()->sunEnable();
// Update the sun direction. Run it east to west at a fixed angle from overhead.
// The sun's speed at day and night may differ, since mSunriseTime and mNightStart
// mark when the sun is level with the horizon.
{
// Shift times into a 24-hour window beginning at mSunriseTime...
float adjustedHour = time.getHour();
float adjustedNightStart = mTimeSettings.mNightStart;
if (time.getHour() < mSunriseTime)
adjustedHour += 24.f;
if (mTimeSettings.mNightStart < mSunriseTime)
adjustedNightStart += 24.f;
const bool isNight = adjustedHour >= adjustedNightStart;
const float dayDuration = adjustedNightStart - mSunriseTime;
const float nightDuration = 24.f - dayDuration;
float orbit;
if (!isNight)
{
float t = (adjustedHour - mSunriseTime) / dayDuration;
orbit = 1.f - 2.f * t;
}
else
{
float t = (adjustedHour - adjustedNightStart) / nightDuration;
orbit = 2.f * t - 1.f;
}
// Hardcoded constant from Morrowind
const osg::Vec3f sunDir(-400.f * orbit, 75.f, -100.f);
mRendering.setSunDirection(sunDir);
mRendering.setNight(isNight);
}
float underwaterFog = mUnderwaterFog.getValue(time.getHour(), mTimeSettings, "Fog");
float peakHour = mSunriseTime + (mTimeSettings.mNightStart - mSunriseTime) / 2;
float glareFade = 1.f;
if (time.getHour() < mSunriseTime || time.getHour() > mTimeSettings.mNightStart)
glareFade = 0.f;
else if (time.getHour() < peakHour)
glareFade = 1.f - (peakHour - time.getHour()) / (peakHour - mSunriseTime);
else
glareFade = 1.f - (time.getHour() - peakHour) / (mTimeSettings.mNightStart - peakHour);
mRendering.getSkyManager()->setGlareTimeOfDayFade(glareFade);
mRendering.getSkyManager()->setMasserState(mMasser.calculateState(time));
mRendering.getSkyManager()->setSecundaState(mSecunda.calculateState(time));
mRendering.configureFog(
result.mFogDepth, underwaterFog, result.mDLFogFactor, result.mDLFogOffset / 100.0f, result.mFogColor);
mRendering.setAmbientColour(result.mAmbientColor);
mRendering.setSunColour(result.mSunColor, result.mSunColor, result.mGlareView * glareFade);
mRendering.getSkyManager()->setWeather(result);
// Play sounds
if (mPlayingAmbientSoundID != result.getAmbientLoopSoundID())
{
if (mAmbientSound)
{
MWBase::Environment::get().getSoundManager()->stopSound(mAmbientSound);
mAmbientSound = nullptr;
}
mPlayingAmbientSoundID = result.getAmbientLoopSoundID();
if (!mPlayingAmbientSoundID.empty())
mAmbientSound = MWBase::Environment::get().getSoundManager()->playSound(mPlayingAmbientSoundID,
result.mAmbientSoundVolume, 1.0, MWSound::Type::Sfx, MWSound::PlayMode::Loop);
}
else if (mAmbientSound)
mAmbientSound->setVolume(result.mAmbientSoundVolume);
if (mPlayingRainSoundID != result.getRainLoopSoundID())
{
if (mRainSound)
{
MWBase::Environment::get().getSoundManager()->stopSound(mRainSound);
mRainSound = nullptr;
}
mPlayingRainSoundID = result.getRainLoopSoundID();
if (!mPlayingRainSoundID.empty())
mRainSound = MWBase::Environment::get().getSoundManager()->playSound(
mPlayingRainSoundID, result.mAmbientSoundVolume, 1.0, MWSound::Type::Sfx, MWSound::PlayMode::Loop);
}
else if (mRainSound)
mRainSound->setVolume(result.mAmbientSoundVolume);
}
void WeatherManager::stopSounds()
{
MWBase::SoundManager* sndMgr = MWBase::Environment::get().getSoundManager();
if (mAmbientSound)
{
sndMgr->stopSound(mAmbientSound);
mAmbientSound = nullptr;
}
mPlayingAmbientSoundID = ESM::RefId();
if (mRainSound)
{
sndMgr->stopSound(mRainSound);
mRainSound = nullptr;
}
mPlayingRainSoundID = ESM::RefId();
const auto stopThunder = [&](ESM::RefId weatherId) {
const Weather* weather = mWeatherStore->search(weatherId);
if (!weather)
return;
const ConstPtr target;
for (const ESM::RefId& soundId : weather->mThunderSoundID)
if (!soundId.empty() && sndMgr->getSoundPlaying(target, soundId))
sndMgr->stopSound3D(target, soundId);
};
stopThunder(mCurrentWeather);
if (inTransition())
stopThunder(mNextWeather);
}
float WeatherManager::getWindSpeed() const
{
return mWindSpeed;
}
bool WeatherManager::isInStorm() const
{
return mIsStorm;
}
void WeatherManager::advanceTime(double hours, bool incremental)
{
// In Morrowind, when the player sleeps/waits, serves jail time, travels, or trains, all weather transitions are
// immediately applied, regardless of whatever transition time might have been remaining.
mTimePassed += static_cast<float>(hours);
mFastForward = !incremental ? true : mFastForward;
}
NightDayMode WeatherManager::getNightDayMode() const
{
return mNightDayMode;
}
bool WeatherManager::useTorches(float hour) const
{
bool isDark = hour < mSunriseTime || hour > mTimeSettings.mNightStart;
return isDark && mUseTorches;
}
float WeatherManager::getSunPercentage(float hour) const
{
if (hour <= mTimeSettings.mNightEnd || hour >= mTimeSettings.mNightStart)
return 0.f;
else if (hour <= mTimeSettings.mDayStart)
return (hour - mTimeSettings.mNightEnd) / mSunriseDuration;
else if (hour > mTimeSettings.mDayEnd)
return 1.f - ((hour - mTimeSettings.mDayEnd) / mSunsetDuration);
return 1.f;
}
float WeatherManager::getSunVisibility() const
{
const Weather* currentWeather = mWeatherStore->search(mCurrentWeather);
if (currentWeather == nullptr)
return 0;
if (const Weather* nextWeather = mWeatherStore->search(mNextWeather))
{
if (mTransitionFactor < nextWeather->mCloudsMaximumPercent)
{
float t = mTransitionFactor / nextWeather->mCloudsMaximumPercent;
return (1.f - t) * currentWeather->mGlareView + t * nextWeather->mGlareView;
}
}
return currentWeather->mGlareView;
}
void WeatherManager::write(ESM::ESMWriter& writer, Loading::Listener& progress) const
{
ESM::WeatherState state;
state.mCurrentRegion = mCurrentRegion;
state.mTimePassed = mTimePassed;
state.mFastForward = mFastForward;
state.mWeatherUpdateTime = mWeatherUpdateTime;
state.mTransitionFactor = mTransitionFactor;
state.mCurrentWeather = mCurrentWeather;
state.mNextWeather = mNextWeather;
state.mQueuedWeather = mQueuedWeather;
auto it = mRegions.begin();
for (; it != mRegions.end(); ++it)
{
state.mRegions.insert(std::make_pair(it->first, it->second));
}
writer.startRecord(ESM::REC_WTHR);
state.save(writer);
writer.endRecord(ESM::REC_WTHR);
}
bool WeatherManager::readRecord(ESM::ESMReader& reader, uint32_t type)
{
if (ESM::REC_WTHR == type)
{
ESM::WeatherState state;
state.load(reader);
std::swap(mCurrentRegion, state.mCurrentRegion);
mTimePassed = state.mTimePassed;
mFastForward = state.mFastForward;
mWeatherUpdateTime = state.mWeatherUpdateTime;
mTransitionFactor = state.mTransitionFactor;
mCurrentWeather = state.mCurrentWeather;
mNextWeather = state.mNextWeather;
mQueuedWeather = state.mQueuedWeather;
mRegions.clear();
importRegions();
for (auto it = state.mRegions.begin(); it != state.mRegions.end(); ++it)
{
auto found = mRegions.find(it->first);
if (found != mRegions.end())
{
found->second = RegionWeather(it->second);
}
}
if (!mWeatherStore->search(mCurrentWeather))
mWeatherUpdateTime = 0.0f;
return true;
}
return false;
}
void WeatherManager::clear()
{
stopSounds();
mCurrentRegion = ESM::RefId();
mTimePassed = 0.0f;
mWeatherUpdateTime = 0.0f;
mWindSpeed = 0.f;
mCurrentWindSpeed = 0.f;
mNextWindSpeed = 0.f;
mIsStorm = false;
mUseTorches = true;
mFastForward = false;
mNightDayMode = Default;
forceWeather(ESM::Weather::indexToRefId(0));
mRegions.clear();
importRegions();
mWeatherStore->reset();
}
inline void WeatherManager::importRegions()
{
for (const ESM::Region& region : mStore.get<ESM::Region>())
{
mRegions.insert(std::make_pair(region.mId, RegionWeather(region)));
}
}
inline void WeatherManager::regionalWeatherChanged(const ESM::RefId& regionID, RegionWeather& region)
{
// If the region is current, then add a weather transition for it.
MWWorld::ConstPtr player = MWMechanics::getPlayer();
if (player.isInCell())
{
if (regionID == mCurrentRegion)
{
addWeatherTransition(region.getWeather(*mWeatherStore));
}
}
}
inline bool WeatherManager::updateWeatherTime()
{
mWeatherUpdateTime -= mTimePassed;
mTimePassed = 0.0f;
if (mWeatherUpdateTime <= 0.0f)
{
// Expire all regional weather, so that any call to getWeather() will return a new weather ID.
auto it = mRegions.begin();
for (; it != mRegions.end(); ++it)
{
it->second.setWeather({});
}
mWeatherUpdateTime += mHoursBetweenWeatherChanges;
return true;
}
return false;
}
inline bool WeatherManager::updateWeatherRegion(const ESM::RefId& playerRegion)
{
if (!playerRegion.empty() && playerRegion != mCurrentRegion)
{
mCurrentRegion = playerRegion;
return true;
}
return false;
}
inline void WeatherManager::updateWeatherTransitions(const float elapsedRealSeconds)
{
// When a player chooses to train, wait, or serves jail time, any transitions will be fast forwarded to the last
// weather type set, regardless of the remaining transition time.
const Weather* next = mWeatherStore->search(mNextWeather);
if (!mFastForward && next != nullptr)
{
const float delta = next->transitionDelta();
mTransitionFactor -= elapsedRealSeconds * delta;
if (mTransitionFactor <= 0.0f)
{
mCurrentWeather = mNextWeather;
mNextWeather = mQueuedWeather;
mQueuedWeather = {};
// We may have begun processing the queued transition, so we need to apply the remaining time towards
// it.
next = mWeatherStore->search(mNextWeather);
if (next != nullptr)
{
const float newDelta = next->transitionDelta();
const float remainingSeconds = -(mTransitionFactor / delta);
mTransitionFactor = 1.0f - (remainingSeconds * newDelta);
}
else
{
mTransitionFactor = 0.0f;
}
}
}
else
{
if (!mQueuedWeather.empty() && mWeatherStore->search(mQueuedWeather))
{
mCurrentWeather = mQueuedWeather;
}
else if (next != nullptr)
{
mCurrentWeather = mNextWeather;
}
mNextWeather = {};
mQueuedWeather = {};
mFastForward = false;
}
}
inline void WeatherManager::forceWeather(ESM::RefId weatherID)
{
mTransitionFactor = 0.0f;
mCurrentWeather = weatherID;
mNextWeather = {};
mQueuedWeather = {};
}
inline bool WeatherManager::inTransition() const
{
return !mNextWeather.empty();
}
inline void WeatherManager::addWeatherTransition(ESM::RefId weatherID)
{
// In order to work like ChangeWeather expects, this method begins transitioning to the new weather immediately
// if no transition is in progress, otherwise it queues it to be transitioned.
if (!inTransition() && (weatherID != mCurrentWeather))
{
mNextWeather = weatherID;
mTransitionFactor = 1.0f;
}
else if (inTransition() && (weatherID != mNextWeather))
{
mQueuedWeather = weatherID;
}
if (mTransitionFactor > 0.f && !mWeatherStore->search(mCurrentWeather))
mTransitionFactor = 0.f;
}
MWRender::WeatherResult WeatherManager::calculateWeatherResult(
const float gameHour, const float elapsedSeconds, const bool isPaused) const
{
MWRender::WeatherResult result;
float flash = 0.0f;
Weather* current = mWeatherStore->search(mCurrentWeather);
if (current == nullptr)
return result;
if (Weather* next = mWeatherStore->search(mNextWeather))
{
result = calculateTransitionResult(*current, *next, 1 - mTransitionFactor, gameHour);
float currentFlash = current->calculateThunder(mTransitionFactor, elapsedSeconds, isPaused);
float nextFlash = next->calculateThunder(1 - mTransitionFactor, elapsedSeconds, isPaused);
flash = currentFlash + nextFlash;
}
else
{
result = calculateResult(*current, gameHour);
flash = current->calculateThunder(1.0f, elapsedSeconds, isPaused);
}
osg::Vec4f flashColor(flash, flash, flash, 0.0f);
result.mFogColor += flashColor;
result.mAmbientColor += flashColor;
result.mSunColor += flashColor;
return result;
}
MWRender::WeatherResult WeatherManager::calculateResult(const Weather& current, const float gameHour) const
{
MWRender::WeatherResult result;
result.mCloudTexture = current.mCloudTexture;
result.mCloudBlendFactor = 0;
result.mNextWindSpeed = 0;
result.mWindSpeed = result.mCurrentWindSpeed = calculateWindSpeed(current, mWindSpeed);
result.mBaseWindSpeed = current.mWindSpeed;
result.mCloudSpeed = current.mCloudSpeed;
result.mGlareView = current.mGlareView;
result.mWeather = &current;
result.mAmbientSoundVolume = 1.f;
result.mPrecipitationAlpha = 1.f;
result.mNight = (gameHour < mSunriseTime
|| gameHour
> mTimeSettings.mNightStart + mTimeSettings.mStarsPostSunsetStart - mTimeSettings.mStarsFadingDuration);
result.mFogDepth = current.mLandFogDepth.getValue(gameHour, mTimeSettings, "Fog");
result.mFogColor = current.mFogColor.getValue(gameHour, mTimeSettings, "Fog");
result.mAmbientColor = current.mAmbientColor.getValue(gameHour, mTimeSettings, "Ambient");
result.mSunColor = current.mSunColor.getValue(gameHour, mTimeSettings, "Sun");
result.mSkyColor = current.mSkyColor.getValue(gameHour, mTimeSettings, "Sky");
result.mNightFade = mNightFade.getValue(gameHour, mTimeSettings, "Stars");
result.mDLFogFactor = current.mDL.FogFactor;
result.mDLFogOffset = current.mDL.FogOffset;
WeatherSetting setting = mTimeSettings.getSetting("Sun");
float preSunsetTime = setting.mPreSunsetTime;
if (gameHour >= mTimeSettings.mDayEnd - preSunsetTime)
{
float factor = 1.f;
if (preSunsetTime > 0)
factor = (gameHour - (mTimeSettings.mDayEnd - preSunsetTime)) / preSunsetTime;
factor = std::min(1.f, factor);
result.mSunDiscColor = lerp(osg::Vec4f(1, 1, 1, 1), current.mSunDiscSunsetColor, factor);
// The SunDiscSunsetColor in the INI isn't exactly the resulting color on screen, most likely because
// MW applied the color to the ambient term as well. After the ambient and emissive terms are added
// together, the fixed pipeline would then clamp the total lighting to (1,1,1). A noticeable change in color
// tone can be observed when only one of the color components gets clamped. Unfortunately that means we
// can't use the INI color as is, have to replicate the above nonsense.
result.mSunDiscColor
= result.mSunDiscColor + osg::componentMultiply(result.mSunDiscColor, result.mAmbientColor);
for (int i = 0; i < 3; ++i)
result.mSunDiscColor[i] = std::min(1.f, result.mSunDiscColor[i]);
}
else
result.mSunDiscColor = osg::Vec4f(1, 1, 1, 1);
if (gameHour >= mTimeSettings.mDayEnd)
{
// sunset
float fade = std::min(
1.f, (gameHour - mTimeSettings.mDayEnd) / (mTimeSettings.mNightStart - mTimeSettings.mDayEnd));
fade = fade * fade;
result.mSunDiscColor.a() = 1.f - fade;
}
else if (gameHour >= mTimeSettings.mNightEnd && gameHour <= mTimeSettings.mNightEnd + mSunriseDuration / 2.f)
{
// sunrise
result.mSunDiscColor.a() = gameHour - mTimeSettings.mNightEnd;
}
else
result.mSunDiscColor.a() = 1;
result.mStormDirection = current.mStormDirection;
result.mStormDirection.normalize();
result.mStormParticleDirection = result.mStormDirection;
return result;
}
MWRender::WeatherResult WeatherManager::calculateTransitionResult(
const Weather& currentWeather, const Weather& nextWeather, const float factor, const float gameHour) const
{
const MWRender::WeatherResult current = calculateResult(currentWeather, gameHour);
const MWRender::WeatherResult other = calculateResult(nextWeather, gameHour);
MWRender::WeatherResult result;
result.mStormDirection = current.mStormDirection;
result.mNextStormDirection = other.mStormDirection;
result.mCloudTexture = current.mCloudTexture;
result.mNextCloudTexture = other.mCloudTexture;
result.mCloudBlendFactor = nextWeather.cloudBlendFactor(factor);
result.mFogColor = lerp(current.mFogColor, other.mFogColor, factor);
result.mSunColor = lerp(current.mSunColor, other.mSunColor, factor);
result.mSkyColor = lerp(current.mSkyColor, other.mSkyColor, factor);
result.mAmbientColor = lerp(current.mAmbientColor, other.mAmbientColor, factor);
result.mSunDiscColor = lerp(current.mSunDiscColor, other.mSunDiscColor, factor);
result.mFogDepth = lerp(current.mFogDepth, other.mFogDepth, factor);
result.mDLFogFactor = lerp(current.mDLFogFactor, other.mDLFogFactor, factor);
result.mDLFogOffset = lerp(current.mDLFogOffset, other.mDLFogOffset, factor);
result.mCurrentWindSpeed = calculateWindSpeed(currentWeather, mCurrentWindSpeed);
result.mNextWindSpeed = calculateWindSpeed(nextWeather, mNextWindSpeed);
result.mBaseWindSpeed = lerp(current.mBaseWindSpeed, other.mBaseWindSpeed, factor);
result.mWindSpeed = lerp(result.mCurrentWindSpeed, result.mNextWindSpeed, factor);
result.mCloudSpeed = lerp(current.mCloudSpeed, other.mCloudSpeed, factor);
result.mGlareView = lerp(current.mGlareView, other.mGlareView, factor);
result.mNightFade = lerp(current.mNightFade, other.mNightFade, factor);
result.mNight = current.mNight;
float threshold = nextWeather.mRainThreshold;
if (threshold <= 0.f)
threshold = 0.5f;
if (factor < threshold)
{
result.mStormParticleDirection = current.mStormParticleDirection;
result.mWeather = current.mWeather;
result.mAmbientSoundVolume = 1.f - factor / threshold;
result.mPrecipitationAlpha = result.mAmbientSoundVolume;
}
else
{
result.mStormParticleDirection = other.mStormParticleDirection;
result.mWeather = other.mWeather;
result.mAmbientSoundVolume = (factor - threshold) / (1 - threshold);
result.mPrecipitationAlpha = result.mAmbientSoundVolume;
}
return result;
}
}