1
0
Fork 1
mirror of https://github.com/TES3MP/openmw-tes3mp.git synced 2025-04-01 04:36:44 +00:00

Port fog of war

Not optimized yet, need to work on fog texture's DataVariance.
This commit is contained in:
scrawl 2015-05-28 03:50:44 +02:00
parent 5628a2b823
commit c811ac6afe
9 changed files with 268 additions and 206 deletions

View file

@ -355,6 +355,7 @@ namespace MWBase
virtual void requestMap(std::set<MWWorld::CellStore*> cells) = 0; virtual void requestMap(std::set<MWWorld::CellStore*> cells) = 0;
virtual void removeCell(MWWorld::CellStore* cell) = 0; virtual void removeCell(MWWorld::CellStore* cell) = 0;
virtual void writeFog(MWWorld::CellStore* cell) = 0;
}; };
} }

View file

@ -216,21 +216,37 @@ namespace MWGui
void LocalMapBase::applyFogOfWar() void LocalMapBase::applyFogOfWar()
{ {
#if 0 TextureVector fogTextures;
for (int mx=0; mx<3; ++mx) for (int mx=0; mx<3; ++mx)
{ {
for (int my=0; my<3; ++my) for (int my=0; my<3; ++my)
{ {
std::string image = mPrefix+"_"+ MyGUI::utility::toString(mCurX + (mx-1)) + "_" int x = mCurX + (mx-1);
+ MyGUI::utility::toString(mCurY + (-1*(my-1))); int y = mCurY + (-1*(my-1));
MyGUI::ImageBox* fog = mFogWidgets[my + 3*mx]; MyGUI::ImageBox* fog = mFogWidgets[my + 3*mx];
fog->setImageTexture(mFogOfWar ?
((MyGUI::RenderManager::getInstance().getTexture(image+"_fog") != 0) ? image+"_fog" if (!mFogOfWar)
: "black" ) {
: ""); fog->setImageTexture("");
continue;
}
osg::ref_ptr<osg::Texture2D> tex = mLocalMapRender->getFogOfWarTexture(x, y);
if (tex)
{
boost::shared_ptr<MyGUI::ITexture> myguitex (new osgMyGUI::OSGTexture(tex));
fog->setRenderItemTexture(myguitex.get());
fog->getSubWidgetMain()->_setUVSet(MyGUI::FloatRect(0.f, 0.f, 1.f, 1.f));
fogTextures.push_back(myguitex);
}
else
fog->setImageTexture("black");
} }
} }
#endif // Move the textures we just set into mFogTextures, and move the previous textures into fogTextures, for deletion when this function ends.
// Note, above we need to ensure that all widgets are getting a new texture set, lest we delete textures that are still in use.
mFogTextures.swap(fogTextures);
redraw(); redraw();
} }
@ -344,7 +360,7 @@ namespace MWGui
mDoorMarkerWidgets.clear(); mDoorMarkerWidgets.clear();
// Update the map textures // Update the map textures
std::vector<boost::shared_ptr<MyGUI::ITexture> > textures; TextureVector textures;
for (int mx=0; mx<3; ++mx) for (int mx=0; mx<3; ++mx)
{ {
for (int my=0; my<3; ++my) for (int my=0; my<3; ++my)
@ -354,7 +370,7 @@ namespace MWGui
MyGUI::ImageBox* box = mMapWidgets[my + 3*mx]; MyGUI::ImageBox* box = mMapWidgets[my + 3*mx];
osg::ref_ptr<osg::Texture2D> texture = mLocalMapRender->getMapTexture(mInterior, mapX, mapY); osg::ref_ptr<osg::Texture2D> texture = mLocalMapRender->getMapTexture(mapX, mapY);
if (texture) if (texture)
{ {
boost::shared_ptr<MyGUI::ITexture> guiTex (new osgMyGUI::OSGTexture(texture)); boost::shared_ptr<MyGUI::ITexture> guiTex (new osgMyGUI::OSGTexture(texture));

View file

@ -106,7 +106,9 @@ namespace MWGui
std::vector<MyGUI::ImageBox*> mMapWidgets; std::vector<MyGUI::ImageBox*> mMapWidgets;
std::vector<MyGUI::ImageBox*> mFogWidgets; std::vector<MyGUI::ImageBox*> mFogWidgets;
std::vector<boost::shared_ptr<MyGUI::ITexture> > mMapTextures; typedef std::vector<boost::shared_ptr<MyGUI::ITexture> > TextureVector;
TextureVector mMapTextures;
TextureVector mFogTextures;
// Keep track of created marker widgets, just to easily remove them later. // Keep track of created marker widgets, just to easily remove them later.
std::vector<MyGUI::Widget*> mDoorMarkerWidgets; std::vector<MyGUI::Widget*> mDoorMarkerWidgets;

View file

@ -2016,4 +2016,9 @@ namespace MWGui
mLocalMapRender->removeCell(cell); mLocalMapRender->removeCell(cell);
} }
void WindowManager::writeFog(MWWorld::CellStore *cell)
{
mLocalMapRender->saveFogOfWar(cell);
}
} }

View file

@ -368,6 +368,7 @@ namespace MWGui
void requestMap(std::set<MWWorld::CellStore*> cells); void requestMap(std::set<MWWorld::CellStore*> cells);
void removeCell(MWWorld::CellStore* cell); void removeCell(MWWorld::CellStore* cell);
void writeFog(MWWorld::CellStore* cell);
private: private:
Resource::ResourceSystem* mResourceSystem; Resource::ResourceSystem* mResourceSystem;

View file

@ -1,16 +1,20 @@
#include "localmap.hpp" #include "localmap.hpp"
#include <iostream> #include <iostream>
#include <stdint.h>
#include <osg/LightModel> #include <osg/LightModel>
#include <osg/Texture2D> #include <osg/Texture2D>
#include <osg/ComputeBoundsVisitor> #include <osg/ComputeBoundsVisitor>
#include <osgDB/ReadFile>
#include <osgViewer/Viewer> #include <osgViewer/Viewer>
#include <components/esm/fogstate.hpp> #include <components/esm/fogstate.hpp>
#include <components/settings/settings.hpp> #include <components/settings/settings.hpp>
#include <components/sceneutil/visitor.hpp> #include <components/sceneutil/visitor.hpp>
#include <components/files/memorystream.hpp>
#include "../mwbase/environment.hpp" #include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp" #include "../mwbase/world.hpp"
@ -44,6 +48,11 @@ namespace
MWRender::LocalMap* mParent; MWRender::LocalMap* mParent;
}; };
float square(float val)
{
return val*val;
}
} }
namespace MWRender namespace MWRender
@ -81,47 +90,37 @@ const osg::Vec2f LocalMap::rotatePoint(const osg::Vec2f& point, const osg::Vec2f
void LocalMap::clear() void LocalMap::clear()
{ {
mSegments.clear();
} }
void LocalMap::saveFogOfWar(MWWorld::CellStore* cell) void LocalMap::saveFogOfWar(MWWorld::CellStore* cell)
{ {
/*
if (!mInterior) if (!mInterior)
{ {
std::string textureName = "Cell_"+coordStr(cell->getCell()->getGridX(), cell->getCell()->getGridY())+"_fog"; const MapSegment& segment = mSegments[std::make_pair(cell->getCell()->getGridX(), cell->getCell()->getGridY())];
std::auto_ptr<ESM::FogState> fog (new ESM::FogState()); std::auto_ptr<ESM::FogState> fog (new ESM::FogState());
fog->mFogTextures.push_back(ESM::FogTexture()); fog->mFogTextures.push_back(ESM::FogTexture());
TexturePtr tex = TextureManager::getSingleton().getByName(textureName); segment.saveFogOfWar(fog->mFogTextures.back());
if (tex.isNull())
return;
Ogre::Image image;
tex->load();
tex->convertToImage(image);
Ogre::DataStreamPtr encoded = image.encode("tga");
fog->mFogTextures.back().mImageData.resize(encoded->size());
encoded->read(&fog->mFogTextures.back().mImageData[0], encoded->size());
cell->setFog(fog.release()); cell->setFog(fog.release());
} }
else else
{ {
Vector2 min(mBounds.getMinimum().x, mBounds.getMinimum().y); // FIXME: segmenting code duplicated from requestMap
Vector2 max(mBounds.getMaximum().x, mBounds.getMaximum().y); osg::Vec2f min(mBounds.xMin(), mBounds.yMin());
Vector2 length = max-min; osg::Vec2f max(mBounds.xMax(), mBounds.yMax());
const int segsX = static_cast<int>(std::ceil(length.x / mMapWorldSize)); osg::Vec2f length = max-min;
const int segsY = static_cast<int>(std::ceil(length.y / mMapWorldSize)); const int segsX = static_cast<int>(std::ceil(length.x() / mMapWorldSize));
const int segsY = static_cast<int>(std::ceil(length.y() / mMapWorldSize));
mInteriorName = cell->getCell()->mName;
std::auto_ptr<ESM::FogState> fog (new ESM::FogState()); std::auto_ptr<ESM::FogState> fog (new ESM::FogState());
fog->mBounds.mMinX = mBounds.getMinimum().x; fog->mBounds.mMinX = mBounds.xMin();
fog->mBounds.mMaxX = mBounds.getMaximum().x; fog->mBounds.mMaxX = mBounds.xMax();
fog->mBounds.mMinY = mBounds.getMinimum().y; fog->mBounds.mMinY = mBounds.yMin();
fog->mBounds.mMaxY = mBounds.getMaximum().y; fog->mBounds.mMaxY = mBounds.yMax();
fog->mNorthMarkerAngle = mAngle; fog->mNorthMarkerAngle = mAngle;
fog->mFogTextures.reserve(segsX*segsY); fog->mFogTextures.reserve(segsX*segsY);
@ -130,21 +129,11 @@ void LocalMap::saveFogOfWar(MWWorld::CellStore* cell)
{ {
for (int y=0; y<segsY; ++y) for (int y=0; y<segsY; ++y)
{ {
std::string textureName = cell->getCell()->mName + "_" + coordStr(x,y) + "_fog"; const MapSegment& segment = mSegments[std::make_pair(x,y)];
TexturePtr tex = TextureManager::getSingleton().getByName(textureName);
if (tex.isNull())
return;
Ogre::Image image;
tex->load();
tex->convertToImage(image);
fog->mFogTextures.push_back(ESM::FogTexture()); fog->mFogTextures.push_back(ESM::FogTexture());
Ogre::DataStreamPtr encoded = image.encode("tga"); segment.saveFogOfWar(fog->mFogTextures.back());
fog->mFogTextures.back().mImageData.resize(encoded->size());
encoded->read(&fog->mFogTextures.back().mImageData[0], encoded->size());
fog->mFogTextures.back().mX = x; fog->mFogTextures.back().mX = x;
fog->mFogTextures.back().mY = y; fog->mFogTextures.back().mY = y;
@ -153,7 +142,6 @@ void LocalMap::saveFogOfWar(MWWorld::CellStore* cell)
cell->setFog(fog.release()); cell->setFog(fog.release());
} }
*/
} }
osg::ref_ptr<osg::Camera> LocalMap::createOrthographicCamera(float x, float y, float width, float height, const osg::Vec3d& upVector, float zmin, float zmax) osg::ref_ptr<osg::Camera> LocalMap::createOrthographicCamera(float x, float y, float width, float height, const osg::Vec3d& upVector, float zmin, float zmax)
@ -221,7 +209,9 @@ void LocalMap::setupRenderToTexture(osg::ref_ptr<osg::Camera> camera, int x, int
camera->addChild(mSceneRoot); camera->addChild(mSceneRoot);
mRoot->addChild(camera); mRoot->addChild(camera);
mActiveCameras.push_back(camera); mActiveCameras.push_back(camera);
mTextures[std::make_pair(x, y)] = texture;
MapSegment& segment = mSegments[std::make_pair(x, y)];
segment.mMapTexture = texture;
} }
void LocalMap::requestMap(std::set<MWWorld::CellStore*> cells) void LocalMap::requestMap(std::set<MWWorld::CellStore*> cells)
@ -238,19 +228,30 @@ void LocalMap::requestMap(std::set<MWWorld::CellStore*> cells)
void LocalMap::removeCell(MWWorld::CellStore *cell) void LocalMap::removeCell(MWWorld::CellStore *cell)
{ {
saveFogOfWar(cell);
if (cell->isExterior()) if (cell->isExterior())
mTextures.erase(std::make_pair(cell->getCell()->getGridX(), cell->getCell()->getGridY())); mSegments.erase(std::make_pair(cell->getCell()->getGridX(), cell->getCell()->getGridY()));
else else
mTextures.clear(); mSegments.clear();
} }
osg::ref_ptr<osg::Texture2D> LocalMap::getMapTexture(bool interior, int x, int y) osg::ref_ptr<osg::Texture2D> LocalMap::getMapTexture(int x, int y)
{ {
TextureMap::iterator found = mTextures.find(std::make_pair(x, y)); SegmentMap::iterator found = mSegments.find(std::make_pair(x, y));
if (found == mTextures.end()) if (found == mSegments.end())
return osg::ref_ptr<osg::Texture2D>(); return osg::ref_ptr<osg::Texture2D>();
else else
return found->second; return found->second.mMapTexture;
}
osg::ref_ptr<osg::Texture2D> LocalMap::getFogOfWarTexture(int x, int y)
{
SegmentMap::iterator found = mSegments.find(std::make_pair(x, y));
if (found == mSegments.end())
return osg::ref_ptr<osg::Texture2D>();
else
return found->second.mFogOfWarTexture;
} }
void LocalMap::markForRemoval(osg::Camera *cam) void LocalMap::markForRemoval(osg::Camera *cam)
@ -277,7 +278,6 @@ void LocalMap::cleanupCameras()
mRoot->removeChild(*it); mRoot->removeChild(*it);
} }
mCamerasPendingRemoval.clear(); mCamerasPendingRemoval.clear();
} }
@ -296,15 +296,11 @@ void LocalMap::requestExteriorMap(MWWorld::CellStore* cell)
osg::Vec3d(0,1,0), zmin, zmax); osg::Vec3d(0,1,0), zmin, zmax);
setupRenderToTexture(camera, cell->getCell()->getGridX(), cell->getCell()->getGridY()); setupRenderToTexture(camera, cell->getCell()->getGridX(), cell->getCell()->getGridY());
/* MapSegment& segment = mSegments[std::make_pair(cell->getCell()->getGridX(), cell->getCell()->getGridY())];
if (mBuffers.find(name) == mBuffers.end()) if (cell->getFog())
{ segment.loadFogOfWar(cell->getFog()->mFogTextures.back());
if (cell->getFog()) else
loadFogOfWar(name, cell->getFog()->mFogTextures.back()); segment.initFogOfWar();
else
createFogOfWar(name);
}
*/
} }
void LocalMap::requestInteriorMap(MWWorld::CellStore* cell) void LocalMap::requestInteriorMap(MWWorld::CellStore* cell)
@ -361,20 +357,19 @@ void LocalMap::requestInteriorMap(MWWorld::CellStore* cell)
// If they changed by too much (for bounds, < padding is considered acceptable) then parts of the interior might not // If they changed by too much (for bounds, < padding is considered acceptable) then parts of the interior might not
// be covered by the map anymore. // be covered by the map anymore.
// The following code detects this, and discards the CellStore's fog state if it needs to. // The following code detects this, and discards the CellStore's fog state if it needs to.
/*
if (cell->getFog()) if (cell->getFog())
{ {
ESM::FogState* fog = cell->getFog(); ESM::FogState* fog = cell->getFog();
Ogre::Vector3 newMin (fog->mBounds.mMinX, fog->mBounds.mMinY, zMin); osg::Vec3f newMin (fog->mBounds.mMinX, fog->mBounds.mMinY, zMin);
Ogre::Vector3 newMax (fog->mBounds.mMaxX, fog->mBounds.mMaxY, zMax); osg::Vec3f newMax (fog->mBounds.mMaxX, fog->mBounds.mMaxY, zMax);
Ogre::Vector3 minDiff = newMin - mBounds.getMinimum(); osg::Vec3f minDiff = newMin - mBounds._min;
Ogre::Vector3 maxDiff = newMax - mBounds.getMaximum(); osg::Vec3f maxDiff = newMax - mBounds._max;
if (std::abs(minDiff.x) > padding || std::abs(minDiff.y) > padding if (std::abs(minDiff.x()) > padding || std::abs(minDiff.y()) > padding
|| std::abs(maxDiff.x) > padding || std::abs(maxDiff.y) > padding || std::abs(maxDiff.x()) > padding || std::abs(maxDiff.y()) > padding
|| std::abs(mAngle - fog->mNorthMarkerAngle) > Ogre::Degree(5).valueRadians()) || std::abs(mAngle - fog->mNorthMarkerAngle) > osg::DegreesToRadians(5.f))
{ {
// Nuke it // Nuke it
cell->setFog(NULL); cell->setFog(NULL);
@ -382,11 +377,10 @@ void LocalMap::requestInteriorMap(MWWorld::CellStore* cell)
else else
{ {
// Looks sane, use it // Looks sane, use it
mBounds = Ogre::AxisAlignedBox(newMin, newMax); mBounds = osg::BoundingBox(newMin, newMax);
mAngle = fog->mNorthMarkerAngle; mAngle = fog->mNorthMarkerAngle;
} }
} }
*/
osg::Vec2f min(mBounds.xMin(), mBounds.yMin()); osg::Vec2f min(mBounds.xMin(), mBounds.yMin());
osg::Vec2f max(mBounds.xMax(), mBounds.yMax()); osg::Vec2f max(mBounds.xMax(), mBounds.yMax());
@ -399,6 +393,7 @@ void LocalMap::requestInteriorMap(MWWorld::CellStore* cell)
const int segsX = static_cast<int>(std::ceil(length.x() / mMapWorldSize)); const int segsX = static_cast<int>(std::ceil(length.x() / mMapWorldSize));
const int segsY = static_cast<int>(std::ceil(length.y() / mMapWorldSize)); const int segsY = static_cast<int>(std::ceil(length.y() / mMapWorldSize));
int i = 0;
for (int x=0; x<segsX; ++x) for (int x=0; x<segsX; ++x)
{ {
for (int y=0; y<segsY; ++y) for (int y=0; y<segsY; ++y)
@ -418,73 +413,27 @@ void LocalMap::requestInteriorMap(MWWorld::CellStore* cell)
setupRenderToTexture(camera, x, y); setupRenderToTexture(camera, x, y);
/* MapSegment& segment = mSegments[std::make_pair(x,y)];
if (!cell->getFog()) if (!cell->getFog())
createFogOfWar(texturePrefix); segment.initFogOfWar();
else else
{ {
ESM::FogState* fog = cell->getFog(); ESM::FogState* fog = cell->getFog();
// We are using the same bounds and angle as we were using when the textures were originally made. Segments should come out the same. // We are using the same bounds and angle as we were using when the textures were originally made. Segments should come out the same.
if (i >= int(fog->mFogTextures.size())) if (i >= int(fog->mFogTextures.size()))
throw std::runtime_error("fog texture count mismatch"); {
std::cout << "Warning: fog texture count mismatch" << std::endl;
break;
}
ESM::FogTexture& esm = fog->mFogTextures[i]; segment.loadFogOfWar(fog->mFogTextures[i]);
loadFogOfWar(texturePrefix, esm);
} }
*/ ++i;
} }
} }
} }
/*
void LocalMap::createFogOfWar(const std::string& texturePrefix)
{
const std::string texName = texturePrefix + "_fog";
TexturePtr tex = createFogOfWarTexture(texName);
// create a buffer to use for dynamic operations
std::vector<uint32> buffer;
// initialize to (0, 0, 0, 1)
buffer.resize(sFogOfWarResolution*sFogOfWarResolution, 0xFF000000);
// upload to the texture
tex->load();
memcpy(tex->getBuffer()->lock(HardwareBuffer::HBL_DISCARD), &buffer[0], sFogOfWarResolution*sFogOfWarResolution*4);
tex->getBuffer()->unlock();
mBuffers[texturePrefix] = buffer;
}
*/
/*
void LocalMap::loadFogOfWar (const std::string& texturePrefix, ESM::FogTexture& esm)
{
std::vector<char>& data = esm.mImageData;
Ogre::DataStreamPtr stream(new Ogre::MemoryDataStream(&data[0], data.size()));
Ogre::Image image;
image.load(stream, "tga");
if (int(image.getWidth()) != sFogOfWarResolution || int(image.getHeight()) != sFogOfWarResolution)
throw std::runtime_error("fog texture size mismatch");
std::string texName = texturePrefix + "_fog";
Ogre::TexturePtr tex = createFogOfWarTexture(texName);
tex->unload();
tex->loadImage(image);
// create a buffer to use for dynamic operations
std::vector<uint32> buffer;
buffer.resize(sFogOfWarResolution*sFogOfWarResolution);
memcpy(&buffer[0], image.getData(), image.getSize());
mBuffers[texturePrefix] = buffer;
}
*/
void LocalMap::worldToInteriorMapPosition (osg::Vec2f pos, float& nX, float& nY, int& x, int& y) void LocalMap::worldToInteriorMapPosition (osg::Vec2f pos, float& nX, float& nY, int& x, int& y)
{ {
pos = rotatePoint(pos, osg::Vec2f(mBounds.center().x(), mBounds.center().y()), mAngle); pos = rotatePoint(pos, osg::Vec2f(mBounds.center().x(), mBounds.center().y()), mAngle);
@ -510,11 +459,8 @@ osg::Vec2f LocalMap::interiorMapToWorldPosition (float nX, float nY, int x, int
bool LocalMap::isPositionExplored (float nX, float nY, int x, int y, bool interior) bool LocalMap::isPositionExplored (float nX, float nY, int x, int y, bool interior)
{ {
return true; const MapSegment& segment = mSegments[std::make_pair(x, y)];
/* if (!segment.mFogOfWarImage)
std::string texName = (interior ? mInteriorName + "_" : "Cell_") + coordStr(x, y);
if (mBuffers.find(texName) == mBuffers.end())
return false; return false;
nX = std::max(0.f, std::min(1.f, nX)); nX = std::max(0.f, std::min(1.f, nX));
@ -523,24 +469,14 @@ bool LocalMap::isPositionExplored (float nX, float nY, int x, int y, bool interi
int texU = static_cast<int>((sFogOfWarResolution - 1) * nX); int texU = static_cast<int>((sFogOfWarResolution - 1) * nX);
int texV = static_cast<int>((sFogOfWarResolution - 1) * nY); int texV = static_cast<int>((sFogOfWarResolution - 1) * nY);
Ogre::uint32 clr = mBuffers[texName][texV * sFogOfWarResolution + texU]; uint32_t clr = ((const uint32_t*)segment.mFogOfWarImage->data())[texV * sFogOfWarResolution + texU];
uint8 alpha = (clr >> 24); uint8_t alpha = (clr >> 24);
return alpha < 200; return alpha < 200;
*/
} }
void LocalMap::updatePlayer (const osg::Vec3f& position, const osg::Quat& orientation, void LocalMap::updatePlayer (const osg::Vec3f& position, const osg::Quat& orientation,
float& u, float& v, int& x, int& y, osg::Vec3f& direction) float& u, float& v, int& x, int& y, osg::Vec3f& direction)
{ {
/*
if (sFogOfWarSkip != 0)
{
static int count=0;
if (++count % sFogOfWarSkip != 0)
return;
}
*/
// retrieve the x,y grid coordinates the player is in // retrieve the x,y grid coordinates the player is in
osg::Vec2f pos(position.x(), position.y()); osg::Vec2f pos(position.x(), position.y());
@ -563,11 +499,9 @@ void LocalMap::updatePlayer (const osg::Vec3f& position, const osg::Quat& orient
v = 1.0f-std::abs((pos.y() - (mMapWorldSize*y))/mMapWorldSize); v = 1.0f-std::abs((pos.y() - (mMapWorldSize*y))/mMapWorldSize);
} }
/*
// explore radius (squared) // explore radius (squared)
const float exploreRadius = (mInterior ? 0.1f : 0.3f) * (sFogOfWarResolution-1); // explore radius from 0 to sFogOfWarResolution-1 const float exploreRadius = (mInterior ? 0.1f : 0.3f) * (sFogOfWarResolution-1); // explore radius from 0 to sFogOfWarResolution-1
const float sqrExploreRadius = Math::Sqr(exploreRadius); const float sqrExploreRadius = square(exploreRadius);
const float exploreRadiusUV = exploreRadius / sFogOfWarResolution; // explore radius from 0 to 1 (UV space) const float exploreRadiusUV = exploreRadius / sFogOfWarResolution; // explore radius from 0 to 1 (UV space)
// change the affected fog of war textures (in a 3x3 grid around the player) // change the affected fog of war textures (in a 3x3 grid around the player)
@ -575,7 +509,6 @@ void LocalMap::updatePlayer (const osg::Vec3f& position, const osg::Quat& orient
{ {
for (int my = -1; my<2; ++my) for (int my = -1; my<2; ++my)
{ {
// is this texture affected at all? // is this texture affected at all?
bool affected = false; bool affected = false;
if (mx == 0 && my == 0) // the player is always in the center of the 3x3 grid if (mx == 0 && my == 0) // the player is always in the center of the 3x3 grid
@ -590,45 +523,137 @@ void LocalMap::updatePlayer (const osg::Vec3f& position, const osg::Quat& orient
if (!affected) if (!affected)
continue; continue;
std::string texName = texBaseName + coordStr(x+mx,y+my*-1); int texX = x + mx;
int texY = y + my*-1;
TexturePtr tex = TextureManager::getSingleton().getByName(texName+"_fog"); MapSegment& segment = mSegments[std::make_pair(texX, texY)];
if (!tex.isNull())
if (!segment.mFogOfWarImage || !segment.mMapTexture)
continue;
unsigned char* data = segment.mFogOfWarImage->data();
for (int texV = 0; texV<sFogOfWarResolution; ++texV)
{ {
std::map <std::string, std::vector<Ogre::uint32> >::iterator anIter; for (int texU = 0; texU<sFogOfWarResolution; ++texU)
// get its buffer
anIter = mBuffers.find(texName);
if (anIter == mBuffers.end()) return;
std::vector<Ogre::uint32>& aBuffer = (*anIter).second;
int i=0;
for (int texV = 0; texV<sFogOfWarResolution; ++texV)
{ {
for (int texU = 0; texU<sFogOfWarResolution; ++texU) float sqrDist = square((texU + mx*(sFogOfWarResolution-1)) - u*(sFogOfWarResolution-1))
{ + square((texV + my*(sFogOfWarResolution-1)) - v*(sFogOfWarResolution-1));
float sqrDist = Math::Sqr((texU + mx*(sFogOfWarResolution-1)) - u*(sFogOfWarResolution-1))
+ Math::Sqr((texV + my*(sFogOfWarResolution-1)) - v*(sFogOfWarResolution-1));
uint32 clr = aBuffer[i];
uint8 alpha = (clr >> 24);
alpha = std::min( alpha, (uint8) (std::max(0.f, std::min(1.f, (sqrDist/sqrExploreRadius)))*255) );
aBuffer[i] = (uint32) (alpha << 24);
++i; uint32_t clr = *(uint32_t*)data;
} uint8_t alpha = (clr >> 24);
alpha = std::min( alpha, (uint8_t) (std::max(0.f, std::min(1.f, (sqrDist/sqrExploreRadius)))*255) );
*(uint32_t*)data = (uint32_t) (alpha << 24);
data += 4;
} }
tex->load();
// copy to the texture
// NOTE: Could be optimized later. We actually only need to update the region that changed.
// Not a big deal at the moment, the FoW is only 32x32 anyway.
memcpy(tex->getBuffer()->lock(HardwareBuffer::HBL_DISCARD), &aBuffer[0], sFogOfWarResolution*sFogOfWarResolution*4);
tex->getBuffer()->unlock();
} }
segment.mHasFogState = true;
segment.mFogOfWarImage->dirty();
} }
} }
*/ }
LocalMap::MapSegment::MapSegment()
: mHasFogState(false)
{
}
LocalMap::MapSegment::~MapSegment()
{
}
void LocalMap::MapSegment::createFogOfWarTexture()
{
if (mFogOfWarTexture)
return;
mFogOfWarTexture = new osg::Texture2D;
mFogOfWarTexture->setDataVariance(osg::Object::DYNAMIC);
mFogOfWarTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
mFogOfWarTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
mFogOfWarTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
mFogOfWarTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
mFogOfWarTexture->setUnRefImageDataAfterApply(false);
}
void LocalMap::MapSegment::initFogOfWar()
{
mFogOfWarImage = new osg::Image;
mFogOfWarImage->allocateImage(sFogOfWarResolution, sFogOfWarResolution, 1, GL_RGBA, GL_UNSIGNED_BYTE);
assert(mFogOfWarImage->isDataContiguous());
std::vector<uint32_t> data;
data.resize(sFogOfWarResolution*sFogOfWarResolution, 0xff000000);
memcpy(mFogOfWarImage->data(), &data[0], data.size()*4);
createFogOfWarTexture();
mFogOfWarTexture->setImage(mFogOfWarImage);
}
void LocalMap::MapSegment::loadFogOfWar(const ESM::FogTexture &esm)
{
const std::vector<char>& data = esm.mImageData;
if (!data.size())
{
initFogOfWar();
return;
}
// TODO: deprecate tga and use raw data instead
osgDB::ReaderWriter* readerwriter = osgDB::Registry::instance()->getReaderWriterForExtension("tga");
if (!readerwriter)
{
std::cerr << "Unable to load fog, can't find a tga ReaderWriter" << std::endl;
return;
}
Files::IMemStream in(&data[0], data.size());
osgDB::ReaderWriter::ReadResult result = readerwriter->readImage(in);
if (!result.success())
{
std::cerr << "Failed to read fog: " << result.message() << std::endl;
return;
}
mFogOfWarImage = result.getImage();
mFogOfWarImage->flipVertical();
mFogOfWarImage->dirty();
createFogOfWarTexture();
mFogOfWarTexture->setImage(mFogOfWarImage);
mHasFogState = true;
}
void LocalMap::MapSegment::saveFogOfWar(ESM::FogTexture &fog) const
{
if (!mFogOfWarImage || !mHasFogState)
return;
std::ostringstream ostream;
osgDB::ReaderWriter* readerwriter = osgDB::Registry::instance()->getReaderWriterForExtension("tga");
if (!readerwriter)
{
std::cerr << "Unable to write fog, can't find a tga ReaderWriter" << std::endl;
return;
}
// extra flips are unfortunate, but required for compatibility with older versions
mFogOfWarImage->flipVertical();
osgDB::ReaderWriter::WriteResult result = readerwriter->writeImage(*mFogOfWarImage, ostream);
if (!result.success())
{
std::cerr << "Unable to write fog: " << result.message() << std::endl;
return;
}
mFogOfWarImage->flipVertical();
std::string data = ostream.str();
fog.mImageData = std::vector<char>(data.begin(), data.end());
} }
} }

View file

@ -27,6 +27,7 @@ namespace osgViewer
namespace osg namespace osg
{ {
class Texture2D; class Texture2D;
class Image;
class Camera; class Camera;
class Group; class Group;
class Node; class Node;
@ -48,12 +49,23 @@ namespace MWRender
*/ */
void clear(); void clear();
/**
* Request a map render for the given cells. Render textures will be immediately created and can be retrieved with the getMapTexture function.
*/
void requestMap (std::set<MWWorld::CellStore*> cells); void requestMap (std::set<MWWorld::CellStore*> cells);
/**
* Remove map and fog textures for the given cell.
*/
void removeCell (MWWorld::CellStore* cell); void removeCell (MWWorld::CellStore* cell);
osg::ref_ptr<osg::Texture2D> getMapTexture (bool interior, int x, int y); osg::ref_ptr<osg::Texture2D> getMapTexture (int x, int y);
osg::ref_ptr<osg::Texture2D> getFogOfWarTexture (int x, int y);
/**
* Indicates a camera has been queued for rendering and can be cleaned up in the next frame. For internal use only.
*/
void markForRemoval(osg::Camera* cam); void markForRemoval(osg::Camera* cam);
/** /**
@ -78,8 +90,7 @@ namespace MWRender
void saveFogOfWar(MWWorld::CellStore* cell); void saveFogOfWar(MWWorld::CellStore* cell);
/** /**
* Get the interior map texture index and normalized position * Get the interior map texture index and normalized position on this texture, given a world position
* on this texture, given a world position
*/ */
void worldToInteriorMapPosition (osg::Vec2f pos, float& nX, float& nY, int& x, int& y); void worldToInteriorMapPosition (osg::Vec2f pos, float& nX, float& nY, int& x, int& y);
@ -102,17 +113,31 @@ namespace MWRender
CameraVector mCamerasPendingRemoval; CameraVector mCamerasPendingRemoval;
typedef std::map<std::pair<int, int>, osg::ref_ptr<osg::Texture2D> > TextureMap; struct MapSegment
TextureMap mTextures; {
MapSegment();
~MapSegment();
void initFogOfWar();
void loadFogOfWar(const ESM::FogTexture& fog);
void saveFogOfWar(ESM::FogTexture& fog) const;
void createFogOfWarTexture();
osg::ref_ptr<osg::Texture2D> mMapTexture;
osg::ref_ptr<osg::Texture2D> mFogOfWarTexture;
osg::ref_ptr<osg::Image> mFogOfWarImage;
bool mHasFogState;
};
typedef std::map<std::pair<int, int>, MapSegment> SegmentMap;
SegmentMap mSegments;
int mMapResolution; int mMapResolution;
// the dynamic texture is a bottleneck, so don't set this too high // the dynamic texture is a bottleneck, so don't set this too high
static const int sFogOfWarResolution = 32; static const int sFogOfWarResolution = 32;
// frames to skip before rendering fog of war
static const int sFogOfWarSkip = 2;
// size of a map segment (for exteriors, 1 cell) // size of a map segment (for exteriors, 1 cell)
float mMapWorldSize; float mMapWorldSize;
@ -125,23 +150,8 @@ namespace MWRender
osg::ref_ptr<osg::Camera> createOrthographicCamera(float left, float top, float width, float height, const osg::Vec3d& upVector, float zmin, float zmax); osg::ref_ptr<osg::Camera> createOrthographicCamera(float left, float top, float width, float height, const osg::Vec3d& upVector, float zmin, float zmax);
void setupRenderToTexture(osg::ref_ptr<osg::Camera> camera, int x, int y); void setupRenderToTexture(osg::ref_ptr<osg::Camera> camera, int x, int y);
// Creates a fog of war texture and initializes it to full black
//void createFogOfWar(const std::string& texturePrefix);
// Loads a fog of war texture from its ESM struct
//void loadFogOfWar(const std::string& texturePrefix, ESM::FogTexture& esm); // FogTexture not const because MemoryDataStream doesn't accept it
// A buffer for the "fog of war" textures of the current cell.
// Both interior and exterior maps are possibly divided into multiple textures.
//std::map <std::string, std::vector<Ogre::uint32> > mBuffers;
// The render texture we will use to create the map images
//Ogre::TexturePtr mRenderTexture;
//Ogre::RenderTarget* mRenderTarget;
bool mInterior; bool mInterior;
osg::BoundingBox mBounds; osg::BoundingBox mBounds;
//std::string mInteriorName;
}; };
} }

View file

@ -179,12 +179,14 @@ void MWState::StateManager::saveGame (const std::string& description, const Slot
profile.mTimePlayed = mTimePlayed; profile.mTimePlayed = mTimePlayed;
profile.mDescription = description; profile.mDescription = description;
/*
int screenshotW = 259*2, screenshotH = 133*2; // *2 to get some nice antialiasing int screenshotW = 259*2, screenshotH = 133*2; // *2 to get some nice antialiasing
Ogre::Image screenshot; Ogre::Image screenshot;
world.screenshot(screenshot, screenshotW, screenshotH); world.screenshot(screenshot, screenshotW, screenshotH);
Ogre::DataStreamPtr encoded = screenshot.encode("jpg"); Ogre::DataStreamPtr encoded = screenshot.encode("jpg");
profile.mScreenshot.resize(encoded->size()); profile.mScreenshot.resize(encoded->size());
encoded->read(&profile.mScreenshot[0], encoded->size()); encoded->read(&profile.mScreenshot[0], encoded->size());
*/
if (!slot) if (!slot)
slot = getCurrentCharacter()->createSlot (profile); slot = getCurrentCharacter()->createSlot (profile);

View file

@ -337,8 +337,8 @@ namespace MWWorld
for (Scene::CellStoreCollection::const_iterator iter (mWorldScene->getActiveCells().begin()); for (Scene::CellStoreCollection::const_iterator iter (mWorldScene->getActiveCells().begin());
iter!=mWorldScene->getActiveCells().end(); ++iter) iter!=mWorldScene->getActiveCells().end(); ++iter)
{ {
//CellStore* cellstore = *iter; CellStore* cellstore = *iter;
//mRendering->writeFog(cellstore); MWBase::Environment::get().getWindowManager()->writeFog(cellstore);
} }
MWMechanics::CreatureStats::writeActorIdCounter(writer); MWMechanics::CreatureStats::writeActorIdCounter(writer);