id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
34,711
|
removedalphafunc.cpp
|
OpenMW_openmw/components/shader/removedalphafunc.cpp
|
#include "removedalphafunc.hpp"
#include <cassert>
#include <osg/State>
namespace Shader
{
std::array<osg::ref_ptr<RemovedAlphaFunc>, GL_ALWAYS - GL_NEVER + 1> RemovedAlphaFunc::sInstances{ nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
osg::ref_ptr<RemovedAlphaFunc> RemovedAlphaFunc::getInstance(GLenum func)
{
assert(func >= GL_NEVER && func <= GL_ALWAYS);
if (!sInstances[func - GL_NEVER])
sInstances[func - GL_NEVER]
= new RemovedAlphaFunc(static_cast<osg::AlphaFunc::ComparisonFunction>(func), 1.0);
return sInstances[func - GL_NEVER];
}
}
| 653
|
C++
|
.cpp
| 16
| 34.8125
| 120
| 0.676145
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,712
|
shadervisitor.cpp
|
OpenMW_openmw/components/shader/shadervisitor.cpp
|
#include "shadervisitor.hpp"
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <osg/AlphaFunc>
#include <osg/BlendFunc>
#include <osg/ColorMaski>
#include <osg/GLExtensions>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/Multisample>
#include <osg/Texture>
#include <osg/ValueObject>
#include <osgParticle/ParticleSystem>
#include <osgUtil/TangentSpaceGenerator>
#include <components/debug/debuglog.hpp>
#include <components/misc/osguservalues.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/resource/imagemanager.hpp>
#include <components/sceneutil/glextensions.hpp>
#include <components/sceneutil/morphgeometry.hpp>
#include <components/sceneutil/riggeometry.hpp>
#include <components/sceneutil/riggeometryosgaextension.hpp>
#include <components/sceneutil/texturetype.hpp>
#include <components/sceneutil/util.hpp>
#include <components/settings/settings.hpp>
#include <components/stereo/stereomanager.hpp>
#include <components/vfs/manager.hpp>
#include "removedalphafunc.hpp"
#include "shadermanager.hpp"
namespace Shader
{
/**
* Miniature version of osg::StateSet used to track state added by the shader visitor which should be ignored when
* it's applied a second time, and removed when shaders are removed.
* Actual StateAttributes aren't kept as they're recoverable from the StateSet this is attached to - we just want
* the TypeMemberPair as that uniquely identifies which of those StateAttributes it was we're tracking.
* Not all StateSet features have been added yet - we implement an equivalently-named method to each of the StateSet
* methods called in createProgram, and implement new ones as they're needed.
* When expanding tracking to cover new things, ensure they're accounted for in ensureFFP.
*/
class AddedState : public osg::Object
{
public:
AddedState() = default;
AddedState(const AddedState& rhs, const osg::CopyOp& copyOp)
: osg::Object(rhs, copyOp)
, mUniforms(rhs.mUniforms)
, mModes(rhs.mModes)
, mAttributes(rhs.mAttributes)
, mTextureModes(rhs.mTextureModes)
{
}
void addUniform(const std::string& name) { mUniforms.emplace(name); }
void setMode(osg::StateAttribute::GLMode mode) { mModes.emplace(mode); }
void setAttribute(osg::StateAttribute::TypeMemberPair typeMemberPair) { mAttributes.emplace(typeMemberPair); }
void setAttribute(const osg::StateAttribute* attribute) { mAttributes.emplace(attribute->getTypeMemberPair()); }
template <typename T>
void setAttribute(osg::ref_ptr<T> attribute)
{
setAttribute(attribute.get());
}
void setAttributeAndModes(const osg::StateAttribute* attribute)
{
setAttribute(attribute);
InterrogateModesHelper helper(this);
attribute->getModeUsage(helper);
}
template <typename T>
void setAttributeAndModes(osg::ref_ptr<T> attribute)
{
setAttributeAndModes(attribute.get());
}
void setTextureMode(unsigned int unit, osg::StateAttribute::GLMode mode) { mTextureModes[unit].emplace(mode); }
void setTextureAttribute(int unit, osg::StateAttribute::TypeMemberPair typeMemberPair)
{
mTextureAttributes[unit].emplace(typeMemberPair);
}
void setTextureAttribute(unsigned int unit, const osg::StateAttribute* attribute)
{
mTextureAttributes[unit].emplace(attribute->getTypeMemberPair());
}
template <typename T>
void setTextureAttribute(unsigned int unit, osg::ref_ptr<T> attribute)
{
setTextureAttribute(unit, attribute.get());
}
void setTextureAttributeAndModes(unsigned int unit, const osg::StateAttribute* attribute)
{
setTextureAttribute(unit, attribute);
InterrogateModesHelper helper(this, unit);
attribute->getModeUsage(helper);
}
template <typename T>
void setTextureAttributeAndModes(unsigned int unit, osg::ref_ptr<T> attribute)
{
setTextureAttributeAndModes(unit, attribute.get());
}
bool hasUniform(const std::string& name) { return mUniforms.count(name); }
bool hasMode(osg::StateAttribute::GLMode mode) { return mModes.count(mode); }
bool hasAttribute(const osg::StateAttribute::TypeMemberPair& typeMemberPair)
{
return mAttributes.count(typeMemberPair);
}
bool hasAttribute(osg::StateAttribute::Type type, unsigned int member)
{
return hasAttribute(osg::StateAttribute::TypeMemberPair(type, member));
}
bool hasTextureMode(int unit, osg::StateAttribute::GLMode mode)
{
auto it = mTextureModes.find(unit);
if (it == mTextureModes.cend())
return false;
return it->second.count(mode);
}
const std::set<osg::StateAttribute::TypeMemberPair>& getAttributes() { return mAttributes; }
const std::unordered_map<unsigned int, std::set<osg::StateAttribute::TypeMemberPair>>& getTextureAttributes()
{
return mTextureAttributes;
}
bool empty()
{
return mUniforms.empty() && mModes.empty() && mAttributes.empty() && mTextureModes.empty()
&& mTextureAttributes.empty();
}
META_Object(Shader, AddedState)
private:
class InterrogateModesHelper : public osg::StateAttribute::ModeUsage
{
public:
InterrogateModesHelper(AddedState* tracker, unsigned int textureUnit = 0)
: mTracker(tracker)
, mTextureUnit(textureUnit)
{
}
void usesMode(osg::StateAttribute::GLMode mode) override { mTracker->setMode(mode); }
void usesTextureMode(osg::StateAttribute::GLMode mode) override
{
mTracker->setTextureMode(mTextureUnit, mode);
}
private:
AddedState* mTracker;
unsigned int mTextureUnit;
};
using ModeSet = std::unordered_set<osg::StateAttribute::GLMode>;
using AttributeSet = std::set<osg::StateAttribute::TypeMemberPair>;
std::unordered_set<std::string> mUniforms;
ModeSet mModes;
AttributeSet mAttributes;
std::unordered_map<unsigned int, ModeSet> mTextureModes;
std::unordered_map<unsigned int, AttributeSet> mTextureAttributes;
};
ShaderVisitor::ShaderRequirements::ShaderRequirements()
: mShaderRequired(false)
, mColorMode(0)
, mMaterialOverridden(false)
, mAlphaTestOverridden(false)
, mAlphaBlendOverridden(false)
, mAlphaFunc(GL_ALWAYS)
, mAlphaRef(1.0)
, mAlphaBlend(false)
, mBlendFuncOverridden(false)
, mAdditiveBlending(false)
, mDiffuseHeight(false)
, mNormalHeight(false)
, mReconstructNormalZ(false)
, mTexStageRequiringTangents(-1)
, mSoftParticles(false)
, mNode(nullptr)
{
}
ShaderVisitor::ShaderVisitor(
ShaderManager& shaderManager, Resource::ImageManager& imageManager, const std::string& defaultShaderPrefix)
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mForceShaders(false)
, mAllowedToModifyStateSets(true)
, mAutoUseNormalMaps(false)
, mAutoUseSpecularMaps(false)
, mApplyLightingToEnvMaps(false)
, mConvertAlphaTestToAlphaToCoverage(false)
, mAdjustCoverageForAlphaTest(false)
, mSupportsNormalsRT(false)
, mShaderManager(shaderManager)
, mImageManager(imageManager)
, mDefaultShaderPrefix(defaultShaderPrefix)
{
}
void ShaderVisitor::setForceShaders(bool force)
{
mForceShaders = force;
}
void ShaderVisitor::apply(osg::Node& node)
{
bool needPop = false;
if (node.getStateSet() || mRequirements.empty())
{
needPop = true;
pushRequirements(node);
if (node.getStateSet())
applyStateSet(node.getStateSet(), node);
}
traverse(node);
if (needPop)
popRequirements();
}
osg::StateSet* getWritableStateSet(osg::Node& node)
{
if (!node.getStateSet())
return node.getOrCreateStateSet();
osg::ref_ptr<osg::StateSet> newStateSet = new osg::StateSet(*node.getStateSet(), osg::CopyOp::SHALLOW_COPY);
node.setStateSet(newStateSet);
return newStateSet.get();
}
osg::UserDataContainer* getWritableUserDataContainer(osg::Object& object)
{
if (!object.getUserDataContainer())
return object.getOrCreateUserDataContainer();
osg::ref_ptr<osg::UserDataContainer> newUserData
= static_cast<osg::UserDataContainer*>(object.getUserDataContainer()->clone(osg::CopyOp::SHALLOW_COPY));
object.setUserDataContainer(newUserData);
return newUserData.get();
}
osg::StateSet* getRemovedState(osg::StateSet& stateSet)
{
if (!stateSet.getUserDataContainer())
return nullptr;
return static_cast<osg::StateSet*>(stateSet.getUserDataContainer()->getUserObject("removedState"));
}
void updateRemovedState(osg::UserDataContainer& userData, osg::StateSet* removedState)
{
unsigned int index = userData.getUserObjectIndex("removedState");
if (index < userData.getNumUserObjects())
userData.setUserObject(index, removedState);
else
userData.addUserObject(removedState);
removedState->setName("removedState");
}
AddedState* getAddedState(osg::StateSet& stateSet)
{
if (!stateSet.getUserDataContainer())
return nullptr;
return static_cast<AddedState*>(stateSet.getUserDataContainer()->getUserObject("addedState"));
}
void updateAddedState(osg::UserDataContainer& userData, AddedState* addedState)
{
unsigned int index = userData.getUserObjectIndex("addedState");
if (index < userData.getNumUserObjects())
userData.setUserObject(index, addedState);
else
userData.addUserObject(addedState);
addedState->setName("addedState");
}
const char* defaultTextures[] = { "diffuseMap", "normalMap", "emissiveMap", "darkMap", "detailMap", "envMap",
"specularMap", "decalMap", "bumpMap", "glossMap" };
bool isTextureNameRecognized(std::string_view name)
{
return std::find(std::begin(defaultTextures), std::end(defaultTextures), name) != std::end(defaultTextures);
}
void ShaderVisitor::applyStateSet(osg::ref_ptr<osg::StateSet> stateset, osg::Node& node)
{
osg::StateSet* writableStateSet = nullptr;
if (mAllowedToModifyStateSets)
writableStateSet = node.getStateSet();
const osg::StateSet::TextureAttributeList& texAttributes = stateset->getTextureAttributeList();
bool shaderRequired = false;
if (node.getUserValue("shaderRequired", shaderRequired) && shaderRequired)
mRequirements.back().mShaderRequired = true;
bool softEffect = false;
if (node.getUserValue(Misc::OsgUserValues::sXSoftEffect, softEffect) && softEffect)
mRequirements.back().mSoftParticles = true;
// Make sure to disregard any state that came from a previous call to createProgram
osg::ref_ptr<AddedState> addedState = getAddedState(*stateset);
if (!texAttributes.empty())
{
const osg::Texture* diffuseMap = nullptr;
const osg::Texture* normalMap = nullptr;
const osg::Texture* specularMap = nullptr;
const osg::Texture* bumpMap = nullptr;
for (unsigned int unit = 0; unit < texAttributes.size(); ++unit)
{
const osg::StateAttribute* attr = stateset->getTextureAttribute(unit, osg::StateAttribute::TEXTURE);
if (attr)
{
// If textures ever get removed in createProgram, expand this to check we're operating on main
// texture attribute list rather than the removed list
if (addedState && addedState->hasTextureMode(unit, GL_TEXTURE_2D))
continue;
const osg::Texture* texture = attr->asTexture();
if (texture)
{
std::string texName = SceneUtil::getTextureType(*stateset, *texture, unit);
if ((texName.empty() || !isTextureNameRecognized(texName)) && unit == 0)
texName = "diffuseMap";
if (texName == "normalHeightMap")
{
mRequirements.back().mNormalHeight = true;
texName = "normalMap";
}
if (!texName.empty())
{
mRequirements.back().mTextures[unit] = texName;
if (texName == "normalMap")
{
mRequirements.back().mTexStageRequiringTangents = unit;
mRequirements.back().mShaderRequired = true;
if (!writableStateSet)
writableStateSet = getWritableStateSet(node);
// normal maps are by default off since the FFP can't render them, now that we'll use
// shaders switch to On
writableStateSet->setTextureMode(unit, GL_TEXTURE_2D, osg::StateAttribute::ON);
normalMap = texture;
}
else if (texName == "diffuseMap")
{
int applyMode;
// Oblivion parallax
if (node.getUserValue("applyMode", applyMode) && applyMode == 4)
{
mRequirements.back().mShaderRequired = true;
mRequirements.back().mDiffuseHeight = true;
mRequirements.back().mTexStageRequiringTangents = unit;
}
diffuseMap = texture;
}
else if (texName == "specularMap")
specularMap = texture;
else if (texName == "bumpMap")
{
bumpMap = texture;
mRequirements.back().mShaderRequired = true;
if (!writableStateSet)
writableStateSet = getWritableStateSet(node);
// Bump maps are off by default as well
writableStateSet->setTextureMode(unit, GL_TEXTURE_2D, osg::StateAttribute::ON);
}
else if (texName == "envMap" && mApplyLightingToEnvMaps)
{
mRequirements.back().mShaderRequired = true;
}
else if (texName == "glossMap")
{
mRequirements.back().mShaderRequired = true;
if (!writableStateSet)
writableStateSet = getWritableStateSet(node);
// As well as gloss maps
writableStateSet->setTextureMode(unit, GL_TEXTURE_2D, osg::StateAttribute::ON);
}
}
else
Log(Debug::Error) << "ShaderVisitor encountered unknown texture " << texture;
}
}
}
if (mAutoUseNormalMaps && diffuseMap != nullptr && normalMap == nullptr && diffuseMap->getImage(0))
{
std::string normalMapFileName = diffuseMap->getImage(0)->getFileName();
osg::ref_ptr<osg::Image> image;
bool normalHeight = false;
std::string normalHeightMap = normalMapFileName;
Misc::StringUtils::replaceLast(normalHeightMap, ".", mNormalHeightMapPattern + ".");
const VFS::Path::Normalized normalHeightMapPath(normalHeightMap);
if (mImageManager.getVFS()->exists(normalHeightMapPath))
{
image = mImageManager.getImage(normalHeightMapPath);
normalHeight = true;
}
else
{
Misc::StringUtils::replaceLast(normalMapFileName, ".", mNormalMapPattern + ".");
const VFS::Path::Normalized normalMapPath(normalMapFileName);
if (mImageManager.getVFS()->exists(normalMapPath))
{
image = mImageManager.getImage(normalMapPath);
}
}
// Avoid using the auto-detected normal map if it's already being used as a bump map.
// It's probably not an actual normal map.
bool hasNamesakeBumpMap = image && bumpMap && bumpMap->getImage(0)
&& image->getFileName() == bumpMap->getImage(0)->getFileName();
if (!hasNamesakeBumpMap && image)
{
osg::ref_ptr<osg::Texture2D> normalMapTex(new osg::Texture2D(image));
normalMapTex->setTextureSize(image->s(), image->t());
normalMapTex->setWrap(osg::Texture::WRAP_S, diffuseMap->getWrap(osg::Texture::WRAP_S));
normalMapTex->setWrap(osg::Texture::WRAP_T, diffuseMap->getWrap(osg::Texture::WRAP_T));
normalMapTex->setFilter(osg::Texture::MIN_FILTER, diffuseMap->getFilter(osg::Texture::MIN_FILTER));
normalMapTex->setFilter(osg::Texture::MAG_FILTER, diffuseMap->getFilter(osg::Texture::MAG_FILTER));
normalMapTex->setMaxAnisotropy(diffuseMap->getMaxAnisotropy());
normalMap = normalMapTex;
int unit = texAttributes.size();
if (!writableStateSet)
writableStateSet = getWritableStateSet(node);
writableStateSet->setTextureAttributeAndModes(unit, normalMapTex, osg::StateAttribute::ON);
writableStateSet->setTextureAttributeAndModes(
unit, new SceneUtil::TextureType("normalMap"), osg::StateAttribute::ON);
mRequirements.back().mTextures[unit] = "normalMap";
mRequirements.back().mTexStageRequiringTangents = unit;
mRequirements.back().mShaderRequired = true;
mRequirements.back().mNormalHeight = normalHeight;
}
}
if (normalMap != nullptr && normalMap->getImage(0))
{
// Special handling for red-green normal maps (e.g. BC5 or R8G8)
switch (SceneUtil::computeUnsizedPixelFormat(normalMap->getImage(0)->getPixelFormat()))
{
case GL_RG:
case GL_RG_INTEGER:
{
mRequirements.back().mReconstructNormalZ = true;
mRequirements.back().mNormalHeight = false;
}
}
}
if (mAutoUseSpecularMaps && diffuseMap != nullptr && specularMap == nullptr && diffuseMap->getImage(0))
{
std::string specularMapFileName = diffuseMap->getImage(0)->getFileName();
Misc::StringUtils::replaceLast(specularMapFileName, ".", mSpecularMapPattern + ".");
const VFS::Path::Normalized specularMapPath(specularMapFileName);
if (mImageManager.getVFS()->exists(specularMapPath))
{
osg::ref_ptr<osg::Image> image(mImageManager.getImage(specularMapPath));
osg::ref_ptr<osg::Texture2D> specularMapTex(new osg::Texture2D(image));
specularMapTex->setTextureSize(image->s(), image->t());
specularMapTex->setWrap(osg::Texture::WRAP_S, diffuseMap->getWrap(osg::Texture::WRAP_S));
specularMapTex->setWrap(osg::Texture::WRAP_T, diffuseMap->getWrap(osg::Texture::WRAP_T));
specularMapTex->setFilter(
osg::Texture::MIN_FILTER, diffuseMap->getFilter(osg::Texture::MIN_FILTER));
specularMapTex->setFilter(
osg::Texture::MAG_FILTER, diffuseMap->getFilter(osg::Texture::MAG_FILTER));
specularMapTex->setMaxAnisotropy(diffuseMap->getMaxAnisotropy());
int unit = texAttributes.size();
if (!writableStateSet)
writableStateSet = getWritableStateSet(node);
writableStateSet->setTextureAttributeAndModes(unit, specularMapTex, osg::StateAttribute::ON);
writableStateSet->setTextureAttributeAndModes(
unit, new SceneUtil::TextureType("specularMap"), osg::StateAttribute::ON);
mRequirements.back().mTextures[unit] = "specularMap";
mRequirements.back().mShaderRequired = true;
}
}
}
const osg::StateSet::AttributeList& attributes = stateset->getAttributeList();
osg::StateSet::AttributeList removedAttributes;
if (osg::ref_ptr<osg::StateSet> removedState = getRemovedState(*stateset))
removedAttributes = removedState->getAttributeList();
for (const auto* attributeMap :
std::initializer_list<const osg::StateSet::AttributeList*>{ &attributes, &removedAttributes })
{
for (osg::StateSet::AttributeList::const_iterator it = attributeMap->begin(); it != attributeMap->end();
++it)
{
if (addedState && attributeMap != &removedAttributes && addedState->hasAttribute(it->first))
continue;
if (it->first.first == osg::StateAttribute::MATERIAL)
{
// This should probably be moved out of ShaderRequirements and be applied directly now it's a
// uniform instead of a define
if (!mRequirements.back().mMaterialOverridden || it->second.second & osg::StateAttribute::PROTECTED)
{
if (it->second.second & osg::StateAttribute::OVERRIDE)
mRequirements.back().mMaterialOverridden = true;
const osg::Material* mat = static_cast<const osg::Material*>(it->second.first.get());
int colorMode;
switch (mat->getColorMode())
{
case osg::Material::OFF:
colorMode = 0;
break;
case osg::Material::EMISSION:
colorMode = 1;
break;
default:
case osg::Material::AMBIENT_AND_DIFFUSE:
colorMode = 2;
break;
case osg::Material::AMBIENT:
colorMode = 3;
break;
case osg::Material::DIFFUSE:
colorMode = 4;
break;
case osg::Material::SPECULAR:
colorMode = 5;
break;
}
mRequirements.back().mColorMode = colorMode;
}
}
else if (it->first.first == osg::StateAttribute::ALPHAFUNC)
{
if (!mRequirements.back().mAlphaTestOverridden
|| it->second.second & osg::StateAttribute::PROTECTED)
{
if (it->second.second & osg::StateAttribute::OVERRIDE)
mRequirements.back().mAlphaTestOverridden = true;
const osg::AlphaFunc* alpha = static_cast<const osg::AlphaFunc*>(it->second.first.get());
mRequirements.back().mAlphaFunc = alpha->getFunction();
mRequirements.back().mAlphaRef = alpha->getReferenceValue();
}
}
else if (it->first.first == osg::StateAttribute::BLENDFUNC)
{
if (!mRequirements.back().mBlendFuncOverridden
|| it->second.second & osg::StateAttribute::PROTECTED)
{
if (it->second.second & osg::StateAttribute::OVERRIDE)
mRequirements.back().mBlendFuncOverridden = true;
const osg::BlendFunc* blend = static_cast<const osg::BlendFunc*>(it->second.first.get());
mRequirements.back().mAdditiveBlending = blend->getSource() == osg::BlendFunc::SRC_ALPHA
&& blend->getDestination() == osg::BlendFunc::ONE;
}
}
}
}
unsigned int alphaBlend = stateset->getMode(GL_BLEND);
if (alphaBlend != osg::StateAttribute::INHERIT
&& (!mRequirements.back().mAlphaBlendOverridden || alphaBlend & osg::StateAttribute::PROTECTED))
{
if (alphaBlend & osg::StateAttribute::OVERRIDE)
mRequirements.back().mAlphaBlendOverridden = true;
mRequirements.back().mAlphaBlend = alphaBlend & osg::StateAttribute::ON;
}
}
void ShaderVisitor::pushRequirements(osg::Node& node)
{
if (mRequirements.empty())
mRequirements.emplace_back();
else
mRequirements.push_back(mRequirements.back());
mRequirements.back().mNode = &node;
}
void ShaderVisitor::popRequirements()
{
mRequirements.pop_back();
}
void ShaderVisitor::createProgram(const ShaderRequirements& reqs)
{
if (!reqs.mShaderRequired && !mForceShaders)
{
ensureFFP(*reqs.mNode);
return;
}
/**
* The shader visitor is supposed to be idempotent and undoable.
* That means we need to back up state we've removed (so it can be restored and/or considered by further
* applications of the visitor) and track which state we added (so it can be removed and/or ignored by further
* applications of the visitor).
* Before editing writableStateSet in a way that explicitly removes state or might overwrite existing state, it
* should be copied to removedState, another StateSet, unless it's there already or was added by a previous
* application of the visitor (is in previousAddedState).
* If it's a new class of state that's not already handled by ReinstateRemovedStateVisitor::apply, make sure to
* add handling there.
* Similarly, any time new state is added to writableStateSet, the equivalent method should be called on
* addedState.
* If that method doesn't exist yet, implement it - we don't use a full StateSet as we only need to check
* existence, not equality, and don't need to actually get the value as we can get it from writableStateSet
* instead.
*/
osg::Node& node = *reqs.mNode;
osg::StateSet* writableStateSet = nullptr;
if (mAllowedToModifyStateSets)
writableStateSet = node.getOrCreateStateSet();
else
writableStateSet = getWritableStateSet(node);
osg::ref_ptr<AddedState> addedState = new AddedState;
osg::ref_ptr<AddedState> previousAddedState = getAddedState(*writableStateSet);
if (!previousAddedState)
previousAddedState = new AddedState;
ShaderManager::DefineMap defineMap;
for (unsigned int i = 0; i < sizeof(defaultTextures) / sizeof(defaultTextures[0]); ++i)
{
defineMap[defaultTextures[i]] = "0";
defineMap[std::string(defaultTextures[i]) + std::string("UV")] = "0";
}
for (std::map<int, std::string>::const_iterator texIt = reqs.mTextures.begin(); texIt != reqs.mTextures.end();
++texIt)
{
defineMap[texIt->second] = "1";
defineMap[texIt->second + std::string("UV")] = std::to_string(texIt->first);
}
if (defineMap["diffuseMap"] == "0")
{
writableStateSet->addUniform(new osg::Uniform("useDiffuseMapForShadowAlpha", false));
addedState->addUniform("useDiffuseMapForShadowAlpha");
}
defineMap["diffuseParallax"] = reqs.mDiffuseHeight ? "1" : "0";
defineMap["parallax"] = reqs.mNormalHeight ? "1" : "0";
defineMap["reconstructNormalZ"] = reqs.mReconstructNormalZ ? "1" : "0";
writableStateSet->addUniform(new osg::Uniform("colorMode", reqs.mColorMode));
addedState->addUniform("colorMode");
defineMap["alphaFunc"] = std::to_string(reqs.mAlphaFunc);
defineMap["additiveBlending"] = reqs.mAdditiveBlending ? "1" : "0";
osg::ref_ptr<osg::StateSet> removedState;
if ((removedState = getRemovedState(*writableStateSet)) && !mAllowedToModifyStateSets)
removedState = new osg::StateSet(*removedState, osg::CopyOp::SHALLOW_COPY);
if (!removedState)
removedState = new osg::StateSet();
defineMap["alphaToCoverage"] = "0";
defineMap["adjustCoverage"] = "0";
if (reqs.mAlphaFunc != osg::AlphaFunc::ALWAYS)
{
writableStateSet->addUniform(new osg::Uniform("alphaRef", reqs.mAlphaRef));
addedState->addUniform("alphaRef");
if (!removedState->getAttributePair(osg::StateAttribute::ALPHAFUNC))
{
const auto* alphaFunc = writableStateSet->getAttributePair(osg::StateAttribute::ALPHAFUNC);
if (alphaFunc && !previousAddedState->hasAttribute(osg::StateAttribute::ALPHAFUNC, 0))
removedState->setAttribute(alphaFunc->first, alphaFunc->second);
}
// This prevents redundant glAlphaFunc calls while letting the shadows bin still see the test
writableStateSet->setAttribute(RemovedAlphaFunc::getInstance(reqs.mAlphaFunc),
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
addedState->setAttribute(RemovedAlphaFunc::getInstance(reqs.mAlphaFunc));
// Blending won't work with A2C as we use the alpha channel for coverage. gl_SampleCoverage from
// ARB_sample_shading would save the day, but requires GLSL 130
if (mConvertAlphaTestToAlphaToCoverage && !reqs.mAlphaBlend)
{
writableStateSet->setMode(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB, osg::StateAttribute::ON);
addedState->setMode(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
defineMap["alphaToCoverage"] = "1";
}
// Adjusting coverage isn't safe with blending on as blending requires the alpha to be intact.
// Maybe we could also somehow (e.g. userdata) detect when the diffuse map has coverage-preserving mip maps
// in the future
if (mAdjustCoverageForAlphaTest && !reqs.mAlphaBlend)
defineMap["adjustCoverage"] = "1";
// Preventing alpha tested stuff shrinking as lower mip levels are used requires knowing the texture size
if (SceneUtil::getGLExtensions().isGpuShader4Supported)
defineMap["useGPUShader4"] = "1";
// We could fall back to a texture size uniform if EXT_gpu_shader4 is missing
}
bool simpleLighting = false;
node.getUserValue("simpleLighting", simpleLighting);
if (simpleLighting)
defineMap["endLight"] = "0";
if (simpleLighting || dynamic_cast<osgParticle::ParticleSystem*>(&node))
defineMap["forcePPL"] = "0";
bool particleOcclusion = false;
node.getUserValue("particleOcclusion", particleOcclusion);
defineMap["particleOcclusion"] = particleOcclusion && mWeatherParticleOcclusion ? "1" : "0";
if (reqs.mAlphaBlend && mSupportsNormalsRT)
{
if (reqs.mSoftParticles)
defineMap["disableNormals"] = "1";
auto colorMask = new osg::ColorMaski(1, false, false, false, false);
writableStateSet->setAttribute(colorMask);
addedState->setAttribute(colorMask);
}
if (reqs.mSoftParticles)
{
const int unitSoftEffect
= mShaderManager.reserveGlobalTextureUnits(Shader::ShaderManager::Slot::OpaqueDepthTexture);
writableStateSet->addUniform(new osg::Uniform("opaqueDepthTex", unitSoftEffect));
addedState->addUniform("opaqueDepthTex");
}
if (writableStateSet->getMode(GL_ALPHA_TEST) != osg::StateAttribute::INHERIT
&& !previousAddedState->hasMode(GL_ALPHA_TEST))
removedState->setMode(GL_ALPHA_TEST, writableStateSet->getMode(GL_ALPHA_TEST));
// This disables the deprecated fixed-function alpha test
writableStateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
addedState->setMode(GL_ALPHA_TEST);
if (!removedState->getModeList().empty() || !removedState->getAttributeList().empty())
{
// user data is normally shallow copied so shared with the original stateset
osg::ref_ptr<osg::UserDataContainer> writableUserData;
if (mAllowedToModifyStateSets)
writableUserData = writableStateSet->getOrCreateUserDataContainer();
else
writableUserData = getWritableUserDataContainer(*writableStateSet);
updateRemovedState(*writableUserData, removedState);
}
defineMap["softParticles"] = reqs.mSoftParticles ? "1" : "0";
Stereo::shaderStereoDefines(defineMap);
std::string shaderPrefix;
if (!node.getUserValue("shaderPrefix", shaderPrefix))
shaderPrefix = mDefaultShaderPrefix;
auto program = mShaderManager.getProgram(shaderPrefix, defineMap, mProgramTemplate);
writableStateSet->setAttributeAndModes(program, osg::StateAttribute::ON);
addedState->setAttributeAndModes(std::move(program));
for (const auto& [unit, name] : reqs.mTextures)
{
writableStateSet->addUniform(new osg::Uniform(name.c_str(), unit), osg::StateAttribute::ON);
addedState->addUniform(name);
}
if (!addedState->empty())
{
// user data is normally shallow copied so shared with the original stateset
osg::ref_ptr<osg::UserDataContainer> writableUserData;
if (mAllowedToModifyStateSets)
writableUserData = writableStateSet->getOrCreateUserDataContainer();
else
writableUserData = getWritableUserDataContainer(*writableStateSet);
updateAddedState(*writableUserData, addedState);
}
}
void ShaderVisitor::ensureFFP(osg::Node& node)
{
if (!node.getStateSet() || !node.getStateSet()->getAttribute(osg::StateAttribute::PROGRAM))
return;
osg::StateSet* writableStateSet = nullptr;
if (mAllowedToModifyStateSets)
writableStateSet = node.getStateSet();
else
writableStateSet = getWritableStateSet(node);
/**
* We might have been using shaders temporarily with the node (e.g. if a GlowUpdater applied a temporary
* environment map for a temporary enchantment).
* We therefore need to remove any state doing so added, and restore any that it removed.
* This is kept track of in createProgram in the StateSet's userdata.
* If new classes of state get added, handling it here is required - not all StateSet features are implemented
* in AddedState yet as so far they've not been necessary.
* Removed state requires no particular special handling as it's dealt with by merging StateSets.
* We don't need to worry about state in writableStateSet having the OVERRIDE flag as if it's in both, it's also
* in addedState, and gets removed first.
*/
// user data is normally shallow copied so shared with the original stateset - we'll need to copy before edits
osg::ref_ptr<osg::UserDataContainer> writableUserData;
if (osg::ref_ptr<AddedState> addedState = getAddedState(*writableStateSet))
{
if (mAllowedToModifyStateSets)
writableUserData = writableStateSet->getUserDataContainer();
else
writableUserData = getWritableUserDataContainer(*writableStateSet);
unsigned int index = writableUserData->getUserObjectIndex("addedState");
writableUserData->removeUserObject(index);
// O(n log n) to use StateSet::removeX, but this is O(n)
for (auto itr = writableStateSet->getUniformList().begin();
itr != writableStateSet->getUniformList().end();)
{
if (addedState->hasUniform(itr->first))
writableStateSet->getUniformList().erase(itr++);
else
++itr;
}
for (auto itr = writableStateSet->getModeList().begin(); itr != writableStateSet->getModeList().end();)
{
if (addedState->hasMode(itr->first))
writableStateSet->getModeList().erase(itr++);
else
++itr;
}
// StateAttributes track the StateSets they're attached to
// We don't have access to the function to do that, and can't call removeAttribute with an iterator
for (const auto& [type, member] : addedState->getAttributes())
writableStateSet->removeAttribute(type, member);
for (unsigned int unit = 0; unit < writableStateSet->getTextureModeList().size(); ++unit)
{
for (auto itr = writableStateSet->getTextureModeList()[unit].begin();
itr != writableStateSet->getTextureModeList()[unit].end();)
{
if (addedState->hasTextureMode(unit, itr->first))
writableStateSet->getTextureModeList()[unit].erase(itr++);
else
++itr;
}
}
for (const auto& [unit, attributeList] : addedState->getTextureAttributes())
{
for (const auto& [type, member] : attributeList)
writableStateSet->removeTextureAttribute(unit, type);
}
}
if (osg::ref_ptr<osg::StateSet> removedState = getRemovedState(*writableStateSet))
{
if (!writableUserData)
{
if (mAllowedToModifyStateSets)
writableUserData = writableStateSet->getUserDataContainer();
else
writableUserData = getWritableUserDataContainer(*writableStateSet);
}
unsigned int index = writableUserData->getUserObjectIndex("removedState");
writableUserData->removeUserObject(index);
writableStateSet->merge(*removedState);
}
}
bool ShaderVisitor::adjustGeometry(osg::Geometry& sourceGeometry, const ShaderRequirements& reqs)
{
bool useShader = reqs.mShaderRequired || mForceShaders;
bool generateTangents = reqs.mTexStageRequiringTangents != -1;
bool changed = false;
if (mAllowedToModifyStateSets && (useShader || generateTangents))
{
// make sure that all UV sets are there
// it's not safe to assume there's one for slot zero, so try and use one from another slot if possible
// if there are none at all, bail.
// the TangentSpaceGenerator would bail, but getTangentArray would give an empty array, which is enough to
// bypass null checks, but feeds the driver a bad pointer
if (sourceGeometry.getTexCoordArray(0) == nullptr)
{
for (const auto& array : sourceGeometry.getTexCoordArrayList())
{
if (array)
{
sourceGeometry.setTexCoordArray(0, array);
break;
}
}
if (sourceGeometry.getTexCoordArray(0) == nullptr)
return changed;
}
for (const auto& [unit, name] : reqs.mTextures)
{
if (sourceGeometry.getTexCoordArray(unit) == nullptr)
{
sourceGeometry.setTexCoordArray(unit, sourceGeometry.getTexCoordArray(0));
changed = true;
}
}
if (generateTangents)
{
osg::ref_ptr<osgUtil::TangentSpaceGenerator> generator(new osgUtil::TangentSpaceGenerator);
generator->generate(&sourceGeometry, reqs.mTexStageRequiringTangents);
sourceGeometry.setTexCoordArray(7, generator->getTangentArray(), osg::Array::BIND_PER_VERTEX);
changed = true;
}
}
return changed;
}
void ShaderVisitor::apply(osg::Geometry& geometry)
{
bool needPop = geometry.getStateSet() || mRequirements.empty();
if (needPop)
pushRequirements(geometry);
if (geometry.getStateSet()) // TODO: check if stateset affects shader permutation before pushing it
applyStateSet(geometry.getStateSet(), geometry);
if (!mRequirements.empty())
{
const ShaderRequirements& reqs = mRequirements.back();
adjustGeometry(geometry, reqs);
createProgram(reqs);
}
else
ensureFFP(geometry);
if (needPop)
popRequirements();
}
void ShaderVisitor::apply(osg::Drawable& drawable)
{
bool needPop = drawable.getStateSet() || mRequirements.empty();
// We need to push and pop a requirements object because particle systems can have
// different shader requirements to other drawables, so might need a different shader variant.
if (!needPop && dynamic_cast<osgParticle::ParticleSystem*>(&drawable))
needPop = true;
if (needPop)
{
pushRequirements(drawable);
if (drawable.getStateSet())
applyStateSet(drawable.getStateSet(), drawable);
}
const ShaderRequirements& reqs = mRequirements.back();
createProgram(reqs);
if (auto rig = dynamic_cast<SceneUtil::RigGeometry*>(&drawable))
{
osg::ref_ptr<osg::Geometry> sourceGeometry = rig->getSourceGeometry();
if (sourceGeometry && adjustGeometry(*sourceGeometry, reqs))
rig->setSourceGeometry(std::move(sourceGeometry));
}
else if (auto morph = dynamic_cast<SceneUtil::MorphGeometry*>(&drawable))
{
osg::ref_ptr<osg::Geometry> sourceGeometry = morph->getSourceGeometry();
if (sourceGeometry && adjustGeometry(*sourceGeometry, reqs))
morph->setSourceGeometry(std::move(sourceGeometry));
}
else if (auto osgaRig = dynamic_cast<SceneUtil::RigGeometryHolder*>(&drawable))
{
osg::ref_ptr<SceneUtil::OsgaRigGeometry> sourceOsgaRigGeometry = osgaRig->getSourceRigGeometry();
osg::ref_ptr<osg::Geometry> sourceGeometry = sourceOsgaRigGeometry->getSourceGeometry();
if (sourceGeometry && adjustGeometry(*sourceGeometry, reqs))
{
sourceOsgaRigGeometry->setSourceGeometry(std::move(sourceGeometry));
osgaRig->setSourceRigGeometry(std::move(sourceOsgaRigGeometry));
}
}
if (needPop)
popRequirements();
}
void ShaderVisitor::setAllowedToModifyStateSets(bool allowed)
{
mAllowedToModifyStateSets = allowed;
}
void ShaderVisitor::setAutoUseNormalMaps(bool use)
{
mAutoUseNormalMaps = use;
}
void ShaderVisitor::setNormalMapPattern(const std::string& pattern)
{
mNormalMapPattern = pattern;
}
void ShaderVisitor::setNormalHeightMapPattern(const std::string& pattern)
{
mNormalHeightMapPattern = pattern;
}
void ShaderVisitor::setAutoUseSpecularMaps(bool use)
{
mAutoUseSpecularMaps = use;
}
void ShaderVisitor::setSpecularMapPattern(const std::string& pattern)
{
mSpecularMapPattern = pattern;
}
void ShaderVisitor::setApplyLightingToEnvMaps(bool apply)
{
mApplyLightingToEnvMaps = apply;
}
void ShaderVisitor::setConvertAlphaTestToAlphaToCoverage(bool convert)
{
mConvertAlphaTestToAlphaToCoverage = convert;
}
void ShaderVisitor::setAdjustCoverageForAlphaTest(bool adjustCoverage)
{
mAdjustCoverageForAlphaTest = adjustCoverage;
}
ReinstateRemovedStateVisitor::ReinstateRemovedStateVisitor(bool allowedToModifyStateSets)
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mAllowedToModifyStateSets(allowedToModifyStateSets)
{
}
void ReinstateRemovedStateVisitor::apply(osg::Node& node)
{
// TODO: this may eventually need to remove added state.
// If so, we can migrate from explicitly copying removed state to just calling osg::StateSet::merge.
// Not everything is transferred from removedState yet - implement more when createProgram starts marking more
// as removed.
if (node.getStateSet())
{
osg::ref_ptr<osg::StateSet> removedState = getRemovedState(*node.getStateSet());
if (removedState)
{
osg::ref_ptr<osg::StateSet> writableStateSet;
if (mAllowedToModifyStateSets)
writableStateSet = node.getStateSet();
else
writableStateSet = getWritableStateSet(node);
// user data is normally shallow copied so shared with the original stateset
osg::ref_ptr<osg::UserDataContainer> writableUserData;
if (mAllowedToModifyStateSets)
writableUserData = writableStateSet->getUserDataContainer();
else
writableUserData = getWritableUserDataContainer(*writableStateSet);
unsigned int index = writableUserData->getUserObjectIndex("removedState");
writableUserData->removeUserObject(index);
for (const auto& [mode, value] : removedState->getModeList())
writableStateSet->setMode(mode, value);
for (const auto& attribute : removedState->getAttributeList())
writableStateSet->setAttribute(attribute.second.first, attribute.second.second);
for (unsigned int unit = 0; unit < removedState->getTextureModeList().size(); ++unit)
{
for (const auto& [mode, value] : removedState->getTextureModeList()[unit])
writableStateSet->setTextureMode(unit, mode, value);
}
}
}
traverse(node);
}
}
| 48,616
|
C++
|
.cpp
| 957
| 37.110763
| 120
| 0.597285
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,713
|
shadow.cpp
|
OpenMW_openmw/components/sceneutil/shadow.cpp
|
#include "shadow.hpp"
#include <osgShadow/ShadowSettings>
#include <osgShadow/ShadowedScene>
#include <components/misc/strings/algorithm.hpp>
#include <components/settings/categories/shadows.hpp>
#include <components/stereo/stereomanager.hpp>
#include "mwshadowtechnique.hpp"
namespace SceneUtil
{
using namespace osgShadow;
ShadowManager* ShadowManager::sInstance = nullptr;
const ShadowManager& ShadowManager::instance()
{
if (sInstance)
return *sInstance;
else
throw std::logic_error("No ShadowManager exists yet");
}
void ShadowManager::setupShadowSettings(
const Settings::ShadowsCategory& settings, Shader::ShaderManager& shaderManager)
{
mEnableShadows = settings.mEnableShadows;
if (!mEnableShadows)
{
mShadowTechnique->disableShadows();
return;
}
mShadowTechnique->enableShadows();
mShadowSettings->setLightNum(0);
mShadowSettings->setReceivesShadowTraversalMask(~0u);
const int numberOfShadowMapsPerLight = settings.mNumberOfShadowMaps;
mShadowSettings->setNumShadowMapsPerLight(numberOfShadowMapsPerLight);
mShadowSettings->setBaseShadowTextureUnit(shaderManager.reserveGlobalTextureUnits(
Shader::ShaderManager::Slot::ShadowMaps, numberOfShadowMapsPerLight));
const float maximumShadowMapDistance = settings.mMaximumShadowMapDistance;
if (maximumShadowMapDistance > 0)
{
const float shadowFadeStart = settings.mShadowFadeStart;
mShadowSettings->setMaximumShadowMapDistance(maximumShadowMapDistance);
mShadowTechnique->setShadowFadeStart(maximumShadowMapDistance * shadowFadeStart);
}
mShadowSettings->setMinimumShadowMapNearFarRatio(settings.mMinimumLispsmNearFarRatio);
const std::string& computeSceneBounds = settings.mComputeSceneBounds;
if (Misc::StringUtils::ciEqual(computeSceneBounds, "primitives"))
mShadowSettings->setComputeNearFarModeOverride(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
else if (Misc::StringUtils::ciEqual(computeSceneBounds, "bounds"))
mShadowSettings->setComputeNearFarModeOverride(osg::CullSettings::COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES);
const int mapres = settings.mShadowMapResolution;
mShadowSettings->setTextureSize(osg::Vec2s(mapres, mapres));
mShadowTechnique->setSplitPointUniformLogarithmicRatio(settings.mSplitPointUniformLogarithmicRatio);
mShadowTechnique->setSplitPointDeltaBias(settings.mSplitPointBias);
mShadowTechnique->setPolygonOffset(settings.mPolygonOffsetFactor, settings.mPolygonOffsetUnits);
if (settings.mUseFrontFaceCulling)
mShadowTechnique->enableFrontFaceCulling();
else
mShadowTechnique->disableFrontFaceCulling();
mShadowSettings->setMultipleShadowMapHint(osgShadow::ShadowSettings::CASCADED);
if (settings.mEnableDebugHud)
mShadowTechnique->enableDebugHUD();
else
mShadowTechnique->disableDebugHUD();
}
void ShadowManager::disableShadowsForStateSet(osg::StateSet& stateset) const
{
if (!mEnableShadows)
return;
osg::ref_ptr<osg::Image> fakeShadowMapImage = new osg::Image();
fakeShadowMapImage->allocateImage(1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT);
*(float*)fakeShadowMapImage->data() = std::numeric_limits<float>::infinity();
osg::ref_ptr<osg::Texture> fakeShadowMapTexture = new osg::Texture2D(fakeShadowMapImage);
fakeShadowMapTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
fakeShadowMapTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
fakeShadowMapTexture->setShadowComparison(true);
fakeShadowMapTexture->setShadowCompareFunc(osg::Texture::ShadowCompareFunc::ALWAYS);
for (unsigned int i = mShadowSettings->getBaseShadowTextureUnit();
i < mShadowSettings->getBaseShadowTextureUnit() + mShadowSettings->getNumShadowMapsPerLight(); ++i)
{
stateset.setTextureAttribute(i, fakeShadowMapTexture,
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE | osg::StateAttribute::PROTECTED);
stateset.addUniform(new osg::Uniform(
("shadowTexture" + std::to_string(i - mShadowSettings->getBaseShadowTextureUnit())).c_str(),
static_cast<int>(i)));
}
}
ShadowManager::ShadowManager(osg::ref_ptr<osg::Group> sceneRoot, osg::ref_ptr<osg::Group> rootNode,
unsigned int outdoorShadowCastingMask, unsigned int indoorShadowCastingMask, unsigned int worldMask,
const Settings::ShadowsCategory& settings, Shader::ShaderManager& shaderManager)
: mShadowedScene(new osgShadow::ShadowedScene)
, mShadowTechnique(new MWShadowTechnique)
, mOutdoorShadowCastingMask(outdoorShadowCastingMask)
, mIndoorShadowCastingMask(indoorShadowCastingMask)
{
if (sInstance)
throw std::logic_error("A ShadowManager already exists");
mShadowedScene->setShadowTechnique(mShadowTechnique);
if (Stereo::getStereo())
Stereo::Manager::instance().setShadowTechnique(mShadowTechnique);
mShadowedScene->addChild(sceneRoot);
rootNode->addChild(mShadowedScene);
mShadowedScene->setNodeMask(sceneRoot->getNodeMask());
mShadowSettings = mShadowedScene->getShadowSettings();
setupShadowSettings(settings, shaderManager);
mShadowTechnique->setupCastingShader(shaderManager);
mShadowTechnique->setWorldMask(worldMask);
enableOutdoorMode();
sInstance = this;
}
ShadowManager::~ShadowManager()
{
if (Stereo::getStereo())
Stereo::Manager::instance().setShadowTechnique(nullptr);
}
Shader::ShaderManager::DefineMap ShadowManager::getShadowDefines(const Settings::ShadowsCategory& settings) const
{
if (!mEnableShadows)
return getShadowsDisabledDefines();
Shader::ShaderManager::DefineMap definesWithShadows;
definesWithShadows["shadows_enabled"] = "1";
for (unsigned int i = 0; i < mShadowSettings->getNumShadowMapsPerLight(); ++i)
definesWithShadows["shadow_texture_unit_list"] += std::to_string(i) + ",";
// remove extra comma
definesWithShadows["shadow_texture_unit_list"] = definesWithShadows["shadow_texture_unit_list"].substr(
0, definesWithShadows["shadow_texture_unit_list"].length() - 1);
definesWithShadows["useShadowDebugOverlay"] = settings.mEnableDebugOverlay ? "1" : "0";
// switch this to reading settings if it's ever exposed to the user
definesWithShadows["perspectiveShadowMaps"]
= mShadowSettings->getShadowMapProjectionHint() == ShadowSettings::PERSPECTIVE_SHADOW_MAP ? "1" : "0";
definesWithShadows["disableNormalOffsetShadows"] = settings.mNormalOffsetDistance == 0.0 ? "1" : "0";
definesWithShadows["shadowNormalOffset"] = std::to_string(settings.mNormalOffsetDistance);
definesWithShadows["limitShadowMapDistance"] = settings.mMaximumShadowMapDistance > 0 ? "1" : "0";
return definesWithShadows;
}
Shader::ShaderManager::DefineMap ShadowManager::getShadowsDisabledDefines()
{
Shader::ShaderManager::DefineMap definesWithoutShadows;
definesWithoutShadows["shadows_enabled"] = "0";
definesWithoutShadows["shadow_texture_unit_list"] = "";
definesWithoutShadows["useShadowDebugOverlay"] = "0";
definesWithoutShadows["perspectiveShadowMaps"] = "0";
definesWithoutShadows["disableNormalOffsetShadows"] = "0";
definesWithoutShadows["shadowNormalOffset"] = "0.0";
definesWithoutShadows["limitShadowMapDistance"] = "0";
return definesWithoutShadows;
}
void ShadowManager::enableIndoorMode(const Settings::ShadowsCategory& settings)
{
if (settings.mEnableIndoorShadows)
mShadowSettings->setCastsShadowTraversalMask(mIndoorShadowCastingMask);
else
mShadowTechnique->disableShadows(true);
}
void ShadowManager::enableOutdoorMode()
{
if (mEnableShadows)
mShadowTechnique->enableShadows();
mShadowSettings->setCastsShadowTraversalMask(mOutdoorShadowCastingMask);
}
}
| 8,510
|
C++
|
.cpp
| 158
| 44.898734
| 119
| 0.716351
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,714
|
visitor.cpp
|
OpenMW_openmw/components/sceneutil/visitor.cpp
|
#include "visitor.hpp"
#include <osg/Drawable>
#include <osg/MatrixTransform>
#include <osgParticle/ParticleSystem>
#include <osgAnimation/Bone>
#include <components/debug/debuglog.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <cstring>
#include <string_view>
namespace SceneUtil
{
bool FindByNameVisitor::checkGroup(osg::Group& group)
{
if (Misc::StringUtils::ciEqual(group.getName(), mNameToFind))
{
mFoundNode = &group;
return true;
}
return false;
}
void FindByClassVisitor::apply(osg::Node& node)
{
if (Misc::StringUtils::ciEqual(node.className(), mNameToFind))
mFoundNodes.push_back(&node);
traverse(node);
}
void FindByNameVisitor::apply(osg::Group& group)
{
if (!mFoundNode && !checkGroup(group))
traverse(group);
}
void FindByNameVisitor::apply(osg::MatrixTransform& node)
{
if (!mFoundNode && !checkGroup(node))
traverse(node);
}
void FindByNameVisitor::apply(osg::Geometry&) {}
void NodeMapVisitorBoneOnly::apply(osg::MatrixTransform& trans)
{
// Choose first found bone in file
if (dynamic_cast<osgAnimation::Bone*>(&trans) != nullptr)
mMap.emplace(trans.getName(), &trans);
traverse(trans);
}
void NodeMapVisitor::apply(osg::MatrixTransform& trans)
{
// Choose first found node in file
mMap.emplace(trans.getName(), &trans);
traverse(trans);
}
void RemoveVisitor::remove()
{
for (RemoveVec::iterator it = mToRemove.begin(); it != mToRemove.end(); ++it)
{
if (!it->second->removeChild(it->first))
Log(Debug::Error) << "error removing " << it->first->getName();
}
}
void CleanObjectRootVisitor::apply(osg::Drawable& drw)
{
applyDrawable(drw);
}
void CleanObjectRootVisitor::apply(osg::Group& node)
{
applyNode(node);
}
void CleanObjectRootVisitor::apply(osg::MatrixTransform& node)
{
applyNode(node);
}
void CleanObjectRootVisitor::apply(osg::Node& node)
{
applyNode(node);
}
void CleanObjectRootVisitor::applyNode(osg::Node& node)
{
if (node.getStateSet())
node.setStateSet(nullptr);
if (node.getNodeMask() == 0x1 && node.getNumParents() == 1)
mToRemove.emplace_back(&node, node.getParent(0));
else
traverse(node);
}
void CleanObjectRootVisitor::applyDrawable(osg::Node& node)
{
osg::NodePath::iterator parent = getNodePath().end() - 2;
// We know that the parent is a Group because only Groups can have children.
osg::Group* parentGroup = static_cast<osg::Group*>(*parent);
// Try to prune nodes that would be empty after the removal
if (parent != getNodePath().begin())
{
// This could be extended to remove the parent's parent, and so on if they are empty as well.
// But for NIF files, there won't be a benefit since only TriShapes can be set to STATIC dataVariance.
osg::Group* parentParent = static_cast<osg::Group*>(*(parent - 1));
if (parentGroup->getNumChildren() == 1 && parentGroup->getDataVariance() == osg::Object::STATIC)
{
mToRemove.emplace_back(parentGroup, parentParent);
return;
}
}
mToRemove.emplace_back(&node, parentGroup);
}
void RemoveTriBipVisitor::apply(osg::Drawable& drw)
{
applyImpl(drw);
}
void RemoveTriBipVisitor::apply(osg::Group& node)
{
traverse(node);
}
void RemoveTriBipVisitor::apply(osg::MatrixTransform& node)
{
traverse(node);
}
void RemoveTriBipVisitor::applyImpl(osg::Node& node)
{
if (Misc::StringUtils::ciStartsWith(node.getName(), "tri bip"))
{
osg::Group* parent = static_cast<osg::Group*>(*(getNodePath().end() - 2));
// Not safe to remove in apply(), since the visitor is still iterating the child list
mToRemove.emplace_back(&node, parent);
}
}
}
| 4,242
|
C++
|
.cpp
| 124
| 26.620968
| 114
| 0.618244
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,715
|
lightmanager.cpp
|
OpenMW_openmw/components/sceneutil/lightmanager.cpp
|
#include "lightmanager.hpp"
#include <algorithm>
#include <array>
#include <cstring>
#include <iterator>
#include <osg/BufferIndexBinding>
#include <osg/BufferObject>
#include <osg/Endian>
#include <osg/ValueObject>
#include <osgUtil/CullVisitor>
#include <components/resource/scenemanager.hpp>
#include <components/sceneutil/glextensions.hpp>
#include <components/sceneutil/util.hpp>
#include <components/shader/shadermanager.hpp>
#include <components/misc/constants.hpp>
#include <components/misc/hash.hpp>
#include <components/debug/debuglog.hpp>
namespace
{
constexpr int ffpMaxLights = 8;
void configurePosition(osg::Matrixf& mat, const osg::Vec4& pos)
{
mat(0, 0) = pos.x();
mat(0, 1) = pos.y();
mat(0, 2) = pos.z();
}
void configureAmbient(osg::Matrixf& mat, const osg::Vec4& color)
{
mat(1, 0) = color.r();
mat(1, 1) = color.g();
mat(1, 2) = color.b();
}
void configureDiffuse(osg::Matrixf& mat, const osg::Vec4& color)
{
mat(2, 0) = color.r();
mat(2, 1) = color.g();
mat(2, 2) = color.b();
}
void configureSpecular(osg::Matrixf& mat, const osg::Vec4& color)
{
mat(3, 0) = color.r();
mat(3, 1) = color.g();
mat(3, 2) = color.b();
mat(3, 3) = color.a();
}
void configureAttenuation(osg::Matrixf& mat, float c, float l, float q, float r)
{
mat(0, 3) = c;
mat(1, 3) = l;
mat(2, 3) = q;
mat(3, 3) = r;
}
}
namespace SceneUtil
{
namespace
{
const std::unordered_map<std::string, LightingMethod> lightingMethodSettingMap = {
{ "legacy", LightingMethod::FFP },
{ "shaders compatibility", LightingMethod::PerObjectUniform },
{ "shaders", LightingMethod::SingleUBO },
};
}
static int sLightId = 0;
// Handles a GLSL shared layout by using configured offsets and strides to fill a continuous buffer, making the data
// upload to GPU simpler.
class LightBuffer : public osg::Referenced
{
public:
enum LayoutOffset
{
Diffuse,
DiffuseSign,
Ambient,
Specular,
Position,
AttenuationRadius
};
LightBuffer(int count)
: mData(new osg::FloatArray(3 * 4 * count))
, mEndian(osg::getCpuByteOrder())
, mCount(count)
, mCachedSunPos(osg::Vec4())
{
}
LightBuffer(const LightBuffer&) = delete;
void setDiffuse(int index, const osg::Vec4& value)
{
// Deal with negative lights (negative diffuse) by passing a sign bit in the unused alpha component
auto positiveColor = value;
unsigned int signBit = 1;
if (value[0] < 0)
{
positiveColor *= -1.0;
signBit = ~0u;
}
unsigned int packedColor = asRGBA(positiveColor);
std::memcpy(&(*mData)[getOffset(index, Diffuse)], &packedColor, sizeof(unsigned int));
std::memcpy(&(*mData)[getOffset(index, DiffuseSign)], &signBit, sizeof(unsigned int));
}
void setAmbient(int index, const osg::Vec4& value)
{
unsigned int packed = asRGBA(value);
std::memcpy(&(*mData)[getOffset(index, Ambient)], &packed, sizeof(unsigned int));
}
void setSpecular(int index, const osg::Vec4& value)
{
unsigned int packed = asRGBA(value);
std::memcpy(&(*mData)[getOffset(index, Specular)], &packed, sizeof(unsigned int));
}
void setPosition(int index, const osg::Vec4& value)
{
std::memcpy(&(*mData)[getOffset(index, Position)], value.ptr(), sizeof(osg::Vec4f));
}
void setAttenuationRadius(int index, const osg::Vec4& value)
{
std::memcpy(&(*mData)[getOffset(index, AttenuationRadius)], value.ptr(), sizeof(osg::Vec4f));
}
auto& getData() { return mData; }
void dirty() { mData->dirty(); }
static constexpr int queryBlockSize(int sz) { return 3 * osg::Vec4::num_components * sizeof(GLfloat) * sz; }
void setCachedSunPos(const osg::Vec4& pos) { mCachedSunPos = pos; }
void uploadCachedSunPos(const osg::Matrix& viewMat)
{
osg::Vec4 viewPos = mCachedSunPos * viewMat;
std::memcpy(&(*mData)[getOffset(0, Position)], viewPos.ptr(), sizeof(osg::Vec4f));
}
unsigned int asRGBA(const osg::Vec4& value) const
{
return mEndian == osg::BigEndian ? value.asABGR() : value.asRGBA();
}
int getOffset(int index, LayoutOffset slot) const { return mOffsets.get(index, slot); }
void configureLayout(int offsetColors, int offsetPosition, int offsetAttenuationRadius, int size, int stride)
{
configureLayout(Offsets(offsetColors, offsetPosition, offsetAttenuationRadius, stride), size);
}
void configureLayout(const LightBuffer* other)
{
mOffsets = other->mOffsets;
int size = other->mData->size();
configureLayout(mOffsets, size);
}
private:
class Offsets
{
public:
Offsets()
: mStride(12)
{
mValues[Diffuse] = 0;
mValues[Ambient] = 1;
mValues[Specular] = 2;
mValues[DiffuseSign] = 3;
mValues[Position] = 4;
mValues[AttenuationRadius] = 8;
}
Offsets(int offsetColors, int offsetPosition, int offsetAttenuationRadius, int stride)
: mStride((offsetAttenuationRadius + sizeof(GLfloat) * osg::Vec4::num_components + stride) / 4)
{
constexpr auto sizeofFloat = sizeof(GLfloat);
const auto diffuseOffset = offsetColors / sizeofFloat;
mValues[Diffuse] = diffuseOffset;
mValues[Ambient] = diffuseOffset + 1;
mValues[Specular] = diffuseOffset + 2;
mValues[DiffuseSign] = diffuseOffset + 3;
mValues[Position] = offsetPosition / sizeofFloat;
mValues[AttenuationRadius] = offsetAttenuationRadius / sizeofFloat;
}
int get(int index, LayoutOffset slot) const { return mStride * index + mValues[slot]; }
private:
int mStride;
std::array<int, 6> mValues;
};
void configureLayout(const Offsets& offsets, int size)
{
// Copy cloned data using current layout into current data using new layout.
// This allows to preserve osg::FloatArray buffer object in mData.
const auto data = mData->asVector();
mData->resizeArray(static_cast<unsigned>(size));
for (int i = 0; i < mCount; ++i)
{
std::memcpy(
&(*mData)[offsets.get(i, Diffuse)], data.data() + getOffset(i, Diffuse), sizeof(osg::Vec4f));
std::memcpy(
&(*mData)[offsets.get(i, Position)], data.data() + getOffset(i, Position), sizeof(osg::Vec4f));
std::memcpy(&(*mData)[offsets.get(i, AttenuationRadius)], data.data() + getOffset(i, AttenuationRadius),
sizeof(osg::Vec4f));
}
mOffsets = offsets;
}
osg::ref_ptr<osg::FloatArray> mData;
osg::Endian mEndian;
int mCount;
Offsets mOffsets;
osg::Vec4 mCachedSunPos;
};
struct LightStateCache
{
std::vector<osg::Light*> lastAppliedLight;
};
LightStateCache* getLightStateCache(size_t contextid, size_t size = 8)
{
static std::vector<LightStateCache> cacheVector;
if (cacheVector.size() < contextid + 1)
cacheVector.resize(contextid + 1);
cacheVector[contextid].lastAppliedLight.resize(size);
return &cacheVector[contextid];
}
void configureStateSetSunOverride(
LightManager* lightManager, const osg::Light* light, osg::StateSet* stateset, int mode)
{
auto method = lightManager->getLightingMethod();
switch (method)
{
case LightingMethod::FFP:
{
break;
}
case LightingMethod::PerObjectUniform:
{
osg::Matrixf lightMat;
configurePosition(lightMat, light->getPosition());
configureAmbient(lightMat, light->getAmbient());
configureDiffuse(lightMat, light->getDiffuse());
configureSpecular(lightMat, light->getSpecular());
stateset->addUniform(lightManager->generateLightBufferUniform(lightMat), mode);
break;
}
case LightingMethod::SingleUBO:
{
osg::ref_ptr<LightBuffer> buffer = new LightBuffer(lightManager->getMaxLightsInScene());
buffer->setDiffuse(0, light->getDiffuse());
buffer->setAmbient(0, light->getAmbient());
buffer->setSpecular(0, light->getSpecular());
buffer->setPosition(0, light->getPosition());
osg::ref_ptr<osg::UniformBufferObject> ubo = new osg::UniformBufferObject;
buffer->getData()->setBufferObject(ubo);
osg::ref_ptr<osg::UniformBufferBinding> ubb
= new osg::UniformBufferBinding(static_cast<int>(Resource::SceneManager::UBOBinding::LightBuffer),
buffer->getData(), 0, buffer->getData()->getTotalDataSize());
stateset->setAttributeAndModes(ubb, mode);
break;
}
}
}
class DisableLight : public osg::StateAttribute
{
public:
DisableLight()
: mIndex(0)
{
}
DisableLight(int index)
: mIndex(index)
{
}
DisableLight(const DisableLight& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY)
: osg::StateAttribute(copy, copyop)
, mIndex(copy.mIndex)
{
}
META_StateAttribute(SceneUtil, DisableLight, osg::StateAttribute::LIGHT)
unsigned int getMember() const override { return mIndex; }
bool getModeUsage(ModeUsage& usage) const override
{
usage.usesMode(GL_LIGHT0 + mIndex);
return true;
}
int compare(const StateAttribute& sa) const override
{
throw std::runtime_error("DisableLight::compare: unimplemented");
}
void apply(osg::State& state) const override
{
int lightNum = GL_LIGHT0 + mIndex;
glLightfv(lightNum, GL_AMBIENT, mNullptr.ptr());
glLightfv(lightNum, GL_DIFFUSE, mNullptr.ptr());
glLightfv(lightNum, GL_SPECULAR, mNullptr.ptr());
LightStateCache* cache = getLightStateCache(state.getContextID());
cache->lastAppliedLight[mIndex] = nullptr;
}
private:
size_t mIndex;
osg::Vec4f mNullptr;
};
class FFPLightStateAttribute : public osg::StateAttribute
{
public:
FFPLightStateAttribute()
: mIndex(0)
{
}
FFPLightStateAttribute(size_t index, const std::vector<osg::ref_ptr<osg::Light>>& lights)
: mIndex(index)
, mLights(lights)
{
}
FFPLightStateAttribute(
const FFPLightStateAttribute& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY)
: osg::StateAttribute(copy, copyop)
, mIndex(copy.mIndex)
, mLights(copy.mLights)
{
}
unsigned int getMember() const override { return mIndex; }
bool getModeUsage(ModeUsage& usage) const override
{
for (size_t i = 0; i < mLights.size(); ++i)
usage.usesMode(GL_LIGHT0 + mIndex + i);
return true;
}
int compare(const StateAttribute& sa) const override
{
throw std::runtime_error("FFPLightStateAttribute::compare: unimplemented");
}
META_StateAttribute(SceneUtil, FFPLightStateAttribute, osg::StateAttribute::LIGHT)
void apply(osg::State& state) const override
{
if (mLights.empty())
return;
osg::Matrix modelViewMatrix = state.getModelViewMatrix();
state.applyModelViewMatrix(state.getInitialViewMatrix());
LightStateCache* cache = getLightStateCache(state.getContextID());
for (size_t i = 0; i < mLights.size(); ++i)
{
osg::Light* current = cache->lastAppliedLight[i + mIndex];
if (current != mLights[i].get())
{
applyLight((GLenum)((int)GL_LIGHT0 + i + mIndex), mLights[i].get());
cache->lastAppliedLight[i + mIndex] = mLights[i].get();
}
}
state.applyModelViewMatrix(modelViewMatrix);
}
void applyLight(GLenum lightNum, const osg::Light* light) const
{
glLightfv(lightNum, GL_AMBIENT, light->getAmbient().ptr());
glLightfv(lightNum, GL_DIFFUSE, light->getDiffuse().ptr());
glLightfv(lightNum, GL_SPECULAR, light->getSpecular().ptr());
glLightfv(lightNum, GL_POSITION, light->getPosition().ptr());
// TODO: enable this once spot lights are supported
// need to transform SPOT_DIRECTION by the world matrix?
// glLightfv(lightNum, GL_SPOT_DIRECTION, light->getDirection().ptr());
// glLightf(lightNum, GL_SPOT_EXPONENT, light->getSpotExponent());
// glLightf(lightNum, GL_SPOT_CUTOFF, light->getSpotCutoff());
glLightf(lightNum, GL_CONSTANT_ATTENUATION, light->getConstantAttenuation());
glLightf(lightNum, GL_LINEAR_ATTENUATION, light->getLinearAttenuation());
glLightf(lightNum, GL_QUADRATIC_ATTENUATION, light->getQuadraticAttenuation());
}
private:
size_t mIndex;
std::vector<osg::ref_ptr<osg::Light>> mLights;
};
struct StateSetGenerator
{
LightManager* mLightManager;
virtual ~StateSetGenerator() {}
virtual osg::ref_ptr<osg::StateSet> generate(const LightManager::LightList& lightList, size_t frameNum) = 0;
virtual void update(osg::StateSet* stateset, const LightManager::LightList& lightList, size_t frameNum) {}
osg::Matrix mViewMatrix;
};
struct StateSetGeneratorFFP : StateSetGenerator
{
osg::ref_ptr<osg::StateSet> generate(const LightManager::LightList& lightList, size_t frameNum) override
{
osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet;
std::vector<osg::ref_ptr<osg::Light>> lights;
lights.reserve(lightList.size());
for (size_t i = 0; i < lightList.size(); ++i)
lights.emplace_back(lightList[i]->mLightSource->getLight(frameNum));
// the first light state attribute handles the actual state setting for all lights
// it's best to batch these up so that we don't need to touch the modelView matrix more than necessary
// don't use setAttributeAndModes, that does not support light indices!
stateset->setAttribute(
new FFPLightStateAttribute(mLightManager->getStartLight(), std::move(lights)), osg::StateAttribute::ON);
for (size_t i = 0; i < lightList.size(); ++i)
stateset->setMode(GL_LIGHT0 + mLightManager->getStartLight() + i, osg::StateAttribute::ON);
// need to push some dummy attributes to ensure proper state tracking
// lights need to reset to their default when the StateSet is popped
for (size_t i = 1; i < lightList.size(); ++i)
stateset->setAttribute(
mLightManager->getDummies()[i + mLightManager->getStartLight()].get(), osg::StateAttribute::ON);
return stateset;
}
};
struct StateSetGeneratorSingleUBO : StateSetGenerator
{
osg::ref_ptr<osg::StateSet> generate(const LightManager::LightList& lightList, size_t frameNum) override
{
osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet;
osg::ref_ptr<osg::Uniform> indicesUni
= new osg::Uniform(osg::Uniform::Type::INT, "PointLightIndex", mLightManager->getMaxLights());
int pointCount = 0;
for (size_t i = 0; i < lightList.size(); ++i)
{
int bufIndex = mLightManager->getLightIndexMap(frameNum)[lightList[i]->mLightSource->getId()];
indicesUni->setElement(pointCount++, bufIndex);
}
stateset->addUniform(indicesUni);
stateset->addUniform(new osg::Uniform("PointLightCount", pointCount));
return stateset;
}
// Cached statesets must be revalidated in case the light indices change. There is no actual link between
// a light's ID and the buffer index it will eventually be assigned (or reassigned) to.
void update(osg::StateSet* stateset, const LightManager::LightList& lightList, size_t frameNum) override
{
int newCount = 0;
int oldCount;
auto uOldArray = stateset->getUniform("PointLightIndex");
auto uOldCount = stateset->getUniform("PointLightCount");
uOldCount->get(oldCount);
// max lights count can change during runtime
oldCount = std::min(mLightManager->getMaxLights(), oldCount);
auto& lightData = mLightManager->getLightIndexMap(frameNum);
for (int i = 0; i < oldCount; ++i)
{
auto* lightSource = lightList[i]->mLightSource;
auto it = lightData.find(lightSource->getId());
if (it != lightData.end())
uOldArray->setElement(newCount++, it->second);
}
uOldArray->dirty();
uOldCount->set(newCount);
}
};
struct StateSetGeneratorPerObjectUniform : StateSetGenerator
{
osg::ref_ptr<osg::StateSet> generate(const LightManager::LightList& lightList, size_t frameNum) override
{
osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet;
osg::ref_ptr<osg::Uniform> data
= mLightManager->generateLightBufferUniform(mLightManager->getSunlightBuffer(frameNum));
for (size_t i = 0; i < lightList.size(); ++i)
{
auto* light = lightList[i]->mLightSource->getLight(frameNum);
osg::Matrixf lightMat;
configurePosition(lightMat, light->getPosition() * mViewMatrix);
configureAmbient(lightMat, light->getAmbient());
configureDiffuse(lightMat, light->getDiffuse());
configureSpecular(lightMat, light->getSpecular());
configureAttenuation(lightMat, light->getConstantAttenuation(), light->getLinearAttenuation(),
light->getQuadraticAttenuation(), lightList[i]->mLightSource->getRadius());
data->setElement(i + 1, lightMat);
}
stateset->addUniform(data);
stateset->addUniform(new osg::Uniform("PointLightCount", static_cast<int>(lightList.size() + 1)));
return stateset;
}
};
LightManager* findLightManager(const osg::NodePath& path)
{
for (size_t i = 0; i < path.size(); ++i)
{
if (LightManager* lightManager = dynamic_cast<LightManager*>(path[i]))
return lightManager;
}
return nullptr;
}
// Set on a LightSource. Adds the light source to its light manager for the current frame.
// This allows us to keep track of the current lights in the scene graph without tying creation & destruction to the
// manager.
class CollectLightCallback : public NodeCallback<CollectLightCallback>
{
public:
CollectLightCallback()
: mLightManager(nullptr)
{
}
CollectLightCallback(const CollectLightCallback& copy, const osg::CopyOp& copyop)
: NodeCallback<CollectLightCallback>(copy, copyop)
, mLightManager(nullptr)
{
}
META_Object(SceneUtil, CollectLightCallback)
void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
if (!mLightManager)
{
mLightManager = findLightManager(nv->getNodePath());
if (!mLightManager)
throw std::runtime_error("can't find parent LightManager");
}
mLightManager->addLight(
static_cast<LightSource*>(node), osg::computeLocalToWorld(nv->getNodePath()), nv->getTraversalNumber());
traverse(node, nv);
}
private:
LightManager* mLightManager;
};
// Set on a LightManager. Clears the data from the previous frame.
class LightManagerUpdateCallback : public SceneUtil::NodeCallback<LightManagerUpdateCallback>
{
public:
void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
LightManager* lightManager = static_cast<LightManager*>(node);
lightManager->update(nv->getTraversalNumber());
traverse(node, nv);
}
};
class LightManagerCullCallback
: public SceneUtil::NodeCallback<LightManagerCullCallback, LightManager*, osgUtil::CullVisitor*>
{
public:
LightManagerCullCallback(LightManager* lightManager)
{
if (!lightManager->getUBOManager())
return;
for (size_t i = 0; i < mUBBs.size(); ++i)
{
auto& buffer = lightManager->getUBOManager()->getLightBuffer(i);
mUBBs[i]
= new osg::UniformBufferBinding(static_cast<int>(Resource::SceneManager::UBOBinding::LightBuffer),
buffer->getData(), 0, buffer->getData()->getTotalDataSize());
}
}
void operator()(LightManager* node, osgUtil::CullVisitor* cv)
{
osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet;
if (node->getLightingMethod() == LightingMethod::SingleUBO)
{
const size_t frameId = cv->getTraversalNumber() % 2;
stateset->setAttributeAndModes(mUBBs[frameId], osg::StateAttribute::ON);
auto& buffer = node->getUBOManager()->getLightBuffer(cv->getTraversalNumber());
if (auto sun = node->getSunlight())
{
buffer->setCachedSunPos(sun->getPosition());
buffer->setAmbient(0, sun->getAmbient());
buffer->setDiffuse(0, sun->getDiffuse());
buffer->setSpecular(0, sun->getSpecular());
}
}
else if (node->getLightingMethod() == LightingMethod::PerObjectUniform)
{
if (auto sun = node->getSunlight())
{
osg::Matrixf lightMat;
configurePosition(
lightMat, sun->getPosition() * (*cv->getCurrentRenderStage()->getInitialViewMatrix()));
configureAmbient(lightMat, sun->getAmbient());
configureDiffuse(lightMat, sun->getDiffuse());
configureSpecular(lightMat, sun->getSpecular());
node->setSunlightBuffer(lightMat, cv->getTraversalNumber());
stateset->addUniform(node->generateLightBufferUniform(lightMat));
}
}
cv->pushStateSet(stateset);
traverse(node, cv);
cv->popStateSet();
if (node->getPPLightsBuffer() && cv->getCurrentCamera()->getName() == Constants::SceneCamera)
node->getPPLightsBuffer()->updateCount(cv->getTraversalNumber());
}
std::array<osg::ref_ptr<osg::UniformBufferBinding>, 2> mUBBs;
};
UBOManager::UBOManager(int lightCount)
: mDummyProgram(new osg::Program)
, mInitLayout(false)
, mDirty({ true, true })
, mTemplate(new LightBuffer(lightCount))
{
static const std::string dummyVertSource = generateDummyShader(lightCount);
// Needed to query the layout of the buffer object. The layout specifier needed to use the std140 layout is not
// reliably available, regardless of extensions, until GLSL 140.
mDummyProgram->addShader(new osg::Shader(osg::Shader::VERTEX, dummyVertSource));
mDummyProgram->addBindUniformBlock(
"LightBufferBinding", static_cast<int>(Resource::SceneManager::UBOBinding::LightBuffer));
for (size_t i = 0; i < mLightBuffers.size(); ++i)
{
mLightBuffers[i] = new LightBuffer(lightCount);
osg::ref_ptr<osg::UniformBufferObject> ubo = new osg::UniformBufferObject;
ubo->setUsage(GL_STREAM_DRAW);
mLightBuffers[i]->getData()->setBufferObject(ubo);
}
}
UBOManager::UBOManager(const UBOManager& copy, const osg::CopyOp& copyop)
: osg::StateAttribute(copy, copyop)
, mDummyProgram(copy.mDummyProgram)
, mInitLayout(copy.mInitLayout)
{
}
void UBOManager::releaseGLObjects(osg::State* state) const
{
mDummyProgram->releaseGLObjects(state);
}
int UBOManager::compare(const StateAttribute& sa) const
{
throw std::runtime_error("LightManagerStateAttribute::compare: unimplemented");
}
void UBOManager::apply(osg::State& state) const
{
unsigned int frame = state.getFrameStamp()->getFrameNumber();
unsigned int index = frame % 2;
if (!mInitLayout)
{
mDummyProgram->apply(state);
auto handle = mDummyProgram->getPCP(state)->getHandle();
auto* ext = state.get<osg::GLExtensions>();
int activeUniformBlocks = 0;
ext->glGetProgramiv(handle, GL_ACTIVE_UNIFORM_BLOCKS, &activeUniformBlocks);
// wait until the UBO binding is created
if (activeUniformBlocks > 0)
{
initSharedLayout(ext, handle, frame);
mInitLayout = true;
}
}
else if (mDirty[index])
{
mDirty[index] = false;
mLightBuffers[index]->configureLayout(mTemplate);
}
mLightBuffers[index]->uploadCachedSunPos(state.getInitialViewMatrix());
mLightBuffers[index]->dirty();
}
std::string UBOManager::generateDummyShader(int maxLightsInScene)
{
const std::string define = "@maxLightsInScene";
std::string shader = R"GLSL(
#version 120
#extension GL_ARB_uniform_buffer_object : require
struct LightData {
ivec4 packedColors;
vec4 position;
vec4 attenuation;
};
uniform LightBufferBinding {
LightData LightBuffer[@maxLightsInScene];
};
void main()
{
gl_Position = vec4(0.0);
}
)GLSL";
shader.replace(shader.find(define), define.length(), std::to_string(maxLightsInScene));
return shader;
}
void UBOManager::initSharedLayout(osg::GLExtensions* ext, int handle, unsigned int frame) const
{
constexpr std::array<unsigned int, 1> index
= { static_cast<unsigned int>(Resource::SceneManager::UBOBinding::LightBuffer) };
int totalBlockSize = -1;
int stride = -1;
ext->glGetActiveUniformBlockiv(handle, 0, GL_UNIFORM_BLOCK_DATA_SIZE, &totalBlockSize);
ext->glGetActiveUniformsiv(handle, index.size(), index.data(), GL_UNIFORM_ARRAY_STRIDE, &stride);
std::array<const char*, 3> names = {
"LightBuffer[0].packedColors",
"LightBuffer[0].position",
"LightBuffer[0].attenuation",
};
std::vector<unsigned int> indices(names.size());
std::vector<int> offsets(names.size());
ext->glGetUniformIndices(handle, names.size(), names.data(), indices.data());
ext->glGetActiveUniformsiv(handle, indices.size(), indices.data(), GL_UNIFORM_OFFSET, offsets.data());
mTemplate->configureLayout(offsets[0], offsets[1], offsets[2], totalBlockSize, stride);
}
LightingMethod LightManager::getLightingMethodFromString(const std::string& value)
{
auto it = lightingMethodSettingMap.find(value);
if (it != lightingMethodSettingMap.end())
return it->second;
constexpr const char* fallback = "shaders compatibility";
Log(Debug::Warning) << "Unknown lighting method '" << value << "', returning fallback '" << fallback << "'";
return LightingMethod::PerObjectUniform;
}
std::string LightManager::getLightingMethodString(LightingMethod method)
{
for (const auto& p : lightingMethodSettingMap)
if (p.second == method)
return p.first;
return "";
}
LightManager::LightManager(const LightSettings& settings)
: mStartLight(0)
, mLightingMask(~0u)
, mSun(nullptr)
, mPointLightRadiusMultiplier(1.f)
, mPointLightFadeEnd(0.f)
, mPointLightFadeStart(0.f)
{
osg::GLExtensions* exts = SceneUtil::glExtensionsReady() ? &SceneUtil::getGLExtensions() : nullptr;
bool supportsUBO = exts && exts->isUniformBufferObjectSupported;
bool supportsGPU4 = exts && exts->isGpuShader4Supported;
mSupported[static_cast<int>(LightingMethod::FFP)] = true;
mSupported[static_cast<int>(LightingMethod::PerObjectUniform)] = true;
mSupported[static_cast<int>(LightingMethod::SingleUBO)] = supportsUBO && supportsGPU4;
setUpdateCallback(new LightManagerUpdateCallback);
if (settings.mLightingMethod == LightingMethod::FFP)
{
initFFP(ffpMaxLights);
}
else
{
static bool hasLoggedWarnings = false;
if (settings.mLightingMethod == LightingMethod::SingleUBO && !hasLoggedWarnings)
{
if (!supportsUBO)
Log(Debug::Warning) << "GL_ARB_uniform_buffer_object not supported: switching to shader "
"compatibility lighting mode";
if (!supportsGPU4)
Log(Debug::Warning)
<< "GL_EXT_gpu_shader4 not supported: switching to shader compatibility lighting mode";
hasLoggedWarnings = true;
}
if (!supportsUBO || !supportsGPU4 || settings.mLightingMethod == LightingMethod::PerObjectUniform)
initPerObjectUniform(settings.mMaxLights);
else
initSingleUBO(settings.mMaxLights);
getOrCreateStateSet()->addUniform(new osg::Uniform("PointLightCount", 0));
addCullCallback(new LightManagerCullCallback(this));
}
updateSettings(settings.mLightBoundsMultiplier, settings.mMaximumLightDistance, settings.mLightFadeStart);
}
LightManager::LightManager(const LightManager& copy, const osg::CopyOp& copyop)
: osg::Group(copy, copyop)
, mStartLight(copy.mStartLight)
, mLightingMask(copy.mLightingMask)
, mSun(copy.mSun)
, mLightingMethod(copy.mLightingMethod)
, mPointLightRadiusMultiplier(copy.mPointLightRadiusMultiplier)
, mPointLightFadeEnd(copy.mPointLightFadeEnd)
, mPointLightFadeStart(copy.mPointLightFadeStart)
, mMaxLights(copy.mMaxLights)
, mPPLightBuffer(copy.mPPLightBuffer)
{
}
LightingMethod LightManager::getLightingMethod() const
{
return mLightingMethod;
}
bool LightManager::usingFFP() const
{
return mLightingMethod == LightingMethod::FFP;
}
int LightManager::getMaxLights() const
{
return mMaxLights;
}
void LightManager::setMaxLights(int value)
{
mMaxLights = value;
}
int LightManager::getMaxLightsInScene() const
{
static constexpr int max = 16384 / LightBuffer::queryBlockSize(1);
return max;
}
Shader::ShaderManager::DefineMap LightManager::getLightDefines() const
{
Shader::ShaderManager::DefineMap defines;
defines["maxLights"] = std::to_string(getMaxLights());
defines["maxLightsInScene"] = std::to_string(getMaxLightsInScene());
defines["lightingMethodFFP"] = getLightingMethod() == LightingMethod::FFP ? "1" : "0";
defines["lightingMethodPerObjectUniform"] = getLightingMethod() == LightingMethod::PerObjectUniform ? "1" : "0";
defines["lightingMethodUBO"] = getLightingMethod() == LightingMethod::SingleUBO ? "1" : "0";
defines["useUBO"] = std::to_string(getLightingMethod() == LightingMethod::SingleUBO);
// exposes bitwise operators
defines["useGPUShader4"] = std::to_string(getLightingMethod() == LightingMethod::SingleUBO);
defines["getLight"] = getLightingMethod() == LightingMethod::FFP ? "gl_LightSource" : "LightBuffer";
defines["startLight"] = getLightingMethod() == LightingMethod::SingleUBO ? "0" : "1";
defines["endLight"] = getLightingMethod() == LightingMethod::FFP ? defines["maxLights"] : "PointLightCount";
return defines;
}
void LightManager::processChangedSettings(
float lightBoundsMultiplier, float maximumLightDistance, float lightFadeStart)
{
updateSettings(lightBoundsMultiplier, maximumLightDistance, lightFadeStart);
}
void LightManager::updateMaxLights(int maxLights)
{
if (usingFFP())
return;
setMaxLights(maxLights);
if (getLightingMethod() == LightingMethod::PerObjectUniform)
{
getStateSet()->removeUniform("LightBuffer");
getStateSet()->addUniform(generateLightBufferUniform(osg::Matrixf()));
}
for (auto& cache : mStateSetCache)
cache.clear();
}
void LightManager::updateSettings(float lightBoundsMultiplier, float maximumLightDistance, float lightFadeStart)
{
mPointLightRadiusMultiplier = lightBoundsMultiplier;
mPointLightFadeEnd = maximumLightDistance;
if (mPointLightFadeEnd > 0)
mPointLightFadeStart = mPointLightFadeEnd * lightFadeStart;
}
void LightManager::initFFP(int targetLights)
{
setLightingMethod(LightingMethod::FFP);
setMaxLights(targetLights);
for (int i = 0; i < getMaxLights(); ++i)
mDummies.push_back(new FFPLightStateAttribute(i, std::vector<osg::ref_ptr<osg::Light>>()));
}
void LightManager::initPerObjectUniform(int targetLights)
{
setLightingMethod(LightingMethod::PerObjectUniform);
setMaxLights(targetLights);
getOrCreateStateSet()->addUniform(generateLightBufferUniform(osg::Matrixf()));
}
void LightManager::initSingleUBO(int targetLights)
{
setLightingMethod(LightingMethod::SingleUBO);
setMaxLights(targetLights);
mUBOManager = new UBOManager(getMaxLightsInScene());
getOrCreateStateSet()->setAttributeAndModes(mUBOManager);
}
void LightManager::setLightingMethod(LightingMethod method)
{
mLightingMethod = method;
switch (method)
{
case LightingMethod::FFP:
mStateSetGenerator = std::make_unique<StateSetGeneratorFFP>();
break;
case LightingMethod::SingleUBO:
mStateSetGenerator = std::make_unique<StateSetGeneratorSingleUBO>();
break;
case LightingMethod::PerObjectUniform:
mStateSetGenerator = std::make_unique<StateSetGeneratorPerObjectUniform>();
break;
}
mStateSetGenerator->mLightManager = this;
}
void LightManager::setLightingMask(size_t mask)
{
mLightingMask = mask;
}
size_t LightManager::getLightingMask() const
{
return mLightingMask;
}
void LightManager::setStartLight(int start)
{
mStartLight = start;
if (!usingFFP())
return;
// Set default light state to zero
// This is necessary because shaders don't respect glDisable(GL_LIGHTX) so in addition to disabling
// we'll have to set a light state that has no visible effect
for (int i = start; i < getMaxLights(); ++i)
{
osg::ref_ptr<DisableLight> defaultLight(new DisableLight(i));
getOrCreateStateSet()->setAttributeAndModes(defaultLight, osg::StateAttribute::OFF);
}
}
int LightManager::getStartLight() const
{
return mStartLight;
}
void LightManager::update(size_t frameNum)
{
if (mPPLightBuffer)
mPPLightBuffer->clear(frameNum);
getLightIndexMap(frameNum).clear();
mLights.clear();
mLightsInViewSpace.clear();
// Do an occasional cleanup for orphaned lights.
for (int i = 0; i < 2; ++i)
{
if (mStateSetCache[i].size() > 5000)
mStateSetCache[i].clear();
}
}
void LightManager::addLight(LightSource* lightSource, const osg::Matrixf& worldMat, size_t frameNum)
{
LightSourceTransform l;
l.mLightSource = lightSource;
l.mWorldMatrix = worldMat;
osg::Vec3f pos = osg::Vec3f(worldMat.getTrans().x(), worldMat.getTrans().y(), worldMat.getTrans().z());
lightSource->getLight(frameNum)->setPosition(osg::Vec4f(pos, 1.f));
mLights.push_back(l);
}
void LightManager::setSunlight(osg::ref_ptr<osg::Light> sun)
{
if (usingFFP())
return;
mSun = sun;
}
osg::ref_ptr<osg::Light> LightManager::getSunlight()
{
return mSun;
}
size_t LightManager::HashLightIdList::operator()(const LightIdList& lightIdList) const
{
size_t hash = 0;
for (size_t i = 0; i < lightIdList.size(); ++i)
Misc::hashCombine(hash, lightIdList[i]);
return hash;
}
osg::ref_ptr<osg::StateSet> LightManager::getLightListStateSet(
const LightList& lightList, size_t frameNum, const osg::RefMatrix* viewMatrix)
{
if (getLightingMethod() == LightingMethod::PerObjectUniform)
{
mStateSetGenerator->mViewMatrix = *viewMatrix;
return mStateSetGenerator->generate(lightList, frameNum);
}
// possible optimization: return a StateSet containing all requested lights plus some extra lights (if a
// suitable one exists)
if (getLightingMethod() == LightingMethod::SingleUBO)
{
for (size_t i = 0; i < lightList.size(); ++i)
{
auto id = lightList[i]->mLightSource->getId();
if (getLightIndexMap(frameNum).find(id) != getLightIndexMap(frameNum).end())
continue;
int index = getLightIndexMap(frameNum).size() + 1;
updateGPUPointLight(index, lightList[i]->mLightSource, frameNum, viewMatrix);
getLightIndexMap(frameNum).emplace(id, index);
}
}
auto& stateSetCache = mStateSetCache[frameNum % 2];
LightIdList lightIdList;
lightIdList.reserve(lightList.size());
std::transform(lightList.begin(), lightList.end(), std::back_inserter(lightIdList),
[](const LightSourceViewBound* l) { return l->mLightSource->getId(); });
auto found = stateSetCache.find(lightIdList);
if (found != stateSetCache.end())
{
mStateSetGenerator->update(found->second, lightList, frameNum);
return found->second;
}
auto stateset = mStateSetGenerator->generate(lightList, frameNum);
stateSetCache.emplace(lightIdList, stateset);
return stateset;
}
const std::vector<LightManager::LightSourceViewBound>& LightManager::getLightsInViewSpace(
osgUtil::CullVisitor* cv, const osg::RefMatrix* viewMatrix, size_t frameNum)
{
osg::Camera* camera = cv->getCurrentCamera();
osg::observer_ptr<osg::Camera> camPtr(camera);
auto it = mLightsInViewSpace.find(camPtr);
if (it == mLightsInViewSpace.end())
{
it = mLightsInViewSpace.insert(std::make_pair(camPtr, LightSourceViewBoundCollection())).first;
for (const auto& transform : mLights)
{
osg::Matrixf worldViewMat = transform.mWorldMatrix * (*viewMatrix);
float radius = transform.mLightSource->getRadius();
osg::BoundingSphere viewBound(osg::Vec3f(), radius * mPointLightRadiusMultiplier);
transformBoundingSphere(worldViewMat, viewBound);
if (transform.mLightSource->getLastAppliedFrame() != frameNum && mPointLightFadeEnd != 0.f)
{
const float fadeDelta = mPointLightFadeEnd - mPointLightFadeStart;
const float viewDelta = viewBound.center().length() - mPointLightFadeStart;
float fade = 1 - std::clamp(viewDelta / fadeDelta, 0.f, 1.f);
if (fade == 0.f)
continue;
auto* light = transform.mLightSource->getLight(frameNum);
light->setDiffuse(light->getDiffuse() * fade);
light->setSpecular(light->getSpecular() * fade);
transform.mLightSource->setLastAppliedFrame(frameNum);
}
LightSourceViewBound l;
l.mLightSource = transform.mLightSource;
l.mViewBound = viewBound;
it->second.push_back(l);
}
const bool fillPPLights = mPPLightBuffer && it->first->getName() == Constants::SceneCamera;
const bool sceneLimitReached = getLightingMethod() == LightingMethod::SingleUBO
&& it->second.size() > static_cast<size_t>(getMaxLightsInScene() - 1);
if (fillPPLights || sceneLimitReached)
{
auto sorter = [](const LightSourceViewBound& left, const LightSourceViewBound& right) {
return left.mViewBound.center().length2() - left.mViewBound.radius2()
< right.mViewBound.center().length2() - right.mViewBound.radius2();
};
std::sort(it->second.begin(), it->second.end(), sorter);
if (fillPPLights)
{
osg::CullingSet& cullingSet = cv->getModelViewCullingStack().front();
for (const auto& bound : it->second)
{
if (bound.mLightSource->getEmpty())
continue;
const auto* light = bound.mLightSource->getLight(frameNum);
// Ignore negative lights
if (light->getDiffuse().x() < 0.f)
continue;
const float radius = bound.mLightSource->getRadius();
osg::BoundingSphere frustumBound = bound.mViewBound;
frustumBound.radius() = radius * 2.f;
// Ignore culled lights
if (cullingSet.isCulled(frustumBound))
continue;
mPPLightBuffer->setLight(frameNum, light, radius);
}
}
if (sceneLimitReached)
it->second.resize(getMaxLightsInScene() - 1);
}
}
return it->second;
}
void LightManager::updateGPUPointLight(
int index, LightSource* lightSource, size_t frameNum, const osg::RefMatrix* viewMatrix)
{
auto* light = lightSource->getLight(frameNum);
auto& buf = getUBOManager()->getLightBuffer(frameNum);
buf->setDiffuse(index, light->getDiffuse());
buf->setAmbient(index, light->getAmbient());
buf->setSpecular(index, light->getSpecular());
buf->setAttenuationRadius(index,
osg::Vec4(light->getConstantAttenuation(), light->getLinearAttenuation(), light->getQuadraticAttenuation(),
lightSource->getRadius()));
buf->setPosition(index, light->getPosition() * (*viewMatrix));
}
osg::ref_ptr<osg::Uniform> LightManager::generateLightBufferUniform(const osg::Matrixf& sun)
{
osg::ref_ptr<osg::Uniform> uniform = new osg::Uniform(osg::Uniform::FLOAT_MAT4, "LightBuffer", getMaxLights());
uniform->setElement(0, sun);
return uniform;
}
void LightManager::setCollectPPLights(bool enabled)
{
if (enabled)
mPPLightBuffer = std::make_shared<PPLightBuffer>();
else
mPPLightBuffer = nullptr;
}
LightSource::LightSource()
: mRadius(0.f)
, mActorFade(1.f)
, mLastAppliedFrame(0)
{
setUpdateCallback(new CollectLightCallback);
mId = sLightId++;
}
LightSource::LightSource(const LightSource& copy, const osg::CopyOp& copyop)
: osg::Node(copy, copyop)
, mRadius(copy.mRadius)
, mActorFade(copy.mActorFade)
, mLastAppliedFrame(copy.mLastAppliedFrame)
{
mId = sLightId++;
for (size_t i = 0; i < mLight.size(); ++i)
mLight[i] = new osg::Light(*copy.mLight[i].get(), copyop);
}
void LightListCallback::operator()(osg::Node* node, osgUtil::CullVisitor* cv)
{
bool pushedState = pushLightState(node, cv);
traverse(node, cv);
if (pushedState)
cv->popStateSet();
}
bool LightListCallback::pushLightState(osg::Node* node, osgUtil::CullVisitor* cv)
{
if (!mLightManager)
{
mLightManager = findLightManager(cv->getNodePath());
if (!mLightManager)
return false;
}
if (!(cv->getTraversalMask() & mLightManager->getLightingMask()))
return false;
// Possible optimizations:
// - organize lights in a quad tree
// Don't use Camera::getViewMatrix, that one might be relative to another camera!
const osg::RefMatrix* viewMatrix = cv->getCurrentRenderStage()->getInitialViewMatrix();
// Update light list if necessary
// This makes sure we don't update it more than once per frame when rendering with multiple cameras
if (mLastFrameNumber != cv->getTraversalNumber())
{
mLastFrameNumber = cv->getTraversalNumber();
// Get the node bounds in view space
// NB: do not node->getBound() * modelView, that would apply the node's transformation twice
osg::BoundingSphere nodeBound;
const osg::Transform* transform = node->asTransform();
if (transform)
{
for (size_t i = 0; i < transform->getNumChildren(); ++i)
nodeBound.expandBy(transform->getChild(i)->getBound());
}
else
nodeBound = node->getBound();
transformBoundingSphere(*cv->getModelViewMatrix(), nodeBound);
const std::vector<LightManager::LightSourceViewBound>& lights
= mLightManager->getLightsInViewSpace(cv, viewMatrix, mLastFrameNumber);
mLightList.clear();
for (const LightManager::LightSourceViewBound& light : lights)
{
if (mIgnoredLightSources.contains(light.mLightSource))
continue;
if (light.mViewBound.intersects(nodeBound))
mLightList.push_back(&light);
}
const size_t maxLights = mLightManager->getMaxLights() - mLightManager->getStartLight();
if (mLightList.size() > maxLights)
{
// Sort by proximity to object: prefer closer lights with larger radius
std::sort(mLightList.begin(), mLightList.end(),
[&](const SceneUtil::LightManager::LightSourceViewBound* left,
const SceneUtil::LightManager::LightSourceViewBound* right) {
const float leftDist = (nodeBound.center() - left->mViewBound.center()).length2();
const float rightDist = (nodeBound.center() - right->mViewBound.center()).length2();
// A tricky way to compare normalized distance. This avoids division by near zero
return left->mViewBound.radius() * rightDist > right->mViewBound.radius() * leftDist;
});
mLightList.resize(maxLights);
}
}
if (!mLightList.empty())
{
cv->pushStateSet(mLightManager->getLightListStateSet(mLightList, mLastFrameNumber, viewMatrix));
return true;
}
return false;
}
}
| 49,568
|
C++
|
.cpp
| 1,110
| 33.513514
| 120
| 0.603251
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,716
|
writescene.cpp
|
OpenMW_openmw/components/sceneutil/writescene.cpp
|
#include "writescene.hpp"
#include <fstream>
#include <stdexcept>
#include <osgDB/Registry>
#include "serialize.hpp"
void SceneUtil::writeScene(osg::Node* node, const std::filesystem::path& filename, const std::string& format)
{
registerSerializers();
osgDB::ReaderWriter* rw = osgDB::Registry::instance()->getReaderWriterForExtension("osgt");
if (!rw)
throw std::runtime_error("can not find readerwriter for " + format);
std::ofstream stream;
stream.open(filename);
osg::ref_ptr<osgDB::Options> options = new osgDB::Options;
options->setPluginStringData("fileType", format);
options->setPluginStringData("WriteImageHint", "UseExternal");
rw->writeNode(*node, stream, options);
}
| 732
|
C++
|
.cpp
| 18
| 36.777778
| 109
| 0.729462
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,717
|
lightutil.cpp
|
OpenMW_openmw/components/sceneutil/lightutil.cpp
|
#include "lightutil.hpp"
#include <osg/Group>
#include <osg/Light>
#include <osgParticle/ParticleSystem>
#include <components/esm3/loadligh.hpp>
#include <components/fallback/fallback.hpp>
#include <components/sceneutil/lightcommon.hpp>
#include "lightcontroller.hpp"
#include "lightmanager.hpp"
#include "visitor.hpp"
namespace
{
class CheckEmptyLightVisitor : public osg::NodeVisitor
{
public:
CheckEmptyLightVisitor()
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
{
}
void apply(osg::Drawable& drawable) override
{
if (!mEmpty)
return;
if (dynamic_cast<const osgParticle::ParticleSystem*>(&drawable))
mEmpty = false;
else
traverse(drawable);
}
void apply(osg::Geometry& geometry) override { mEmpty = false; }
bool mEmpty = true;
};
}
namespace SceneUtil
{
void configureLight(osg::Light* light, float radius, bool isExterior)
{
float quadraticAttenuation = 0.f;
float linearAttenuation = 0.f;
float constantAttenuation = 0.f;
static const bool useConstant = Fallback::Map::getBool("LightAttenuation_UseConstant");
static const bool useLinear = Fallback::Map::getBool("LightAttenuation_UseLinear");
static const bool useQuadratic = Fallback::Map::getBool("LightAttenuation_UseQuadratic");
// User file might provide nonsense values
// Clamp these settings to prevent badness (e.g. illegal OpenGL calls)
static const float constantValue = std::max(Fallback::Map::getFloat("LightAttenuation_ConstantValue"), 0.f);
static const float linearValue = std::max(Fallback::Map::getFloat("LightAttenuation_LinearValue"), 0.f);
static const float quadraticValue = std::max(Fallback::Map::getFloat("LightAttenuation_QuadraticValue"), 0.f);
static const float linearRadiusMult
= std::max(Fallback::Map::getFloat("LightAttenuation_LinearRadiusMult"), 0.f);
static const float quadraticRadiusMult
= std::max(Fallback::Map::getFloat("LightAttenuation_QuadraticRadiusMult"), 0.f);
static const int linearMethod = Fallback::Map::getInt("LightAttenuation_LinearMethod");
static const int quadraticMethod = Fallback::Map::getInt("LightAttenuation_QuadraticMethod");
static const bool outQuadInLin = Fallback::Map::getBool("LightAttenuation_OutQuadInLin");
if (useConstant)
constantAttenuation = constantValue;
if (useLinear)
{
linearAttenuation = linearMethod == 0 ? linearValue : 0.01f;
float r = radius * linearRadiusMult;
if (r > 0.f && (linearMethod == 1 || linearMethod == 2))
linearAttenuation = linearValue / std::pow(r, linearMethod);
}
if (useQuadratic && (!outQuadInLin || isExterior))
{
quadraticAttenuation = quadraticMethod == 0 ? quadraticValue : 0.01f;
float r = radius * quadraticRadiusMult;
if (r > 0.f && (quadraticMethod == 1 || quadraticMethod == 2))
quadraticAttenuation = quadraticValue / std::pow(r, quadraticMethod);
}
// If the values are still nonsense, try to at least prevent UB and disable attenuation
if (constantAttenuation == 0.f && linearAttenuation == 0.f && quadraticAttenuation == 0.f)
constantAttenuation = 1.f;
light->setConstantAttenuation(constantAttenuation);
light->setLinearAttenuation(linearAttenuation);
light->setQuadraticAttenuation(quadraticAttenuation);
}
osg::ref_ptr<LightSource> addLight(
osg::Group* node, const SceneUtil::LightCommon& esmLight, unsigned int lightMask, bool isExterior)
{
SceneUtil::FindByNameVisitor visitor("AttachLight");
node->accept(visitor);
osg::Group* attachTo = visitor.mFoundNode ? visitor.mFoundNode : node;
osg::ref_ptr<LightSource> lightSource
= createLightSource(esmLight, lightMask, isExterior, osg::Vec4f(0, 0, 0, 1));
attachTo->addChild(lightSource);
CheckEmptyLightVisitor emptyVisitor;
node->accept(emptyVisitor);
lightSource->setEmpty(emptyVisitor.mEmpty);
return lightSource;
}
osg::ref_ptr<LightSource> createLightSource(
const SceneUtil::LightCommon& esmLight, unsigned int lightMask, bool isExterior, const osg::Vec4f& ambient)
{
osg::ref_ptr<SceneUtil::LightSource> lightSource(new SceneUtil::LightSource);
osg::ref_ptr<osg::Light> light(new osg::Light);
lightSource->setNodeMask(lightMask);
float radius = esmLight.mRadius;
lightSource->setRadius(radius);
configureLight(light, radius, isExterior);
osg::Vec4f diffuse = esmLight.mColor;
osg::Vec4f specular = esmLight.mColor; // ESM format doesn't provide specular
if (esmLight.mNegative)
{
diffuse *= -1;
diffuse.a() = 1;
// Using specular lighting for negative lights is unreasonable
specular = osg::Vec4f();
}
light->setDiffuse(diffuse);
light->setAmbient(ambient);
light->setSpecular(specular);
lightSource->setLight(light);
osg::ref_ptr<SceneUtil::LightController> ctrl(new SceneUtil::LightController);
ctrl->setDiffuse(light->getDiffuse());
ctrl->setSpecular(light->getSpecular());
if (esmLight.mFlicker)
ctrl->setType(SceneUtil::LightController::LT_Flicker);
if (esmLight.mFlickerSlow)
ctrl->setType(SceneUtil::LightController::LT_FlickerSlow);
if (esmLight.mPulse)
ctrl->setType(SceneUtil::LightController::LT_Pulse);
if (esmLight.mPulseSlow)
ctrl->setType(SceneUtil::LightController::LT_PulseSlow);
lightSource->addUpdateCallback(ctrl);
return lightSource;
}
}
| 6,000
|
C++
|
.cpp
| 128
| 38.015625
| 118
| 0.664841
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,718
|
workqueue.cpp
|
OpenMW_openmw/components/sceneutil/workqueue.cpp
|
#include "workqueue.hpp"
#include <components/debug/debuglog.hpp>
#include <numeric>
namespace SceneUtil
{
void WorkItem::waitTillDone()
{
if (mDone)
return;
std::unique_lock<std::mutex> lock(mMutex);
while (!mDone)
{
mCondition.wait(lock);
}
}
void WorkItem::signalDone()
{
{
std::unique_lock<std::mutex> lock(mMutex);
mDone = true;
}
mCondition.notify_all();
}
bool WorkItem::isDone() const
{
return mDone;
}
WorkQueue::WorkQueue(std::size_t workerThreads)
: mIsReleased(false)
{
start(workerThreads);
}
WorkQueue::~WorkQueue()
{
stop();
}
void WorkQueue::start(std::size_t workerThreads)
{
{
const std::lock_guard lock(mMutex);
mIsReleased = false;
}
while (mThreads.size() < workerThreads)
mThreads.emplace_back(std::make_unique<WorkThread>(*this));
}
void WorkQueue::stop()
{
{
std::unique_lock<std::mutex> lock(mMutex);
while (!mQueue.empty())
mQueue.pop_back();
mIsReleased = true;
mCondition.notify_all();
}
mThreads.clear();
}
void WorkQueue::addWorkItem(osg::ref_ptr<WorkItem> item, bool front)
{
if (item->isDone())
{
Log(Debug::Error) << "Error: trying to add a work item that is already completed";
return;
}
std::unique_lock<std::mutex> lock(mMutex);
if (front)
mQueue.push_front(std::move(item));
else
mQueue.push_back(std::move(item));
mCondition.notify_one();
}
osg::ref_ptr<WorkItem> WorkQueue::removeWorkItem()
{
std::unique_lock<std::mutex> lock(mMutex);
while (mQueue.empty() && !mIsReleased)
{
mCondition.wait(lock);
}
if (!mQueue.empty())
{
osg::ref_ptr<WorkItem> item = std::move(mQueue.front());
mQueue.pop_front();
return item;
}
return nullptr;
}
unsigned int WorkQueue::getNumItems() const
{
std::unique_lock<std::mutex> lock(mMutex);
return mQueue.size();
}
unsigned int WorkQueue::getNumActiveThreads() const
{
return std::accumulate(
mThreads.begin(), mThreads.end(), 0u, [](auto r, const auto& t) { return r + t->isActive(); });
}
WorkThread::WorkThread(WorkQueue& workQueue)
: mWorkQueue(&workQueue)
, mActive(false)
, mThread([this] { run(); })
{
}
WorkThread::~WorkThread()
{
mThread.join();
}
void WorkThread::run()
{
while (true)
{
osg::ref_ptr<WorkItem> item = mWorkQueue->removeWorkItem();
if (!item)
return;
mActive = true;
item->doWork();
item->signalDone();
mActive = false;
}
}
bool WorkThread::isActive() const
{
return mActive;
}
}
| 3,175
|
C++
|
.cpp
| 123
| 17.512195
| 107
| 0.530693
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,719
|
util.cpp
|
OpenMW_openmw/components/sceneutil/util.cpp
|
#include "util.hpp"
#include <algorithm>
#include <array>
#include <iomanip>
#include <sstream>
#include <osg/FrameBufferObject>
#include <osg/Node>
#include <osg/NodeVisitor>
#include <osg/TexEnvCombine>
#include <osg/TexGen>
#include <osgUtil/CullVisitor>
#include <osgUtil/RenderStage>
#include <components/resource/imagemanager.hpp>
#include <components/resource/scenemanager.hpp>
#include <components/sceneutil/texturetype.hpp>
#include <components/vfs/pathutil.hpp>
namespace SceneUtil
{
namespace
{
std::array<VFS::Path::Normalized, 32> generateGlowTextureNames()
{
constexpr VFS::Path::NormalizedView prefix("textures/magicitem");
std::array<VFS::Path::Normalized, 32> result;
for (std::size_t i = 0; i < result.size(); ++i)
{
std::stringstream stream;
stream << "caust";
stream << std::setw(2);
stream << std::setfill('0');
stream << i;
stream << ".dds";
result[i] = prefix / VFS::Path::Normalized(std::move(stream).str());
}
return result;
}
const std::array<VFS::Path::Normalized, 32> glowTextureNames = generateGlowTextureNames();
struct FindLowestUnusedTexUnitVisitor : public osg::NodeVisitor
{
FindLowestUnusedTexUnitVisitor()
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
{
}
void apply(osg::Node& node) override
{
if (osg::StateSet* stateset = node.getStateSet())
mLowestUnusedTexUnit
= std::max(mLowestUnusedTexUnit, int(stateset->getTextureAttributeList().size()));
traverse(node);
}
int mLowestUnusedTexUnit = 0;
};
}
GlowUpdater::GlowUpdater(int texUnit, const osg::Vec4f& color,
const std::vector<osg::ref_ptr<osg::Texture2D>>& textures, osg::Node* node, float duration,
Resource::ResourceSystem* resourcesystem)
: mTexUnit(texUnit)
, mColor(color)
, mOriginalColor(color)
, mTextures(textures)
, mNode(node)
, mDuration(duration)
, mOriginalDuration(duration)
, mStartingTime(0)
, mResourceSystem(resourcesystem)
, mColorChanged(false)
, mDone(false)
{
}
void GlowUpdater::setDefaults(osg::StateSet* stateset)
{
if (mDone)
removeTexture(stateset);
else
{
stateset->setTextureMode(mTexUnit, GL_TEXTURE_2D, osg::StateAttribute::ON);
osg::TexGen* texGen = new osg::TexGen;
texGen->setMode(osg::TexGen::SPHERE_MAP);
stateset->setTextureAttributeAndModes(
mTexUnit, texGen, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
osg::TexEnvCombine* texEnv = new osg::TexEnvCombine;
texEnv->setSource0_RGB(osg::TexEnvCombine::CONSTANT);
texEnv->setConstantColor(mColor);
texEnv->setCombine_RGB(osg::TexEnvCombine::INTERPOLATE);
texEnv->setSource2_RGB(osg::TexEnvCombine::TEXTURE);
texEnv->setOperand2_RGB(osg::TexEnvCombine::SRC_COLOR);
stateset->setTextureAttributeAndModes(mTexUnit, texEnv, osg::StateAttribute::ON);
stateset->addUniform(new osg::Uniform("envMapColor", mColor));
}
}
void GlowUpdater::removeTexture(osg::StateSet* stateset)
{
stateset->removeTextureAttribute(mTexUnit, osg::StateAttribute::TEXTURE);
stateset->removeTextureAttribute(mTexUnit, osg::StateAttribute::TEXGEN);
stateset->removeTextureAttribute(mTexUnit, osg::StateAttribute::TEXENV);
stateset->removeTextureMode(mTexUnit, GL_TEXTURE_2D);
stateset->removeUniform("envMapColor");
osg::StateSet::TextureAttributeList& list = stateset->getTextureAttributeList();
while (list.size() && list.rbegin()->empty())
list.pop_back();
}
void GlowUpdater::apply(osg::StateSet* stateset, osg::NodeVisitor* nv)
{
if (mColorChanged)
{
this->reset();
setDefaults(stateset);
mColorChanged = false;
}
if (mDone)
return;
// Set the starting time to measure glow duration from if this is a temporary glow
if ((mDuration >= 0) && mStartingTime == 0)
mStartingTime = nv->getFrameStamp()->getSimulationTime();
float time = nv->getFrameStamp()->getSimulationTime();
int index = (int)(time * 16) % mTextures.size();
stateset->setTextureAttribute(
mTexUnit, mTextures[index], osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
if ((mDuration >= 0)
&& (time - mStartingTime > mDuration)) // If this is a temporary glow and it has finished its duration
{
if (mOriginalDuration >= 0) // if this glowupdater was a temporary glow since its creation
{
removeTexture(stateset);
this->reset();
mDone = true;
// normally done in StateSetUpdater::operator(), but needs doing here so the shader visitor sees the
// right StateSet
mNode->setStateSet(stateset);
mResourceSystem->getSceneManager()->recreateShaders(mNode);
}
if (mOriginalDuration < 0) // if this glowupdater was originally a permanent glow
{
mDuration = mOriginalDuration;
mStartingTime = 0;
mColor = mOriginalColor;
this->reset();
setDefaults(stateset);
}
}
}
bool GlowUpdater::isPermanentGlowUpdater()
{
return (mDuration < 0);
}
bool GlowUpdater::isDone()
{
return mDone;
}
void GlowUpdater::setColor(const osg::Vec4f& color)
{
mColor = color;
mColorChanged = true;
}
void GlowUpdater::setDuration(float duration)
{
mDuration = duration;
}
osg::Vec4f colourFromRGB(unsigned int clr)
{
osg::Vec4f colour(
((clr >> 0) & 0xFF) / 255.0f, ((clr >> 8) & 0xFF) / 255.0f, ((clr >> 16) & 0xFF) / 255.0f, 1.f);
return colour;
}
osg::Vec4f colourFromRGBA(unsigned int value)
{
return osg::Vec4f(makeOsgColorComponent(value, 0), makeOsgColorComponent(value, 8),
makeOsgColorComponent(value, 16), makeOsgColorComponent(value, 24));
}
float makeOsgColorComponent(unsigned int value, unsigned int shift)
{
return float((value >> shift) & 0xFFu) / 255.0f;
}
bool hasUserDescription(const osg::Node* node, std::string_view pattern)
{
if (node == nullptr)
return false;
const osg::UserDataContainer* udc = node->getUserDataContainer();
if (udc && udc->getNumDescriptions() > 0)
{
for (auto& descr : udc->getDescriptions())
{
if (descr == pattern)
return true;
}
}
return false;
}
osg::ref_ptr<GlowUpdater> addEnchantedGlow(osg::ref_ptr<osg::Node> node, Resource::ResourceSystem* resourceSystem,
const osg::Vec4f& glowColor, float glowDuration)
{
std::vector<osg::ref_ptr<osg::Texture2D>> textures;
for (const VFS::Path::Normalized& name : glowTextureNames)
{
osg::ref_ptr<osg::Image> image = resourceSystem->getImageManager()->getImage(name);
osg::ref_ptr<osg::Texture2D> tex(new osg::Texture2D(image));
tex->setWrap(osg::Texture::WRAP_S, osg::Texture2D::REPEAT);
tex->setWrap(osg::Texture::WRAP_T, osg::Texture2D::REPEAT);
resourceSystem->getSceneManager()->applyFilterSettings(tex);
textures.push_back(tex);
}
FindLowestUnusedTexUnitVisitor findLowestUnusedTexUnitVisitor;
node->accept(findLowestUnusedTexUnitVisitor);
int texUnit = findLowestUnusedTexUnitVisitor.mLowestUnusedTexUnit;
osg::ref_ptr<GlowUpdater> glowUpdater
= new GlowUpdater(texUnit, glowColor, textures, node, glowDuration, resourceSystem);
node->addUpdateCallback(glowUpdater);
// set a texture now so that the ShaderVisitor can find it
osg::ref_ptr<osg::StateSet> writableStateSet = nullptr;
if (!node->getStateSet())
writableStateSet = node->getOrCreateStateSet();
else
{
writableStateSet = new osg::StateSet(*node->getStateSet(), osg::CopyOp::SHALLOW_COPY);
node->setStateSet(writableStateSet);
}
writableStateSet->setTextureAttributeAndModes(texUnit, textures.front(), osg::StateAttribute::ON);
writableStateSet->setTextureAttributeAndModes(texUnit, new TextureType("envMap"), osg::StateAttribute::ON);
writableStateSet->addUniform(new osg::Uniform("envMapColor", glowColor));
resourceSystem->getSceneManager()->recreateShaders(std::move(node));
return glowUpdater;
}
void attachAlphaToCoverageFriendlyFramebufferToCamera(osg::Camera* camera, osg::Camera::BufferComponent buffer,
osg::Texture* texture, unsigned int level, unsigned int face, bool mipMapGeneration,
bool addMSAAIntermediateTarget)
{
unsigned int samples = 0;
unsigned int colourSamples = 0;
if (addMSAAIntermediateTarget)
{
// Alpha-to-coverage requires a multisampled framebuffer.
// OSG will set that up automatically and resolve it to the specified single-sample texture for us.
// For some reason, two samples are needed, at least with some drivers.
samples = 2;
colourSamples = 1;
}
camera->attach(buffer, texture, level, face, mipMapGeneration, samples, colourSamples);
}
OperationSequence::OperationSequence(bool keep)
: Operation("OperationSequence", keep)
, mOperationQueue(new osg::OperationQueue())
{
}
void OperationSequence::operator()(osg::Object* object)
{
mOperationQueue->runOperations(object);
}
void OperationSequence::add(osg::Operation* operation)
{
mOperationQueue->add(operation);
}
GLenum computeUnsizedPixelFormat(GLenum format)
{
switch (format)
{
// Try compressed formats first, they're more likely to be used
// Generic
case GL_COMPRESSED_ALPHA_ARB:
return GL_ALPHA;
case GL_COMPRESSED_INTENSITY_ARB:
return GL_INTENSITY;
case GL_COMPRESSED_LUMINANCE_ALPHA_ARB:
return GL_LUMINANCE_ALPHA;
case GL_COMPRESSED_LUMINANCE_ARB:
return GL_LUMINANCE;
case GL_COMPRESSED_RGB_ARB:
return GL_RGB;
case GL_COMPRESSED_RGBA_ARB:
return GL_RGBA;
// S3TC
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT:
return GL_RGB;
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:
return GL_RGBA;
// RGTC
case GL_COMPRESSED_RED_RGTC1_EXT:
case GL_COMPRESSED_SIGNED_RED_RGTC1_EXT:
return GL_RED;
case GL_COMPRESSED_RED_GREEN_RGTC2_EXT:
case GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT:
return GL_RG;
// PVRTC
case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
return GL_RGB;
case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
return GL_RGBA;
// ETC
case GL_COMPRESSED_R11_EAC:
case GL_COMPRESSED_SIGNED_R11_EAC:
return GL_RED;
case GL_COMPRESSED_RG11_EAC:
case GL_COMPRESSED_SIGNED_RG11_EAC:
return GL_RG;
case GL_ETC1_RGB8_OES:
case GL_COMPRESSED_RGB8_ETC2:
case GL_COMPRESSED_SRGB8_ETC2:
return GL_RGB;
case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
case GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
case GL_COMPRESSED_RGBA8_ETC2_EAC:
case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
return GL_RGBA;
// ASTC
case GL_COMPRESSED_RGBA_ASTC_4x4_KHR:
case GL_COMPRESSED_RGBA_ASTC_5x4_KHR:
case GL_COMPRESSED_RGBA_ASTC_5x5_KHR:
case GL_COMPRESSED_RGBA_ASTC_6x5_KHR:
case GL_COMPRESSED_RGBA_ASTC_6x6_KHR:
case GL_COMPRESSED_RGBA_ASTC_8x5_KHR:
case GL_COMPRESSED_RGBA_ASTC_8x6_KHR:
case GL_COMPRESSED_RGBA_ASTC_8x8_KHR:
case GL_COMPRESSED_RGBA_ASTC_10x5_KHR:
case GL_COMPRESSED_RGBA_ASTC_10x6_KHR:
case GL_COMPRESSED_RGBA_ASTC_10x8_KHR:
case GL_COMPRESSED_RGBA_ASTC_10x10_KHR:
case GL_COMPRESSED_RGBA_ASTC_12x10_KHR:
case GL_COMPRESSED_RGBA_ASTC_12x12_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
return GL_RGBA;
// Plug in some holes computePixelFormat has, you never know when these could come in handy
case GL_INTENSITY4:
case GL_INTENSITY8:
case GL_INTENSITY12:
case GL_INTENSITY16:
return GL_INTENSITY;
case GL_LUMINANCE4:
case GL_LUMINANCE8:
case GL_LUMINANCE12:
case GL_LUMINANCE16:
return GL_LUMINANCE;
case GL_LUMINANCE4_ALPHA4:
case GL_LUMINANCE6_ALPHA2:
case GL_LUMINANCE8_ALPHA8:
case GL_LUMINANCE12_ALPHA4:
case GL_LUMINANCE12_ALPHA12:
case GL_LUMINANCE16_ALPHA16:
return GL_LUMINANCE_ALPHA;
}
return osg::Image::computePixelFormat(format);
}
const std::string& getTextureType(const osg::StateSet& stateset, const osg::Texture& texture, unsigned int texUnit)
{
const osg::StateAttribute* type = stateset.getTextureAttribute(texUnit, SceneUtil::TextureType::AttributeType);
if (type)
return static_cast<const SceneUtil::TextureType*>(type)->getName();
return texture.getName();
}
}
| 15,629
|
C++
|
.cpp
| 369
| 31.642276
| 119
| 0.612244
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,720
|
color.cpp
|
OpenMW_openmw/components/sceneutil/color.cpp
|
#include "color.hpp"
#include <algorithm>
#include <array>
namespace SceneUtil
{
bool isColorFormat(GLenum format)
{
static constexpr std::array<GLenum, 42> formats = {
GL_RGB,
GL_RGB4,
GL_RGB5,
GL_RGB8,
GL_RGB8_SNORM,
GL_RGB10,
GL_RGB12,
GL_RGB16,
GL_RGB16_SNORM,
GL_SRGB,
GL_SRGB8,
GL_RGB16F,
GL_RGB32F,
GL_R11F_G11F_B10F,
GL_RGB9_E5,
GL_RGB8I,
GL_RGB8UI,
GL_RGB16I,
GL_RGB16UI,
GL_RGB32I,
GL_RGB32UI,
GL_RGBA,
GL_RGBA2,
GL_RGBA4,
GL_RGB5_A1,
GL_RGBA8,
GL_RGBA8_SNORM,
GL_RGB10_A2,
GL_RGB10_A2UI,
GL_RGBA12,
GL_RGBA16,
GL_RGBA16_SNORM,
GL_SRGB_ALPHA8,
GL_SRGB8_ALPHA8,
GL_RGBA16F,
GL_RGBA32F,
GL_RGBA8I,
GL_RGBA8UI,
GL_RGBA16I,
GL_RGBA16UI,
GL_RGBA32I,
GL_RGBA32UI,
};
return std::find(formats.cbegin(), formats.cend(), format) != formats.cend();
}
bool isFloatingPointColorFormat(GLenum format)
{
static constexpr std::array<GLenum, 5> formats = {
GL_RGB16F,
GL_RGB32F,
GL_R11F_G11F_B10F,
GL_RGBA16F,
GL_RGBA32F,
};
return std::find(formats.cbegin(), formats.cend(), format) != formats.cend();
}
int getColorFormatChannelCount(GLenum format)
{
static constexpr std::array<GLenum, 21> formats = {
GL_RGBA,
GL_RGBA2,
GL_RGBA4,
GL_RGB5_A1,
GL_RGBA8,
GL_RGBA8_SNORM,
GL_RGB10_A2,
GL_RGB10_A2UI,
GL_RGBA12,
GL_RGBA16,
GL_RGBA16_SNORM,
GL_SRGB_ALPHA8,
GL_SRGB8_ALPHA8,
GL_RGBA16F,
GL_RGBA32F,
GL_RGBA8I,
GL_RGBA8UI,
GL_RGBA16I,
GL_RGBA16UI,
GL_RGBA32I,
GL_RGBA32UI,
};
if (std::find(formats.cbegin(), formats.cend(), format) != formats.cend())
return 4;
return 3;
}
void getColorFormatSourceFormatAndType(GLenum internalFormat, GLenum& sourceFormat, GLenum& sourceType)
{
if (getColorFormatChannelCount(internalFormat == 4))
sourceFormat = GL_RGBA;
else
sourceFormat = GL_RGB;
if (isFloatingPointColorFormat(internalFormat))
sourceType = GL_FLOAT;
else
sourceType = GL_UNSIGNED_BYTE;
}
namespace Color
{
GLenum sColorInternalFormat;
GLenum sColorSourceFormat;
GLenum sColorSourceType;
GLenum colorInternalFormat()
{
return sColorInternalFormat;
}
GLenum colorSourceFormat()
{
return sColorSourceFormat;
}
GLenum colorSourceType()
{
return sColorSourceType;
}
void SelectColorFormatOperation::operator()([[maybe_unused]] osg::GraphicsContext* graphicsContext)
{
sColorInternalFormat = GL_RGB;
for (auto supportedFormat : mSupportedFormats)
{
if (isColorFormat(supportedFormat))
{
sColorInternalFormat = supportedFormat;
break;
}
}
getColorFormatSourceFormatAndType(sColorInternalFormat, sColorSourceFormat, sColorSourceType);
}
}
}
| 3,796
|
C++
|
.cpp
| 136
| 16.852941
| 107
| 0.507958
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,721
|
lightcontroller.cpp
|
OpenMW_openmw/components/sceneutil/lightcontroller.cpp
|
#include "lightcontroller.hpp"
#include <cmath>
#include <osg/NodeVisitor>
#include <components/sceneutil/lightmanager.hpp>
#include <components/misc/rng.hpp>
namespace SceneUtil
{
LightController::LightController()
: mType(LT_Normal)
, mPhase(0.25f + Misc::Rng::rollClosedProbability() * 0.75f)
, mBrightness(0.675f)
, mStartTime(0.0)
, mLastTime(0.0)
, mTicksToAdvance(0.f)
{
}
void LightController::setType(LightController::LightType type)
{
mType = type;
}
void LightController::operator()(SceneUtil::LightSource* node, osg::NodeVisitor* nv)
{
double time = nv->getFrameStamp()->getSimulationTime();
if (mStartTime == 0)
mStartTime = time;
// disabled early out, light state needs to be set every frame regardless of change, due to the double buffering
// if (time == mLastTime)
// return;
osg::Light* light = node->getLight(nv->getTraversalNumber());
if (mType == LT_Normal)
{
light->setDiffuse(mDiffuseColor);
light->setSpecular(mSpecularColor);
traverse(node, nv);
return;
}
// Updating flickering at 15 FPS like vanilla.
constexpr float updateRate = 15.f;
mTicksToAdvance
= static_cast<float>(time - mStartTime - mLastTime) * updateRate * 0.25f + mTicksToAdvance * 0.75f;
mLastTime = time - mStartTime;
float speed = (mType == LT_Flicker || mType == LT_Pulse) ? 0.1f : 0.05f;
if (mBrightness >= mPhase)
mBrightness -= mTicksToAdvance * speed;
else
mBrightness += mTicksToAdvance * speed;
if (std::abs(mBrightness - mPhase) < speed)
{
if (mType == LT_Flicker || mType == LT_FlickerSlow)
mPhase = 0.25f + Misc::Rng::rollClosedProbability() * 0.75f;
else // if (mType == LT_Pulse || mType == LT_PulseSlow)
mPhase = mPhase <= 0.5f ? 1.f : 0.25f;
}
const float result = mBrightness * node->getActorFade();
light->setDiffuse(mDiffuseColor * result);
light->setSpecular(mSpecularColor * result);
traverse(node, nv);
}
void LightController::setDiffuse(const osg::Vec4f& color)
{
mDiffuseColor = color;
}
void LightController::setSpecular(const osg::Vec4f& color)
{
mSpecularColor = color;
}
}
| 2,484
|
C++
|
.cpp
| 67
| 28.791045
| 120
| 0.605757
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,722
|
agentpath.cpp
|
OpenMW_openmw/components/sceneutil/agentpath.cpp
|
#include "agentpath.hpp"
#include "detourdebugdraw.hpp"
#include <osg/Material>
#include <components/detournavigator/recastparams.hpp>
#include <components/detournavigator/settings.hpp>
#include <algorithm>
namespace
{
void drawAgent(duDebugDraw& debugDraw, const osg::Vec3f& pos, const float radius, const float height,
const float climb, const unsigned color)
{
debugDraw.depthMask(false);
duDebugDrawCylinderWire(&debugDraw, pos.x() - radius, pos.z() + 0.02f, pos.y() - radius, pos.x() + radius,
pos.z() + height, pos.y() + radius, color, radius * 0.2f);
duDebugDrawCircle(&debugDraw, pos.x(), pos.z() + climb, pos.y(), radius, duRGBA(0, 0, 0, 64), radius * 0.1f);
const auto colb = duRGBA(0, 0, 0, 196);
debugDraw.begin(DU_DRAW_LINES);
debugDraw.vertex(pos.x(), pos.z() - climb, pos.y(), colb);
debugDraw.vertex(pos.x(), pos.z() + climb, pos.y(), colb);
debugDraw.vertex(pos.x() - radius / 2, pos.z() + 0.02f, pos.y(), colb);
debugDraw.vertex(pos.x() + radius / 2, pos.z() + 0.02f, pos.y(), colb);
debugDraw.vertex(pos.x(), pos.z() + 0.02f, pos.y() - radius / 2, colb);
debugDraw.vertex(pos.x(), pos.z() + 0.02f, pos.y() + radius / 2, colb);
debugDraw.end();
debugDraw.depthMask(true);
}
}
namespace SceneUtil
{
osg::ref_ptr<osg::Group> createAgentPathGroup(const std::deque<osg::Vec3f>& path,
const DetourNavigator::AgentBounds& agentBounds, const osg::Vec3f& start, const osg::Vec3f& end,
const DetourNavigator::RecastSettings& settings, const osg::ref_ptr<osg::StateSet>& debugDrawStateSet)
{
using namespace DetourNavigator;
osg::ref_ptr<osg::Group> group(new osg::Group);
DebugDraw debugDraw(*group, debugDrawStateSet, osg::Vec3f(0, 0, 0), 1);
const auto agentRadius = DetourNavigator::getAgentRadius(agentBounds);
const auto agentHeight = DetourNavigator::getAgentHeight(agentBounds);
const auto agentClimb = settings.mMaxClimb;
const auto startColor = duRGBA(128, 25, 0, 192);
const auto endColor = duRGBA(51, 102, 0, 129);
drawAgent(debugDraw, start, agentRadius, agentHeight, agentClimb, startColor);
drawAgent(debugDraw, end, agentRadius, agentHeight, agentClimb, endColor);
const auto pathColor = duRGBA(0, 0, 0, 220);
debugDraw.depthMask(false);
debugDraw.begin(osg::PrimitiveSet::LINE_STRIP, agentRadius * 0.5f);
debugDraw.vertex(osg::Vec3f(start.x(), start.z() + agentClimb, start.y()).ptr(), startColor);
std::for_each(path.begin(), path.end(), [&](const osg::Vec3f& v) {
debugDraw.vertex(osg::Vec3f(v.x(), v.z() + agentClimb, v.y()).ptr(), pathColor);
});
debugDraw.vertex(osg::Vec3f(end.x(), end.z() + agentClimb, end.y()).ptr(), endColor);
debugDraw.end();
debugDraw.depthMask(true);
return group;
}
}
| 2,979
|
C++
|
.cpp
| 56
| 45.857143
| 117
| 0.645317
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,723
|
lightcommon.cpp
|
OpenMW_openmw/components/sceneutil/lightcommon.cpp
|
#include "lightcommon.hpp"
#include <components/esm3/loadligh.hpp>
#include <components/esm4/loadligh.hpp>
#include <components/sceneutil/util.hpp>
namespace SceneUtil
{
LightCommon::LightCommon(const ESM::Light& light)
: mFlicker(light.mData.mFlags & ESM::Light::Flicker)
, mFlickerSlow(light.mData.mFlags & ESM::Light::FlickerSlow)
, mNegative(light.mData.mFlags & ESM::Light::Negative)
, mPulse(light.mData.mFlags & ESM::Light::Pulse)
, mPulseSlow(light.mData.mFlags & ESM::Light::PulseSlow)
, mOffDefault(light.mData.mFlags & ESM::Light::OffDefault)
, mColor(SceneUtil::colourFromRGB(light.mData.mColor))
, mRadius(light.mData.mRadius)
{
}
LightCommon::LightCommon(const ESM4::Light& light)
: mFlicker(light.mData.flags & ESM4::Light::Flicker)
, mFlickerSlow(light.mData.flags & ESM4::Light::FlickerSlow)
, mNegative(light.mData.flags & ESM::Light::Negative)
, mPulse(light.mData.flags & ESM4::Light::Pulse)
, mPulseSlow(light.mData.flags & ESM4::Light::PulseSlow)
, mOffDefault(light.mData.flags & ESM4::Light::OffDefault)
, mColor(SceneUtil::colourFromRGB(light.mData.colour))
, mRadius(light.mData.radius)
{
}
}
| 1,275
|
C++
|
.cpp
| 29
| 37.586207
| 68
| 0.685185
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,724
|
pathgridutil.cpp
|
OpenMW_openmw/components/sceneutil/pathgridutil.cpp
|
#include "pathgridutil.hpp"
#include <osg/Geometry>
#include <osg/Material>
#include <components/esm3/loadpgrd.hpp>
#include <limits>
namespace SceneUtil
{
namespace
{
constexpr unsigned short DiamondVertexCount = 6;
constexpr unsigned short DiamondIndexCount = 24;
constexpr unsigned short DiamondWireframeIndexCount = 24;
constexpr unsigned short DiamondConnectorVertexCount = 4;
constexpr unsigned short DiamondTotalVertexCount = DiamondVertexCount + DiamondConnectorVertexCount;
constexpr float DiamondWireframeScalar = 1.1f;
const osg::Vec3f DiamondPoints[DiamondVertexCount] = { osg::Vec3f(0.f, 0.f, DiamondHalfHeight * 2.f),
osg::Vec3f(-DiamondHalfWidth, -DiamondHalfWidth, DiamondHalfHeight),
osg::Vec3f(-DiamondHalfWidth, DiamondHalfWidth, DiamondHalfHeight),
osg::Vec3f(DiamondHalfWidth, -DiamondHalfWidth, DiamondHalfHeight),
osg::Vec3f(DiamondHalfWidth, DiamondHalfWidth, DiamondHalfHeight), osg::Vec3f(0.f, 0.f, 0.f) };
constexpr unsigned short DiamondIndices[DiamondIndexCount]
= { 0, 2, 1, 0, 1, 3, 0, 3, 4, 0, 4, 2, 5, 1, 2, 5, 3, 1, 5, 4, 3, 5, 2, 4 };
constexpr unsigned short DiamondWireframeIndices[DiamondWireframeIndexCount]
= { 0, 1, 0, 2, 0, 3, 0, 4, 1, 2, 2, 4, 4, 3, 3, 1, 5, 1, 5, 2, 5, 3, 5, 4 };
constexpr unsigned short DiamondConnectorVertices[DiamondConnectorVertexCount] = { 1, 2, 3, 4 };
const osg::Vec4f DiamondColors[DiamondVertexCount]
= { osg::Vec4f(0.f, 0.f, 1.f, 1.f), osg::Vec4f(0.f, .05f, .95f, 1.f), osg::Vec4f(0.f, .1f, .95f, 1.f),
osg::Vec4f(0.f, .15f, .95f, 1.f), osg::Vec4f(0.f, .2f, .95f, 1.f), osg::Vec4f(0.f, .25f, 9.f, 1.f) };
const osg::Vec4f DiamondEdgeColor = osg::Vec4f(0.5f, 1.f, 1.f, 1.f);
const osg::Vec4f DiamondWireColor = osg::Vec4f(0.72f, 0.f, 0.96f, 1.f);
const osg::Vec4f DiamondFocusWireColor = osg::Vec4f(0.91f, 0.66f, 1.f, 1.f);
template <class PType, class LType>
void addPathgridToGeometry(const size_t vertexCount, const size_t pointIndexCount, const size_t edgeIndexCount,
osg::ref_ptr<osg::Geometry>& gridGeometry, const ESM::Pathgrid& pathgrid)
{
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(vertexCount);
osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(vertexCount);
osg::ref_ptr<PType> pointIndices = new PType(osg::PrimitiveSet::TRIANGLES, pointIndexCount);
osg::ref_ptr<LType> lineIndices = new LType(osg::PrimitiveSet::LINES, edgeIndexCount);
// Add each point/node
for (size_t pointIndex = 0; pointIndex < pathgrid.mPoints.size(); ++pointIndex)
{
const ESM::Pathgrid::Point& point = pathgrid.mPoints[pointIndex];
osg::Vec3f position = osg::Vec3f(point.mX, point.mY, point.mZ);
size_t vertexOffset = pointIndex * DiamondTotalVertexCount;
size_t indexOffset = pointIndex * DiamondIndexCount;
// Point
for (unsigned short i = 0; i < DiamondVertexCount; ++i)
{
(*vertices)[vertexOffset + i] = position + DiamondPoints[i];
(*colors)[vertexOffset + i] = DiamondColors[i];
}
for (unsigned short i = 0; i < DiamondIndexCount; ++i)
{
pointIndices->setElement(indexOffset + i, vertexOffset + DiamondIndices[i]);
}
// Connectors
vertexOffset += DiamondVertexCount;
for (unsigned short i = 0; i < DiamondConnectorVertexCount; ++i)
{
(*vertices)[vertexOffset + i] = position + DiamondPoints[DiamondConnectorVertices[i]];
(*colors)[vertexOffset + i] = DiamondEdgeColor;
}
}
// Add edges
unsigned int lineIndex = 0;
for (const ESM::Pathgrid::Edge& edge : pathgrid.mEdges)
{
if (edge.mV0 == edge.mV1 || edge.mV0 >= pathgrid.mPoints.size() || edge.mV1 >= pathgrid.mPoints.size())
continue;
const ESM::Pathgrid::Point& from = pathgrid.mPoints[edge.mV0];
const ESM::Pathgrid::Point& to = pathgrid.mPoints[edge.mV1];
osg::Vec3f fromPos = osg::Vec3f(from.mX, from.mY, from.mZ);
osg::Vec3f toPos = osg::Vec3f(to.mX, to.mY, to.mZ);
osg::Vec3f dir = toPos - fromPos;
dir.normalize();
osg::Quat rot(static_cast<float>(-osg::PI_2), osg::Vec3f(0, 0, 1));
dir = rot * dir;
unsigned short diamondIndex = 0;
if (dir.isNaN())
diamondIndex = 0;
else if (dir.y() >= 0 && dir.x() > 0)
diamondIndex = 3;
else if (dir.x() <= 0 && dir.y() > 0)
diamondIndex = 1;
else if (dir.y() <= 0 && dir.x() < 0)
diamondIndex = 0;
else if (dir.x() >= 0 && dir.y() < 0)
diamondIndex = 2;
unsigned fromIndex = static_cast<unsigned>(edge.mV0);
unsigned toIndex = static_cast<unsigned>(edge.mV1);
lineIndices->setElement(
lineIndex++, fromIndex * DiamondTotalVertexCount + DiamondVertexCount + diamondIndex);
lineIndices->setElement(
lineIndex++, toIndex * DiamondTotalVertexCount + DiamondVertexCount + diamondIndex);
}
lineIndices->resize(lineIndex);
gridGeometry->setVertexArray(vertices);
gridGeometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX);
if (pointIndexCount)
gridGeometry->addPrimitiveSet(pointIndices);
if (edgeIndexCount)
gridGeometry->addPrimitiveSet(lineIndices);
gridGeometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
}
template <class T>
void addWireFrameGeometry(const size_t vertexCount, const size_t indexCount,
osg::ref_ptr<osg::Geometry>& wireframeGeometry, const ESM::Pathgrid& pathgrid,
const std::vector<unsigned short>& selected)
{
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(vertexCount);
osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(vertexCount);
osg::ref_ptr<T> indices = new T(osg::PrimitiveSet::LINES, indexCount);
osg::Vec3f wireOffset = osg::Vec3f(0, 0, (1 - DiamondWireframeScalar) * DiamondHalfHeight);
// Add each point/node
for (size_t it = 0; it < selected.size(); ++it)
{
const ESM::Pathgrid::Point& point = pathgrid.mPoints[selected[it]];
osg::Vec3f position = osg::Vec3f(point.mX, point.mY, point.mZ) + wireOffset;
size_t vertexOffset = it * DiamondVertexCount;
size_t indexOffset = it * DiamondWireframeIndexCount;
// Point
for (unsigned short i = 0; i < DiamondVertexCount; ++i)
{
(*vertices)[vertexOffset + i] = position + DiamondPoints[i] * DiamondWireframeScalar;
if (it == selected.size() - 1)
(*colors)[vertexOffset + i] = DiamondFocusWireColor;
else
(*colors)[vertexOffset + i] = DiamondWireColor;
}
for (unsigned short i = 0; i < DiamondWireframeIndexCount; ++i)
{
indices->setElement(indexOffset + i, vertexOffset + DiamondWireframeIndices[i]);
}
}
wireframeGeometry->setVertexArray(vertices);
wireframeGeometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX);
wireframeGeometry->addPrimitiveSet(indices);
wireframeGeometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
}
}
osg::ref_ptr<osg::Geometry> createPathgridGeometry(const ESM::Pathgrid& pathgrid)
{
const size_t vertexCount = pathgrid.mPoints.size() * DiamondTotalVertexCount;
const size_t pointIndexCount = pathgrid.mPoints.size() * DiamondIndexCount;
const size_t edgeIndexCount = pathgrid.mEdges.size() * 2;
osg::ref_ptr<osg::Geometry> gridGeometry = new osg::Geometry();
if (pointIndexCount || edgeIndexCount)
{
const bool useIntPoints = pointIndexCount > std::numeric_limits<unsigned short>::max();
const bool useIntVertices = vertexCount > std::numeric_limits<unsigned short>::max();
if (useIntPoints && useIntVertices)
addPathgridToGeometry<osg::DrawElementsUInt, osg::DrawElementsUInt>(
vertexCount, pointIndexCount, edgeIndexCount, gridGeometry, pathgrid);
else if (useIntPoints)
addPathgridToGeometry<osg::DrawElementsUInt, osg::DrawElementsUShort>(
vertexCount, pointIndexCount, edgeIndexCount, gridGeometry, pathgrid);
else if (useIntVertices)
addPathgridToGeometry<osg::DrawElementsUShort, osg::DrawElementsUInt>(
vertexCount, pointIndexCount, edgeIndexCount, gridGeometry, pathgrid);
else
addPathgridToGeometry<osg::DrawElementsUShort, osg::DrawElementsUShort>(
vertexCount, pointIndexCount, edgeIndexCount, gridGeometry, pathgrid);
}
osg::ref_ptr<osg::Material> material = new osg::Material;
material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
gridGeometry->getOrCreateStateSet()->setAttribute(material);
return gridGeometry;
}
osg::ref_ptr<osg::Geometry> createPathgridSelectedWireframe(
const ESM::Pathgrid& pathgrid, const std::vector<unsigned short>& selected)
{
const size_t vertexCount = selected.size() * DiamondVertexCount;
const size_t indexCount = selected.size() * DiamondWireframeIndexCount;
osg::ref_ptr<osg::Geometry> wireframeGeometry = new osg::Geometry();
if (indexCount)
{
if (vertexCount > std::numeric_limits<unsigned short>::max())
addWireFrameGeometry<osg::DrawElementsUInt>(
vertexCount, indexCount, wireframeGeometry, pathgrid, selected);
else
addWireFrameGeometry<osg::DrawElementsUShort>(
vertexCount, indexCount, wireframeGeometry, pathgrid, selected);
}
return wireframeGeometry;
}
unsigned short getPathgridNode(unsigned vertexIndex)
{
return static_cast<unsigned short>(vertexIndex / (DiamondVertexCount + DiamondConnectorVertexCount));
}
}
| 11,057
|
C++
|
.cpp
| 191
| 44.282723
| 119
| 0.600924
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,725
|
recastmesh.cpp
|
OpenMW_openmw/components/sceneutil/recastmesh.cpp
|
#include "recastmesh.hpp"
#include "detourdebugdraw.hpp"
#include <components/detournavigator/recastmesh.hpp>
#include <components/detournavigator/recastmeshbuilder.hpp>
#include <components/detournavigator/settings.hpp>
#include <RecastDebugDraw.h>
#include <osg/Group>
#include <osg/Material>
#include <osg/PolygonOffset>
#include <algorithm>
#include <vector>
namespace
{
std::vector<float> calculateNormals(const std::vector<float>& vertices, const std::vector<int>& indices)
{
std::vector<float> result(indices.size());
for (std::size_t i = 0, n = indices.size(); i < n; i += 3)
{
const float* v0_ptr = &vertices[indices[i] * 3];
const float* v1_ptr = &vertices[indices[i + 1] * 3];
const float* v2_ptr = &vertices[indices[i + 2] * 3];
const osg::Vec3f v0(v0_ptr[0], v0_ptr[1], v0_ptr[2]);
const osg::Vec3f v1(v1_ptr[0], v1_ptr[1], v1_ptr[2]);
const osg::Vec3f v2(v2_ptr[0], v2_ptr[1], v2_ptr[2]);
const osg::Vec3f e0 = v1 - v0;
const osg::Vec3f e1 = v2 - v0;
osg::Vec3f normal = e0 ^ e1;
normal.normalize();
for (std::size_t j = 0; j < 3; ++j)
result[i + j] = normal[j];
}
return result;
}
}
namespace SceneUtil
{
osg::ref_ptr<osg::Group> createRecastMeshGroup(const DetourNavigator::RecastMesh& recastMesh,
const DetourNavigator::RecastSettings& settings, const osg::ref_ptr<osg::StateSet>& debugDrawStateSet)
{
using namespace DetourNavigator;
const osg::ref_ptr<osg::Group> group(new osg::Group);
DebugDraw debugDraw(*group, debugDrawStateSet, osg::Vec3f(0, 0, 0), 1.0f);
const DetourNavigator::Mesh& mesh = recastMesh.getMesh();
std::vector<int> indices = mesh.getIndices();
std::vector<float> vertices = mesh.getVertices();
for (const Heightfield& heightfield : recastMesh.getHeightfields())
{
const Mesh heightfieldMesh = makeMesh(heightfield);
const int indexShift = static_cast<int>(vertices.size() / 3);
std::copy(heightfieldMesh.getVertices().begin(), heightfieldMesh.getVertices().end(),
std::back_inserter(vertices));
std::transform(heightfieldMesh.getIndices().begin(), heightfieldMesh.getIndices().end(),
std::back_inserter(indices), [&](int index) { return index + indexShift; });
}
for (std::size_t i = 0; i < vertices.size(); i += 3)
std::swap(vertices[i + 1], vertices[i + 2]);
const auto normals = calculateNormals(vertices, indices);
const auto texScale = 1.0f / (settings.mCellSize * 10.0f);
duDebugDrawTriMeshSlope(&debugDraw, vertices.data(), static_cast<int>(vertices.size() / 3), indices.data(),
normals.data(), static_cast<int>(indices.size() / 3), settings.mMaxSlope, texScale);
return group;
}
}
| 2,979
|
C++
|
.cpp
| 63
| 39.15873
| 115
| 0.626593
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,726
|
animblendrules.cpp
|
OpenMW_openmw/components/sceneutil/animblendrules.cpp
|
#include "animblendrules.hpp"
#include <iterator>
#include <map>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/format.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/debug/debuglog.hpp>
#include <components/files/configfileparser.hpp>
#include <components/files/conversion.hpp>
#include <components/sceneutil/controller.hpp>
#include <components/sceneutil/textkeymap.hpp>
#include <stdexcept>
#include <yaml-cpp/yaml.h>
namespace SceneUtil
{
namespace
{
std::pair<std::string, std::string> splitRuleName(std::string full)
{
std::string group;
std::string key;
size_t delimiterInd = full.find(":");
Misc::StringUtils::lowerCaseInPlace(full);
if (delimiterInd == std::string::npos)
{
group = std::move(full);
Misc::StringUtils::trim(group);
}
else
{
group = full.substr(0, delimiterInd);
key = full.substr(delimiterInd + 1);
Misc::StringUtils::trim(group);
Misc::StringUtils::trim(key);
}
return std::make_pair(group, key);
}
}
using BlendRule = AnimBlendRules::BlendRule;
AnimBlendRules::AnimBlendRules(const AnimBlendRules& copy, const osg::CopyOp& copyop)
: mRules(copy.mRules)
{
}
AnimBlendRules::AnimBlendRules(const std::vector<BlendRule>& rules)
: mRules(rules)
{
}
osg::ref_ptr<AnimBlendRules> AnimBlendRules::fromFile(const VFS::Manager* vfs, VFS::Path::NormalizedView configPath)
{
Log(Debug::Debug) << "Attempting to load animation blending config '" << configPath << "'";
if (!vfs->exists(configPath))
return nullptr;
// Retrieving and parsing animation rules
std::string rawYaml(std::istreambuf_iterator<char>(*vfs->get(configPath)), {});
std::vector<BlendRule> rules;
YAML::Node root = YAML::Load(rawYaml);
if (!root.IsDefined() || root.IsNull() || root.IsScalar())
{
Log(Debug::Error) << Misc::StringUtils::format(
"Can't parse file '%s'. Check that it's a valid YAML/JSON file.", configPath);
return nullptr;
}
if (root["blending_rules"])
{
for (const auto& it : root["blending_rules"])
{
if (it["from"] && it["to"] && it["duration"] && it["easing"])
{
auto fromNames = splitRuleName(it["from"].as<std::string>());
auto toNames = splitRuleName(it["to"].as<std::string>());
BlendRule ruleObj = {
.mFromGroup = fromNames.first,
.mFromKey = fromNames.second,
.mToGroup = toNames.first,
.mToKey = toNames.second,
.mDuration = it["duration"].as<float>(),
.mEasing = it["easing"].as<std::string>(),
};
rules.emplace_back(ruleObj);
}
else
{
Log(Debug::Warning) << "Warning: Blending rule '"
<< (it["from"] ? it["from"].as<std::string>() : "undefined") << "->"
<< (it["to"] ? it["to"].as<std::string>() : "undefined")
<< "' is missing some properties. File: '" << configPath << "'.";
}
}
}
else
{
throw std::domain_error(
Misc::StringUtils::format("'blending_rules' object not found in '%s' file!", configPath));
}
// If no rules then dont allocate any instance
if (rules.size() == 0)
return nullptr;
return new AnimBlendRules(rules);
}
void AnimBlendRules::addOverrideRules(const AnimBlendRules& overrideRules)
{
auto rules = overrideRules.getRules();
// Concat the rules together, overrides added at the end since the bottom-most rule has the highest priority.
mRules.insert(mRules.end(), rules.begin(), rules.end());
}
inline bool AnimBlendRules::fitsRuleString(const std::string_view str, const std::string_view ruleStr) const
{
// A wildcard only supported in the beginning or the end of the rule string in hopes that this will be more
// performant. And most likely this kind of support is enough.
return ruleStr == "*" || str == ruleStr || (ruleStr.starts_with("*") && str.ends_with(ruleStr.substr(1)))
|| (ruleStr.ends_with("*") && str.starts_with(ruleStr.substr(0, ruleStr.length() - 1)));
}
std::optional<BlendRule> AnimBlendRules::findBlendingRule(
std::string fromGroup, std::string fromKey, std::string toGroup, std::string toKey) const
{
Misc::StringUtils::lowerCaseInPlace(fromGroup);
Misc::StringUtils::lowerCaseInPlace(fromKey);
Misc::StringUtils::lowerCaseInPlace(toGroup);
Misc::StringUtils::lowerCaseInPlace(toKey);
for (auto rule = mRules.rbegin(); rule != mRules.rend(); ++rule)
{
bool fromMatch = false;
bool toMatch = false;
// Pseudocode:
// If not a wildcard and found a wildcard
// starts with substr(0,wildcard)
if (fitsRuleString(fromGroup, rule->mFromGroup)
&& (rule->mFromKey.empty() || fitsRuleString(fromKey, rule->mFromKey)))
{
fromMatch = true;
}
if ((fitsRuleString(toGroup, rule->mToGroup) || (rule->mToGroup == "$" && toGroup == fromGroup))
&& (rule->mToKey.empty() || fitsRuleString(toKey, rule->mToKey)))
{
toMatch = true;
}
if (fromMatch && toMatch)
return std::make_optional<BlendRule>(*rule);
}
return std::nullopt;
}
}
| 6,121
|
C++
|
.cpp
| 142
| 31.598592
| 120
| 0.557721
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,727
|
serialize.cpp
|
OpenMW_openmw/components/sceneutil/serialize.cpp
|
#include "serialize.hpp"
#include <osgDB/ObjectWrapper>
#include <osgDB/Registry>
#include <components/nifosg/fog.hpp>
#include <components/nifosg/matrixtransform.hpp>
#include <components/sceneutil/morphgeometry.hpp>
#include <components/sceneutil/positionattitudetransform.hpp>
#include <components/sceneutil/riggeometry.hpp>
#include <components/sceneutil/riggeometryosgaextension.hpp>
#include <components/sceneutil/skeleton.hpp>
#include <components/sceneutil/texturetype.hpp>
namespace SceneUtil
{
template <class Cls>
static osg::Object* createInstanceFunc()
{
return new Cls;
}
class PositionAttitudeTransformSerializer : public osgDB::ObjectWrapper
{
public:
PositionAttitudeTransformSerializer()
: osgDB::ObjectWrapper(createInstanceFunc<SceneUtil::PositionAttitudeTransform>,
"SceneUtil::PositionAttitudeTransform",
"osg::Object osg::Node osg::Group osg::Transform SceneUtil::PositionAttitudeTransform")
{
addSerializer(new osgDB::PropByRefSerializer<SceneUtil::PositionAttitudeTransform, osg::Vec3f>("position",
osg::Vec3f(), &SceneUtil::PositionAttitudeTransform::getPosition,
&SceneUtil::PositionAttitudeTransform::setPosition),
osgDB::BaseSerializer::RW_VEC3F);
addSerializer(new osgDB::PropByRefSerializer<SceneUtil::PositionAttitudeTransform, osg::Quat>("attitude",
osg::Quat(), &SceneUtil::PositionAttitudeTransform::getAttitude,
&SceneUtil::PositionAttitudeTransform::setAttitude),
osgDB::BaseSerializer::RW_QUAT);
addSerializer(
new osgDB::PropByRefSerializer<SceneUtil::PositionAttitudeTransform, osg::Vec3f>("scale", osg::Vec3f(),
&SceneUtil::PositionAttitudeTransform::getScale, &SceneUtil::PositionAttitudeTransform::setScale),
osgDB::BaseSerializer::RW_VEC3F);
}
};
class SkeletonSerializer : public osgDB::ObjectWrapper
{
public:
SkeletonSerializer()
: osgDB::ObjectWrapper(createInstanceFunc<SceneUtil::Skeleton>, "SceneUtil::Skeleton",
"osg::Object osg::Node osg::Group SceneUtil::Skeleton")
{
}
};
class RigGeometrySerializer : public osgDB::ObjectWrapper
{
public:
RigGeometrySerializer()
: osgDB::ObjectWrapper(createInstanceFunc<SceneUtil::RigGeometry>, "SceneUtil::RigGeometry",
"osg::Object osg::Node osg::Drawable SceneUtil::RigGeometry")
{
}
};
class RigGeometryHolderSerializer : public osgDB::ObjectWrapper
{
public:
RigGeometryHolderSerializer()
: osgDB::ObjectWrapper(createInstanceFunc<SceneUtil::RigGeometryHolder>, "SceneUtil::RigGeometryHolder",
"osg::Object osg::Node osg::Drawable SceneUtil::RigGeometryHolder")
{
}
};
class OsgaRigGeometrySerializer : public osgDB::ObjectWrapper
{
public:
OsgaRigGeometrySerializer()
: osgDB::ObjectWrapper(createInstanceFunc<SceneUtil::OsgaRigGeometry>, "SceneUtil::OsgaRigGeometry",
"osg::Object osg::Node osg::Geometry osgAnimation::RigGeometry SceneUtil::OsgaRigGeometry")
{
}
};
class MorphGeometrySerializer : public osgDB::ObjectWrapper
{
public:
MorphGeometrySerializer()
: osgDB::ObjectWrapper(createInstanceFunc<SceneUtil::MorphGeometry>, "SceneUtil::MorphGeometry",
"osg::Object osg::Node osg::Drawable SceneUtil::MorphGeometry")
{
}
};
class LightManagerSerializer : public osgDB::ObjectWrapper
{
public:
LightManagerSerializer()
: osgDB::ObjectWrapper(createInstanceFunc<osg::Group>, "SceneUtil::LightManager",
"osg::Object osg::Node osg::Group SceneUtil::LightManager")
{
}
};
class CameraRelativeTransformSerializer : public osgDB::ObjectWrapper
{
public:
CameraRelativeTransformSerializer()
: osgDB::ObjectWrapper(createInstanceFunc<osg::Group>, "MWRender::CameraRelativeTransform",
"osg::Object osg::Node osg::Group MWRender::CameraRelativeTransform")
{
}
};
class MatrixTransformSerializer : public osgDB::ObjectWrapper
{
public:
MatrixTransformSerializer()
: osgDB::ObjectWrapper(createInstanceFunc<NifOsg::MatrixTransform>, "NifOsg::MatrixTransform",
"osg::Object osg::Node osg::Group osg::Transform osg::MatrixTransform NifOsg::MatrixTransform")
{
}
};
class FogSerializer : public osgDB::ObjectWrapper
{
public:
FogSerializer()
: osgDB::ObjectWrapper(
createInstanceFunc<osg::Fog>, "NifOsg::Fog", "osg::Object osg::StateAttribute osg::Fog NifOsg::Fog")
{
addSerializer(new osgDB::PropByValSerializer<NifOsg::Fog, float>(
"Depth", 1.f, &NifOsg::Fog::getDepth, &NifOsg::Fog::setDepth),
osgDB::BaseSerializer::RW_FLOAT);
}
};
class TextureTypeSerializer : public osgDB::ObjectWrapper
{
public:
TextureTypeSerializer()
: osgDB::ObjectWrapper(createInstanceFunc<SceneUtil::TextureType>, "SceneUtil::TextureType",
"osg::Object osg::StateAttribute SceneUtil::TextureType")
{
}
};
osgDB::ObjectWrapper* makeDummySerializer(const std::string& classname)
{
return new osgDB::ObjectWrapper(createInstanceFunc<osg::DummyObject>, classname, "osg::Object");
}
class GeometrySerializer : public osgDB::ObjectWrapper
{
public:
GeometrySerializer()
: osgDB::ObjectWrapper(
createInstanceFunc<osg::Drawable>, "osg::Geometry", "osg::Object osg::Drawable osg::Geometry")
{
}
};
void registerSerializers()
{
static bool done = false;
if (!done)
{
osgDB::ObjectWrapperManager* mgr = osgDB::Registry::instance()->getObjectWrapperManager();
mgr->addWrapper(new PositionAttitudeTransformSerializer);
mgr->addWrapper(new SkeletonSerializer);
mgr->addWrapper(new RigGeometrySerializer);
mgr->addWrapper(new RigGeometryHolderSerializer);
mgr->addWrapper(new OsgaRigGeometrySerializer);
mgr->addWrapper(new MorphGeometrySerializer);
mgr->addWrapper(new LightManagerSerializer);
mgr->addWrapper(new CameraRelativeTransformSerializer);
mgr->addWrapper(new MatrixTransformSerializer);
mgr->addWrapper(new FogSerializer);
mgr->addWrapper(new TextureTypeSerializer);
// Don't serialize Geometry data as we are more interested in the overall structure rather than tons of
// vertex data that would make the file large and hard to read.
mgr->removeWrapper(mgr->findWrapper("osg::Geometry"));
mgr->addWrapper(new GeometrySerializer);
// ignore the below for now to avoid warning spam
const char* ignore[] = {
"Debug::DebugDrawer",
"MWRender::NifAnimBlendController",
"MWRender::BoneAnimBlendController",
"MWRender::BoneAnimBlendControllerWrapper",
"MWRender::PtrHolder",
"Resource::TemplateRef",
"Resource::TemplateMultiRef",
"SceneUtil::CompositeStateSetUpdater",
"SceneUtil::UBOManager",
"SceneUtil::LightListCallback",
"SceneUtil::LightManagerUpdateCallback",
"SceneUtil::FFPLightStateAttribute",
"SceneUtil::UpdateRigBounds",
"SceneUtil::UpdateRigGeometry",
"SceneUtil::LightSource",
"SceneUtil::DisableLight",
"SceneUtil::MWShadowTechnique",
"SceneUtil::TextKeyMapHolder",
"Shader::AddedState",
"Shader::RemovedAlphaFunc",
"NifOsg::FlipController",
"NifOsg::KeyframeController",
"NifOsg::Emitter",
"NifOsg::ParticleColorAffector",
"NifOsg::ParticleSystem",
"NifOsg::GravityAffector",
"NifOsg::ParticleBomb",
"NifOsg::GrowFadeAffector",
"NifOsg::InverseWorldMatrix",
"NifOsg::StaticBoundingBoxCallback",
"NifOsg::GeomMorpherController",
"NifOsg::UpdateMorphGeometry",
"NifOsg::UVController",
"NifOsg::VisController",
"osgMyGUI::Drawable",
"osg::DrawCallback",
"osg::UniformBufferObject",
"osgOQ::ClearQueriesCallback",
"osgOQ::RetrieveQueriesCallback",
"osg::DummyObject",
};
for (size_t i = 0; i < sizeof(ignore) / sizeof(ignore[0]); ++i)
{
mgr->addWrapper(makeDummySerializer(ignore[i]));
}
done = true;
}
}
}
| 9,355
|
C++
|
.cpp
| 218
| 31.944954
| 119
| 0.626618
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,728
|
controller.cpp
|
OpenMW_openmw/components/sceneutil/controller.cpp
|
#include "controller.hpp"
#include <algorithm>
#include "statesetupdater.hpp"
#include <osg/Drawable>
#include <osg/Geometry>
#include <osg/MatrixTransform>
#include <osg/NodeCallback>
namespace SceneUtil
{
Controller::Controller() {}
bool Controller::hasInput() const
{
return mSource.get() != nullptr;
}
float Controller::getInputValue(osg::NodeVisitor* nv)
{
if (mFunction)
return mFunction->calculate(mSource->getValue(nv));
else
return mSource->getValue(nv);
}
void Controller::setSource(std::shared_ptr<ControllerSource> source)
{
mSource = std::move(source);
}
void Controller::setFunction(std::shared_ptr<ControllerFunction> function)
{
mFunction = std::move(function);
}
std::shared_ptr<ControllerSource> Controller::getSource() const
{
return mSource;
}
std::shared_ptr<ControllerFunction> Controller::getFunction() const
{
return mFunction;
}
FrameTimeSource::FrameTimeSource() {}
float FrameTimeSource::getValue(osg::NodeVisitor* nv)
{
return nv->getFrameStamp()->getSimulationTime();
}
ControllerVisitor::ControllerVisitor()
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
{
}
void ControllerVisitor::apply(osg::Node& node)
{
applyNode(node);
}
void ControllerVisitor::apply(osg::MatrixTransform& node)
{
applyNode(node);
}
void ControllerVisitor::apply(osg::Geometry& node)
{
applyNode(node);
}
void ControllerVisitor::applyNode(osg::Node& node)
{
osg::Callback* callback = node.getUpdateCallback();
while (callback)
{
if (Controller* ctrl = dynamic_cast<Controller*>(callback))
visit(node, *ctrl);
if (CompositeStateSetUpdater* composite = dynamic_cast<CompositeStateSetUpdater*>(callback))
{
for (unsigned int i = 0; i < composite->getNumControllers(); ++i)
{
StateSetUpdater* statesetcontroller = composite->getController(i);
if (Controller* ctrl = dynamic_cast<Controller*>(statesetcontroller))
visit(node, *ctrl);
}
}
callback = callback->getNestedCallback();
}
if (node.getNumChildrenRequiringUpdateTraversal() > 0)
traverse(node);
}
AssignControllerSourcesVisitor::AssignControllerSourcesVisitor()
: ControllerVisitor()
{
}
AssignControllerSourcesVisitor::AssignControllerSourcesVisitor(std::shared_ptr<ControllerSource> toAssign)
: ControllerVisitor()
, mToAssign(std::move(toAssign))
{
}
void AssignControllerSourcesVisitor::visit(osg::Node&, Controller& ctrl)
{
if (!ctrl.getSource())
ctrl.setSource(mToAssign);
}
ForceControllerSourcesVisitor::ForceControllerSourcesVisitor()
: AssignControllerSourcesVisitor()
{
}
ForceControllerSourcesVisitor::ForceControllerSourcesVisitor(std::shared_ptr<ControllerSource> toAssign)
: AssignControllerSourcesVisitor(std::move(toAssign))
{
}
void ForceControllerSourcesVisitor::visit(osg::Node&, Controller& ctrl)
{
ctrl.setSource(mToAssign);
}
FindMaxControllerLengthVisitor::FindMaxControllerLengthVisitor()
: SceneUtil::ControllerVisitor()
, mMaxLength(0)
{
}
void FindMaxControllerLengthVisitor::visit(osg::Node&, Controller& ctrl)
{
if (ctrl.getFunction())
mMaxLength = std::max(mMaxLength, ctrl.getFunction()->getMaximum());
}
float FindMaxControllerLengthVisitor::getMaxLength() const
{
return mMaxLength;
}
}
| 3,834
|
C++
|
.cpp
| 120
| 24.6
| 110
| 0.651194
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,729
|
statesetupdater.cpp
|
OpenMW_openmw/components/sceneutil/statesetupdater.cpp
|
#include "statesetupdater.hpp"
#include <components/stereo/stereomanager.hpp>
#include <osg/Node>
#include <osg/NodeVisitor>
#include <osgUtil/CullVisitor>
namespace SceneUtil
{
void StateSetUpdater::operator()(osg::Node* node, osg::NodeVisitor* nv)
{
bool isCullVisitor = nv->getVisitorType() == osg::NodeVisitor::CULL_VISITOR;
if (isCullVisitor)
return applyCull(node, static_cast<osgUtil::CullVisitor*>(nv));
else
return applyUpdate(node, nv);
}
void StateSetUpdater::applyUpdate(osg::Node* node, osg::NodeVisitor* nv)
{
if (!mStateSetsUpdate[0])
{
for (int i = 0; i < 2; ++i)
{
mStateSetsUpdate[i] = new osg::StateSet(*node->getOrCreateStateSet(),
osg::CopyOp::SHALLOW_COPY); // Using SHALLOW_COPY for StateAttributes, if users want to modify it is
// their responsibility to set a non-shared one first in setDefaults
setDefaults(mStateSetsUpdate[i]);
}
}
osg::ref_ptr<osg::StateSet> stateset = mStateSetsUpdate[nv->getTraversalNumber() % 2];
apply(stateset, nv);
node->setStateSet(stateset);
traverse(node, nv);
}
void StateSetUpdater::applyCull(osg::Node* node, osgUtil::CullVisitor* cv)
{
auto stateset = getCvDependentStateset(cv);
apply(stateset, cv);
if (Stereo::getStereo())
{
auto& sm = Stereo::Manager::instance();
if (sm.getEye(cv) == Stereo::Eye::Left)
applyLeft(stateset, cv);
if (sm.getEye(cv) == Stereo::Eye::Right)
applyRight(stateset, cv);
}
cv->pushStateSet(stateset);
traverse(node, cv);
cv->popStateSet();
}
osg::StateSet* StateSetUpdater::getCvDependentStateset(osgUtil::CullVisitor* cv)
{
auto it = mStateSetsCull.find(cv);
if (it == mStateSetsCull.end())
{
osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet;
mStateSetsCull.emplace(cv, stateset);
setDefaults(stateset);
return stateset;
}
return it->second;
}
void StateSetUpdater::reset()
{
mStateSetsUpdate[0] = nullptr;
mStateSetsUpdate[1] = nullptr;
mStateSetsCull.clear();
}
StateSetUpdater::StateSetUpdater() {}
StateSetUpdater::StateSetUpdater(const StateSetUpdater& copy, const osg::CopyOp& copyop)
: SceneUtil::NodeCallback<StateSetUpdater>(copy, copyop)
{
}
// ----------------------------------------------------------------------------------
void CompositeStateSetUpdater::apply(osg::StateSet* stateset, osg::NodeVisitor* nv)
{
for (unsigned int i = 0; i < mCtrls.size(); ++i)
mCtrls[i]->apply(stateset, nv);
}
void CompositeStateSetUpdater::setDefaults(osg::StateSet* stateset)
{
for (unsigned int i = 0; i < mCtrls.size(); ++i)
mCtrls[i]->setDefaults(stateset);
}
CompositeStateSetUpdater::CompositeStateSetUpdater() {}
CompositeStateSetUpdater::CompositeStateSetUpdater(const CompositeStateSetUpdater& copy, const osg::CopyOp& copyop)
: StateSetUpdater(copy, copyop)
{
for (unsigned int i = 0; i < copy.mCtrls.size(); ++i)
mCtrls.emplace_back(osg::clone(copy.mCtrls[i].get(), copyop));
}
unsigned int CompositeStateSetUpdater::getNumControllers()
{
return mCtrls.size();
}
StateSetUpdater* CompositeStateSetUpdater::getController(int i)
{
return mCtrls[i];
}
void CompositeStateSetUpdater::addController(StateSetUpdater* ctrl)
{
mCtrls.emplace_back(ctrl);
}
}
| 3,820
|
C++
|
.cpp
| 102
| 28.970588
| 120
| 0.603789
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,730
|
mwshadowtechnique.cpp
|
OpenMW_openmw/components/sceneutil/mwshadowtechnique.cpp
|
// clang-format off
/* This file is based on OpenSceneGraph's src/osgShadow/ViewDependentShadowMap.cpp.
* Where applicable, any changes made are covered by OpenMW's GPL 3 license, not the OSGPL.
* The original copyright notice is listed below.
*/
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2011 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include "mwshadowtechnique.hpp"
#include <osgShadow/ShadowedScene>
#include <osg/CullFace>
#include <osg/Geometry>
#include <osg/io_utils>
#include <osg/Depth>
#include <osg/ClipControl>
#include <sstream>
#include <deque>
#include <vector>
#include "glextensions.hpp"
#include "shadowsbin.hpp"
namespace {
using namespace osgShadow;
using namespace SceneUtil;
#define dbl_max std::numeric_limits<double>::max()
//////////////////////////////////////////////////////////////////
// fragment shader
//
#if 0
static const char fragmentShaderSource_withBaseTexture[] =
"uniform sampler2D baseTexture; \n"
"uniform sampler2DShadow shadowTexture; \n"
" \n"
"void main(void) \n"
"{ \n"
" vec4 colorAmbientEmissive = gl_FrontLightModelProduct.sceneColor; \n"
" vec4 color = texture2D( baseTexture, gl_TexCoord[0].xy ); \n"
" color *= mix( colorAmbientEmissive, gl_Color, shadow2DProj( shadowTexture, gl_TexCoord[1] ).r ); \n"
" gl_FragColor = color; \n"
"} \n";
#else
static const char fragmentShaderSource_withBaseTexture[] =
"uniform sampler2D baseTexture; \n"
"uniform int baseTextureUnit; \n"
"uniform sampler2DShadow shadowTexture0; \n"
"uniform int shadowTextureUnit0; \n"
" \n"
"void main(void) \n"
"{ \n"
" vec4 colorAmbientEmissive = gl_FrontLightModelProduct.sceneColor; \n"
" vec4 color = texture2D( baseTexture, gl_TexCoord[baseTextureUnit].xy ); \n"
" color *= mix( colorAmbientEmissive, gl_Color, shadow2DProj( shadowTexture0, gl_TexCoord[shadowTextureUnit0] ).r ); \n"
" gl_FragColor = color; \n"
"} \n";
static const char fragmentShaderSource_withBaseTexture_twoShadowMaps[] =
"uniform sampler2D baseTexture; \n"
"uniform int baseTextureUnit; \n"
"uniform sampler2DShadow shadowTexture0; \n"
"uniform int shadowTextureUnit0; \n"
"uniform sampler2DShadow shadowTexture1; \n"
"uniform int shadowTextureUnit1; \n"
" \n"
"void main(void) \n"
"{ \n"
" vec4 colorAmbientEmissive = gl_FrontLightModelProduct.sceneColor; \n"
" vec4 color = texture2D( baseTexture, gl_TexCoord[baseTextureUnit].xy ); \n"
" float shadow0 = shadow2DProj( shadowTexture0, gl_TexCoord[shadowTextureUnit0] ).r; \n"
" float shadow1 = shadow2DProj( shadowTexture1, gl_TexCoord[shadowTextureUnit1] ).r; \n"
" color *= mix( colorAmbientEmissive, gl_Color, shadow0*shadow1 ); \n"
" gl_FragColor = color; \n"
"} \n";
#endif
std::string debugVertexShaderSource = "void main(void){gl_Position = gl_Vertex; gl_TexCoord[0]=gl_MultiTexCoord0;}";
std::string debugFragmentShaderSource =
"uniform sampler2D texture; \n"
" \n"
"void main(void) \n"
"{ \n"
#if 1
" float f = texture2D(texture, gl_TexCoord[0].xy).r; \n"
" \n"
" f = 256.0 * f; \n"
" float fC = floor( f ) / 256.0; \n"
" \n"
" f = 256.0 * fract( f ); \n"
" float fS = floor( f ) / 256.0; \n"
" \n"
" f = 256.0 * fract( f ); \n"
" float fH = floor( f ) / 256.0; \n"
" \n"
" fS *= 0.5; \n"
" fH = ( fH * 0.34 + 0.66 ) * ( 1.0 - fS ); \n"
" \n"
" vec3 rgb = vec3( ( fC > 0.5 ? ( 1.0 - fC ) : fC ), \n"
" abs( fC - 0.333333 ), \n"
" abs( fC - 0.666667 ) ); \n"
" \n"
" rgb = min( vec3( 1.0, 1.0, 1.0 ), 3.0 * rgb ); \n"
" \n"
" float fMax = max( max( rgb.r, rgb.g ), rgb.b ); \n"
" fMax = 1.0 / fMax; \n"
" \n"
" vec3 color = fMax * rgb; \n"
" \n"
" gl_FragColor = vec4( fS + fH * color, 1 ); \n"
#else
" gl_FragColor = texture2D(texture, gl_TexCoord[0].xy); \n"
#endif
"} \n";
std::string debugFrustumVertexShaderSource = "varying float depth; uniform mat4 transform; void main(void){gl_Position = transform * gl_Vertex; depth = gl_Position.z / gl_Position.w;}";
std::string debugFrustumFragmentShaderSource =
"varying float depth; \n"
" \n"
"void main(void) \n"
"{ \n"
#if 1
" float f = depth; \n"
" \n"
" f = 256.0 * f; \n"
" float fC = floor( f ) / 256.0; \n"
" \n"
" f = 256.0 * fract( f ); \n"
" float fS = floor( f ) / 256.0; \n"
" \n"
" f = 256.0 * fract( f ); \n"
" float fH = floor( f ) / 256.0; \n"
" \n"
" fS *= 0.5; \n"
" fH = ( fH * 0.34 + 0.66 ) * ( 1.0 - fS ); \n"
" \n"
" vec3 rgb = vec3( ( fC > 0.5 ? ( 1.0 - fC ) : fC ), \n"
" abs( fC - 0.333333 ), \n"
" abs( fC - 0.666667 ) ); \n"
" \n"
" rgb = min( vec3( 1.0, 1.0, 1.0 ), 3.0 * rgb ); \n"
" \n"
" float fMax = max( max( rgb.r, rgb.g ), rgb.b ); \n"
" fMax = 1.0 / fMax; \n"
" \n"
" vec3 color = fMax * rgb; \n"
" \n"
" gl_FragColor = vec4( fS + fH * color, 1 ); \n"
#else
" gl_FragColor = vec4(0.0, 0.0, 1.0, 0.0); \n"
#endif
"} \n";
template<class T>
class RenderLeafTraverser : public T
{
public:
RenderLeafTraverser()
{
}
void traverse(const osgUtil::RenderStage* rs)
{
traverse(static_cast<const osgUtil::RenderBin*>(rs));
}
void traverse(const osgUtil::RenderBin* renderBin)
{
const osgUtil::RenderBin::RenderBinList& rbl = renderBin->getRenderBinList();
for(osgUtil::RenderBin::RenderBinList::const_iterator itr = rbl.begin();
itr != rbl.end();
++itr)
{
traverse(itr->second.get());
}
const osgUtil::RenderBin::RenderLeafList& rll = renderBin->getRenderLeafList();
for(osgUtil::RenderBin::RenderLeafList::const_iterator itr = rll.begin();
itr != rll.end();
++itr)
{
handle(*itr);
}
const osgUtil::RenderBin::StateGraphList& rgl = renderBin->getStateGraphList();
for(osgUtil::RenderBin::StateGraphList::const_iterator itr = rgl.begin();
itr != rgl.end();
++itr)
{
traverse(*itr);
}
}
void traverse(const osgUtil::StateGraph* stateGraph)
{
const osgUtil::StateGraph::ChildList& cl = stateGraph->_children;
for(osgUtil::StateGraph::ChildList::const_iterator itr = cl.begin();
itr != cl.end();
++itr)
{
traverse(itr->second.get());
}
const osgUtil::StateGraph::LeafList& ll = stateGraph->_leaves;
for(osgUtil::StateGraph::LeafList::const_iterator itr = ll.begin();
itr != ll.end();
++itr)
{
handle(itr->get());
}
}
inline void handle(const osgUtil::RenderLeaf* renderLeaf)
{
this->operator()(renderLeaf);
}
};
///////////////////////////////////////////////////////////////////////////////////////////////
//
// VDSMCameraCullCallback
//
class VDSMCameraCullCallback : public osg::NodeCallback
{
public:
VDSMCameraCullCallback(MWShadowTechnique* vdsm, osg::Polytope& polytope);
void operator()(osg::Node*, osg::NodeVisitor* nv) override;
osg::RefMatrix* getProjectionMatrix() { return _projectionMatrix.get(); }
osgUtil::RenderStage* getRenderStage() { return _renderStage.get(); }
protected:
MWShadowTechnique* _vdsm;
osg::ref_ptr<osg::RefMatrix> _projectionMatrix;
osg::ref_ptr<osgUtil::RenderStage> _renderStage;
osg::Polytope _polytope;
};
VDSMCameraCullCallback::VDSMCameraCullCallback(MWShadowTechnique* vdsm, osg::Polytope& polytope):
_vdsm(vdsm),
_polytope(polytope)
{
}
void VDSMCameraCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
{
osgUtil::CullVisitor* cv = static_cast<osgUtil::CullVisitor*>(nv);
osg::Camera* camera = node->asCamera();
OSG_INFO<<"VDSMCameraCullCallback::operator()(osg::Node* "<<camera<<", osg::NodeVisitor* "<<cv<<")"<<std::endl;
#if 1
if (!_polytope.empty())
{
OSG_INFO<<"Pushing custom Polytope"<<std::endl;
osg::CullingSet& cs = cv->getProjectionCullingStack().back();
cs.setFrustum(_polytope);
cv->pushCullingSet();
}
#endif
// bin has to go inside camera cull or the rendertexture stage will override it
cv->pushStateSet(_vdsm->getOrCreateShadowsBinStateSet());
if (_vdsm->getShadowedScene())
{
_vdsm->getShadowedScene()->osg::Group::traverse(*nv);
}
cv->popStateSet();
#if 1
if (!_polytope.empty())
{
OSG_INFO<<"Popping custom Polytope"<<std::endl;
cv->popCullingSet();
}
#endif
_renderStage = cv->getCurrentRenderBin()->getStage();
OSG_INFO<<"VDSM second : _renderStage = "<<_renderStage<<std::endl;
if (cv->getComputeNearFarMode() != osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR)
{
// make sure that the near plane is computed correctly.
cv->computeNearPlane();
osg::Matrixd projection = *(cv->getProjectionMatrix());
OSG_INFO<<"RTT Projection matrix "<<projection<<std::endl;
osg::Matrix::value_type left, right, bottom, top, zNear, zFar;
osg::Matrix::value_type epsilon = 1e-6;
if (fabs(projection(0,3))<epsilon && fabs(projection(1,3))<epsilon && fabs(projection(2,3))<epsilon )
{
projection.getOrtho(left, right,
bottom, top,
zNear, zFar);
OSG_INFO<<"Ortho zNear="<<zNear<<", zFar="<<zFar<<std::endl;
}
else
{
projection.getFrustum(left, right,
bottom, top,
zNear, zFar);
OSG_INFO<<"Frustum zNear="<<zNear<<", zFar="<<zFar<<std::endl;
}
OSG_INFO<<"Calculated zNear = "<<cv->getCalculatedNearPlane()<<", zFar = "<<cv->getCalculatedFarPlane()<<std::endl;
zNear = osg::maximum(zNear, cv->getCalculatedNearPlane());
zFar = osg::minimum(zFar, cv->getCalculatedFarPlane());
cv->setCalculatedNearPlane(zNear);
cv->setCalculatedFarPlane(zFar);
cv->clampProjectionMatrix(projection, zNear, zFar);
//OSG_INFO<<"RTT zNear = "<<zNear<<", zFar = "<<zFar<<std::endl;
OSG_INFO<<"RTT Projection matrix after clamping "<<projection<<std::endl;
camera->setProjectionMatrix(projection);
}
_projectionMatrix = cv->getProjectionMatrix();
}
} // namespace
MWShadowTechnique::ComputeLightSpaceBounds::ComputeLightSpaceBounds() :
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN)
{
setCullingMode(osg::CullSettings::VIEW_FRUSTUM_CULLING);
}
void MWShadowTechnique::ComputeLightSpaceBounds::reset()
{
osg::CullStack::reset();
_bb = osg::BoundingBox();
}
void MWShadowTechnique::ComputeLightSpaceBounds::apply(osg::Node& node)
{
if (isCulled(node)) return;
// push the culling mode.
pushCurrentMask();
traverse(node);
// pop the culling mode.
popCurrentMask();
}
void MWShadowTechnique::ComputeLightSpaceBounds::apply(osg::Group& node)
{
apply(static_cast<osg::Node&>(node));
}
void MWShadowTechnique::ComputeLightSpaceBounds::apply(osg::Drawable& drawable)
{
if (isCulled(drawable)) return;
// push the culling mode.
pushCurrentMask();
updateBound(drawable.getBoundingBox());
// pop the culling mode.
popCurrentMask();
}
void MWShadowTechnique::ComputeLightSpaceBounds::apply(osg::Geometry& drawable)
{
apply(static_cast<osg::Drawable&>(drawable));
}
void MWShadowTechnique::ComputeLightSpaceBounds::apply(osg::Billboard&)
{
OSG_INFO << "Warning Billboards not yet supported" << std::endl;
return;
}
void MWShadowTechnique::ComputeLightSpaceBounds::apply(osg::Projection&)
{
// projection nodes won't affect a shadow map so their subgraphs should be ignored
return;
}
void MWShadowTechnique::ComputeLightSpaceBounds::apply(osg::Transform& transform)
{
if (isCulled(transform)) return;
// push the culling mode.
pushCurrentMask();
// absolute transforms won't affect a shadow map so their subgraphs should be ignored.
if (transform.getReferenceFrame() == osg::Transform::RELATIVE_RF)
{
osg::RefMatrix* matrix = createOrReuseMatrix(*getModelViewMatrix());
transform.computeLocalToWorldMatrix(*matrix, this);
pushModelViewMatrix(matrix, transform.getReferenceFrame());
traverse(transform);
popModelViewMatrix();
}
// pop the culling mode.
popCurrentMask();
}
void MWShadowTechnique::ComputeLightSpaceBounds::apply(osg::MatrixTransform& transform)
{
apply(static_cast<osg::Transform&>(transform));
}
void MWShadowTechnique::ComputeLightSpaceBounds::apply(osg::Camera&)
{
// camera nodes won't affect a shadow map so their subgraphs should be ignored
return;
}
void MWShadowTechnique::ComputeLightSpaceBounds::updateBound(const osg::BoundingBox& bb)
{
if (!bb.valid()) return;
const osg::Matrix& matrix = *getModelViewMatrix() * *getProjectionMatrix();
update(bb.corner(0) * matrix);
update(bb.corner(1) * matrix);
update(bb.corner(2) * matrix);
update(bb.corner(3) * matrix);
update(bb.corner(4) * matrix);
update(bb.corner(5) * matrix);
update(bb.corner(6) * matrix);
update(bb.corner(7) * matrix);
}
void MWShadowTechnique::ComputeLightSpaceBounds::update(const osg::Vec3& v)
{
if (v.z()<-1.0f)
{
//OSG_NOTICE<<"discarding("<<v<<")"<<std::endl;
return;
}
float x = v.x();
if (x<-1.0f) x = -1.0f;
if (x>1.0f) x = 1.0f;
float y = v.y();
if (y<-1.0f) y = -1.0f;
if (y>1.0f) y = 1.0f;
_bb.expandBy(osg::Vec3(x, y, v.z()));
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// LightData
//
MWShadowTechnique::LightData::LightData(MWShadowTechnique::ViewDependentData* vdd):
_viewDependentData(vdd),
directionalLight(false)
{
}
void MWShadowTechnique::LightData::setLightData(osg::RefMatrix* lm, const osg::Light* l, const osg::Matrixd& modelViewMatrix)
{
lightMatrix = lm;
light = l;
lightPos = light->getPosition();
directionalLight = (light->getPosition().w()== 0.0);
if (directionalLight)
{
lightPos3.set(0.0, 0.0, 0.0); // directional light has no destinct position
lightDir.set(-lightPos.x(), -lightPos.y(), -lightPos.z());
lightDir.normalize();
OSG_INFO<<" Directional light, lightPos="<<lightPos<<", lightDir="<<lightDir<<std::endl;
if (lightMatrix.valid() && lightMatrix->operator==(osg::Matrixf(modelViewMatrix)))
{
OSG_INFO<<" Light matrix "<<*lightMatrix<<std::endl;
osg::Matrix lightToLocalMatrix(*lightMatrix * osg::Matrix::inverse(modelViewMatrix) );
lightDir = osg::Matrix::transform3x3( lightDir, lightToLocalMatrix );
lightDir.normalize();
OSG_INFO<<" new LightDir ="<<lightDir<<std::endl;
}
}
else
{
OSG_INFO<<" Positional light, lightPos="<<lightPos<<std::endl;
lightDir = light->getDirection();
lightDir.normalize();
if (lightMatrix.valid())
{
OSG_INFO<<" Light matrix "<<*lightMatrix<<std::endl;
osg::Matrix lightToLocalMatrix(*lightMatrix * osg::Matrix::inverse(modelViewMatrix) );
lightPos = lightPos * lightToLocalMatrix;
lightDir = osg::Matrix::transform3x3( lightDir, lightToLocalMatrix );
lightDir.normalize();
OSG_INFO<<" new LightPos ="<<lightPos<<std::endl;
OSG_INFO<<" new LightDir ="<<lightDir<<std::endl;
}
lightPos3.set(lightPos.x()/lightPos.w(), lightPos.y()/lightPos.w(), lightPos.z()/lightPos.w());
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// ShadowData
//
MWShadowTechnique::ShadowData::ShadowData(MWShadowTechnique::ViewDependentData* vdd):
_viewDependentData(vdd),
_textureUnit(0)
{
const ShadowSettings* settings = vdd->getViewDependentShadowMap()->getShadowedScene()->getShadowSettings();
bool debug = settings->getDebugDraw();
// set up the texture
_texture = new osg::Texture2D;
osg::Vec2s textureSize = debug ? osg::Vec2s(512,512) : settings->getTextureSize();
_texture->setTextureSize(textureSize.x(), textureSize.y());
if (debug)
{
_texture->setInternalFormat(GL_RGB);
}
else
{
_texture->setInternalFormat(GL_DEPTH_COMPONENT);
_texture->setShadowComparison(true);
_texture->setShadowTextureMode(osg::Texture2D::LUMINANCE);
}
_texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
// the shader clips sampled coordinates, so no need for border
_texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_EDGE);
_texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_EDGE);
// set up the camera
_camera = new osg::Camera;
_camera->setName("ShadowCamera");
_camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF_INHERIT_VIEWPOINT);
#ifndef __APPLE__ // workaround shadow issue on macOS, https://gitlab.com/OpenMW/openmw/-/issues/6057
_camera->setImplicitBufferAttachmentMask(0, 0);
#endif
//_camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
_camera->setClearColor(osg::Vec4(0.0f,0.0f,0.0f,0.0f));
//_camera->setComputeNearFarMode(osg::Camera::COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES);
//_camera->setComputeNearFarMode(osg::Camera::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
// Now we are using Depth Clamping, we want to not cull things on the wrong side of the near plane.
// When the near and far planes are computed, OSG always culls anything on the wrong side of the near plane, even if it's told not to.
// Even if that weren't an issue, the near plane can't go past any shadow receivers or the depth-clamped fragments which ended up on the near plane can't cast shadows on those receivers.
// Unfortunately, this change will make shadows have less depth precision when there are no casters outside the view frustum.
// TODO: Find a better solution. E.g. detect when there are no casters outside the view frustum, write a new cull visitor that does all the wacky things we'd need it to.
_camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
// switch off small feature culling as this can cull out geometry that will still be large enough once perspective correction takes effect.
_camera->setCullingMode(_camera->getCullingMode() & ~osg::CullSettings::SMALL_FEATURE_CULLING);
// set viewport
_camera->setViewport(0,0,textureSize.x(),textureSize.y());
if (debug)
{
// clear just the depth buffer
_camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
// render after the main camera
_camera->setRenderOrder(osg::Camera::POST_RENDER);
// attach the texture and use it as the color buffer.
//_camera->attach(osg::Camera::DEPTH_BUFFER, _texture.get());
_camera->attach(osg::Camera::COLOR_BUFFER, _texture.get());
}
else
{
// clear the depth and colour bufferson each clear.
_camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
// set the camera to render before the main camera.
_camera->setRenderOrder(osg::Camera::PRE_RENDER);
// tell the camera to use OpenGL frame buffer object where supported.
_camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
// attach the texture and use it as the color buffer.
_camera->attach(osg::Camera::DEPTH_BUFFER, _texture.get());
//_camera->attach(osg::Camera::COLOR_BUFFER, _texture.get());
}
}
void MWShadowTechnique::ShadowData::releaseGLObjects(osg::State* state) const
{
OSG_INFO<<"MWShadowTechnique::ShadowData::releaseGLObjects"<<std::endl;
_texture->releaseGLObjects(state);
_camera->releaseGLObjects(state);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// Frustum
//
MWShadowTechnique::Frustum::Frustum(osgUtil::CullVisitor* cv, double minZNear, double maxZFar):
useCustomClipSpace(false),
corners(8),
faces(6),
edges(12)
{
projectionMatrix = *(cv->getProjectionMatrix());
modelViewMatrix = *(cv->getModelViewMatrix());
OSG_INFO<<"Projection matrix "<<projectionMatrix<<std::endl;
if (cv->getComputeNearFarMode()!=osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR)
{
osg::Matrix::value_type zNear = osg::maximum<osg::Matrix::value_type>(cv->getCalculatedNearPlane(),minZNear);
osg::Matrix::value_type zFar = osg::minimum<osg::Matrix::value_type>(cv->getCalculatedFarPlane(),maxZFar);
cv->clampProjectionMatrix(projectionMatrix, zNear, zFar);
OSG_INFO<<"zNear = "<<zNear<<", zFar = "<<zFar<<std::endl;
OSG_INFO<<"Projection matrix after clamping "<<projectionMatrix<<std::endl;
}
}
void SceneUtil::MWShadowTechnique::Frustum::setCustomClipSpace(const osg::BoundingBoxd& clipCornersOverride)
{
useCustomClipSpace = true;
customClipSpace = clipCornersOverride;
}
void SceneUtil::MWShadowTechnique::Frustum::init()
{
osg::Matrixd clipToWorld;
clipToWorld.invert(modelViewMatrix * projectionMatrix);
if (useCustomClipSpace)
{
corners.clear();
// Add corners in the same order OSG expects them
for (int i : {0, 1, 5, 4, 2, 3, 7, 6})
{
corners.push_back(customClipSpace.corner(i));
}
}
else
{
corners[0].set(-1.0, -1.0, -1.0);
corners[1].set(1.0, -1.0, -1.0);
corners[2].set(1.0, -1.0, 1.0);
corners[3].set(-1.0, -1.0, 1.0);
corners[4].set(-1.0, 1.0, -1.0);
corners[5].set(1.0, 1.0, -1.0);
corners[6].set(1.0, 1.0, 1.0);
corners[7].set(-1.0, 1.0, 1.0);
}
// transform frustum corners from clipspace to world coords, and compute center
for(Vertices::iterator itr = corners.begin();
itr != corners.end();
++itr)
{
*itr = (*itr) * clipToWorld;
OSG_INFO<<" corner "<<*itr<<std::endl;
}
// compute eye point
eye = osg::Vec3d(0.0,0.0,0.0) * osg::Matrix::inverse(modelViewMatrix);
// compute center and the frustumCenterLine
centerNearPlane = (corners[0]+corners[1]+corners[5]+corners[4])*0.25;
centerFarPlane = (corners[3]+corners[2]+corners[6]+corners[7])*0.25;
center = (centerNearPlane+centerFarPlane)*0.5;
frustumCenterLine = centerFarPlane-centerNearPlane;
frustumCenterLine.normalize();
OSG_INFO<<" center "<<center<<std::endl;
faces[0].push_back(0);
faces[0].push_back(3);
faces[0].push_back(7);
faces[0].push_back(4);
faces[1].push_back(1);
faces[1].push_back(5);
faces[1].push_back(6);
faces[1].push_back(2);
faces[2].push_back(0);
faces[2].push_back(1);
faces[2].push_back(2);
faces[2].push_back(3);
faces[3].push_back(4);
faces[3].push_back(7);
faces[3].push_back(6);
faces[3].push_back(5);
faces[4].push_back(0);
faces[4].push_back(4);
faces[4].push_back(5);
faces[4].push_back(1);
faces[5].push_back(2);
faces[5].push_back(6);
faces[5].push_back(7);
faces[5].push_back(3);
edges[0].push_back(0); edges[0].push_back(1); // corner points on edge
edges[0].push_back(2); edges[0].push_back(4); // faces on edge
edges[1].push_back(1); edges[1].push_back(2); // corner points on edge
edges[1].push_back(2); edges[1].push_back(1); // faces on edge
edges[2].push_back(2); edges[2].push_back(3); // corner points on edge
edges[2].push_back(2); edges[2].push_back(5); // faces on edge
edges[3].push_back(3); edges[3].push_back(0); // corner points on edge
edges[3].push_back(2); edges[3].push_back(0); // faces on edge
edges[4].push_back(0); edges[4].push_back(4); // corner points on edge
edges[4].push_back(0); edges[4].push_back(4); // faces on edge
edges[5].push_back(1); edges[5].push_back(5); // corner points on edge
edges[5].push_back(4); edges[5].push_back(1); // faces on edge
edges[6].push_back(2); edges[6].push_back(6); // corner points on edge
edges[6].push_back(1); edges[6].push_back(5); // faces on edge
edges[7].push_back(3); edges[7].push_back(7); // corner points on edge
edges[7].push_back(5); edges[7].push_back(0); // faces on edge
edges[8].push_back(4); edges[8].push_back(5); // corner points on edge
edges[8].push_back(3); edges[8].push_back(4); // faces on edge
edges[9].push_back(5); edges[9].push_back(6); // corner points on edge
edges[9].push_back(3); edges[9].push_back(1); // faces on edge
edges[10].push_back(6);edges[10].push_back(7); // corner points on edge
edges[10].push_back(3);edges[10].push_back(5); // faces on edge
edges[11].push_back(7); edges[11].push_back(4); // corner points on edge
edges[11].push_back(3); edges[11].push_back(0); // faces on edge
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// ViewDependentData
//
MWShadowTechnique::ViewDependentData::ViewDependentData(MWShadowTechnique* vdsm):
_viewDependentShadowMap(vdsm)
{
OSG_INFO<<"ViewDependentData::ViewDependentData()"<<this<<std::endl;
for (auto& perFrameStateset : _stateset)
perFrameStateset = new osg::StateSet;
}
void MWShadowTechnique::ViewDependentData::releaseGLObjects(osg::State* state) const
{
for(ShadowDataList::const_iterator itr = _shadowDataList.begin();
itr != _shadowDataList.end();
++itr)
{
(*itr)->releaseGLObjects(state);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// MWShadowTechnique
//
MWShadowTechnique::MWShadowTechnique():
ShadowTechnique(),
_enableShadows(false),
_debugHud(nullptr),
_castingPrograms{ nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }
{
_shadowRecievingPlaceholderStateSet = new osg::StateSet;
mSetDummyStateWhenDisabled = false;
}
MWShadowTechnique::MWShadowTechnique(const MWShadowTechnique& vdsm, const osg::CopyOp& copyop):
ShadowTechnique(vdsm,copyop)
, _castingPrograms(vdsm._castingPrograms)
{
_shadowRecievingPlaceholderStateSet = new osg::StateSet;
_enableShadows = vdsm._enableShadows;
mSetDummyStateWhenDisabled = vdsm.mSetDummyStateWhenDisabled;
}
MWShadowTechnique::~MWShadowTechnique()
{
if (_shadowsBin != nullptr)
osgUtil::RenderBin::removeRenderBinPrototype(_shadowsBin);
}
void MWShadowTechnique::init()
{
if (!_shadowedScene) return;
OSG_INFO<<"MWShadowTechnique::init()"<<std::endl;
createShaders();
_dirty = false;
}
void MWShadowTechnique::cleanSceneGraph()
{
OSG_INFO<<"MWShadowTechnique::cleanSceneGraph()"<<std::endl;
}
void MWShadowTechnique::enableShadows()
{
_enableShadows = true;
}
void MWShadowTechnique::disableShadows(bool setDummyState)
{
_enableShadows = false;
mSetDummyStateWhenDisabled = setDummyState;
}
void SceneUtil::MWShadowTechnique::enableDebugHUD()
{
_debugHud = new DebugHUD(getShadowedScene()->getShadowSettings()->getNumShadowMapsPerLight());
}
void SceneUtil::MWShadowTechnique::disableDebugHUD()
{
_debugHud = nullptr;
}
void SceneUtil::MWShadowTechnique::setSplitPointUniformLogarithmicRatio(double ratio)
{
_splitPointUniformLogRatio = ratio;
}
void SceneUtil::MWShadowTechnique::setSplitPointDeltaBias(double bias)
{
_splitPointDeltaBias = bias;
}
void SceneUtil::MWShadowTechnique::setPolygonOffset(float factor, float units)
{
_polygonOffsetFactor = factor;
_polygonOffsetUnits = units;
if (_polygonOffset)
{
_polygonOffset->setFactor(factor);
_polygonOffset->setUnits(units);
}
}
void SceneUtil::MWShadowTechnique::setShadowFadeStart(float shadowFadeStart)
{
_shadowFadeStart = shadowFadeStart;
}
void SceneUtil::MWShadowTechnique::enableFrontFaceCulling()
{
_useFrontFaceCulling = true;
if (_shadowCastingStateSet)
{
_shadowCastingStateSet->setAttribute(new osg::CullFace(osg::CullFace::FRONT), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
_shadowCastingStateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
}
}
void SceneUtil::MWShadowTechnique::disableFrontFaceCulling()
{
_useFrontFaceCulling = false;
if (_shadowCastingStateSet)
{
_shadowCastingStateSet->removeAttribute(osg::StateAttribute::CULLFACE);
_shadowCastingStateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
}
}
void SceneUtil::MWShadowTechnique::setupCastingShader(Shader::ShaderManager & shaderManager)
{
// This can't be part of the constructor as OSG mandates that there be a trivial constructor available
osg::ref_ptr<osg::Shader> castingVertexShader = shaderManager.getShader("shadowcasting.vert");
std::string useGPUShader4 = SceneUtil::getGLExtensions().isGpuShader4Supported ? "1" : "0";
for (int alphaFunc = GL_NEVER; alphaFunc <= GL_ALWAYS; ++alphaFunc)
{
auto& program = _castingPrograms[alphaFunc - GL_NEVER];
program = new osg::Program();
program->addShader(castingVertexShader);
program->addShader(shaderManager.getShader("shadowcasting.frag", { {"alphaFunc", std::to_string(alphaFunc)},
{"alphaToCoverage", "0"},
{"adjustCoverage", "1"},
{"useGPUShader4", useGPUShader4}
}));
}
}
MWShadowTechnique::ViewDependentData* MWShadowTechnique::createViewDependentData(osgUtil::CullVisitor* /*cv*/)
{
return new ViewDependentData(this);
}
MWShadowTechnique::ViewDependentData* MWShadowTechnique::getViewDependentData(osgUtil::CullVisitor* cv)
{
std::lock_guard<std::mutex> lock(_viewDependentDataMapMutex);
ViewDependentDataMap::iterator itr = _viewDependentDataMap.find(cv);
if (itr!=_viewDependentDataMap.end()) return itr->second.get();
osg::ref_ptr<ViewDependentData> vdd = createViewDependentData(cv);
_viewDependentDataMap[cv] = vdd;
return vdd.release();
}
void SceneUtil::MWShadowTechnique::copyShadowMap(osgUtil::CullVisitor& cv, ViewDependentData* lhs, ViewDependentData* rhs)
{
// Prepare for rendering shadows using the shadow map owned by rhs.
// To achieve this i first copy all data that is not specific to this cv's camera and thus read-only,
// trusting openmw and osg won't overwrite that data before this frame is done rendering.
// This works due to the double buffering of CullVisitors by osg, but also requires that cull passes are serialized (relative to one another).
// Then initialize new copies of the data that will be written with view-specific data
// (the stateset and the texgens).
lhs->_viewDependentShadowMap = rhs->_viewDependentShadowMap;
auto* stateset = lhs->getStateSet(cv.getTraversalNumber());
stateset->clear();
lhs->_lightDataList = rhs->_lightDataList;
lhs->_numValidShadows = rhs->_numValidShadows;
ShadowDataList& sdl = lhs->getShadowDataList();
ShadowDataList previous_sdl;
previous_sdl.swap(sdl);
for (const auto& rhs_sd : rhs->getShadowDataList())
{
osg::ref_ptr<ShadowData> lhs_sd;
if (previous_sdl.empty())
{
OSG_INFO << "Create new ShadowData" << std::endl;
lhs_sd = new ShadowData(lhs);
}
else
{
OSG_INFO << "Taking ShadowData from from of previous_sdl" << std::endl;
lhs_sd = previous_sdl.front();
previous_sdl.erase(previous_sdl.begin());
}
lhs_sd->_camera = rhs_sd->_camera;
lhs_sd->_textureUnit = rhs_sd->_textureUnit;
lhs_sd->_texture = rhs_sd->_texture;
sdl.push_back(lhs_sd);
}
if (lhs->_numValidShadows > 0)
{
prepareStateSetForRenderingShadow(*lhs, cv.getTraversalNumber());
}
}
void SceneUtil::MWShadowTechnique::setCustomFrustumCallback(CustomFrustumCallback* cfc)
{
_customFrustumCallback = cfc;
}
void MWShadowTechnique::update(osg::NodeVisitor& nv)
{
OSG_INFO<<"MWShadowTechnique::update(osg::NodeVisitor& "<<&nv<<")"<<std::endl;
_shadowedScene->osg::Group::traverse(nv);
}
void MWShadowTechnique::cull(osgUtil::CullVisitor& cv)
{
if (!_enableShadows)
{
if (mSetDummyStateWhenDisabled)
{
osg::ref_ptr<osg::StateSet> dummyState = new osg::StateSet();
ShadowSettings* settings = getShadowedScene()->getShadowSettings();
int baseUnit = settings->getBaseShadowTextureUnit();
int endUnit = baseUnit + settings->getNumShadowMapsPerLight();
for (int i = baseUnit; i < endUnit; ++i)
{
dummyState->setTextureAttribute(i, _fallbackShadowMapTexture, osg::StateAttribute::ON);
dummyState->addUniform(new osg::Uniform(("shadowTexture" + std::to_string(i - baseUnit)).c_str(), i));
}
cv.pushStateSet(dummyState);
}
_shadowedScene->osg::Group::traverse(cv);
if (mSetDummyStateWhenDisabled)
cv.popStateSet();
return;
}
OSG_INFO<<std::endl<<std::endl<<"MWShadowTechnique::cull(osg::CullVisitor&"<<&cv<<")"<<std::endl;
if (!_shadowCastingStateSet)
{
OSG_INFO<<"Warning, init() has not yet been called so ShadowCastingStateSet has not been setup yet, unable to create shadows."<<std::endl;
_shadowedScene->osg::Group::traverse(cv);
return;
}
ViewDependentData* vdd = getViewDependentData(&cv);
if (!vdd)
{
OSG_INFO<<"Warning, now ViewDependentData created, unable to create shadows."<<std::endl;
_shadowedScene->osg::Group::traverse(cv);
return;
}
ShadowSettings* settings = getShadowedScene()->getShadowSettings();
OSG_INFO<<"cv->getProjectionMatrix()="<<*cv.getProjectionMatrix()<<std::endl;
osg::CullSettings::ComputeNearFarMode cachedNearFarMode = cv.getComputeNearFarMode();
osg::RefMatrix& viewProjectionMatrix = *cv.getProjectionMatrix();
// check whether this main views projection is perspective or orthographic
bool orthographicViewFrustum = viewProjectionMatrix(0,3)==0.0 &&
viewProjectionMatrix(1,3)==0.0 &&
viewProjectionMatrix(2,3)==0.0;
double minZNear = 0.0;
double maxZFar = dbl_max;
if (cachedNearFarMode==osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR)
{
double left, right, top, bottom;
if (orthographicViewFrustum)
{
viewProjectionMatrix.getOrtho(left, right, bottom, top, minZNear, maxZFar);
}
else
{
viewProjectionMatrix.getFrustum(left, right, bottom, top, minZNear, maxZFar);
}
OSG_INFO<<"minZNear="<<minZNear<<", maxZFar="<<maxZFar<<std::endl;
}
// set the compute near/far mode to the highest quality setting to ensure we push the near plan out as far as possible
if (settings->getComputeNearFarModeOverride()!=osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR)
{
cv.setComputeNearFarMode(settings->getComputeNearFarModeOverride());
}
// 1. Traverse main scene graph
auto* shadowReceiverStateSet = vdd->getStateSet(cv.getTraversalNumber());
shadowReceiverStateSet->clear();
cv.pushStateSet(shadowReceiverStateSet);
cullShadowReceivingScene(&cv);
cv.popStateSet();
if (cv.getComputeNearFarMode()!=osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR)
{
OSG_INFO<<"Just done main subgraph traversak"<<std::endl;
// make sure that the near plane is computed correctly so that any projection matrix computations
// are all done correctly.
cv.computeNearPlane();
}
// clamp the minZNear and maxZFar to those provided by ShadowSettings
maxZFar = osg::minimum(settings->getMaximumShadowMapDistance(),maxZFar);
if (minZNear>maxZFar) minZNear = maxZFar*settings->getMinimumShadowMapNearFarRatio();
//OSG_NOTICE<<"maxZFar "<<maxZFar<<std::endl;
// Workaround for absurdly huge viewing distances where OSG would otherwise push the near plane out.
cv.setNearFarRatio(minZNear / maxZFar);
Frustum frustum(&cv, minZNear, maxZFar);
if (_customFrustumCallback)
{
OSG_INFO << "Calling custom frustum callback" << std::endl;
osgUtil::CullVisitor* sharedFrustumHint = nullptr;
_customClipSpace.init();
_customFrustumCallback->operator()(cv, _customClipSpace, sharedFrustumHint);
frustum.setCustomClipSpace(_customClipSpace);
if (sharedFrustumHint)
{
// user hinted another view shares its frustum
std::lock_guard<std::mutex> lock(_viewDependentDataMapMutex);
auto itr = _viewDependentDataMap.find(sharedFrustumHint);
if (itr != _viewDependentDataMap.end())
{
OSG_INFO << "User provided a valid shared frustum hint, re-using previously generated shadow map" << std::endl;
copyShadowMap(cv, vdd, itr->second);
// return compute near far mode back to it's original settings
cv.setComputeNearFarMode(cachedNearFarMode);
return;
}
else
{
OSG_INFO << "User provided a shared frustum hint, but it was not valid." << std::endl;
}
}
}
frustum.init();
if (_debugHud)
{
osg::ref_ptr<osg::Vec3Array> vertexArray = new osg::Vec3Array();
for (osg::Vec3d &vertex : frustum.corners)
vertexArray->push_back((osg::Vec3)vertex);
_debugHud->setFrustumVertices(vertexArray, cv.getTraversalNumber());
}
double reducedNear, reducedFar;
if (cv.getComputeNearFarMode() != osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR)
{
reducedNear = osg::maximum<double>(cv.getCalculatedNearPlane(), minZNear);
reducedFar = osg::minimum<double>(cv.getCalculatedFarPlane(), maxZFar);
}
else
{
reducedNear = minZNear;
reducedFar = maxZFar;
}
// return compute near far mode back to it's original settings
cv.setComputeNearFarMode(cachedNearFarMode);
OSG_INFO<<"frustum.eye="<<frustum.eye<<", frustum.centerNearPlane, "<<frustum.centerNearPlane<<" distance = "<<(frustum.eye-frustum.centerNearPlane).length()<<std::endl;
// 2. select active light sources
// create a list of light sources + their matrices to place them
selectActiveLights(&cv, vdd);
unsigned int pos_x = 0;
unsigned int textureUnit = settings->getBaseShadowTextureUnit();
unsigned int numValidShadows = 0;
ShadowDataList& sdl = vdd->getShadowDataList();
ShadowDataList previous_sdl;
previous_sdl.swap(sdl);
unsigned int numShadowMapsPerLight = settings->getNumShadowMapsPerLight();
LightDataList& pll = vdd->getLightDataList();
for(LightDataList::iterator itr = pll.begin();
itr != pll.end();
++itr)
{
// 3. create per light/per shadow map division of lightspace/frustum
// create a list of light/shadow map data structures
LightData& pl = **itr;
// 3.1 compute light space polytope
//
osg::Polytope polytope = computeLightViewFrustumPolytope(frustum, pl);
// if polytope is empty then no rendering.
if (polytope.empty())
{
OSG_NOTICE<<"Polytope empty no shadow to render"<<std::endl;
continue;
}
// 3.2 compute RTT camera view+projection matrix settings
//
osg::Matrixd projectionMatrix;
osg::Matrixd viewMatrix;
if (!computeShadowCameraSettings(frustum, pl, projectionMatrix, viewMatrix))
{
OSG_NOTICE<<"No valid Camera settings, no shadow to render"<<std::endl;
continue;
}
// if we are using multiple shadow maps and CastShadowTraversalMask is being used
// traverse the scene to compute the extents of the objects
if (/*numShadowMapsPerLight>1 &&*/ (_shadowedScene->getCastsShadowTraversalMask() & _worldMask) == 0)
{
// osg::ElapsedTime timer;
osg::ref_ptr<osg::Viewport> viewport = new osg::Viewport(0,0,2048,2048);
if (!_clsb) _clsb = new ComputeLightSpaceBounds;
ComputeLightSpaceBounds& clsb = *_clsb;
clsb.reset();
clsb.pushViewport(viewport);
clsb.pushProjectionMatrix(new osg::RefMatrix(projectionMatrix));
clsb.pushModelViewMatrix(new osg::RefMatrix(viewMatrix), osg::Transform::ABSOLUTE_RF);
clsb.setTraversalMask(_shadowedScene->getCastsShadowTraversalMask());
osg::Matrixd invertModelView;
invertModelView.invert(viewMatrix);
osg::Polytope local_polytope(polytope);
local_polytope.transformProvidingInverse(invertModelView);
osg::CullingSet& cs = clsb.getProjectionCullingStack().back();
cs.setFrustum(local_polytope);
clsb.pushCullingSet();
_shadowedScene->accept(clsb);
clsb.popCullingSet();
clsb.popModelViewMatrix();
clsb.popProjectionMatrix();
clsb.popViewport();
// OSG_NOTICE<<"Extents of LightSpace "<<clsb._bb.xMin()<<", "<<clsb._bb.xMax()<<", "<<clsb._bb.yMin()<<", "<<clsb._bb.yMax()<<", "<<clsb._bb.zMin()<<", "<<clsb._bb.zMax()<<std::endl;
// OSG_NOTICE<<" time "<<timer.elapsedTime_m()<<"ms, mask = "<<std::hex<<_shadowedScene->getCastsShadowTraversalMask()<<std::endl;
if (clsb._bb.xMin()>-1.0f || clsb._bb.xMax()<1.0f || clsb._bb.yMin()>-1.0f || clsb._bb.yMax()<1.0f)
{
// OSG_NOTICE<<"Need to clamp projection matrix"<<std::endl;
#if 1
double xMid = (clsb._bb.xMin()+clsb._bb.xMax())*0.5f;
double xRange = clsb._bb.xMax()-clsb._bb.xMin();
#else
double xMid = 0.0;
double xRange = 2.0;
#endif
double yMid = (clsb._bb.yMin()+clsb._bb.yMax())*0.5f;
double yRange = (clsb._bb.yMax()-clsb._bb.yMin());
osg::Matrixd cornerConverter = osg::Matrixd::inverse(projectionMatrix) * osg::Matrixd::inverse(viewMatrix) * *cv.getModelViewMatrix();
double minZ = dbl_max;
double maxZ = -dbl_max;
clsb._bb._max[2] = 1.0;
for (unsigned int i = 0; i < 8; i++)
{
osg::Vec3 corner = clsb._bb.corner(i);
corner = corner * cornerConverter;
maxZ = osg::maximum<double>(maxZ, -corner.z());
minZ = osg::minimum<double>(minZ, -corner.z());
}
reducedNear = osg::maximum<double>(reducedNear, minZ);
reducedFar = osg::minimum<double>(reducedFar, maxZ);
// OSG_NOTICE<<" xMid="<<xMid<<", yMid="<<yMid<<", xRange="<<xRange<<", yRange="<<yRange<<std::endl;
projectionMatrix =
projectionMatrix *
osg::Matrixd::translate(osg::Vec3d(-xMid,-yMid,0.0)) *
osg::Matrixd::scale(osg::Vec3d(2.0/xRange, 2.0/yRange,1.0));
}
}
#if 0
double splitPoint = 0.0;
if (numShadowMapsPerLight>1)
{
osg::Vec3d eye_v = frustum.eye * viewMatrix;
osg::Vec3d center_v = frustum.center * viewMatrix;
osg::Vec3d viewdir_v = center_v-eye_v; viewdir_v.normalize();
osg::Vec3d lightdir(0.0,0.0,-1.0);
double dotProduct_v = lightdir * viewdir_v;
double angle = acosf(dotProduct_v);
osg::Vec3d eye_ls = eye_v * projectionMatrix;
OSG_INFO<<"Angle between view vector and eye "<<osg::RadiansToDegrees(angle)<<std::endl;
OSG_INFO<<"eye_ls="<<eye_ls<<std::endl;
if (eye_ls.y()>=-1.0 && eye_ls.y()<=1.0)
{
OSG_INFO<<"Eye point inside light space clip region "<<std::endl;
splitPoint = 0.0;
}
else
{
double n = -1.0-eye_ls.y();
double f = 1.0-eye_ls.y();
double sqrt_nf = sqrt(n*f);
double mid = eye_ls.y()+sqrt_nf;
double ratioOfMidToUseForSplit = 0.8;
splitPoint = mid * ratioOfMidToUseForSplit;
OSG_INFO<<" n="<<n<<", f="<<f<<", sqrt_nf="<<sqrt_nf<<" mid="<<mid<<std::endl;
}
}
#endif
// 4. For each light/shadow map
for (unsigned int sm_i=0; sm_i<numShadowMapsPerLight; ++sm_i)
{
osg::ref_ptr<ShadowData> sd;
if (previous_sdl.empty())
{
OSG_INFO<<"Create new ShadowData"<<std::endl;
sd = new ShadowData(vdd);
}
else
{
OSG_INFO<<"Taking ShadowData from from of previous_sdl"<<std::endl;
sd = previous_sdl.front();
previous_sdl.erase(previous_sdl.begin());
}
osg::ref_ptr<osg::Camera> camera = sd->_camera;
camera->setProjectionMatrix(projectionMatrix);
camera->setViewMatrix(viewMatrix);
if (settings->getDebugDraw())
{
camera->getViewport()->x() = pos_x;
pos_x += static_cast<unsigned int>(camera->getViewport()->width()) + 40;
}
// transform polytope in model coords into light spaces eye coords.
osg::Matrixd invertModelView;
invertModelView.invert(camera->getViewMatrix());
osg::Polytope local_polytope(polytope);
local_polytope.transformProvidingInverse(invertModelView);
double cascaseNear = reducedNear;
double cascadeFar = reducedFar;
if (numShadowMapsPerLight>1)
{
// compute the start and end range in non-dimensional coords
#if 0
double r_start = (sm_i==0) ? -1.0 : (double(sm_i)/double(numShadowMapsPerLight)*2.0-1.0);
double r_end = (sm_i+1==numShadowMapsPerLight) ? 1.0 : (double(sm_i+1)/double(numShadowMapsPerLight)*2.0-1.0);
#elif 0
// hardwired for 2 splits
double r_start = (sm_i==0) ? -1.0 : splitPoint;
double r_end = (sm_i+1==numShadowMapsPerLight) ? 1.0 : splitPoint;
#else
double r_start, r_end;
// split system based on the original Parallel Split Shadow Maps paper.
double n = reducedNear;
double f = reducedFar;
double i = double(sm_i);
double m = double(numShadowMapsPerLight);
if (sm_i == 0)
r_start = -1.0;
else
{
// compute the split point in main camera view
double ciLog = n * pow(f / n, i / m);
double ciUniform = n + (f - n) * i / m;
double ci = _splitPointUniformLogRatio * ciLog + (1.0 - _splitPointUniformLogRatio) * ciUniform + _splitPointDeltaBias;
cascaseNear = ci;
// work out where this is in light space
osg::Vec3d worldSpacePos = frustum.eye + frustum.frustumCenterLine * ci;
osg::Vec3d lightSpacePos = worldSpacePos * viewMatrix * projectionMatrix;
r_start = lightSpacePos.y();
}
if (sm_i + 1 == numShadowMapsPerLight)
r_end = 1.0;
else
{
// compute the split point in main camera view
double ciLog = n * pow(f / n, (i + 1) / m);
double ciUniform = n + (f - n) * (i + 1) / m;
double ci = _splitPointUniformLogRatio * ciLog + (1.0 - _splitPointUniformLogRatio) * ciUniform + _splitPointDeltaBias;
cascadeFar = ci;
// work out where this is in light space
osg::Vec3d worldSpacePos = frustum.eye + frustum.frustumCenterLine * ci;
osg::Vec3d lightSpacePos = worldSpacePos * viewMatrix * projectionMatrix;
r_end = lightSpacePos.y();
}
#endif
// for all by the last shadowmap shift the r_end so that it overlaps slightly with the next shadowmap
// to prevent a seam showing through between the shadowmaps
if (sm_i+1<numShadowMapsPerLight) r_end+=0.01;
// We can't add these clipping planes with cascaded shadow maps as they wouldn't be parallel to the light direction.
if (settings->getMultipleShadowMapHint() == ShadowSettings::PARALLEL_SPLIT && sm_i>0)
{
// not the first shadowmap so insert a polytope to clip the scene from before r_start
// plane in clip space coords
osg::Plane plane(0.0,1.0,0.0,-r_start);
// transform into eye coords
plane.transformProvidingInverse(projectionMatrix);
local_polytope.getPlaneList().push_back(plane);
//OSG_NOTICE<<"Adding r_start plane "<<plane<<std::endl;
}
if (settings->getMultipleShadowMapHint() == ShadowSettings::PARALLEL_SPLIT && sm_i+1<numShadowMapsPerLight)
{
// not the last shadowmap so insert a polytope to clip the scene from beyond r_end
// plane in clip space coords
osg::Plane plane(0.0,-1.0,0.0,r_end);
// transform into eye coords
plane.transformProvidingInverse(projectionMatrix);
local_polytope.getPlaneList().push_back(plane);
//OSG_NOTICE<<"Adding r_end plane "<<plane<<std::endl;
}
local_polytope.setupMask();
if (settings->getMultipleShadowMapHint() == ShadowSettings::PARALLEL_SPLIT)
{
// OSG_NOTICE<<"Need to adjust RTT camera projection and view matrix here, r_start="<<r_start<<", r_end="<<r_end<<std::endl;
// OSG_NOTICE<<" textureUnit = "<<textureUnit<<std::endl;
double mid_r = (r_start + r_end)*0.5;
double range_r = (r_end - r_start);
// OSG_NOTICE<<" mid_r = "<<mid_r<<", range_r = "<<range_r<<std::endl;
camera->setProjectionMatrix(
camera->getProjectionMatrix() *
osg::Matrixd::translate(osg::Vec3d(0.0,-mid_r,0.0)) *
osg::Matrixd::scale(osg::Vec3d(1.0,2.0/range_r,1.0)));
}
}
std::vector<osg::Plane> extraPlanes;
if (settings->getMultipleShadowMapHint() == ShadowSettings::CASCADED)
{
cropShadowCameraToMainFrustum(frustum, camera, cascaseNear, cascadeFar, extraPlanes);
for (const auto& plane : extraPlanes)
local_polytope.getPlaneList().push_back(plane);
local_polytope.setupMask();
}
else
cropShadowCameraToMainFrustum(frustum, camera, reducedNear, reducedFar, extraPlanes);
osg::ref_ptr<VDSMCameraCullCallback> vdsmCallback = new VDSMCameraCullCallback(this, local_polytope);
camera->setCullCallback(vdsmCallback.get());
// 4.3 traverse RTT camera
//
cv.pushStateSet(_shadowCastingStateSet.get());
cullShadowCastingScene(&cv, camera.get());
cv.popStateSet();
if (!orthographicViewFrustum && settings->getShadowMapProjectionHint()==ShadowSettings::PERSPECTIVE_SHADOW_MAP)
{
{
osg::Matrix validRegionMatrix = cv.getCurrentCamera()->getInverseViewMatrix() * camera->getViewMatrix() * camera->getProjectionMatrix();
std::string validRegionUniformName = "validRegionMatrix" + std::to_string(sm_i);
osg::ref_ptr<osg::Uniform> validRegionUniform;
for (const auto & uniform : _uniforms[cv.getTraversalNumber() % 2])
{
if (uniform->getName() == validRegionUniformName)
{
validRegionUniform = uniform;
break;
}
}
if (!validRegionUniform)
{
validRegionUniform = new osg::Uniform(osg::Uniform::FLOAT_MAT4, validRegionUniformName);
_uniforms[cv.getTraversalNumber() % 2].push_back(validRegionUniform);
}
validRegionUniform->set(validRegionMatrix);
}
if (settings->getMultipleShadowMapHint() == ShadowSettings::CASCADED)
adjustPerspectiveShadowMapCameraSettings(vdsmCallback->getRenderStage(), frustum, pl, camera.get(), cascaseNear, cascadeFar);
else
adjustPerspectiveShadowMapCameraSettings(vdsmCallback->getRenderStage(), frustum, pl, camera.get(), reducedNear, reducedFar);
if (vdsmCallback->getProjectionMatrix())
{
vdsmCallback->getProjectionMatrix()->set(camera->getProjectionMatrix());
}
}
// 4.4 compute main scene graph TexGen + uniform settings + setup state
//
{
osg::Matrix shadowSpaceMatrix = cv.getCurrentCamera()->getInverseViewMatrix() *
camera->getViewMatrix() *
camera->getProjectionMatrix() *
osg::Matrix::translate(1.0,1.0,1.0) *
osg::Matrix::scale(0.5,0.5,0.5);
std::string shadowSpaceUniformName = "shadowSpaceMatrix" + std::to_string(sm_i);
osg::ref_ptr<osg::Uniform> shadowSpaceUniform;
for (const auto & uniform : _uniforms[cv.getTraversalNumber() % 2])
{
if (uniform->getName() == shadowSpaceUniformName)
{
shadowSpaceUniform = uniform;
break;
}
}
if (!shadowSpaceUniform)
{
shadowSpaceUniform = new osg::Uniform(osg::Uniform::FLOAT_MAT4, shadowSpaceUniformName);
_uniforms[cv.getTraversalNumber() % 2].push_back(shadowSpaceUniform);
}
shadowSpaceUniform->set(shadowSpaceMatrix);
}
// mark the light as one that has active shadows and requires shaders
pl.textureUnits.push_back(textureUnit);
// pass on shadow data to ShadowDataList
sd->_textureUnit = textureUnit;
sdl.push_back(sd);
// increment counters.
++textureUnit;
++numValidShadows ;
if (_debugHud)
_debugHud->draw(sd->_texture, sm_i, camera->getViewMatrix() * camera->getProjectionMatrix(), cv);
}
}
vdd->setNumValidShadows(numValidShadows);
if (numValidShadows>0)
{
prepareStateSetForRenderingShadow(*vdd, cv.getTraversalNumber());
}
// OSG_NOTICE<<"End of shadow setup Projection matrix "<<*cv.getProjectionMatrix()<<std::endl;
}
bool MWShadowTechnique::selectActiveLights(osgUtil::CullVisitor* cv, ViewDependentData* vdd) const
{
OSG_INFO<<"selectActiveLights"<<std::endl;
LightDataList& pll = vdd->getLightDataList();
LightDataList previous_ldl;
previous_ldl.swap(pll);
//MR testing giving a specific light
osgUtil::RenderStage * rs = cv->getCurrentRenderBin()->getStage();
OSG_INFO<<"selectActiveLights osgUtil::RenderStage="<<rs<<std::endl;
osg::Matrixd modelViewMatrix = *(cv->getModelViewMatrix());
osgUtil::PositionalStateContainer::AttrMatrixList& aml =
rs->getPositionalStateContainer()->getAttrMatrixList();
const ShadowSettings* settings = getShadowedScene()->getShadowSettings();
for(osgUtil::PositionalStateContainer::AttrMatrixList::reverse_iterator itr = aml.rbegin();
itr != aml.rend();
++itr)
{
const osg::Light* light = dynamic_cast<const osg::Light*>(itr->first.get());
if (light && light->getLightNum() >= 0)
{
// is LightNum matched to that defined in settings
if (settings && settings->getLightNum()>=0 && light->getLightNum()!=settings->getLightNum()) continue;
LightDataList::iterator pll_itr = pll.begin();
for(; pll_itr != pll.end(); ++pll_itr)
{
if ((*pll_itr)->light->getLightNum()==light->getLightNum()) break;
}
if (pll_itr==pll.end())
{
OSG_INFO<<"Light num "<<light->getLightNum()<<std::endl;
LightData* ld = new LightData(vdd);
ld->setLightData(itr->second.get(), light, modelViewMatrix);
pll.push_back(ld);
}
else
{
OSG_INFO<<"Light num "<<light->getLightNum()<<" already used, ignore light"<<std::endl;
}
}
}
return !pll.empty();
}
void MWShadowTechnique::createShaders()
{
OSG_INFO<<"MWShadowTechnique::createShaders()"<<std::endl;
unsigned int _baseTextureUnit = 0;
_shadowCastingStateSet = new osg::StateSet;
ShadowSettings* settings = getShadowedScene()->getShadowSettings();
if (!settings->getDebugDraw())
{
// note soft (attribute only no mode override) setting. When this works ?
// 1. for objects prepared for backface culling
// because they usually also set CullFace and CullMode on in their state
// For them we override CullFace but CullMode remains set by them
// 2. For one faced, trees, and similar objects which cannot use
// backface nor front face so they usually use CullMode off set here.
// In this case we will draw them in their entirety.
if (_useFrontFaceCulling)
{
_shadowCastingStateSet->setAttribute(new osg::CullFace(osg::CullFace::FRONT), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
// make sure GL_CULL_FACE is off by default
// we assume that if object has cull face attribute set to back
// it will also set cull face mode ON so no need for override
_shadowCastingStateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
}
else
_shadowCastingStateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
}
_polygonOffset = new osg::PolygonOffset(_polygonOffsetFactor, _polygonOffsetUnits);
_shadowCastingStateSet->setAttribute(_polygonOffset.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
_shadowCastingStateSet->setMode(GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
osg::ref_ptr<osg::Uniform> baseTextureSampler = new osg::Uniform("baseTexture",(int)_baseTextureUnit);
osg::ref_ptr<osg::Uniform> baseTextureUnit = new osg::Uniform("baseTextureUnit",(int)_baseTextureUnit);
osg::ref_ptr<osg::Uniform> maxDistance = new osg::Uniform("maximumShadowMapDistance", (float)settings->getMaximumShadowMapDistance());
osg::ref_ptr<osg::Uniform> fadeStart = new osg::Uniform("shadowFadeStart", (float)_shadowFadeStart);
for (auto& perFrameUniformList : _uniforms)
{
perFrameUniformList.clear();
perFrameUniformList.push_back(baseTextureSampler);
perFrameUniformList.emplace_back(baseTextureUnit.get());
perFrameUniformList.push_back(maxDistance);
perFrameUniformList.push_back(fadeStart);
}
for(unsigned int sm_i=0; sm_i<settings->getNumShadowMapsPerLight(); ++sm_i)
{
{
std::stringstream sstr;
sstr<<"shadowTexture"<<sm_i;
osg::ref_ptr<osg::Uniform> shadowTextureSampler = new osg::Uniform(sstr.str().c_str(),(int)(settings->getBaseShadowTextureUnit()+sm_i));
for (auto& perFrameUniformList : _uniforms)
perFrameUniformList.emplace_back(shadowTextureSampler.get());
}
}
switch(settings->getShaderHint())
{
case(ShadowSettings::NO_SHADERS):
{
OSG_INFO<<"No shaders provided by, user must supply own shaders"<<std::endl;
break;
}
case(ShadowSettings::PROVIDE_VERTEX_AND_FRAGMENT_SHADER):
case(ShadowSettings::PROVIDE_FRAGMENT_SHADER):
{
_program = new osg::Program;
//osg::ref_ptr<osg::Shader> fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_noBaseTexture);
if (settings->getNumShadowMapsPerLight()==2)
{
_program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_withBaseTexture_twoShadowMaps));
}
else
{
_program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_withBaseTexture));
}
break;
}
}
{
osg::ref_ptr<osg::Image> image = new osg::Image;
image->allocateImage( 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE );
*(osg::Vec4ub*)image->data() = osg::Vec4ub( 0xFF, 0xFF, 0xFF, 0xFF );
_fallbackBaseTexture = new osg::Texture2D(image.get());
_fallbackBaseTexture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::REPEAT);
_fallbackBaseTexture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::REPEAT);
_fallbackBaseTexture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::NEAREST);
_fallbackBaseTexture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::NEAREST);
_fallbackShadowMapTexture = new osg::Texture2D(image.get());
_fallbackShadowMapTexture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::REPEAT);
_fallbackShadowMapTexture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::REPEAT);
_fallbackShadowMapTexture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::NEAREST);
_fallbackShadowMapTexture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::NEAREST);
_fallbackShadowMapTexture->setShadowComparison(true);
_fallbackShadowMapTexture->setShadowCompareFunc(osg::Texture::ShadowCompareFunc::ALWAYS);
}
if (!_castingPrograms[GL_ALWAYS - GL_NEVER])
OSG_NOTICE << "Shadow casting shader has not been set up. Remember to call setupCastingShader(Shader::ShaderManager &)" << std::endl;
// Always use the GL_ALWAYS shader as the shadows bin will change it if necessary
_shadowCastingStateSet->setAttributeAndModes(_castingPrograms[GL_ALWAYS - GL_NEVER], osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
// The casting program uses a sampler, so to avoid undefined behaviour, we must bind a dummy texture in case no other is supplied
_shadowCastingStateSet->setTextureAttribute(0, _fallbackBaseTexture.get(), osg::StateAttribute::ON);
_shadowCastingStateSet->addUniform(new osg::Uniform("useDiffuseMapForShadowAlpha", true));
_shadowCastingStateSet->addUniform(new osg::Uniform("alphaTestShadows", false));
osg::ref_ptr<osg::Depth> depth = new osg::Depth;
depth->setWriteMask(true);
osg::ref_ptr<osg::ClipControl> clipcontrol = new osg::ClipControl(osg::ClipControl::LOWER_LEFT, osg::ClipControl::NEGATIVE_ONE_TO_ONE);
_shadowCastingStateSet->setAttribute(clipcontrol, osg::StateAttribute::ON|osg::StateAttribute::OVERRIDE);
_shadowCastingStateSet->setAttribute(depth, osg::StateAttribute::ON|osg::StateAttribute::OVERRIDE);
_shadowCastingStateSet->setMode(GL_DEPTH_CLAMP, osg::StateAttribute::ON);
// TODO: compare performance when alpha testing is handled here versus using a discard in the fragment shader
}
osg::Polytope MWShadowTechnique::computeLightViewFrustumPolytope(Frustum& frustum, LightData& positionedLight)
{
OSG_INFO<<"computeLightViewFrustumPolytope()"<<std::endl;
osg::Polytope polytope;
if (frustum.useCustomClipSpace)
{
polytope.setToBoundingBox(frustum.customClipSpace);
}
else
{
polytope.setToUnitFrustum();
}
polytope.transformProvidingInverse( frustum.projectionMatrix );
polytope.transformProvidingInverse( frustum.modelViewMatrix );
osg::Polytope lightVolumePolytope;
if (positionedLight.directionalLight)
{
osg::Polytope::PlaneList& planes = polytope.getPlaneList();
osg::Polytope::ClippingMask selector_mask = 0x1;
osg::Polytope::ClippingMask result_mask = 0x0;
for(unsigned int i=0; i<planes.size(); ++i, selector_mask <<= 1)
{
OSG_INFO<<" plane "<<planes[i]<<" planes["<<i<<"].dotProductNormal(lightDir)="<<planes[i].dotProductNormal(positionedLight.lightDir);
if (planes[i].dotProductNormal(positionedLight.lightDir)>=0.0)
{
OSG_INFO<<" Need remove side "<<i<<std::endl;
}
else
{
OSG_INFO<<std::endl;
lightVolumePolytope.add(planes[i]);
result_mask = result_mask | selector_mask;
}
}
OSG_INFO<<" planes.size() = "<<planes.size()<<std::endl;
OSG_INFO<<" planes.getResultMask() = "<<polytope.getResultMask()<<std::endl;
OSG_INFO<<" resultMask = "<<result_mask<<std::endl;
polytope.setResultMask(result_mask);
}
else
{
const osg::Polytope::PlaneList& planes = polytope.getPlaneList();
osg::Polytope::ClippingMask selector_mask = 0x1;
osg::Polytope::ClippingMask result_mask = 0x0;
for(unsigned int i=0; i<planes.size(); ++i, selector_mask <<= 1)
{
double d = planes[i].distance(positionedLight.lightPos3);
OSG_INFO<<" plane "<<planes[i]<<" planes["<<i<<"].distance(lightPos3)="<<d;
if (d<0.0)
{
OSG_INFO<<" Need remove side "<<i<<std::endl;
}
else
{
OSG_INFO<<std::endl;
lightVolumePolytope.add(planes[i]);
result_mask = result_mask | selector_mask;
}
}
OSG_INFO<<" planes.size() = "<<planes.size()<<std::endl;
OSG_INFO<<" planes.getResultMask() = "<<polytope.getResultMask()<<std::endl;
OSG_INFO<<" resultMask = "<<result_mask<<std::endl;
polytope.setResultMask(result_mask);
}
OSG_INFO<<"Which frustum edges are active?"<<std::endl;
for(unsigned int i=0; i<12; ++i)
{
Frustum::Indices& indices = frustum.edges[i];
unsigned int corner_a = indices[0];
unsigned int corner_b = indices[1];
unsigned int face_a = indices[2];
unsigned int face_b = indices[3];
bool face_a_active = (polytope.getResultMask()&(0x1<<face_a))!=0;
bool face_b_active = (polytope.getResultMask()&(0x1<<face_b))!=0;
unsigned int numActive = 0;
if (face_a_active) ++numActive;
if (face_b_active) ++numActive;
if (numActive==1)
{
osg::Plane boundaryPlane;
if (positionedLight.directionalLight)
{
osg::Vec3d normal = (frustum.corners[corner_b]-frustum.corners[corner_a])^positionedLight.lightDir;
normal.normalize();
boundaryPlane.set(normal, frustum.corners[corner_a]);
}
else
{
boundaryPlane.set(positionedLight.lightPos3, frustum.corners[corner_a], frustum.corners[corner_b]);
}
OSG_INFO<<"Boundary Edge "<<i<<", corner_a="<<corner_a<<", corner_b="<<corner_b<<", face_a_active="<<face_a_active<<", face_b_active="<<face_b_active;
if (boundaryPlane.distance(frustum.center)<0.0)
{
boundaryPlane.flip();
OSG_INFO<<", flipped boundary edge "<<boundaryPlane<<std::endl;
}
else
{
OSG_INFO<<", no need to flip boundary edge "<<boundaryPlane<<std::endl;
}
lightVolumePolytope.add(boundaryPlane);
}
else OSG_INFO<<"Internal Edge "<<i<<", corner_a="<<corner_a<<", corner_b="<<corner_b<<", face_a_active="<<face_a_active<<", face_b_active="<<face_b_active<<std::endl;
}
const osg::Polytope::PlaneList& planes = lightVolumePolytope.getPlaneList();
for(unsigned int i=0; i<planes.size(); ++i)
{
OSG_INFO<<" plane "<<planes[i]<<" "<<((lightVolumePolytope.getResultMask() & (0x1<<i))?"on":"off")<<std::endl;
}
return lightVolumePolytope;
}
bool MWShadowTechnique::computeShadowCameraSettings(Frustum& frustum, LightData& positionedLight, osg::Matrixd& projectionMatrix, osg::Matrixd& viewMatrix)
{
OSG_INFO<<"standardShadowMapCameraSettings()"<<std::endl;
osg::Vec3d lightSide;
const ShadowSettings* settings = getShadowedScene()->getShadowSettings();
double dotProduct_v = positionedLight.lightDir * frustum.frustumCenterLine;
double gamma_v = acos(dotProduct_v);
if (gamma_v<osg::DegreesToRadians(settings->getPerspectiveShadowMapCutOffAngle()) || gamma_v>osg::DegreesToRadians(180.0-settings->getPerspectiveShadowMapCutOffAngle()))
{
OSG_INFO<<"View direction and Light direction below tolerance"<<std::endl;
osg::Vec3d viewSide = osg::Matrixd::transform3x3(frustum.modelViewMatrix, osg::Vec3d(1.0,0.0,0.0));
lightSide = positionedLight.lightDir ^ (viewSide ^ positionedLight.lightDir);
lightSide.normalize();
}
else
{
lightSide = positionedLight.lightDir ^ frustum.frustumCenterLine;
lightSide.normalize();
}
osg::Vec3d lightUp = lightSide ^ positionedLight.lightDir;
#if 0
OSG_NOTICE<<"positionedLight.lightDir="<<positionedLight.lightDir<<std::endl;
OSG_NOTICE<<"lightSide="<<lightSide<<std::endl;
OSG_NOTICE<<"lightUp="<<lightUp<<std::endl;
#endif
if (positionedLight.directionalLight)
{
double xMin=0.0, xMax=0.0;
double yMin=0.0, yMax=0.0;
double zMin=0.0, zMax=0.0;
for(Frustum::Vertices::iterator itr = frustum.corners.begin();
itr != frustum.corners.end();
++itr)
{
osg::Vec3d cornerDelta(*itr - frustum.center);
osg::Vec3d cornerInLightCoords(cornerDelta*lightSide,
cornerDelta*lightUp,
cornerDelta*positionedLight.lightDir);
OSG_INFO<<" corner ="<<*itr<<" in lightcoords "<<cornerInLightCoords<<std::endl;
xMin = osg::minimum( xMin, cornerInLightCoords.x());
xMax = osg::maximum( xMax, cornerInLightCoords.x());
yMin = osg::minimum( yMin, cornerInLightCoords.y());
yMax = osg::maximum( yMax, cornerInLightCoords.y());
zMin = osg::minimum( zMin, cornerInLightCoords.z());
zMax = osg::maximum( zMax, cornerInLightCoords.z());
}
OSG_INFO<<"before bs xMin="<<xMin<<", xMax="<<xMax<<", yMin="<<yMin<<", yMax="<<yMax<<", zMin="<<zMin<<", zMax="<<zMax<<std::endl;
osg::BoundingSphere bs = _shadowedScene->getBound();
osg::Vec3d modelCenterRelativeFrustumCenter(bs.center()-frustum.center);
osg::Vec3d modelCenterInLightCoords(modelCenterRelativeFrustumCenter*lightSide,
modelCenterRelativeFrustumCenter*lightUp,
modelCenterRelativeFrustumCenter*positionedLight.lightDir);
OSG_INFO<<"modelCenterInLight="<<modelCenterInLightCoords<<" radius="<<bs.radius()<<std::endl;
double radius(bs.radius());
xMin = osg::maximum(xMin, modelCenterInLightCoords.x()-radius);
xMax = osg::minimum(xMax, modelCenterInLightCoords.x()+radius);
yMin = osg::maximum(yMin, modelCenterInLightCoords.y()-radius);
yMax = osg::minimum(yMax, modelCenterInLightCoords.y()+radius);
zMin = modelCenterInLightCoords.z()-radius;
zMax = osg::minimum(zMax, modelCenterInLightCoords.z()+radius);
OSG_INFO<<"after bs xMin="<<xMin<<", xMax="<<xMax<<", yMin="<<yMin<<", yMax="<<yMax<<", zMin="<<zMin<<", zMax="<<zMax<<std::endl;
if (xMin>=xMax || yMin>=yMax || zMin>=zMax)
{
OSG_INFO<<"Warning nothing available to create shadows"<<zMax<<std::endl;
return false;
}
else
{
projectionMatrix.makeOrtho(xMin,xMax, yMin, yMax,0.0,zMax-zMin);
viewMatrix.makeLookAt(frustum.center+positionedLight.lightDir*zMin, frustum.center+positionedLight.lightDir*zMax, lightUp);
}
}
else
{
double zMax=-dbl_max;
OSG_INFO<<"lightDir = "<<positionedLight.lightDir<<std::endl;
OSG_INFO<<"lightPos3 = "<<positionedLight.lightPos3<<std::endl;
for(Frustum::Vertices::iterator itr = frustum.corners.begin();
itr != frustum.corners.end();
++itr)
{
osg::Vec3d cornerDelta(*itr - positionedLight.lightPos3);
osg::Vec3d cornerInLightCoords(cornerDelta*lightSide,
cornerDelta*lightUp,
cornerDelta*positionedLight.lightDir);
OSG_INFO<<" cornerInLightCoords= "<<cornerInLightCoords<<std::endl;
zMax = osg::maximum( zMax, cornerInLightCoords.z());
}
OSG_INFO<<"zMax = "<<zMax<<std::endl;
if (zMax<0.0)
{
// view frustum entirely behind light
return false;
}
double minRatio = 0.0001;
double zMin=zMax*minRatio;
double fov = positionedLight.light->getSpotCutoff() * 2.0;
if(fov < 180.0) // spotlight
{
projectionMatrix.makePerspective(fov, 1.0, zMin, zMax);
viewMatrix.makeLookAt(positionedLight.lightPos3,
positionedLight.lightPos3+positionedLight.lightDir, lightUp);
}
else
{
double fovMAX = 160.0f;
fov = 0.0;
// calculate the max FOV from the corners of the frustum relative to the light position
for(Frustum::Vertices::iterator itr = frustum.corners.begin();
itr != frustum.corners.end();
++itr)
{
osg::Vec3d cornerDelta(*itr - positionedLight.lightPos3);
double length = cornerDelta.length();
if (length==0.0) fov = osg::minimum(fov, 180.0);
else
{
double dotProduct = cornerDelta*positionedLight.lightDir;
double angle = 2.0*osg::RadiansToDegrees( acos(dotProduct/length) );
fov = osg::maximum(fov, angle);
}
}
OSG_INFO<<"Computed fov = "<<fov<<std::endl;
if (fov>fovMAX)
{
OSG_INFO<<"Clampping fov = "<<fov<<std::endl;
fov=fovMAX;
}
projectionMatrix.makePerspective(fov, 1.0, zMin, zMax);
viewMatrix.makeLookAt(positionedLight.lightPos3,
positionedLight.lightPos3+positionedLight.lightDir, lightUp);
}
}
return true;
}
struct ConvexHull
{
typedef std::vector<osg::Vec3d> Vertices;
typedef std::pair<osg::Vec3d, osg::Vec3d> Edge;
typedef std::vector<Edge> Edges;
typedef std::vector<osg::Vec3d> VertexSet;
Edges _edges;
bool valid() const { return !_edges.empty(); }
void setToFrustum(MWShadowTechnique::Frustum& frustum)
{
_edges.emplace_back(frustum.corners[0], frustum.corners[1]);
_edges.emplace_back(frustum.corners[1], frustum.corners[2]);
_edges.emplace_back(frustum.corners[2], frustum.corners[3]);
_edges.emplace_back(frustum.corners[3], frustum.corners[0]);
_edges.emplace_back(frustum.corners[4], frustum.corners[5]);
_edges.emplace_back(frustum.corners[5], frustum.corners[6]);
_edges.emplace_back(frustum.corners[6], frustum.corners[7]);
_edges.emplace_back(frustum.corners[7], frustum.corners[4]);
_edges.emplace_back(frustum.corners[0], frustum.corners[4]);
_edges.emplace_back(frustum.corners[1], frustum.corners[5]);
_edges.emplace_back(frustum.corners[2], frustum.corners[6]);
_edges.emplace_back(frustum.corners[3], frustum.corners[7]);
}
struct ConvexHull2D
{
// Implementation based on https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain#C++
typedef osg::Vec3d Point;
static double cross(const Point &O, const Point &A, const Point &B)
{
return (A.x() - O.x())*(B.y() - O.y()) - (A.y() - O.y())*(B.x() - O.x());
}
// Calculates the 2D convex hull and returns it as a vector containing the points in CCW order with the first and last point being the same.
static Vertices convexHull(const VertexSet &P)
{
size_t n = P.size(), k = 0;
if (n <= 3)
return Vertices(P.cbegin(), P.cend());
Vertices H(2 * n);
// Points are already sorted in a std::set
// Build lower hull
for(const auto& vert : P)
{
while (k >= 2 && cross(H[k - 2], H[k - 1], vert) <= 0)
k--;
H[k++] = vert;
}
// Build upper hull
size_t t = k + 1;
for (auto pItr = std::next(P.crbegin()); pItr != P.crend(); ++pItr)
{
while (k >= t && cross(H[k - 2], H[k - 1], *pItr) <= 0)
k--;
H[k++] = *pItr;
}
H.resize(k - 1);
return H;
}
};
Vertices findInternalEdges(const osg::Vec3d& mainVertex, const Vertices& connectedVertices)
{
Vertices internalEdgeVertices;
for (const auto& vertex : connectedVertices)
{
osg::Matrixd matrix;
osg::Vec3d dir = vertex - mainVertex;
matrix.makeLookAt(mainVertex, vertex, dir.z() == 0 ? osg::Vec3d(0, 0, 1) : osg::Vec3d(1, 0, 0));
Vertices testVertices;
for (const auto& testVertex : connectedVertices)
{
if (vertex != testVertex)
testVertices.push_back(testVertex);
}
std::vector<double> bearings;
for (const auto& testVertex : testVertices)
{
osg::Vec3d transformedVertex = testVertex * matrix;
bearings.push_back(atan2(transformedVertex.y(), transformedVertex.x()));
}
std::sort(bearings.begin(), bearings.end());
bool keep = false;
for (auto itr = bearings.begin(); itr + 1 != bearings.end(); ++itr)
{
if (*itr + osg::PI < *(itr + 1))
{
keep = true;
break;
}
}
if (!keep && bearings[0] + osg::PI > bearings.back())
keep = true;
if (!keep)
internalEdgeVertices.push_back(vertex);
}
return internalEdgeVertices;
}
void extendTowardsNegativeZ()
{
// Collect the set of vertices
VertexSet vertices;
for (const Edge& edge : _edges)
{
vertices.emplace_back(edge.first);
vertices.emplace_back(edge.second);
}
// Sort and make unique.
std::sort(vertices.begin(), vertices.end());
vertices.erase(std::unique(vertices.begin(), vertices.end()), vertices.end());
if (vertices.size() == 0)
return;
// Get the vertices contributing to the 2D convex hull
Vertices extremeVertices = ConvexHull2D::convexHull(vertices);
// Add their extrusions to the final edge collection
// We extrude as far as -1.5 as the coordinate space shouldn't ever put any shadow casters further than -1.0
Edges finalEdges;
// Add edges towards -Z
for (const auto& vertex : extremeVertices)
finalEdges.emplace_back(vertex, osg::Vec3d(vertex.x(), vertex.y(), -1.5));
// Add edge loop to 'seal' the hull
for (auto itr = extremeVertices.cbegin(); itr != extremeVertices.cend() - 1; ++itr)
finalEdges.emplace_back(osg::Vec3d(itr->x(), itr->y(), -1.5), osg::Vec3d((itr + 1)->x(), (itr + 1)->y(), -1.5));
// The convex hull algorithm we are using sometimes places a point at both ends of the vector, so we don't always need to add the last edge separately.
if (extremeVertices.front() != extremeVertices.back())
finalEdges.emplace_back(osg::Vec3d(extremeVertices.front().x(), extremeVertices.front().y(), -1.5), osg::Vec3d(extremeVertices.back().x(), extremeVertices.back().y(), -1.5));
// Remove internal edges connected to extreme vertices
for (const auto& vertex : extremeVertices)
{
Vertices connectedVertices;
for (const Edge& edge : _edges)
{
if (edge.first == vertex)
connectedVertices.push_back(edge.second);
else if (edge.second == vertex)
connectedVertices.push_back(edge.first);
}
connectedVertices.emplace_back(vertex.x(), vertex.y(), -1.5);
Vertices unwantedEdgeEnds = findInternalEdges(vertex, connectedVertices);
for (const auto& edgeEnd : unwantedEdgeEnds)
{
const auto edgeA = Edge(vertex, edgeEnd);
const auto edgeB = Edge(edgeEnd, vertex);
_edges.erase(std::remove_if(_edges.begin(), _edges.end(), [&](const auto& elem)
{
return elem == edgeA || elem == edgeB;
}), _edges.end());
}
}
// Gather connected vertices
VertexSet unprocessedConnectedVertices = std::move(extremeVertices);
VertexSet connectedVertices;
const auto containsVertex = [&](const auto& vert)
{
return std::find(connectedVertices.begin(), connectedVertices.end(), vert) != connectedVertices.end();
};
while (!unprocessedConnectedVertices.empty())
{
osg::Vec3d vertex = unprocessedConnectedVertices.back();
unprocessedConnectedVertices.pop_back();
connectedVertices.emplace_back(vertex);
for (const Edge& edge : _edges)
{
osg::Vec3d otherEnd;
if (edge.first == vertex)
otherEnd = edge.second;
else if (edge.second == vertex)
otherEnd = edge.first;
else
continue;
if (containsVertex(otherEnd))
continue;
unprocessedConnectedVertices.emplace_back(otherEnd);
}
}
for (const Edge& edge : _edges)
{
if (containsVertex(edge.first) || containsVertex(edge.second))
finalEdges.push_back(edge);
}
_edges = std::move(finalEdges);
}
void transform(const osg::Matrixd& m)
{
for (auto& edge : _edges)
{
edge.first = edge.first * m;
edge.second = edge.second * m;
}
}
void clip(const osg::Plane& plane)
{
Vertices intersections;
// OSG_NOTICE<<"clip("<<plane<<") edges.size()="<<_edges.size()<<std::endl;
for(auto itr = _edges.begin(); itr != _edges.end();)
{
double d0 = plane.distance(itr->first);
double d1 = plane.distance(itr->second);
if (d0<0.0 && d1<0.0)
{
// OSG_NOTICE<<" Edge completely outside, removing"<<std::endl;
itr = _edges.erase(itr);
}
else if (d0>=0.0 && d1>=0.0)
{
// OSG_NOTICE<<" Edge completely inside"<<std::endl;
++itr;
}
else
{
osg::Vec3d& v0 = itr->first;
osg::Vec3d& v1 = itr->second;
osg::Vec3d intersection = v0 - (v1-v0)*(d0/(d1-d0));
intersections.push_back(intersection);
// OSG_NOTICE<<" Edge across clip plane, v0="<<v0<<", v1="<<v1<<", intersection= "<<intersection<<std::endl;
if (d0<0.0)
{
// move first vertex on edge
v0 = intersection;
}
else
{
// move second vertex on edge
v1 = intersection;
}
++itr;
}
}
// OSG_NOTICE<<"After clipping, have "<<intersections.size()<<" to insert"<<std::endl;
if (intersections.size() < 2)
{
return;
}
if (intersections.size() == 2)
{
_edges.emplace_back(intersections[0], intersections[1]);
return;
}
if (intersections.size() == 3)
{
_edges.emplace_back(intersections[0], intersections[1]);
_edges.emplace_back(intersections[1], intersections[2]);
_edges.emplace_back(intersections[2], intersections[0]);
return;
}
// more than 3 intersections so have to sort them in clockwise order so that
// we can generate the edges correctly.
osg::Vec3d normal(plane.getNormal());
osg::Vec3d side_x = osg::Vec3d(1.0,0.0,0.0) ^ normal;
osg::Vec3d side_y = osg::Vec3d(0.0,1.0,0.0) ^ normal;
osg::Vec3d side = (side_x.length2()>=side_y.length2()) ? side_x : side_y;
side.normalize();
osg::Vec3d up = side ^ normal;
up.normalize();
osg::Vec3d center;
for(auto& vertex : intersections)
{
center += vertex;
center.x() = osg::maximum(center.x(), -dbl_max);
center.y() = osg::maximum(center.y(), -dbl_max);
center.z() = osg::maximum(center.z(), -dbl_max);
center.x() = osg::minimum(center.x(), dbl_max);
center.y() = osg::minimum(center.y(), dbl_max);
center.z() = osg::minimum(center.z(), dbl_max);
}
center /= double(intersections.size());
typedef std::map<double, std::list<std::pair<osg::Vec3d, double>>> VertexMap;
VertexMap vertexMap;
for (const auto& vertex : intersections)
{
osg::Vec3d dv = vertex - center;
double h = dv * side;
double v = dv * up;
double angle = atan2(h,v);
// OSG_NOTICE<<"angle = "<<osg::RadiansToDegrees(angle)<<", h="<<h<<" v= "<<v<<std::endl;
// We need to make sure all intersections are added to the list in the right order, even if they're so far away that their angles work out the same.
double sortValue;
if (angle < osg::DegreesToRadians(-135.0) || angle > osg::DegreesToRadians(135.0))
sortValue = -h;
else if (angle < osg::DegreesToRadians(-45.0))
sortValue = v;
else if (angle < osg::DegreesToRadians(45.0))
sortValue = h;
else
sortValue = -v;
if (vertexMap.count(angle))
{
auto listItr = vertexMap[angle].begin();
while (listItr != vertexMap[angle].end() && listItr->second < sortValue)
++listItr;
vertexMap[angle].emplace(listItr, std::make_pair(vertex, sortValue));
}
else
vertexMap[angle].emplace_back(vertex, sortValue);
}
osg::Vec3d previous_v = vertexMap.rbegin()->second.back().first;
for (auto itr = vertexMap.begin(); itr != vertexMap.end(); ++itr)
{
for (const auto& vertex : itr->second)
{
_edges.emplace_back(previous_v, vertex.first);
previous_v = vertex.first;
}
}
// OSG_NOTICE<<" after clip("<<plane<<") edges.size()="<<_edges.size()<<std::endl;
}
void clip(const osg::Polytope& polytope)
{
const osg::Polytope::PlaneList& planes = polytope.getPlaneList();
for(const auto& plane : planes)
{
clip(plane);
}
}
double min(unsigned int index) const
{
double m = dbl_max;
for(const auto& edge : _edges)
{
if (edge.first[index] < m) m = edge.first[index];
if (edge.second[index] < m) m = edge.second[index];
}
return m;
}
double max(unsigned int index) const
{
double m = -dbl_max;
for (const auto& edge : _edges)
{
if (edge.first[index] > m) m = edge.first[index];
if (edge.second[index] > m) m = edge.second[index];
}
return m;
}
double minRatio(const osg::Vec3d& eye, unsigned int index) const
{
double m = dbl_max;
osg::Vec3d delta;
double ratio;
for (const auto& edge : _edges)
{
delta = edge.first - eye;
ratio = delta[index] / delta[1];
if (ratio < m) m = ratio;
delta = edge.second - eye;
ratio = delta[index] / delta[1];
if (ratio < m) m = ratio;
}
return m;
}
double maxRatio(const osg::Vec3d& eye, unsigned int index) const
{
double m = -dbl_max;
osg::Vec3d delta;
double ratio;
for (const auto& edge : _edges)
{
delta = edge.first - eye;
ratio = delta[index] / delta[1];
if (ratio > m) m = ratio;
delta = edge.second - eye;
ratio = delta[index] / delta[1];
if (ratio > m) m = ratio;
}
return m;
}
void output(std::ostream& out)
{
out << "ConvexHull" << std::endl;
for (const auto& edge : _edges)
{
out << " edge (" << edge.first << ") (" << edge.second << ")" << std::endl;
}
}
};
struct RenderLeafBounds
{
RenderLeafBounds():
computeRatios(false),
numRenderLeaf(0),
n(0.0),
previous_modelview(0),
clip_min_x(-1.0), clip_max_x(1.0),
clip_min_y(-1.0), clip_max_y(1.0),
clip_min_z(-1.0), clip_max_z(1.0),
clip_min_x_ratio(-dbl_max), clip_max_x_ratio(dbl_max),
clip_min_z_ratio(-dbl_max), clip_max_z_ratio(dbl_max),
min_x_ratio(dbl_max), max_x_ratio(-dbl_max),
min_z_ratio(dbl_max), max_z_ratio(-dbl_max),
min_x(1.0), max_x(-1.0),
min_y(1.0), max_y(-1.0),
min_z(1.0), max_z(-1.0)
{
//OSG_NOTICE<<std::endl<<"RenderLeafBounds"<<std::endl;
}
void set(const osg::Matrixd& p)
{
computeRatios = false;
light_p = p;
clip_min_x = -dbl_max; clip_max_x = dbl_max;
clip_min_y = -dbl_max; clip_max_y = dbl_max;
clip_min_z = -dbl_max; clip_max_z = dbl_max;
min_x = dbl_max; max_x = -dbl_max;
min_y = dbl_max; max_y = -dbl_max;
min_z = dbl_max; max_z = -dbl_max;
}
void set(const osg::Matrixd& p, osg::Vec3d& e_ls, double nr)
{
computeRatios = true;
light_p = p;
eye_ls = e_ls;
n = nr;
}
void operator() (const osgUtil::RenderLeaf* renderLeaf)
{
++numRenderLeaf;
if (renderLeaf->_modelview.get()!=previous_modelview)
{
previous_modelview = renderLeaf->_modelview.get();
if (previous_modelview)
{
light_mvp.mult(*renderLeaf->_modelview, light_p);
}
else
{
// no modelview matrix (such as when LightPointNode is in the scene graph) so assume
// that modelview matrix is indentity.
light_mvp = light_p;
}
// OSG_INFO<<"Computing new light_mvp "<<light_mvp<<std::endl;
}
else
{
// OSG_INFO<<"Reusing light_mvp "<<light_mvp<<std::endl;
}
const osg::BoundingBox& bb = renderLeaf->_drawable->getBoundingBox();
if (bb.valid())
{
// OSG_NOTICE<<"checked extents of "<<renderLeaf->_drawable->getName()<<std::endl;
handle(osg::Vec3d(bb.xMin(),bb.yMin(),bb.zMin()));
handle(osg::Vec3d(bb.xMax(),bb.yMin(),bb.zMin()));
handle(osg::Vec3d(bb.xMin(),bb.yMax(),bb.zMin()));
handle(osg::Vec3d(bb.xMax(),bb.yMax(),bb.zMin()));
handle(osg::Vec3d(bb.xMin(),bb.yMin(),bb.zMax()));
handle(osg::Vec3d(bb.xMax(),bb.yMin(),bb.zMax()));
handle(osg::Vec3d(bb.xMin(),bb.yMax(),bb.zMax()));
handle(osg::Vec3d(bb.xMax(),bb.yMax(),bb.zMax()));
}
else
{
OSG_INFO<<"bb invalid"<<std::endl;
}
}
void handle(const osg::Vec3d& v)
{
osg::Vec3d ls = v * light_mvp;
// OSG_NOTICE<<" corner v="<<v<<", ls="<<ls<<std::endl;
if (computeRatios)
{
osg::Vec3d delta = ls-eye_ls;
double x_ratio, z_ratio;
if (delta.y()>n)
{
x_ratio = delta.x()/delta.y();
z_ratio = delta.z()/delta.y();
}
else
{
x_ratio = delta.x()/n;
z_ratio = delta.z()/n;
}
if (x_ratio<min_x_ratio) min_x_ratio = x_ratio;
if (x_ratio>max_x_ratio) max_x_ratio = x_ratio;
if (z_ratio<min_z_ratio) min_z_ratio = z_ratio;
if (z_ratio>max_z_ratio) max_z_ratio = z_ratio;
}
// clip to the light space
if (ls.x()<clip_min_x) ls.x()=clip_min_x;
if (ls.x()>clip_max_x) ls.x()=clip_max_x;
if (ls.y()<clip_min_y) ls.y()=clip_min_y;
if (ls.y()>clip_max_y) ls.y()=clip_max_y;
if (ls.z()<clip_min_z) ls.z()=clip_min_z;
if (ls.z()>clip_max_z) ls.z()=clip_max_z;
// compute the xyz range.
if (ls.x()<min_x) min_x=ls.x();
if (ls.x()>max_x) max_x=ls.x();
if (ls.y()<min_y) min_y=ls.y();
if (ls.y()>max_y) max_y=ls.y();
if (ls.z()<min_z) { min_z=ls.z(); /* OSG_NOTICE<<" - ";*/ }
if (ls.z()>max_z) { max_z=ls.z(); /* OSG_NOTICE<<" + ";*/ }
// OSG_NOTICE<<" bb.z() in ls = "<<ls.z()<<std::endl;
}
bool computeRatios;
unsigned int numRenderLeaf;
osg::Matrixd light_p;
osg::Vec3d eye_ls;
double n;
osg::Matrixd light_mvp;
osg::RefMatrix* previous_modelview;
double clip_min_x, clip_max_x;
double clip_min_y, clip_max_y;
double clip_min_z, clip_max_z;
double clip_min_x_ratio, clip_max_x_ratio;
double clip_min_z_ratio, clip_max_z_ratio;
double min_x_ratio, max_x_ratio;
double min_z_ratio, max_z_ratio;
double min_x, max_x;
double min_y, max_y;
double min_z, max_z;
};
bool MWShadowTechnique::cropShadowCameraToMainFrustum(Frustum& frustum, osg::Camera* camera, double viewNear, double viewFar, std::vector<osg::Plane>& planeList)
{
osg::Matrixd light_p = camera->getProjectionMatrix();
osg::Matrixd light_v = camera->getViewMatrix();
osg::Matrixd light_vp = light_v * light_p;
osg::Matrixd oldLightP = light_p;
ConvexHull convexHull;
convexHull.setToFrustum(frustum);
osg::Vec3d nearPoint = frustum.eye + frustum.frustumCenterLine * viewNear;
osg::Vec3d farPoint = frustum.eye + frustum.frustumCenterLine * viewFar;
double nearDist = -frustum.frustumCenterLine * nearPoint;
double farDist = frustum.frustumCenterLine * farPoint;
convexHull.clip(osg::Plane(frustum.frustumCenterLine, nearDist));
convexHull.clip(osg::Plane(-frustum.frustumCenterLine, farDist));
convexHull.transform(light_vp);
double xMin = -1.0, xMax = 1.0;
double yMin = -1.0, yMax = 1.0;
double zMin = -1.0, zMax = 1.0;
if (convexHull.valid())
{
xMin = osg::maximum(-1.0, convexHull.min(0));
xMax = osg::minimum(1.0, convexHull.max(0));
yMin = osg::maximum(-1.0, convexHull.min(1));
yMax = osg::minimum(1.0, convexHull.max(1));
zMin = osg::maximum(-1.0, convexHull.min(2));
zMax = osg::minimum(1.0, convexHull.max(2));
}
else
return false;
if (xMin != -1.0 || yMin != -1.0 || zMin != -1.0 ||
xMax != 1.0 || yMax != 1.0 || zMax != 1.0)
{
osg::Matrix m;
m.makeTranslate(osg::Vec3d(-0.5*(xMax + xMin),
-0.5*(yMax + yMin),
-0.5*(zMax + zMin)));
m.postMultScale(osg::Vec3d(2.0 / (xMax - xMin),
2.0 / (yMax - yMin),
2.0 / (zMax - zMin)));
light_p.postMult(m);
camera->setProjectionMatrix(light_p);
convexHull.transform(osg::Matrixd::inverse(oldLightP));
xMin = convexHull.min(0);
xMax = convexHull.max(0);
yMin = convexHull.min(1);
yMax = convexHull.max(1);
zMin = convexHull.min(2);
planeList.emplace_back(0.0, -1.0, 0.0, yMax);
planeList.emplace_back(0.0, 1.0, 0.0, -yMin);
planeList.emplace_back(-1.0, 0.0, 0.0, xMax);
planeList.emplace_back(1.0, 0.0, 0.0, -xMin);
// In view space, the light is at the most positive value, and we want to cull stuff beyond the minimum value.
planeList.emplace_back(0.0, 0.0, 1.0, -zMin);
// Don't add a zMax culling plane - we still want those objects, but don't care about their depth buffer value.
}
return true;
}
bool MWShadowTechnique::adjustPerspectiveShadowMapCameraSettings(osgUtil::RenderStage* renderStage, Frustum& frustum, LightData& /*positionedLight*/, osg::Camera* camera, double viewNear, double viewFar)
{
const ShadowSettings* settings = getShadowedScene()->getShadowSettings();
//frustum.projectionMatrix;
//frustum.modelViewMatrix;
osg::Matrixd light_p = camera->getProjectionMatrix();
osg::Matrixd light_v = camera->getViewMatrix();
osg::Matrixd light_vp = light_v * light_p;
osg::Vec3d lightdir(0.0,0.0,-1.0);
// check whether this light space projection is perspective or orthographic.
bool orthographicLightSpaceProjection = light_p(0,3)==0.0 && light_p(1,3)==0.0 && light_p(2,3)==0.0;
if (!orthographicLightSpaceProjection)
{
OSG_INFO<<"perspective light space projection not yet supported."<<std::endl;
return false;
}
//OSG_NOTICE<<"light_v="<<light_v<<std::endl;
//OSG_NOTICE<<"light_p="<<light_p<<std::endl;
ConvexHull convexHull;
convexHull.setToFrustum(frustum);
osg::Vec3d nearPoint = frustum.eye + frustum.frustumCenterLine * viewNear;
osg::Vec3d farPoint = frustum.eye + frustum.frustumCenterLine * viewFar;
double nearDist = -frustum.frustumCenterLine * nearPoint;
double farDist = frustum.frustumCenterLine * farPoint;
convexHull.clip(osg::Plane(frustum.frustumCenterLine, nearDist));
convexHull.clip(osg::Plane(-frustum.frustumCenterLine, farDist));
#if 0
OSG_NOTICE<<"ws ConvexHull xMin="<<convexHull.min(0)<<", xMax="<<convexHull.max(0)<<std::endl;
OSG_NOTICE<<"ws ConvexHull yMin="<<convexHull.min(1)<<", yMax="<<convexHull.max(1)<<std::endl;
OSG_NOTICE<<"ws ConvexHull zMin="<<convexHull.min(2)<<", zMax="<<convexHull.max(2)<<std::endl;
convexHull.output(osg::notify(osg::NOTICE));
#endif
convexHull.transform(light_vp);
ConvexHull convexHullUnextended = convexHull;
convexHull.extendTowardsNegativeZ();
#if 0
convexHull.output(osg::notify(osg::NOTICE));
OSG_NOTICE<<"ls ConvexHull xMin="<<convexHull.min(0)<<", xMax="<<convexHull.max(0)<<std::endl;
OSG_NOTICE<<"ls ConvexHull yMin="<<convexHull.min(1)<<", yMax="<<convexHull.max(1)<<std::endl;
OSG_NOTICE<<"ls ConvexHull zMin="<<convexHull.min(2)<<", zMax="<<convexHull.max(2)<<std::endl;
#endif
#if 0
// only applicable when the light space contains the whole model contained in the view frustum.
{
convexHull.clip(osg::Plane(0.0,0.0,1,1.0)); // clip by near plane of light space.
convexHull.clip(osg::Plane(0.0,0.0,-1,1.0)); // clip by far plane of light space.
}
#endif
#if 1
if (renderStage)
{
#if 1
osg::ElapsedTime timer;
#endif
RenderLeafTraverser<RenderLeafBounds> rli;
rli.set(light_p);
rli.traverse(renderStage);
if (rli.numRenderLeaf==0)
{
return false;
}
#if 0
OSG_NOTICE<<"New Time for RenderLeafTraverser "<<timer.elapsedTime_m()<<"ms, number of render leaves "<<rli.numRenderLeaf<<std::endl;
OSG_NOTICE<<" scene bounds min_x="<<rli.min_x<<", max_x="<<rli.max_x<<std::endl;
OSG_NOTICE<<" scene bounds min_y="<<rli.min_y<<", max_y="<<rli.max_y<<std::endl;
OSG_NOTICE<<" scene bounds min_z="<<rli.min_z<<", max_z="<<rli.max_z<<std::endl;
#endif
#if 0
double widest_x = osg::maximum(fabs(rli.min_x), fabs(rli.max_x));
double widest_y = osg::maximum(fabs(rli.min_y), fabs(rli.max_y));
double widest_z = osg::maximum(fabs(rli.min_z), fabs(rli.max_z));
#endif
#if 1
#if 1
convexHull.clip(osg::Plane(1.0,0.0,0.0,-rli.min_x));
convexHull.clip(osg::Plane(-1.0,0.0,0.0,rli.max_x));
convexHullUnextended.clip(osg::Plane(1.0, 0.0, 0.0, -rli.min_x));
convexHullUnextended.clip(osg::Plane(-1.0, 0.0, 0.0, rli.max_x));
#else
convexHull.clip(osg::Plane(1.0,0.0,0.0,widest_x));
convexHull.clip(osg::Plane(-1.0,0.0,0.0,widest_x));
#endif
#if 1
convexHull.clip(osg::Plane(0.0,1.0,0.0,-rli.min_y));
convexHull.clip(osg::Plane(0.0,-1.0,0.0,rli.max_y));
convexHullUnextended.clip(osg::Plane(0.0, 1.0, 0.0, -rli.min_y));
convexHullUnextended.clip(osg::Plane(0.0, -1.0, 0.0, rli.max_y));
#endif
#endif
#if 1
convexHull.clip(osg::Plane(0.0,0.0,1.0,-rli.min_z));
convexHull.clip(osg::Plane(0.0,0.0,-1.0,rli.max_z));
convexHullUnextended.clip(osg::Plane(0.0, 0.0, 1.0, -rli.min_z));
convexHullUnextended.clip(osg::Plane(0.0, 0.0, -1.0, rli.max_z));
#elif 0
convexHull.clip(osg::Plane(0.0,0.0,1.0,1.0));
convexHull.clip(osg::Plane(0.0,0.0,-1.0,1.0));
#endif
#if 0
OSG_NOTICE<<"widest_x = "<<widest_x<<std::endl;
OSG_NOTICE<<"widest_y = "<<widest_y<<std::endl;
OSG_NOTICE<<"widest_z = "<<widest_z<<std::endl;
#endif
}
#endif
#if 0
convexHull.output(osg::notify(osg::NOTICE));
OSG_NOTICE<<"after clipped ls ConvexHull xMin="<<convexHull.min(0)<<", xMax="<<convexHull.max(0)<<std::endl;
OSG_NOTICE<<"after clipped ls ConvexHull yMin="<<convexHull.min(1)<<", yMax="<<convexHull.max(1)<<std::endl;
OSG_NOTICE<<"after clipped ls ConvexHull zMin="<<convexHull.min(2)<<", zMax="<<convexHull.max(2)<<std::endl;
#endif
double xMin=-1.0, xMax=1.0;
double yMin=-1.0, yMax=1.0;
double zMin=-1.0, zMax=1.0;
if (convexHull.valid())
{
double widest_x = osg::maximum(fabs(convexHull.min(0)), fabs(convexHull.max(0)));
xMin = osg::maximum(-1.0,-widest_x);
xMax = osg::minimum(1.0,widest_x);
yMin = osg::maximum(-1.0,convexHull.min(1));
yMax = osg::minimum(1.0,convexHull.max(1));
}
else
{
// clipping of convex hull has invalidated it, so reset it so later checks on it provide valid results.
convexHull.setToFrustum(frustum);
convexHull.transform(light_vp);
}
#if 0
OSG_NOTICE<<"xMin = "<<xMin<<", \txMax = "<<xMax<<std::endl;
OSG_NOTICE<<"yMin = "<<yMin<<", \tyMax = "<<yMax<<std::endl;
OSG_NOTICE<<"zMin = "<<zMin<<", \tzMax = "<<zMax<<std::endl;
#endif
#if 1
// we always want the lightspace to include the computed near plane.
zMin = -1.0;
if (xMin!=-1.0 || yMin!=-1.0 || zMin!=-1.0 ||
xMax!=1.0 || yMax!=1.0 || zMax!=1.0)
{
osg::Matrix m;
m.makeTranslate(osg::Vec3d(-0.5*(xMax+xMin),
-0.5*(yMax+yMin),
-0.5*(zMax+zMin)));
m.postMultScale(osg::Vec3d(2.0/(xMax-xMin),
2.0/(yMax-yMin),
2.0/(zMax-zMin)));
convexHull.transform(m);
convexHullUnextended.transform(m);
light_p.postMult(m);
light_vp = light_v * light_p;
#if 0
OSG_NOTICE<<"Adjusting projection matrix "<<m<<std::endl;
convexHull.output(osg::notify(osg::NOTICE));
#endif
camera->setProjectionMatrix(light_p);
}
#endif
osg::Vec3d eye_v = frustum.eye * light_v;
//osg::Vec3d centerNearPlane_v = frustum.centerNearPlane * light_v;
osg::Vec3d center_v = frustum.center * light_v;
osg::Vec3d viewdir_v = center_v-eye_v; viewdir_v.normalize();
double dotProduct_v = lightdir * viewdir_v;
double gamma_v = acos(dotProduct_v);
if (gamma_v<osg::DegreesToRadians(settings->getPerspectiveShadowMapCutOffAngle()) || gamma_v>osg::DegreesToRadians(180-settings->getPerspectiveShadowMapCutOffAngle()))
{
// OSG_NOTICE<<"Light and view vectors near parallel - use standard shadow map."<<std::endl;
return true;
}
//OSG_NOTICE<<"gamma="<<osg::RadiansToDegrees(gamma_v)<<std::endl;
//OSG_NOTICE<<"eye_v="<<eye_v<<std::endl;
//OSG_NOTICE<<"viewdir_v="<<viewdir_v<<std::endl;
osg::Vec3d eye_ls = frustum.eye * light_vp;
#if 0
if (eye_ls.y()>-1.0)
{
OSG_NOTICE<<"Eye point within light space - use standard shadow map."<<std::endl;
return true;
}
#endif
//osg::Vec3d centerNearPlane_ls = frustum.centerNearPlane * light_vp;
//osg::Vec3d centerFarPlane_ls = frustum.centerFarPlane * light_vp;
osg::Vec3d center_ls = frustum.center * light_vp;
osg::Vec3d viewdir_ls = center_ls-eye_ls; viewdir_ls.normalize();
osg::Vec3d side = lightdir ^ viewdir_ls; side.normalize();
osg::Vec3d up = side ^ lightdir;
double d = 2.0;
double alpha = osg::DegreesToRadians(30.0);
double n = tan(alpha)*tan(osg::PI_2-gamma_v)*tan(osg::PI_2-gamma_v);
//double n = tan(alpha)*tan(osg::PI_2-gamma_v);
//OSG_NOTICE<<"n = "<<n<<", eye_ls.y()="<<eye_ls.y()<<", eye_v="<<eye_v<<", eye="<<frustum.eye<<std::endl;
double min_n = osg::maximum(-1.0-eye_ls.y(), settings->getMinimumShadowMapNearFarRatio());
if (n<min_n)
{
//OSG_NOTICE<<"Clamping n to eye point"<<std::endl;
n=min_n;
}
//n = min_n;
//n = 0.01;
//n = z_n;
double f = n+d;
double a = (f+n)/(f-n);
double b = -2.0*f*n/(f-n);
osg::Vec3d virtual_eye(0.0,-1.0-n, eye_ls.z());
osg::Matrixd lightView;
lightView.makeLookAt(virtual_eye, virtual_eye+lightdir, up);
#if 0
OSG_NOTICE<<"n = "<<n<<", f="<<f<<std::endl;
OSG_NOTICE<<"eye_ls = "<<eye_ls<<", virtual_eye="<<virtual_eye<<std::endl;
OSG_NOTICE<<"frustum.eyes="<<frustum.eye<<std::endl;
#endif
double min_x_ratio = 0.0;
double max_x_ratio = 0.0;
double min_z_ratio = dbl_max;
double max_z_ratio = -dbl_max;
min_x_ratio = convexHull.valid() ? convexHull.minRatio(virtual_eye,0) : -dbl_max;
max_x_ratio = convexHull.valid() ? convexHull.maxRatio(virtual_eye,0) : dbl_max;
//min_z_ratio = convexHull.minRatio(virtual_eye,2);
//max_z_ratio = convexHull.maxRatio(virtual_eye,2);
if (convexHullUnextended.valid())
{
min_z_ratio = convexHullUnextended.minRatio(virtual_eye, 2);
max_z_ratio = convexHullUnextended.maxRatio(virtual_eye, 2);
}
#if 0
OSG_NOTICE<<"convexHull min_x_ratio = "<<min_x_ratio<<std::endl;
OSG_NOTICE<<"convexHull max_x_ratio = "<<max_x_ratio<<std::endl;
OSG_NOTICE<<"convexHull min_z_ratio = "<<min_z_ratio<<std::endl;
OSG_NOTICE<<"convexHull max_z_ratio = "<<max_z_ratio<<std::endl;
#endif
#if 1
if (renderStage)
{
#if 1
osg::ElapsedTime timer;
#endif
RenderLeafTraverser<RenderLeafBounds> rli;
rli.set(light_p, virtual_eye, n);
rli.traverse(renderStage);
if (rli.numRenderLeaf==0)
{
return false;
}
#if 0
OSG_NOTICE<<"Time for RenderLeafTraverser "<<timer.elapsedTime_m()<<"ms, number of render leaves "<<rli.numRenderLeaf<<std::endl;
OSG_NOTICE<<"scene bounds min_x="<<rli.min_x<<", max_x="<<rli.max_x<<std::endl;
OSG_NOTICE<<"scene bounds min_y="<<rli.min_y<<", max_y="<<rli.max_y<<std::endl;
OSG_NOTICE<<"scene bounds min_z="<<rli.min_z<<", max_z="<<rli.max_z<<std::endl;
OSG_NOTICE<<"min_x_ratio="<<rli.min_x_ratio<<", max_x_ratio="<<rli.max_x_ratio<<std::endl;
OSG_NOTICE<<"min_z_ratio="<<rli.min_z_ratio<<", max_z_ratio="<<rli.max_z_ratio<<std::endl;
#endif
if (rli.min_x_ratio>min_x_ratio) min_x_ratio = rli.min_x_ratio;
if (rli.max_x_ratio<max_x_ratio) max_x_ratio = rli.max_x_ratio;
if (min_z_ratio == dbl_max || rli.min_z_ratio > min_z_ratio)
min_z_ratio = rli.min_z_ratio;
if (max_z_ratio == -dbl_max || rli.max_z_ratio < max_z_ratio)
max_z_ratio = rli.max_z_ratio;
}
#endif
double best_x_ratio = osg::maximum(fabs(min_x_ratio),fabs(max_x_ratio));
double best_z_ratio = osg::maximum(fabs(min_z_ratio),fabs(max_z_ratio));
//best_z_ratio = osg::maximum(1.0, best_z_ratio);
#if 0
OSG_NOTICE<<"min_x_ratio = "<<min_x_ratio<<std::endl;
OSG_NOTICE<<"max_x_ratio = "<<max_x_ratio<<std::endl;
OSG_NOTICE<<"best_x_ratio = "<<best_x_ratio<<std::endl;
OSG_NOTICE<<"min_z_ratio = "<<min_z_ratio<<std::endl;
OSG_NOTICE<<"max_z_ratio = "<<max_z_ratio<<std::endl;
OSG_NOTICE<<"best_z_ratio = "<<best_z_ratio<<std::endl;
#endif
//best_z_ratio *= 10.0;
osg::Matrixd lightPerspective( 1.0/best_x_ratio, 0.0, 0.0, 0.0,
0.0, a, 0.0, 1.0,
0.0, 0.0, 1.0/best_z_ratio, 0.0,
0.0, b, 0.0, 0.0 );
osg::Matrixd light_persp = light_p * lightView * lightPerspective;
#if 0
OSG_NOTICE<<"light_p = "<<light_p<<std::endl;
OSG_NOTICE<<"lightView = "<<lightView<<std::endl;
OSG_NOTICE<<"lightPerspective = "<<lightPerspective<<std::endl;
OSG_NOTICE<<"light_persp result = "<<light_persp<<std::endl;
#endif
camera->setProjectionMatrix(light_persp);
return true;
}
void MWShadowTechnique::cullShadowReceivingScene(osgUtil::CullVisitor* cv) const
{
OSG_INFO<<"cullShadowReceivingScene()"<<std::endl;
// record the traversal mask on entry so we can reapply it later.
unsigned int traversalMask = cv->getTraversalMask();
cv->setTraversalMask( traversalMask & _shadowedScene->getShadowSettings()->getReceivesShadowTraversalMask() );
_shadowedScene->osg::Group::traverse(*cv);
cv->setTraversalMask( traversalMask );
return;
}
void MWShadowTechnique::cullShadowCastingScene(osgUtil::CullVisitor* cv, osg::Camera* camera) const
{
OSG_INFO<<"cullShadowCastingScene()"<<std::endl;
// record the traversal mask on entry so we can reapply it later.
unsigned int traversalMask = cv->getTraversalMask();
cv->setTraversalMask( traversalMask & _shadowedScene->getShadowSettings()->getCastsShadowTraversalMask() );
if (camera) camera->accept(*cv);
cv->setTraversalMask( traversalMask );
return;
}
osg::StateSet* MWShadowTechnique::prepareStateSetForRenderingShadow(ViewDependentData& vdd, unsigned int traversalNumber) const
{
OSG_INFO<<" prepareStateSetForRenderingShadow() "<<vdd.getStateSet(traversalNumber)<<std::endl;
osg::ref_ptr<osg::StateSet> stateset = vdd.getStateSet(traversalNumber);
stateset->clear();
stateset->setTextureAttributeAndModes(0, _fallbackBaseTexture.get(), osg::StateAttribute::ON);
for(const auto& uniform : _uniforms[traversalNumber % 2])
{
OSG_INFO<<"addUniform("<<uniform->getName()<<")"<<std::endl;
stateset->addUniform(uniform);
}
if (_program.valid())
{
stateset->setAttribute(_program.get());
}
LightDataList& pll = vdd.getLightDataList();
for(LightDataList::iterator itr = pll.begin();
itr != pll.end();
++itr)
{
// 3. create per light/per shadow map division of lightspace/frustum
// create a list of light/shadow map data structures
LightData& pl = (**itr);
// if no texture units have been activated for this light then no shadow state required.
if (pl.textureUnits.empty()) continue;
for(LightData::ActiveTextureUnits::iterator atu_itr = pl.textureUnits.begin();
atu_itr != pl.textureUnits.end();
++atu_itr)
{
OSG_INFO<<" Need to assign state for "<<*atu_itr<<std::endl;
}
}
const ShadowSettings* settings = getShadowedScene()->getShadowSettings();
unsigned int shadowMapModeValue = settings->getUseOverrideForShadowMapTexture() ?
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE :
osg::StateAttribute::ON;
ShadowDataList& sdl = vdd.getShadowDataList();
for(ShadowDataList::iterator itr = sdl.begin();
itr != sdl.end();
++itr)
{
// 3. create per light/per shadow map division of lightspace/frustum
// create a list of light/shadow map data structures
ShadowData& sd = (**itr);
OSG_INFO<<" ShadowData for "<<sd._textureUnit<<std::endl;
stateset->setTextureAttribute(sd._textureUnit, sd._texture.get(), shadowMapModeValue);
}
return stateset;
}
void MWShadowTechnique::resizeGLObjectBuffers(unsigned int /*maxSize*/)
{
// the way that ViewDependentData is mapped shouldn't
}
void MWShadowTechnique::releaseGLObjects(osg::State* state) const
{
std::lock_guard<std::mutex> lock(_viewDependentDataMapMutex);
for(ViewDependentDataMap::const_iterator itr = _viewDependentDataMap.begin();
itr != _viewDependentDataMap.end();
++itr)
{
ViewDependentData* vdd = itr->second.get();
if (vdd)
{
vdd->releaseGLObjects(state);
}
}
if (_debugHud)
_debugHud->releaseGLObjects(state);
}
class DoubleBufferCallback : public osg::Callback
{
public:
DoubleBufferCallback(osg::NodeList &children) : mChildren(children) {}
bool run(osg::Object* node, osg::Object* visitor) override
{
// We can't use a static cast as NodeVisitor virtually inherits from Object
osg::ref_ptr<osg::NodeVisitor> nodeVisitor = visitor->asNodeVisitor();
unsigned int traversalNumber = nodeVisitor->getTraversalNumber();
mChildren[traversalNumber % 2]->accept(*nodeVisitor);
return true;
}
protected:
osg::NodeList mChildren;
};
SceneUtil::MWShadowTechnique::DebugHUD::DebugHUD(int numberOfShadowMapsPerLight) : mDebugProgram(new osg::Program)
{
osg::ref_ptr<osg::Shader> vertexShader = new osg::Shader(osg::Shader::VERTEX, debugVertexShaderSource);
mDebugProgram->addShader(vertexShader);
osg::ref_ptr<osg::Shader> fragmentShader = new osg::Shader(osg::Shader::FRAGMENT, debugFragmentShaderSource);
mDebugProgram->addShader(fragmentShader);
osg::ref_ptr<osg::Program> frustumProgram = new osg::Program;
vertexShader = new osg::Shader(osg::Shader::VERTEX, debugFrustumVertexShaderSource);
frustumProgram->addShader(vertexShader);
fragmentShader = new osg::Shader(osg::Shader::FRAGMENT, debugFrustumFragmentShaderSource);
frustumProgram->addShader(fragmentShader);
for (auto& frustumGeometry : mFrustumGeometries)
{
frustumGeometry = new osg::Geometry();
frustumGeometry->setCullingActive(false);
frustumGeometry->getOrCreateStateSet()->setAttributeAndModes(frustumProgram, osg::StateAttribute::ON);
}
osg::ref_ptr<osg::DrawElementsUShort> frustumDrawElements = new osg::DrawElementsUShort(osg::PrimitiveSet::LINE_STRIP);
for (auto & geom : mFrustumGeometries)
geom->addPrimitiveSet(frustumDrawElements);
frustumDrawElements->push_back(0);
frustumDrawElements->push_back(1);
frustumDrawElements->push_back(2);
frustumDrawElements->push_back(3);
frustumDrawElements->push_back(0);
frustumDrawElements->push_back(4);
frustumDrawElements->push_back(5);
frustumDrawElements->push_back(6);
frustumDrawElements->push_back(7);
frustumDrawElements->push_back(4);
frustumDrawElements = new osg::DrawElementsUShort(osg::PrimitiveSet::LINES);
for (auto & geom : mFrustumGeometries)
geom->addPrimitiveSet(frustumDrawElements);
frustumDrawElements->push_back(1);
frustumDrawElements->push_back(5);
frustumDrawElements->push_back(2);
frustumDrawElements->push_back(6);
frustumDrawElements->push_back(3);
frustumDrawElements->push_back(7);
for (int i = 0; i < numberOfShadowMapsPerLight; ++i)
addAnotherShadowMap();
}
void SceneUtil::MWShadowTechnique::DebugHUD::draw(osg::ref_ptr<osg::Texture2D> texture, unsigned int shadowMapNumber, const osg::Matrixd &matrix, osgUtil::CullVisitor& cv)
{
// It might be possible to change shadow settings at runtime
if (shadowMapNumber > mDebugCameras.size())
addAnotherShadowMap();
osg::ref_ptr<osg::StateSet> stateSet = new osg::StateSet();
stateSet->setTextureAttribute(sDebugTextureUnit, texture, osg::StateAttribute::ON);
auto frustumUniform = mFrustumUniforms[cv.getTraversalNumber() % 2][shadowMapNumber];
frustumUniform->set(matrix);
stateSet->addUniform(frustumUniform);
// Some of these calls may be superfluous.
unsigned int traversalMask = cv.getTraversalMask();
cv.setTraversalMask(mDebugGeometry[shadowMapNumber]->getNodeMask());
cv.pushStateSet(stateSet);
mDebugCameras[shadowMapNumber]->accept(cv);
cv.popStateSet();
cv.setTraversalMask(traversalMask);
}
void SceneUtil::MWShadowTechnique::DebugHUD::releaseGLObjects(osg::State* state) const
{
for (auto const& camera : mDebugCameras)
camera->releaseGLObjects(state);
mDebugProgram->releaseGLObjects(state);
for (auto const& node : mDebugGeometry)
node->releaseGLObjects(state);
for (auto const& node : mFrustumTransforms)
node->releaseGLObjects(state);
for (auto const& node : mFrustumGeometries)
node->releaseGLObjects(state);
}
void SceneUtil::MWShadowTechnique::DebugHUD::setFrustumVertices(osg::ref_ptr<osg::Vec3Array> vertices, unsigned int traversalNumber)
{
mFrustumGeometries[traversalNumber % 2]->setVertexArray(vertices);
}
void SceneUtil::MWShadowTechnique::DebugHUD::addAnotherShadowMap()
{
unsigned int shadowMapNumber = mDebugCameras.size();
mDebugCameras.push_back(new osg::Camera);
mDebugCameras[shadowMapNumber]->setViewport(200 * shadowMapNumber, 0, 200, 200);
mDebugCameras[shadowMapNumber]->setRenderOrder(osg::Camera::POST_RENDER);
mDebugCameras[shadowMapNumber]->setClearColor(osg::Vec4(1.0, 1.0, 0.0, 1.0));
mDebugCameras[shadowMapNumber]->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
mDebugGeometry.emplace_back(osg::createTexturedQuadGeometry(osg::Vec3(-1, -1, 0), osg::Vec3(2, 0, 0), osg::Vec3(0, 2, 0)));
mDebugGeometry[shadowMapNumber]->setCullingActive(false);
mDebugCameras[shadowMapNumber]->addChild(mDebugGeometry[shadowMapNumber]);
osg::ref_ptr<osg::StateSet> stateSet = mDebugGeometry[shadowMapNumber]->getOrCreateStateSet();
stateSet->setAttributeAndModes(mDebugProgram, osg::StateAttribute::ON);
osg::ref_ptr<osg::Uniform> textureUniform = new osg::Uniform("texture", sDebugTextureUnit);
//textureUniform->setType(osg::Uniform::SAMPLER_2D);
stateSet->addUniform(textureUniform.get());
mFrustumTransforms.push_back(new osg::Group);
osg::NodeList frustumGeometryNodeList(mFrustumGeometries.cbegin(), mFrustumGeometries.cend());
mFrustumTransforms[shadowMapNumber]->setCullCallback(new DoubleBufferCallback(frustumGeometryNodeList));
mFrustumTransforms[shadowMapNumber]->setCullingActive(false);
mDebugCameras[shadowMapNumber]->addChild(mFrustumTransforms[shadowMapNumber]);
for(auto& uniformVector : mFrustumUniforms)
uniformVector.push_back(new osg::Uniform(osg::Uniform::FLOAT_MAT4, "transform"));
}
osg::ref_ptr<osg::StateSet> SceneUtil::MWShadowTechnique::getOrCreateShadowsBinStateSet()
{
if (_shadowsBinStateSet == nullptr)
{
if (_shadowsBin == nullptr)
{
_shadowsBin = new ShadowsBin(_castingPrograms);
osgUtil::RenderBin::addRenderBinPrototype(_shadowsBinName, _shadowsBin);
}
_shadowsBinStateSet = new osg::StateSet;
_shadowsBinStateSet->setRenderBinDetails(osg::StateSet::OPAQUE_BIN, _shadowsBinName, osg::StateSet::OVERRIDE_PROTECTED_RENDERBIN_DETAILS);
}
return _shadowsBinStateSet;
}
// clang-format on
| 128,813
|
C++
|
.cpp
| 2,759
| 37.679594
| 203
| 0.585518
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,731
|
glextensions.cpp
|
OpenMW_openmw/components/sceneutil/glextensions.cpp
|
#include "glextensions.hpp"
#include <osg/GraphicsContext>
namespace SceneUtil
{
namespace
{
std::set<osg::observer_ptr<osg::GLExtensions>> sGLExtensions;
class GLExtensionsObserver : public osg::Observer
{
public:
static GLExtensionsObserver sInstance;
~GLExtensionsObserver() override
{
for (auto& ptr : sGLExtensions)
{
osg::ref_ptr<osg::GLExtensions> ref;
if (ptr.lock(ref))
ref->removeObserver(this);
}
}
void objectDeleted(void* referenced) override
{
sGLExtensions.erase(static_cast<osg::GLExtensions*>(referenced));
}
};
// construct after sGLExtensions so this gets destroyed first.
GLExtensionsObserver GLExtensionsObserver::sInstance{};
}
bool glExtensionsReady()
{
return !sGLExtensions.empty();
}
osg::GLExtensions& getGLExtensions()
{
if (sGLExtensions.empty())
throw std::runtime_error(
"GetGLExtensionsOperation was not used when the current context was created or there is no current "
"context");
return **sGLExtensions.begin();
}
GetGLExtensionsOperation::GetGLExtensionsOperation()
: GraphicsOperation("GetGLExtensionsOperation", false)
{
}
void GetGLExtensionsOperation::operator()(osg::GraphicsContext* graphicsContext)
{
auto [itr, _] = sGLExtensions.emplace(graphicsContext->getState()->get<osg::GLExtensions>());
(*itr)->addObserver(&GLExtensionsObserver::sInstance);
}
}
| 1,727
|
C++
|
.cpp
| 50
| 24.94
| 116
| 0.606479
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,732
|
osgacontroller.cpp
|
OpenMW_openmw/components/sceneutil/osgacontroller.cpp
|
#include <components/sceneutil/osgacontroller.hpp>
#include <osg/MatrixTransform>
#include <osg/Node>
#include <osg/NodeVisitor>
#include <osg/ref_ptr>
#include <osgAnimation/Animation>
#include <osgAnimation/Channel>
#include <osgAnimation/Sampler>
#include <osgAnimation/UpdateMatrixTransform>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/resource/animation.hpp>
#include <components/sceneutil/controller.hpp>
#include <components/sceneutil/keyframe.hpp>
namespace SceneUtil
{
LinkVisitor::LinkVisitor()
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
{
mAnimation = nullptr;
}
void LinkVisitor::link(osgAnimation::UpdateMatrixTransform* umt)
{
const osgAnimation::ChannelList& channels = mAnimation->getChannels();
for (const auto& channel : channels)
{
const std::string& channelName = channel->getName();
const std::string& channelTargetName = channel->getTargetName();
if (channelTargetName != umt->getName())
continue;
// check if we can link a StackedTransformElement to the current Channel
for (const auto& stackedTransform : umt->getStackedTransforms())
{
osgAnimation::StackedTransformElement* element = stackedTransform.get();
if (element && !element->getName().empty() && channelName == element->getName())
{
osgAnimation::Target* target = element->getOrCreateTarget();
if (target)
{
channel->setTarget(target);
}
}
}
}
}
void LinkVisitor::setAnimation(Resource::Animation* animation)
{
mAnimation = animation;
}
void LinkVisitor::apply(osg::Node& node)
{
osg::Callback* cb = node.getUpdateCallback();
while (cb)
{
osgAnimation::UpdateMatrixTransform* umt = dynamic_cast<osgAnimation::UpdateMatrixTransform*>(cb);
if (umt)
if (Misc::StringUtils::lowerCase(node.getName()) != "bip01")
link(umt);
cb = cb->getNestedCallback();
}
if (node.getNumChildrenRequiringUpdateTraversal())
traverse(node);
}
OsgAnimationController::OsgAnimationController(const OsgAnimationController& copy, const osg::CopyOp& copyop)
: osg::Object(copy, copyop)
, SceneUtil::KeyframeController(copy)
, SceneUtil::NodeCallback<OsgAnimationController>(copy, copyop)
, mEmulatedAnimations(copy.mEmulatedAnimations)
{
mLinker = nullptr;
for (const auto& mergedAnimationTrack : copy.mMergedAnimationTracks)
{
Resource::Animation* copiedAnimationTrack
= static_cast<Resource::Animation*>(mergedAnimationTrack.get()->clone(copyop));
mMergedAnimationTracks.emplace_back(copiedAnimationTrack);
}
}
osg::Matrixf OsgAnimationController::getTransformForNode(float time, const std::string_view name) const
{
std::string animationName;
float newTime = time;
// Find the correct animation based on time
for (const EmulatedAnimation& emulatedAnimation : mEmulatedAnimations)
{
if (time >= emulatedAnimation.mStartTime && time <= emulatedAnimation.mStopTime)
{
newTime = time - emulatedAnimation.mStartTime;
animationName = emulatedAnimation.mName;
break;
}
}
// Find the bone's transform track in animation
for (const auto& mergedAnimationTrack : mMergedAnimationTracks)
{
if (mergedAnimationTrack->getName() != animationName)
continue;
const osgAnimation::ChannelList& channels = mergedAnimationTrack->getChannels();
for (const auto& channel : channels)
{
if (!Misc::StringUtils::ciEqual(name, channel->getTargetName()) || channel->getName() != "transform")
continue;
if (osgAnimation::MatrixLinearSampler* templateSampler
= dynamic_cast<osgAnimation::MatrixLinearSampler*>(channel->getSampler()))
{
osg::Matrixf matrix;
templateSampler->getValueAt(newTime, matrix);
return matrix;
}
}
}
return osg::Matrixf::identity();
}
osg::Vec3f OsgAnimationController::getTranslation(float time) const
{
return getTransformForNode(time, "bip01").getTrans();
}
void OsgAnimationController::update(float time, const std::string& animationName)
{
for (const auto& mergedAnimationTrack : mMergedAnimationTracks)
{
if (mergedAnimationTrack->getName() == animationName)
mergedAnimationTrack->update(time);
}
}
void OsgAnimationController::operator()(osg::Node* node, osg::NodeVisitor* nv)
{
if (hasInput())
{
if (mNeedToLink)
{
for (const auto& mergedAnimationTrack : mMergedAnimationTracks)
{
if (!mLinker.valid())
mLinker = new LinkVisitor();
mLinker->setAnimation(mergedAnimationTrack);
node->accept(*mLinker);
}
mNeedToLink = false;
}
float time = getInputValue(nv);
for (const EmulatedAnimation& emulatedAnimation : mEmulatedAnimations)
{
if (time > emulatedAnimation.mStartTime && time < emulatedAnimation.mStopTime)
{
update(time - emulatedAnimation.mStartTime, emulatedAnimation.mName);
}
}
// Reset the transform of this node to whats in the animation
// we force this here because downstream some code relies on the bone having a non-modified transform
// as this is how the NIF controller behaves. RotationController is a good example of this.
// Without this here, it causes osgAnimation skeletons to spin wildly
static_cast<osg::MatrixTransform*>(node)->setMatrix(getTransformForNode(time, node->getName()));
}
traverse(node, nv);
}
void OsgAnimationController::setEmulatedAnimations(const std::vector<EmulatedAnimation>& emulatedAnimations)
{
mEmulatedAnimations = emulatedAnimations;
}
void OsgAnimationController::addMergedAnimationTrack(osg::ref_ptr<Resource::Animation> animationTrack)
{
mMergedAnimationTracks.emplace_back(animationTrack);
}
}
| 6,871
|
C++
|
.cpp
| 164
| 31.195122
| 117
| 0.61976
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,733
|
extradata.cpp
|
OpenMW_openmw/components/sceneutil/extradata.cpp
|
#include "extradata.hpp"
#include <unordered_set>
#include <osg/Node>
#include <osg/ValueObject>
#include <osgParticle/ParticleSystem>
#include <yaml-cpp/yaml.h>
#include <components/misc/osguservalues.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/resource/scenemanager.hpp>
#include <components/sceneutil/depth.hpp>
#include <components/shader/shadermanager.hpp>
namespace SceneUtil
{
void setupSoftEffect(osg::Node& node, float size, bool falloff, float falloffDepth)
{
static const osg::ref_ptr<SceneUtil::AutoDepth> depth = new SceneUtil::AutoDepth(osg::Depth::LESS, 0, 1, false);
osg::StateSet* stateset = node.getOrCreateStateSet();
stateset->addUniform(new osg::Uniform("particleSize", size));
stateset->addUniform(new osg::Uniform("particleFade", falloff));
stateset->addUniform(new osg::Uniform("softFalloffDepth", falloffDepth));
stateset->setAttributeAndModes(depth, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
node.setUserValue(Misc::OsgUserValues::sXSoftEffect, true);
}
void setupDistortion(osg::Node& node, float distortionStrength)
{
static const osg::ref_ptr<SceneUtil::AutoDepth> depth
= new SceneUtil::AutoDepth(osg::Depth::ALWAYS, 0, 1, false);
osg::StateSet* stateset = node.getOrCreateStateSet();
stateset->setNestRenderBins(false);
stateset->setRenderBinDetails(14, "Distortion", osg::StateSet::OVERRIDE_PROTECTED_RENDERBIN_DETAILS);
stateset->addUniform(new osg::Uniform("distortionStrength", distortionStrength));
stateset->setAttributeAndModes(depth, osg::StateAttribute::ON);
}
void ProcessExtraDataVisitor::apply(osg::Node& node)
{
if (!mSceneMgr->getSoftParticles())
return;
std::string source;
constexpr float defaultFalloffDepth = 300.f; // arbitrary value that simply looks good with common cases
if (node.getUserValue(Misc::OsgUserValues::sExtraData, source) && !source.empty())
{
YAML::Node root = YAML::Load(source);
for (const auto& it : root["shader"])
{
std::string key = it.first.as<std::string>();
if (key == "soft_effect")
{
auto size = it.second["size"].as<float>(45.f);
auto falloff = it.second["falloff"].as<bool>(false);
auto falloffDepth = it.second["falloffDepth"].as<float>(defaultFalloffDepth);
setupSoftEffect(node, size, falloff, falloffDepth);
}
else if (key == "distortion")
{
auto strength = it.second["strength"].as<float>(0.1f);
setupDistortion(node, strength);
}
}
node.setUserValue(Misc::OsgUserValues::sExtraData, std::string{});
}
else if (osgParticle::ParticleSystem* partsys = dynamic_cast<osgParticle::ParticleSystem*>(&node))
{
setupSoftEffect(
node, partsys->getDefaultParticleTemplate().getSizeRange().maximum, false, defaultFalloffDepth);
}
traverse(node);
}
}
| 3,257
|
C++
|
.cpp
| 68
| 38.279412
| 120
| 0.64509
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,734
|
riggeometry.cpp
|
OpenMW_openmw/components/sceneutil/riggeometry.cpp
|
#include "riggeometry.hpp"
#include <unordered_map>
#include <osg/MatrixTransform>
#include <osgUtil/CullVisitor>
#include <components/debug/debuglog.hpp>
#include <components/resource/scenemanager.hpp>
#include "skeleton.hpp"
#include "util.hpp"
namespace SceneUtil
{
RigGeometry::RigGeometry()
{
setNumChildrenRequiringUpdateTraversal(1);
// update done in accept(NodeVisitor&)
}
RigGeometry::RigGeometry(const RigGeometry& copy, const osg::CopyOp& copyop)
: Drawable(copy, copyop)
, mData(copy.mData)
{
setSourceGeometry(copy.mSourceGeometry);
setNumChildrenRequiringUpdateTraversal(1);
}
void RigGeometry::setSourceGeometry(osg::ref_ptr<osg::Geometry> sourceGeometry)
{
for (unsigned int i = 0; i < 2; ++i)
mGeometry[i] = nullptr;
mSourceGeometry = sourceGeometry;
for (unsigned int i = 0; i < 2; ++i)
{
const osg::Geometry& from = *sourceGeometry;
// DO NOT COPY AND PASTE THIS CODE. Cloning osg::Geometry without also cloning its contained Arrays is
// generally unsafe. In this specific case the operation is safe under the following two assumptions:
// - When Arrays are removed or replaced in the cloned geometry, the original Arrays in their place must
// outlive the cloned geometry regardless. (ensured by mSourceGeometry)
// - Arrays that we add or replace in the cloned geometry must be explicitely forbidden from reusing
// BufferObjects of the original geometry. (ensured by vbo below)
mGeometry[i] = new osg::Geometry(from, osg::CopyOp::SHALLOW_COPY);
mGeometry[i]->getOrCreateUserDataContainer()->addUserObject(new Resource::TemplateRef(mSourceGeometry));
osg::Geometry& to = *mGeometry[i];
to.setSupportsDisplayList(false);
to.setUseVertexBufferObjects(true);
to.setCullingActive(false); // make sure to disable culling since that's handled by this class
to.setComputeBoundingBoxCallback(new CopyBoundingBoxCallback());
to.setComputeBoundingSphereCallback(new CopyBoundingSphereCallback());
// vertices and normals are modified every frame, so we need to deep copy them.
// assign a dedicated VBO to make sure that modifications don't interfere with source geometry's VBO.
osg::ref_ptr<osg::VertexBufferObject> vbo(new osg::VertexBufferObject);
vbo->setUsage(GL_DYNAMIC_DRAW_ARB);
osg::ref_ptr<osg::Array> vertexArray
= static_cast<osg::Array*>(from.getVertexArray()->clone(osg::CopyOp::DEEP_COPY_ALL));
if (vertexArray)
{
vertexArray->setVertexBufferObject(vbo);
to.setVertexArray(vertexArray);
}
if (const osg::Array* normals = from.getNormalArray())
{
osg::ref_ptr<osg::Array> normalArray
= static_cast<osg::Array*>(normals->clone(osg::CopyOp::DEEP_COPY_ALL));
if (normalArray)
{
normalArray->setVertexBufferObject(vbo);
to.setNormalArray(normalArray, osg::Array::BIND_PER_VERTEX);
}
}
if (const osg::Vec4Array* tangents = dynamic_cast<const osg::Vec4Array*>(from.getTexCoordArray(7)))
{
mSourceTangents = tangents;
osg::ref_ptr<osg::Array> tangentArray
= static_cast<osg::Array*>(tangents->clone(osg::CopyOp::DEEP_COPY_ALL));
tangentArray->setVertexBufferObject(vbo);
to.setTexCoordArray(7, tangentArray, osg::Array::BIND_PER_VERTEX);
}
else
mSourceTangents = nullptr;
}
}
osg::ref_ptr<osg::Geometry> RigGeometry::getSourceGeometry() const
{
return mSourceGeometry;
}
bool RigGeometry::initFromParentSkeleton(osg::NodeVisitor* nv)
{
const osg::NodePath& path = nv->getNodePath();
for (osg::NodePath::const_reverse_iterator it = path.rbegin() + 1; it != path.rend(); ++it)
{
osg::Node* node = *it;
if (node->asTransform())
continue;
if (Skeleton* skel = dynamic_cast<Skeleton*>(node))
{
mSkeleton = skel;
break;
}
}
if (!mSkeleton)
{
Log(Debug::Error) << "Error: A RigGeometry did not find its parent skeleton";
return false;
}
if (!mData)
{
Log(Debug::Error) << "Error: No influence data set on RigGeometry";
return false;
}
mNodes.clear();
for (const BoneInfo& info : mData->mBones)
{
mNodes.push_back(mSkeleton->getBone(info.mName));
if (!mNodes.back())
Log(Debug::Error) << "Error: RigGeometry did not find bone " << info.mName;
}
return true;
}
void RigGeometry::cull(osg::NodeVisitor* nv)
{
if (!mSkeleton)
{
Log(Debug::Error)
<< "Error: RigGeometry rendering with no skeleton, should have been initialized by UpdateVisitor";
// try to recover anyway, though rendering is likely to be incorrect.
if (!initFromParentSkeleton(nv))
return;
}
unsigned int traversalNumber = nv->getTraversalNumber();
if (mLastFrameNumber == traversalNumber || (mLastFrameNumber != 0 && !mSkeleton->getActive()))
{
osg::Geometry& geom = *getGeometry(mLastFrameNumber);
nv->pushOntoNodePath(&geom);
nv->apply(geom);
nv->popFromNodePath();
return;
}
mLastFrameNumber = traversalNumber;
osg::Geometry& geom = *getGeometry(mLastFrameNumber);
mSkeleton->updateBoneMatrices(traversalNumber);
// skinning
const osg::Vec3Array* positionSrc = static_cast<osg::Vec3Array*>(mSourceGeometry->getVertexArray());
const osg::Vec3Array* normalSrc = static_cast<osg::Vec3Array*>(mSourceGeometry->getNormalArray());
const osg::Vec4Array* tangentSrc = mSourceTangents;
osg::Vec3Array* positionDst = static_cast<osg::Vec3Array*>(geom.getVertexArray());
osg::Vec3Array* normalDst = static_cast<osg::Vec3Array*>(geom.getNormalArray());
osg::Vec4Array* tangentDst = static_cast<osg::Vec4Array*>(geom.getTexCoordArray(7));
for (const auto& [influences, vertices] : mData->mInfluences)
{
osg::Matrixf resultMat(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
for (const auto& [index, weight] : influences)
{
const Bone* bone = mNodes[index];
if (bone == nullptr)
continue;
osg::Matrixf boneMat = mData->mBones[index].mInvBindMatrix * bone->mMatrixInSkeletonSpace;
float* boneMatPtr = boneMat.ptr();
float* resultMatPtr = resultMat.ptr();
for (int i = 0; i < 16; ++i, ++resultMatPtr, ++boneMatPtr)
if (i % 4 != 3)
*resultMatPtr += *boneMatPtr * weight;
}
if (mGeomToSkelMatrix)
resultMat *= (*mGeomToSkelMatrix);
for (unsigned short vertex : vertices)
{
(*positionDst)[vertex] = resultMat.preMult((*positionSrc)[vertex]);
if (normalDst)
(*normalDst)[vertex] = osg::Matrixf::transform3x3((*normalSrc)[vertex], resultMat);
if (tangentDst)
{
const osg::Vec4f& srcTangent = (*tangentSrc)[vertex];
osg::Vec3f transformedTangent = osg::Matrixf::transform3x3(
osg::Vec3f(srcTangent.x(), srcTangent.y(), srcTangent.z()), resultMat);
(*tangentDst)[vertex] = osg::Vec4f(transformedTangent, srcTangent.w());
}
}
}
positionDst->dirty();
if (normalDst)
normalDst->dirty();
if (tangentDst)
tangentDst->dirty();
geom.osg::Drawable::dirtyGLObjects();
nv->pushOntoNodePath(&geom);
nv->apply(geom);
nv->popFromNodePath();
}
void RigGeometry::updateBounds(osg::NodeVisitor* nv)
{
if (!mSkeleton)
{
if (!initFromParentSkeleton(nv))
return;
}
if (!mSkeleton->getActive() && !mBoundsFirstFrame)
return;
mBoundsFirstFrame = false;
mSkeleton->updateBoneMatrices(nv->getTraversalNumber());
updateGeomToSkelMatrix(nv->getNodePath());
osg::BoundingBox box;
size_t index = 0;
for (const BoneInfo& info : mData->mBones)
{
const Bone* bone = mNodes[index++];
if (bone == nullptr)
continue;
osg::BoundingSpheref bs = info.mBoundSphere;
if (mGeomToSkelMatrix)
transformBoundingSphere(bone->mMatrixInSkeletonSpace * (*mGeomToSkelMatrix), bs);
else
transformBoundingSphere(bone->mMatrixInSkeletonSpace, bs);
box.expandBy(bs);
}
if (box != _boundingBox)
{
_boundingBox = box;
_boundingSphere = osg::BoundingSphere(_boundingBox);
_boundingSphereComputed = true;
for (unsigned int i = 0; i < getNumParents(); ++i)
getParent(i)->dirtyBound();
for (unsigned int i = 0; i < 2; ++i)
{
osg::Geometry& geom = *mGeometry[i];
static_cast<CopyBoundingBoxCallback*>(geom.getComputeBoundingBoxCallback())->boundingBox = _boundingBox;
static_cast<CopyBoundingSphereCallback*>(geom.getComputeBoundingSphereCallback())->boundingSphere
= _boundingSphere;
geom.dirtyBound();
}
}
}
void RigGeometry::updateGeomToSkelMatrix(const osg::NodePath& nodePath)
{
bool foundSkel = false;
osg::RefMatrix* geomToSkelMatrix = mGeomToSkelMatrix;
if (geomToSkelMatrix)
geomToSkelMatrix->makeIdentity();
for (osg::NodePath::const_iterator it = nodePath.begin(); it != nodePath.end() - 1; ++it)
{
osg::Node* node = *it;
if (!foundSkel)
{
if (node == mSkeleton)
foundSkel = true;
}
else
{
if (osg::Transform* trans = node->asTransform())
{
osg::MatrixTransform* matrixTrans = trans->asMatrixTransform();
if (matrixTrans && matrixTrans->getMatrix().isIdentity())
continue;
if (!geomToSkelMatrix)
geomToSkelMatrix = mGeomToSkelMatrix = new osg::RefMatrix;
trans->computeWorldToLocalMatrix(*geomToSkelMatrix, nullptr);
}
}
}
}
void RigGeometry::setBoneInfo(std::vector<BoneInfo>&& bones)
{
if (!mData)
mData = new InfluenceData;
mData->mBones = std::move(bones);
}
void RigGeometry::setInfluences(const std::vector<VertexWeights>& influences)
{
if (!mData)
mData = new InfluenceData;
std::unordered_map<unsigned short, BoneWeights> vertexToInfluences;
size_t index = 0;
for (const auto& influence : influences)
{
for (const auto& [vertex, weight] : influence)
vertexToInfluences[vertex].emplace_back(index, weight);
index++;
}
std::map<BoneWeights, VertexList> influencesToVertices;
for (const auto& [vertex, weights] : vertexToInfluences)
influencesToVertices[weights].emplace_back(vertex);
mData->mInfluences.reserve(influencesToVertices.size());
mData->mInfluences.assign(influencesToVertices.begin(), influencesToVertices.end());
}
void RigGeometry::setInfluences(const std::vector<BoneWeights>& influences)
{
if (!mData)
mData = new InfluenceData;
std::map<BoneWeights, VertexList> influencesToVertices;
for (size_t i = 0; i < influences.size(); i++)
influencesToVertices[influences[i]].emplace_back(i);
mData->mInfluences.reserve(influencesToVertices.size());
mData->mInfluences.assign(influencesToVertices.begin(), influencesToVertices.end());
}
void RigGeometry::accept(osg::NodeVisitor& nv)
{
if (!nv.validNodeMask(*this))
return;
nv.pushOntoNodePath(this);
if (nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR)
{
// The cull visitor won't be applied to the node itself,
// but we want to use its state to render the child geometry.
osg::StateSet* stateset = getStateSet();
osgUtil::CullVisitor* cv = static_cast<osgUtil::CullVisitor*>(&nv);
if (stateset)
cv->pushStateSet(stateset);
cull(&nv);
if (stateset)
cv->popStateSet();
}
else if (nv.getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR)
updateBounds(&nv);
else
nv.apply(*this);
nv.popFromNodePath();
}
void RigGeometry::accept(osg::PrimitiveFunctor& func) const
{
getGeometry(mLastFrameNumber)->accept(func);
}
osg::Geometry* RigGeometry::getGeometry(unsigned int frame) const
{
return mGeometry[frame % 2].get();
}
}
| 13,899
|
C++
|
.cpp
| 321
| 31.707165
| 120
| 0.583691
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,735
|
waterutil.cpp
|
OpenMW_openmw/components/sceneutil/waterutil.cpp
|
#include "waterutil.hpp"
#include <osg/Depth>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/StateSet>
#include "depth.hpp"
namespace SceneUtil
{
// disable nonsense test against a worldsize bb what will always pass
class WaterBoundCallback : public osg::Drawable::ComputeBoundingBoxCallback
{
osg::BoundingBox computeBound(const osg::Drawable&) const override { return osg::BoundingBox(); }
};
osg::ref_ptr<osg::Geometry> createWaterGeometry(float size, int segments, float textureRepeats)
{
osg::ref_ptr<osg::Vec3Array> verts(new osg::Vec3Array);
osg::ref_ptr<osg::Vec2Array> texcoords(new osg::Vec2Array);
// some drivers don't like huge triangles, so we do some subdivisons
// a paged solution would be even better
const float step = size / segments;
const float texCoordStep = textureRepeats / segments;
for (int x = 0; x < segments; ++x)
{
for (int y = 0; y < segments; ++y)
{
float x1 = -size / 2.f + x * step;
float y1 = -size / 2.f + y * step;
float x2 = x1 + step;
float y2 = y1 + step;
verts->push_back(osg::Vec3f(x1, y2, 0.f));
verts->push_back(osg::Vec3f(x1, y1, 0.f));
verts->push_back(osg::Vec3f(x2, y1, 0.f));
verts->push_back(osg::Vec3f(x2, y2, 0.f));
float u1 = x * texCoordStep;
float v1 = y * texCoordStep;
float u2 = u1 + texCoordStep;
float v2 = v1 + texCoordStep;
texcoords->push_back(osg::Vec2f(u1, v2));
texcoords->push_back(osg::Vec2f(u1, v1));
texcoords->push_back(osg::Vec2f(u2, v1));
texcoords->push_back(osg::Vec2f(u2, v2));
}
}
osg::ref_ptr<osg::Geometry> waterGeom(new osg::Geometry);
waterGeom->setVertexArray(verts);
waterGeom->setTexCoordArray(0, texcoords);
osg::ref_ptr<osg::Vec3Array> normal(new osg::Vec3Array);
normal->push_back(osg::Vec3f(0, 0, 1));
waterGeom->setNormalArray(normal, osg::Array::BIND_OVERALL);
waterGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, verts->size()));
waterGeom->setComputeBoundingBoxCallback(new WaterBoundCallback);
waterGeom->setCullingActive(false);
return waterGeom;
}
osg::ref_ptr<osg::StateSet> createSimpleWaterStateSet(float alpha, int renderBin)
{
osg::ref_ptr<osg::StateSet> stateset(new osg::StateSet);
osg::ref_ptr<osg::Material> material(new osg::Material);
material->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(0.f, 0.f, 0.f, 1.f));
material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(1.f, 1.f, 1.f, alpha));
material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(1.f, 1.f, 1.f, 1.f));
material->setColorMode(osg::Material::OFF);
stateset->setAttributeAndModes(material, osg::StateAttribute::ON);
stateset->setMode(GL_BLEND, osg::StateAttribute::ON);
stateset->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
osg::ref_ptr<osg::Depth> depth = new SceneUtil::AutoDepth;
depth->setWriteMask(false);
stateset->setAttributeAndModes(depth, osg::StateAttribute::ON);
stateset->setRenderBinDetails(renderBin, "RenderBin");
return stateset;
}
}
| 3,510
|
C++
|
.cpp
| 72
| 39.125
| 105
| 0.617363
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,736
|
attach.cpp
|
OpenMW_openmw/components/sceneutil/attach.cpp
|
#include "attach.hpp"
#include <stdexcept>
#include <osg/FrontFace>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/MatrixTransform>
#include <osg/NodeVisitor>
#include <osg/PositionAttitudeTransform>
#include <components/resource/scenemanager.hpp>
#include <components/sceneutil/riggeometry.hpp>
#include <components/sceneutil/riggeometryosgaextension.hpp>
#include <components/sceneutil/skeleton.hpp>
#include "visitor.hpp"
namespace SceneUtil
{
class CopyRigVisitor : public osg::NodeVisitor
{
public:
CopyRigVisitor(osg::ref_ptr<osg::Group> parent, std::string_view filter)
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mParent(std::move(parent))
, mFilter(filter)
{
}
void apply(osg::MatrixTransform& node) override { traverse(node); }
void apply(osg::Node& node) override { traverse(node); }
void apply(osg::Group& node) override { traverse(node); }
void apply(osg::Drawable& drawable) override
{
if (!filterMatches(drawable.getName()))
return;
const osg::Node* node = &drawable;
bool isRig = dynamic_cast<const SceneUtil::RigGeometry*>(node) != nullptr;
if (!isRig)
isRig = dynamic_cast<const SceneUtil::RigGeometryHolder*>(node) != nullptr;
if (!isRig)
return;
for (auto it = getNodePath().rbegin() + 1; it != getNodePath().rend(); ++it)
{
const osg::Node* parent = *it;
if (!filterMatches(parent->getName()))
break;
node = parent;
}
mToCopy.emplace(node);
}
void doCopy(Resource::SceneManager* sceneManager)
{
for (const osg::ref_ptr<const osg::Node>& node : mToCopy)
{
mParent->addChild(sceneManager->getInstance(node));
}
mToCopy.clear();
}
private:
bool filterMatches(std::string_view name) const
{
if (Misc::StringUtils::ciStartsWith(name, mFilter))
return true;
constexpr std::string_view prefix = "tri ";
if (Misc::StringUtils::ciStartsWith(name, prefix))
return Misc::StringUtils::ciStartsWith(name.substr(prefix.size()), mFilter);
return false;
}
using NodeSet = std::set<osg::ref_ptr<const osg::Node>>;
NodeSet mToCopy;
osg::ref_ptr<osg::Group> mParent;
std::string_view mFilter;
};
namespace
{
void mergeUserData(const osg::UserDataContainer* source, osg::Object* target)
{
if (!source)
return;
if (!target->getUserDataContainer())
target->setUserDataContainer(osg::clone(source, osg::CopyOp::SHALLOW_COPY));
else
{
for (unsigned int i = 0; i < source->getNumUserObjects(); ++i)
target->getUserDataContainer()->addUserObject(
osg::clone(source->getUserObject(i), osg::CopyOp::SHALLOW_COPY));
}
}
osg::ref_ptr<osg::StateSet> makeFrontFaceStateSet()
{
osg::ref_ptr<osg::FrontFace> frontFace = new osg::FrontFace;
frontFace->setMode(osg::FrontFace::CLOCKWISE);
osg::ref_ptr<osg::StateSet> frontFaceStateSet = new osg::StateSet;
frontFaceStateSet->setAttributeAndModes(frontFace, osg::StateAttribute::ON);
return frontFaceStateSet;
}
}
osg::ref_ptr<osg::Node> attach(osg::ref_ptr<const osg::Node> toAttach, osg::Node* master, std::string_view filter,
osg::Group* attachNode, Resource::SceneManager* sceneManager, const osg::Quat* attitude)
{
if (dynamic_cast<const SceneUtil::Skeleton*>(toAttach.get()))
{
osg::ref_ptr<osg::Group> handle = new osg::Group;
CopyRigVisitor copyVisitor(handle, filter);
const_cast<osg::Node*>(toAttach.get())->accept(copyVisitor);
copyVisitor.doCopy(sceneManager);
// add a ref to the original template to hint to the cache that it is still being used and should be kept in
// cache.
handle->getOrCreateUserDataContainer()->addUserObject(new Resource::TemplateRef(toAttach));
if (handle->getNumChildren() == 1)
{
osg::ref_ptr<osg::Node> newHandle = handle->getChild(0);
handle->removeChild(newHandle);
master->asGroup()->addChild(newHandle);
mergeUserData(toAttach->getUserDataContainer(), newHandle);
return newHandle;
}
else
{
master->asGroup()->addChild(handle);
mergeUserData(toAttach->getUserDataContainer(), handle);
return handle;
}
}
else
{
osg::ref_ptr<osg::Node> clonedToAttach = sceneManager->getInstance(toAttach);
FindByNameVisitor findBoneOffset("BoneOffset");
clonedToAttach->accept(findBoneOffset);
osg::ref_ptr<osg::PositionAttitudeTransform> trans;
if (findBoneOffset.mFoundNode)
{
osg::MatrixTransform* boneOffset = dynamic_cast<osg::MatrixTransform*>(findBoneOffset.mFoundNode);
if (!boneOffset)
throw std::runtime_error("BoneOffset must be a MatrixTransform");
trans = new osg::PositionAttitudeTransform;
trans->setPosition(boneOffset->getMatrix().getTrans());
// Now that we used it, get rid of the redundant node.
if (boneOffset->getNumChildren() == 0 && boneOffset->getNumParents() == 1)
boneOffset->getParent(0)->removeChild(boneOffset);
}
if (attachNode->getName().find("Left") != std::string::npos)
{
if (!trans)
trans = new osg::PositionAttitudeTransform;
trans->setScale(osg::Vec3f(-1.f, 1.f, 1.f));
// Need to invert culling because of the negative scale
// Note: for absolute correctness we would need to check the current front face for every mesh then
// invert it However MW isn't doing this either, so don't. Assuming all meshes are using backface
// culling is more efficient.
static const osg::ref_ptr<osg::StateSet> frontFaceStateSet = makeFrontFaceStateSet();
trans->setStateSet(frontFaceStateSet);
}
if (attitude)
{
if (!trans)
trans = new osg::PositionAttitudeTransform;
trans->setAttitude(*attitude);
}
if (trans)
{
attachNode->addChild(trans);
trans->addChild(clonedToAttach);
return trans;
}
else
{
attachNode->addChild(clonedToAttach);
return clonedToAttach;
}
}
}
}
| 7,243
|
C++
|
.cpp
| 169
| 30.751479
| 120
| 0.574066
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,737
|
morphgeometry.cpp
|
OpenMW_openmw/components/sceneutil/morphgeometry.cpp
|
#include "morphgeometry.hpp"
#include <osgUtil/CullVisitor>
#include <cassert>
#include <components/resource/scenemanager.hpp>
namespace SceneUtil
{
MorphGeometry::MorphGeometry()
: mLastFrameNumber(0)
, mDirty(true)
, mMorphedBoundingBox(false)
{
}
MorphGeometry::MorphGeometry(const MorphGeometry& copy, const osg::CopyOp& copyop)
: osg::Drawable(copy, copyop)
, mMorphTargets(copy.mMorphTargets)
, mLastFrameNumber(0)
, mDirty(true)
, mMorphedBoundingBox(false)
{
setSourceGeometry(copy.getSourceGeometry());
}
void MorphGeometry::setSourceGeometry(osg::ref_ptr<osg::Geometry> sourceGeom)
{
for (unsigned int i = 0; i < 2; ++i)
mGeometry[i] = nullptr;
mSourceGeometry = sourceGeom;
for (unsigned int i = 0; i < 2; ++i)
{
// DO NOT COPY AND PASTE THIS CODE. Cloning osg::Geometry without also cloning its contained Arrays is
// generally unsafe. In this specific case the operation is safe under the following two assumptions:
// - When Arrays are removed or replaced in the cloned geometry, the original Arrays in their place must
// outlive the cloned geometry regardless. (ensured by TemplateRef)
// - Arrays that we add or replace in the cloned geometry must be explicitely forbidden from reusing
// BufferObjects of the original geometry. (ensured by vbo below)
mGeometry[i] = new osg::Geometry(*mSourceGeometry, osg::CopyOp::SHALLOW_COPY);
mGeometry[i]->getOrCreateUserDataContainer()->addUserObject(new Resource::TemplateRef(mSourceGeometry));
const osg::Geometry& from = *mSourceGeometry;
osg::Geometry& to = *mGeometry[i];
to.setSupportsDisplayList(false);
to.setUseVertexBufferObjects(true);
to.setCullingActive(false); // make sure to disable culling since that's handled by this class
// vertices are modified every frame, so we need to deep copy them.
// assign a dedicated VBO to make sure that modifications don't interfere with source geometry's VBO.
osg::ref_ptr<osg::VertexBufferObject> vbo(new osg::VertexBufferObject);
vbo->setUsage(GL_DYNAMIC_DRAW_ARB);
osg::ref_ptr<osg::Array> vertexArray
= static_cast<osg::Array*>(from.getVertexArray()->clone(osg::CopyOp::DEEP_COPY_ALL));
if (vertexArray)
{
vertexArray->setVertexBufferObject(vbo);
to.setVertexArray(vertexArray);
}
}
}
void MorphGeometry::addMorphTarget(osg::Vec3Array* offsets, float weight)
{
mMorphTargets.push_back(MorphTarget(offsets, weight));
mMorphedBoundingBox = false;
dirty();
}
void MorphGeometry::dirty()
{
mDirty = true;
if (!mMorphedBoundingBox)
dirtyBound();
}
osg::ref_ptr<osg::Geometry> MorphGeometry::getSourceGeometry() const
{
return mSourceGeometry;
}
void MorphGeometry::accept(osg::NodeVisitor& nv)
{
if (!nv.validNodeMask(*this))
return;
nv.pushOntoNodePath(this);
if (nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR)
{
// The cull visitor won't be applied to the node itself,
// but we want to use its state to render the child geometry.
osg::StateSet* stateset = getStateSet();
osgUtil::CullVisitor* cv = static_cast<osgUtil::CullVisitor*>(&nv);
if (stateset)
cv->pushStateSet(stateset);
cull(&nv);
if (stateset)
cv->popStateSet();
}
else
nv.apply(*this);
nv.popFromNodePath();
}
void MorphGeometry::accept(osg::PrimitiveFunctor& func) const
{
getGeometry(mLastFrameNumber)->accept(func);
}
osg::BoundingBox MorphGeometry::computeBoundingBox() const
{
bool anyMorphTarget = false;
for (unsigned int i = 1; i < mMorphTargets.size(); ++i)
if (mMorphTargets[i].getWeight() != 0)
{
anyMorphTarget = true;
break;
}
// before the MorphGeometry has started animating, we will use a regular bounding box (this is required
// for correct object placements, which uses the bounding box)
if (!mMorphedBoundingBox && !anyMorphTarget)
{
return mSourceGeometry->getBoundingBox();
}
// once it animates, use a bounding box that encompasses all possible animations so as to avoid recalculating
else
{
mMorphedBoundingBox = true;
const osg::Vec3Array* sourceVerts = static_cast<const osg::Vec3Array*>(mSourceGeometry->getVertexArray());
if (mMorphTargets.size() != 0)
sourceVerts = mMorphTargets[0].getOffsets();
std::vector<osg::BoundingBox> vertBounds(sourceVerts->size());
// Since we don't know what combinations of morphs are being applied we need to keep track of a bounding box
// for each vertex. The minimum/maximum of the box is the minimum/maximum offset the vertex can have from
// its starting position.
// Start with zero offsets which will happen when no morphs are applied.
for (unsigned int i = 0; i < vertBounds.size(); ++i)
vertBounds[i].set(osg::Vec3f(0, 0, 0), osg::Vec3f(0, 0, 0));
for (unsigned int i = 1; i < mMorphTargets.size(); ++i)
{
const osg::Vec3Array& offsets = *mMorphTargets[i].getOffsets();
for (unsigned int j = 0; j < offsets.size() && j < vertBounds.size(); ++j)
{
osg::BoundingBox& bounds = vertBounds[j];
bounds.expandBy(bounds._max + offsets[j]);
bounds.expandBy(bounds._min + offsets[j]);
}
}
osg::BoundingBox box;
for (unsigned int i = 0; i < vertBounds.size(); ++i)
{
vertBounds[i]._max += (*sourceVerts)[i];
vertBounds[i]._min += (*sourceVerts)[i];
box.expandBy(vertBounds[i]);
}
return box;
}
}
void MorphGeometry::cull(osg::NodeVisitor* nv)
{
if (mLastFrameNumber == nv->getTraversalNumber() || !mDirty || mMorphTargets.size() == 0)
{
osg::Geometry& geom = *getGeometry(mLastFrameNumber);
nv->pushOntoNodePath(&geom);
nv->apply(geom);
nv->popFromNodePath();
return;
}
mDirty = false;
mLastFrameNumber = nv->getTraversalNumber();
osg::Geometry& geom = *getGeometry(mLastFrameNumber);
const osg::Vec3Array* positionSrc = mMorphTargets[0].getOffsets();
osg::Vec3Array* positionDst = static_cast<osg::Vec3Array*>(geom.getVertexArray());
assert(positionSrc->size() == positionDst->size());
for (unsigned int vertex = 0; vertex < positionSrc->size(); ++vertex)
(*positionDst)[vertex] = (*positionSrc)[vertex];
for (unsigned int i = 1; i < mMorphTargets.size(); ++i)
{
float weight = mMorphTargets[i].getWeight();
if (weight == 0.f)
continue;
const osg::Vec3Array* offsets = mMorphTargets[i].getOffsets();
for (unsigned int vertex = 0; vertex < positionSrc->size(); ++vertex)
(*positionDst)[vertex] += (*offsets)[vertex] * weight;
}
positionDst->dirty();
geom.osg::Drawable::dirtyGLObjects();
nv->pushOntoNodePath(&geom);
nv->apply(geom);
nv->popFromNodePath();
}
osg::Geometry* MorphGeometry::getGeometry(unsigned int frame) const
{
return mGeometry[frame % 2];
}
}
| 8,038
|
C++
|
.cpp
| 182
| 33.626374
| 120
| 0.599616
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,738
|
positionattitudetransform.cpp
|
OpenMW_openmw/components/sceneutil/positionattitudetransform.cpp
|
#include "positionattitudetransform.hpp"
namespace SceneUtil
{
PositionAttitudeTransform::PositionAttitudeTransform()
: _scale(1.0, 1.0, 1.0)
{
}
bool PositionAttitudeTransform::computeLocalToWorldMatrix(osg::Matrix& matrix, osg::NodeVisitor*) const
{
if (_referenceFrame == RELATIVE_RF)
{
matrix.preMultTranslate(_position);
matrix.preMultRotate(_attitude);
matrix.preMultScale(_scale);
}
else // absolute
{
matrix.makeRotate(_attitude);
matrix.postMultTranslate(_position);
matrix.preMultScale(_scale);
}
return true;
}
bool PositionAttitudeTransform::computeWorldToLocalMatrix(osg::Matrix& matrix, osg::NodeVisitor*) const
{
if (_scale.x() == 0.0 || _scale.y() == 0.0 || _scale.z() == 0.0)
return false;
if (_referenceFrame == RELATIVE_RF)
{
matrix.postMultTranslate(-_position);
matrix.postMultRotate(_attitude.inverse());
matrix.postMultScale(osg::Vec3f(1.0 / _scale.x(), 1.0 / _scale.y(), 1.0 / _scale.z()));
}
else // absolute
{
matrix.makeRotate(_attitude.inverse());
matrix.preMultTranslate(-_position);
matrix.postMultScale(osg::Vec3f(1.0 / _scale.x(), 1.0 / _scale.y(), 1.0 / _scale.z()));
}
return true;
}
}
| 1,446
|
C++
|
.cpp
| 42
| 25.666667
| 107
| 0.579399
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,739
|
skeleton.cpp
|
OpenMW_openmw/components/sceneutil/skeleton.cpp
|
#include "skeleton.hpp"
#include <osg/MatrixTransform>
#include <components/debug/debuglog.hpp>
#include <components/misc/strings/lower.hpp>
#include <algorithm>
namespace SceneUtil
{
class InitBoneCacheVisitor : public osg::NodeVisitor
{
public:
typedef std::vector<osg::MatrixTransform*> TransformPath;
InitBoneCacheVisitor(std::unordered_map<std::string, TransformPath>& cache)
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mCache(cache)
{
}
void apply(osg::MatrixTransform& node) override
{
mPath.push_back(&node);
mCache.emplace(Misc::StringUtils::lowerCase(node.getName()), mPath);
traverse(node);
mPath.pop_back();
}
private:
TransformPath mPath;
std::unordered_map<std::string, TransformPath>& mCache;
};
Skeleton::Skeleton()
: mBoneCacheInit(false)
, mNeedToUpdateBoneMatrices(true)
, mActive(Active)
, mLastFrameNumber(0)
, mLastCullFrameNumber(0)
{
}
Skeleton::Skeleton(const Skeleton& copy, const osg::CopyOp& copyop)
: osg::Group(copy, copyop)
, mBoneCacheInit(false)
, mNeedToUpdateBoneMatrices(true)
, mActive(copy.mActive)
, mLastFrameNumber(0)
, mLastCullFrameNumber(0)
{
}
Bone* Skeleton::getBone(const std::string& name)
{
if (!mBoneCacheInit)
{
InitBoneCacheVisitor visitor(mBoneCache);
accept(visitor);
mBoneCacheInit = true;
}
BoneCache::iterator found = mBoneCache.find(Misc::StringUtils::lowerCase(name));
if (found == mBoneCache.end())
return nullptr;
// find or insert in the bone hierarchy
if (!mRootBone.get())
{
mRootBone = std::make_unique<Bone>();
}
Bone* bone = mRootBone.get();
for (osg::MatrixTransform* matrixTransform : found->second)
{
const auto it = std::find_if(bone->mChildren.begin(), bone->mChildren.end(),
[&](const auto& v) { return v->mNode == matrixTransform; });
if (it == bone->mChildren.end())
{
bone = bone->mChildren.emplace_back(std::make_unique<Bone>()).get();
mNeedToUpdateBoneMatrices = true;
}
else
bone = it->get();
bone->mNode = matrixTransform;
}
return bone;
}
void Skeleton::updateBoneMatrices(unsigned int traversalNumber)
{
if (traversalNumber != mLastFrameNumber)
mNeedToUpdateBoneMatrices = true;
mLastFrameNumber = traversalNumber;
if (mNeedToUpdateBoneMatrices)
{
if (mRootBone.get())
{
for (const auto& child : mRootBone->mChildren)
child->update(nullptr);
}
mNeedToUpdateBoneMatrices = false;
}
}
void Skeleton::setActive(ActiveType active)
{
mActive = active;
}
bool Skeleton::getActive() const
{
return mActive != Inactive;
}
void Skeleton::markDirty()
{
mLastFrameNumber = 0;
mBoneCache.clear();
mBoneCacheInit = false;
}
void Skeleton::traverse(osg::NodeVisitor& nv)
{
if (nv.getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR)
{
if (mActive == Inactive && mLastFrameNumber != 0)
return;
if (mActive == SemiActive && mLastFrameNumber != 0 && mLastCullFrameNumber + 3 <= nv.getTraversalNumber())
return;
}
else if (nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR)
mLastCullFrameNumber = nv.getTraversalNumber();
osg::Group::traverse(nv);
}
void Skeleton::childInserted(unsigned int)
{
markDirty();
}
void Skeleton::childRemoved(unsigned int, unsigned int)
{
markDirty();
}
Bone::Bone()
: mNode(nullptr)
{
}
void Bone::update(const osg::Matrixf* parentMatrixInSkeletonSpace)
{
if (!mNode)
{
Log(Debug::Error) << "Error: Bone without node";
return;
}
if (parentMatrixInSkeletonSpace)
mMatrixInSkeletonSpace = mNode->getMatrix() * (*parentMatrixInSkeletonSpace);
else
mMatrixInSkeletonSpace = mNode->getMatrix();
for (const auto& child : mChildren)
child->update(&mMatrixInSkeletonSpace);
}
}
| 4,621
|
C++
|
.cpp
| 145
| 22.924138
| 118
| 0.583933
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,741
|
unrefqueue.cpp
|
OpenMW_openmw/components/sceneutil/unrefqueue.cpp
|
#include "unrefqueue.hpp"
#include <components/sceneutil/workqueue.hpp>
namespace SceneUtil
{
namespace
{
struct ClearVector final : SceneUtil::WorkItem
{
std::vector<osg::ref_ptr<osg::Referenced>> mObjects;
explicit ClearVector(std::vector<osg::ref_ptr<osg::Referenced>>&& objects)
: mObjects(std::move(objects))
{
}
void doWork() override { mObjects.clear(); }
};
}
void UnrefQueue::flush(SceneUtil::WorkQueue& workQueue)
{
if (mObjects.empty())
return;
// Move only objects to keep allocated storage in mObjects
workQueue.addWorkItem(new ClearVector(std::vector<osg::ref_ptr<osg::Referenced>>(
std::move_iterator(mObjects.begin()), std::move_iterator(mObjects.end()))));
mObjects.clear();
}
}
| 882
|
C++
|
.cpp
| 26
| 25.769231
| 89
| 0.610588
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,742
|
screencapture.cpp
|
OpenMW_openmw/components/sceneutil/screencapture.cpp
|
#include "screencapture.hpp"
#include <components/debug/debuglog.hpp>
#include <components/files/conversion.hpp>
#include <components/sceneutil/workqueue.hpp>
#include <osg/Image>
#include <osg/ref_ptr>
#include <osgDB/ReaderWriter>
#include <osgDB/Registry>
#include <atomic>
#include <cassert>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
namespace
{
class ScreenCaptureWorkItem : public SceneUtil::WorkItem
{
public:
ScreenCaptureWorkItem(const osg::ref_ptr<osgViewer::ScreenCaptureHandler::CaptureOperation>& impl,
const osg::Image& image, unsigned int contextId)
: mImpl(impl)
, mImage(new osg::Image(image))
, mContextId(contextId)
{
assert(mImpl != nullptr);
}
void doWork() override
{
if (mAborted)
return;
try
{
(*mImpl)(*mImage, mContextId);
}
catch (const std::exception& e)
{
Log(Debug::Error) << "ScreenCaptureWorkItem exception: " << e.what();
}
}
void abort() override { mAborted = true; }
private:
const osg::ref_ptr<osgViewer::ScreenCaptureHandler::CaptureOperation> mImpl;
const osg::ref_ptr<const osg::Image> mImage;
const unsigned int mContextId;
std::atomic_bool mAborted{ false };
};
}
namespace SceneUtil
{
std::filesystem::path writeScreenshotToFile(
const std::filesystem::path& screenshotPath, const std::string& screenshotFormat, const osg::Image& image)
{
// Count screenshots.
int shotCount = 0;
// Find the first unused filename with a do-while
std::ostringstream stream;
std::string lastFileName;
std::filesystem::path lastFilePath;
do
{
// Reset the stream
stream.str("");
stream.clear();
stream << "screenshot" << std::setw(3) << std::setfill('0') << shotCount++ << "." << screenshotFormat;
lastFileName = stream.str();
lastFilePath = screenshotPath / lastFileName;
} while (std::filesystem::exists(lastFilePath));
std::ofstream outStream;
outStream.open(lastFilePath, std::ios::binary);
osgDB::ReaderWriter* readerwriter = osgDB::Registry::instance()->getReaderWriterForExtension(screenshotFormat);
if (!readerwriter)
{
Log(Debug::Error) << "Error: Can't write screenshot, no '" << screenshotFormat << "' readerwriter found";
return std::string();
}
osgDB::ReaderWriter::WriteResult result = readerwriter->writeImage(image, outStream);
if (!result.success())
{
Log(Debug::Error) << "Error: Can't write screenshot: " << result.message() << " code " << result.status();
return std::string();
}
return lastFileName;
}
WriteScreenshotToFileOperation::WriteScreenshotToFileOperation(const std::filesystem::path& screenshotPath,
const std::string& screenshotFormat, std::function<void(std::string)> callback)
: mScreenshotPath(screenshotPath)
, mScreenshotFormat(screenshotFormat)
, mCallback(std::move(callback))
{
}
void WriteScreenshotToFileOperation::operator()(const osg::Image& image, const unsigned int /*context_id*/)
{
std::filesystem::path fileName;
try
{
fileName = writeScreenshotToFile(mScreenshotPath, mScreenshotFormat, image);
}
catch (const std::exception& e)
{
Log(Debug::Error) << "Failed to write screenshot to file with path=\"" << mScreenshotPath << "\", format=\""
<< mScreenshotFormat << "\": " << e.what();
}
if (fileName.empty())
mCallback(std::string());
else
{
mCallback(Files::pathToUnicodeString(fileName));
Log(Debug::Info) << mScreenshotPath / fileName << " has been saved";
}
}
AsyncScreenCaptureOperation::AsyncScreenCaptureOperation(
osg::ref_ptr<WorkQueue> queue, osg::ref_ptr<CaptureOperation> impl)
: mQueue(std::move(queue))
, mImpl(std::move(impl))
{
assert(mQueue != nullptr);
assert(mImpl != nullptr);
}
AsyncScreenCaptureOperation::~AsyncScreenCaptureOperation()
{
stop();
}
void AsyncScreenCaptureOperation::stop()
{
for (const osg::ref_ptr<SceneUtil::WorkItem>& item : *mWorkItems.lockConst())
item->abort();
for (const osg::ref_ptr<SceneUtil::WorkItem>& item : *mWorkItems.lockConst())
item->waitTillDone();
}
void AsyncScreenCaptureOperation::operator()(const osg::Image& image, const unsigned int context_id)
{
osg::ref_ptr<SceneUtil::WorkItem> item(new ScreenCaptureWorkItem(mImpl, image, context_id));
mQueue->addWorkItem(item);
const auto isDone = [](const osg::ref_ptr<SceneUtil::WorkItem>& v) { return v->isDone(); };
const auto workItems = mWorkItems.lock();
workItems->erase(std::remove_if(workItems->begin(), workItems->end(), isDone), workItems->end());
workItems->emplace_back(std::move(item));
}
}
| 5,379
|
C++
|
.cpp
| 141
| 29.758865
| 120
| 0.616993
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,743
|
clone.cpp
|
OpenMW_openmw/components/sceneutil/clone.cpp
|
#include "clone.hpp"
#include <osg/StateSet>
#include <osgAnimation/MorphGeometry>
#include <osgAnimation/RigGeometry>
#include <osgParticle/Emitter>
#include <osgParticle/ParticleProcessor>
#include <osgParticle/ParticleSystemUpdater>
#include <components/sceneutil/morphgeometry.hpp>
#include <components/sceneutil/riggeometry.hpp>
#include <components/sceneutil/riggeometryosgaextension.hpp>
namespace SceneUtil
{
CopyOp::CopyOp()
{
setCopyFlags(osg::CopyOp::DEEP_COPY_NODES
// Controller might need different inputs per scene instance
| osg::CopyOp::DEEP_COPY_CALLBACKS | osg::CopyOp::DEEP_COPY_USERDATA);
}
osg::Node* CopyOp::operator()(const osg::Node* node) const
{
if (const osgParticle::ParticleProcessor* processor = dynamic_cast<const osgParticle::ParticleProcessor*>(node))
return operator()(processor);
if (const osgParticle::ParticleSystemUpdater* updater
= dynamic_cast<const osgParticle::ParticleSystemUpdater*>(node))
{
osgParticle::ParticleSystemUpdater* cloned
= new osgParticle::ParticleSystemUpdater(*updater, osg::CopyOp::SHALLOW_COPY);
mUpdaterToOldPs[cloned] = updater->getParticleSystem(0);
return cloned;
}
return osg::CopyOp::operator()(node);
}
osg::Drawable* CopyOp::operator()(const osg::Drawable* drawable) const
{
if (const osgParticle::ParticleSystem* partsys = dynamic_cast<const osgParticle::ParticleSystem*>(drawable))
return operator()(partsys);
if (dynamic_cast<const SceneUtil::RigGeometry*>(drawable)
|| dynamic_cast<const SceneUtil::MorphGeometry*>(drawable)
|| dynamic_cast<const osgAnimation::RigGeometry*>(drawable)
|| dynamic_cast<const osgAnimation::MorphGeometry*>(drawable)
|| dynamic_cast<const SceneUtil::RigGeometryHolder*>(drawable))
{
return static_cast<osg::Drawable*>(drawable->clone(*this));
}
return osg::CopyOp::operator()(drawable);
}
osgParticle::ParticleProcessor* CopyOp::operator()(const osgParticle::ParticleProcessor* processor) const
{
osgParticle::ParticleProcessor* cloned
= static_cast<osgParticle::ParticleProcessor*>(processor->clone(osg::CopyOp::DEEP_COPY_CALLBACKS));
for (const auto& oldPsNewPsPair : mOldPsToNewPs)
{
if (processor->getParticleSystem() == oldPsNewPsPair.first)
{
cloned->setParticleSystem(oldPsNewPsPair.second);
return cloned;
}
}
mProcessorToOldPs[cloned] = processor->getParticleSystem();
return cloned;
}
osgParticle::ParticleSystem* CopyOp::operator()(const osgParticle::ParticleSystem* partsys) const
{
osgParticle::ParticleSystem* cloned = static_cast<osgParticle::ParticleSystem*>(partsys->clone(*this));
for (const auto& processorPsPair : mProcessorToOldPs)
{
if (processorPsPair.second == partsys)
{
processorPsPair.first->setParticleSystem(cloned);
}
}
for (const auto& updaterPsPair : mUpdaterToOldPs)
{
if (updaterPsPair.second == partsys)
{
osgParticle::ParticleSystemUpdater* updater = updaterPsPair.first;
updater->removeParticleSystem(updater->getParticleSystem(0));
updater->addParticleSystem(cloned);
}
}
// In rare situations a particle processor may be placed after the particle system in the scene graph.
mOldPsToNewPs[partsys] = cloned;
return cloned;
}
}
| 3,750
|
C++
|
.cpp
| 85
| 35.117647
| 120
| 0.663195
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,744
|
detourdebugdraw.cpp
|
OpenMW_openmw/components/sceneutil/detourdebugdraw.cpp
|
#include "detourdebugdraw.hpp"
#include "depth.hpp"
#include "util.hpp"
#include <osg/BlendFunc>
#include <osg/Group>
#include <osg/LineWidth>
#include <osg/Material>
#include <osg/PolygonOffset>
#include <algorithm>
namespace
{
osg::PrimitiveSet::Mode toOsgPrimitiveSetMode(duDebugDrawPrimitives value)
{
switch (value)
{
case DU_DRAW_POINTS:
return osg::PrimitiveSet::POINTS;
case DU_DRAW_LINES:
return osg::PrimitiveSet::LINES;
case DU_DRAW_TRIS:
return osg::PrimitiveSet::TRIANGLES;
case DU_DRAW_QUADS:
return osg::PrimitiveSet::QUADS;
}
throw std::logic_error(
"Can't convert duDebugDrawPrimitives to osg::PrimitiveSet::Mode, value=" + std::to_string(value));
}
}
namespace SceneUtil
{
DebugDraw::DebugDraw(osg::Group& group, const osg::ref_ptr<osg::StateSet>& stateSet, const osg::Vec3f& shift,
float recastInvertedScaleFactor)
: mGroup(group)
, mStateSet(stateSet)
, mShift(shift)
, mRecastInvertedScaleFactor(recastInvertedScaleFactor)
, mMode(osg::PrimitiveSet::POINTS)
, mSize(1.0f)
{
}
void DebugDraw::depthMask(bool) {}
void DebugDraw::texture(bool) {}
void DebugDraw::begin(osg::PrimitiveSet::Mode mode, float size)
{
mMode = mode;
mVertices = new osg::Vec3Array;
mColors = new osg::Vec4Array;
mSize = size;
}
void DebugDraw::begin(duDebugDrawPrimitives prim, float size)
{
begin(toOsgPrimitiveSetMode(prim), size);
}
void DebugDraw::vertex(const float* pos, unsigned color)
{
vertex(pos[0], pos[1], pos[2], color);
}
void DebugDraw::vertex(const float x, const float y, const float z, unsigned color)
{
addVertex(osg::Vec3f(x, y, z));
addColor(SceneUtil::colourFromRGBA(color));
}
void DebugDraw::vertex(const float* pos, unsigned color, const float* uv)
{
vertex(pos[0], pos[1], pos[2], color, uv[0], uv[1]);
}
void DebugDraw::vertex(const float x, const float y, const float z, unsigned color, const float, const float)
{
addVertex(osg::Vec3f(x, y, z));
addColor(SceneUtil::colourFromRGBA(color));
}
void DebugDraw::end()
{
const osg::ref_ptr<osg::DrawArrays> drawArrays
= new osg::DrawArrays(mMode, 0, static_cast<int>(mVertices->size()));
osg::ref_ptr<osg::Geometry> geometry(new osg::Geometry);
geometry->setStateSet(mStateSet);
geometry->addPrimitiveSet(drawArrays);
geometry->setVertexArray(std::exchange(mVertices, nullptr));
geometry->setColorArray(std::exchange(mColors, nullptr), osg::Array::BIND_PER_VERTEX);
mGroup.addChild(geometry);
}
void DebugDraw::addVertex(osg::Vec3f&& position)
{
std::swap(position.y(), position.z());
mVertices->push_back(position * mRecastInvertedScaleFactor + mShift);
}
void DebugDraw::addColor(osg::Vec4f&& value)
{
mColors->push_back(value);
}
osg::ref_ptr<osg::StateSet> makeDetourGroupStateSet()
{
osg::ref_ptr<osg::Material> material = new osg::Material;
material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
const float polygonOffsetFactor = SceneUtil::AutoDepth::isReversed() ? 1.0 : -1.0;
const float polygonOffsetUnits = SceneUtil::AutoDepth::isReversed() ? 1.0 : -1.0;
osg::ref_ptr<osg::PolygonOffset> polygonOffset
= new osg::PolygonOffset(polygonOffsetFactor, polygonOffsetUnits);
osg::ref_ptr<osg::StateSet> stateSet = new osg::StateSet;
stateSet->setAttribute(material);
stateSet->setAttributeAndModes(polygonOffset);
return stateSet;
}
}
| 3,865
|
C++
|
.cpp
| 105
| 29.619048
| 113
| 0.647405
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,745
|
shadowsbin.cpp
|
OpenMW_openmw/components/sceneutil/shadowsbin.cpp
|
#include "shadowsbin.hpp"
#include <osg/AlphaFunc>
#include <osg/Material>
#include <osg/Program>
#include <osg/StateSet>
#include <osgUtil/StateGraph>
#include <unordered_set>
using namespace osgUtil;
namespace
{
template <typename T>
inline void accumulateState(T& currentValue, T newValue, bool& isOverride, unsigned int overrideFlags)
{
if (isOverride && !(overrideFlags & osg::StateAttribute::PROTECTED))
return;
if (overrideFlags & osg::StateAttribute::OVERRIDE)
isOverride = true;
currentValue = newValue;
}
inline void accumulateModeState(const osg::StateSet* ss, bool& currentValue, bool& isOverride, int mode)
{
const osg::StateSet::ModeList& l = ss->getModeList();
osg::StateSet::ModeList::const_iterator mf = l.find(mode);
if (mf == l.end())
return;
unsigned int flags = mf->second;
bool newValue = flags & osg::StateAttribute::ON;
accumulateState(currentValue, newValue, isOverride, flags);
}
inline bool materialNeedShadows(osg::Material* m)
{
// I'm pretty sure this needs to check the colour mode - vertex colours might override this value.
return m->getDiffuse(osg::Material::FRONT).a() > 0.5;
}
}
namespace SceneUtil
{
ShadowsBin::ShadowsBin(const CastingPrograms& castingPrograms)
{
mNoTestStateSet = new osg::StateSet;
mNoTestStateSet->addUniform(new osg::Uniform("useDiffuseMapForShadowAlpha", false));
mNoTestStateSet->addUniform(new osg::Uniform("alphaTestShadows", false));
mShaderAlphaTestStateSet = new osg::StateSet;
mShaderAlphaTestStateSet->addUniform(new osg::Uniform("alphaTestShadows", true));
mShaderAlphaTestStateSet->addUniform(new osg::Uniform("useDiffuseMapForShadowAlpha", true));
mShaderAlphaTestStateSet->setMode(
GL_BLEND, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED | osg::StateAttribute::OVERRIDE);
for (size_t i = 0; i < castingPrograms.size(); ++i)
{
mAlphaFuncShaders[i] = new osg::StateSet;
mAlphaFuncShaders[i]->setAttribute(castingPrograms[i],
osg::StateAttribute::ON | osg::StateAttribute::PROTECTED | osg::StateAttribute::OVERRIDE);
}
}
StateGraph* ShadowsBin::cullStateGraph(
StateGraph* sg, StateGraph* root, std::unordered_set<StateGraph*>& uninterestingCache, bool cullFaceOverridden)
{
std::vector<StateGraph*> return_path;
State state;
StateGraph* sg_new = sg;
do
{
if (uninterestingCache.find(sg_new) != uninterestingCache.end())
break;
return_path.push_back(sg_new);
sg_new = sg_new->_parent;
} while (sg_new && sg_new != root);
for (auto itr = return_path.rbegin(); itr != return_path.rend(); ++itr)
{
const osg::StateSet* ss = (*itr)->getStateSet();
if (!ss)
continue;
accumulateModeState(ss, state.mAlphaBlend, state.mAlphaBlendOverride, GL_BLEND);
const osg::StateSet::AttributeList& attributes = ss->getAttributeList();
osg::StateSet::AttributeList::const_iterator found
= attributes.find(std::make_pair(osg::StateAttribute::MATERIAL, 0));
if (found != attributes.end())
{
const osg::StateSet::RefAttributePair& rap = found->second;
accumulateState(
state.mMaterial, static_cast<osg::Material*>(rap.first.get()), state.mMaterialOverride, rap.second);
if (state.mMaterial && !materialNeedShadows(state.mMaterial))
state.mMaterial = nullptr;
}
found = attributes.find(std::make_pair(osg::StateAttribute::ALPHAFUNC, 0));
if (found != attributes.end())
{
// As force shaders is on, we know this is really a RemovedAlphaFunc
const osg::StateSet::RefAttributePair& rap = found->second;
accumulateState(state.mAlphaFunc, static_cast<osg::AlphaFunc*>(rap.first.get()),
state.mAlphaFuncOverride, rap.second);
}
if (!cullFaceOverridden)
{
// osg::FrontFace specifies triangle winding, not front-face culling. We can't safely reparent anything
// under it unless GL_CULL_FACE is off or we flip face culling.
found = attributes.find(std::make_pair(osg::StateAttribute::FRONTFACE, 0));
if (found != attributes.end())
state.mImportantState = true;
}
if ((*itr) != sg && !state.interesting())
uninterestingCache.insert(*itr);
}
if (!state.needShadows())
return nullptr;
if (!state.needTexture() && !state.mImportantState)
{
for (RenderLeaf* leaf : sg->_leaves)
{
leaf->_parent = root;
root->_leaves.push_back(leaf);
}
return nullptr;
}
if (state.mAlphaBlend)
{
sg_new = sg->find_or_insert(mShaderAlphaTestStateSet);
sg_new->_leaves = std::move(sg->_leaves);
for (RenderLeaf* leaf : sg_new->_leaves)
leaf->_parent = sg_new;
sg = sg_new;
}
// GL_ALWAYS is set by default by mwshadowtechnique
if (state.mAlphaFunc && state.mAlphaFunc->getFunction() != GL_ALWAYS)
{
sg_new = sg->find_or_insert(mAlphaFuncShaders[state.mAlphaFunc->getFunction() - GL_NEVER]);
sg_new->_leaves = std::move(sg->_leaves);
for (RenderLeaf* leaf : sg_new->_leaves)
leaf->_parent = sg_new;
sg = sg_new;
}
return sg;
}
inline bool ShadowsBin::State::needTexture() const
{
return mAlphaBlend || (mAlphaFunc && mAlphaFunc->getFunction() != GL_ALWAYS);
}
bool ShadowsBin::State::needShadows() const
{
if (mAlphaFunc && mAlphaFunc->getFunction() == GL_NEVER)
return false;
// other alpha func + material combinations might be skippable
if (mAlphaBlend && mMaterial)
return materialNeedShadows(mMaterial);
return true;
}
void ShadowsBin::sortImplementation()
{
// The cull visitor contains a stategraph.
// When a stateset is pushed, it's added/found as a child of the current stategraph node, then that node becomes
// the new current stategraph node. When a drawable is added, the current stategraph node is added to the
// current renderbin (if it's not there already) and the drawable is added as a renderleaf to the stategraph
// This means our list only contains stategraph nodes with directly-attached renderleaves, but they might have
// parents with more state set that needs to be considered.
if (!_stateGraphList.size())
return;
StateGraph* root = _stateGraphList[0];
while (root->_parent)
{
root = root->_parent;
const osg::StateSet* ss = root->getStateSet();
if (ss->getMode(GL_NORMALIZE) & osg::StateAttribute::ON // that is root stategraph of renderingmanager cpp
|| ss->getAttribute(osg::StateAttribute::VIEWPORT)) // fallback to rendertarget's sg just in case
break;
if (!root->_parent)
return;
}
StateGraph* noTestRoot = root->find_or_insert(mNoTestStateSet.get());
// noTestRoot is now a stategraph with useDiffuseMapForShadowAlpha disabled but minimal other state
bool cullFaceOverridden = false;
while (root->_parent)
{
root = root->_parent;
if (!root->getStateSet())
continue;
unsigned int cullFaceFlags = root->getStateSet()->getMode(GL_CULL_FACE);
if (cullFaceFlags & osg::StateAttribute::OVERRIDE && !(cullFaceFlags & osg::StateAttribute::ON))
{
cullFaceOverridden = true;
break;
}
}
noTestRoot->_leaves.reserve(_stateGraphList.size());
StateGraphList newList;
std::unordered_set<StateGraph*> uninterestingCache;
for (StateGraph* graph : _stateGraphList)
{
// Render leaves which shouldn't use the diffuse map for shadow alpha but do cast shadows become children of
// root, so graph is now empty. Don't add to newList. Graphs containing just render leaves which don't cast
// shadows are discarded. Don't add to newList. Graphs containing other leaves need to be in newList.
StateGraph* graphToAdd = cullStateGraph(graph, noTestRoot, uninterestingCache, cullFaceOverridden);
if (graphToAdd)
newList.push_back(graphToAdd);
}
if (!noTestRoot->_leaves.empty())
newList.push_back(noTestRoot);
_stateGraphList = std::move(newList);
}
}
| 9,177
|
C++
|
.cpp
| 199
| 35.60804
| 120
| 0.612402
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,746
|
optimizer.cpp
|
OpenMW_openmw/components/sceneutil/optimizer.cpp
|
// clang-format off
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
/* Modified for OpenMW */
#include "optimizer.hpp"
#include <osg/Transform>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/LOD>
#include <osg/Sequence>
#include <osg/Billboard>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/Timer>
#include <osg/io_utils>
#include <osg/Depth>
#include <osgDB/SharedStateManager>
#include <osgUtil/TransformAttributeFunctor>
#include <osgUtil/Statistics>
#include <osgUtil/MeshOptimizers>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <cassert>
#include <components/sceneutil/depth.hpp>
using namespace osgUtil;
namespace SceneUtil
{
void Optimizer::reset()
{
}
void Optimizer::optimize(osg::Node* node, unsigned int options)
{
StatsVisitor stats;
if (osg::getNotifyLevel()>=osg::INFO)
{
node->accept(stats);
stats.totalUpStats();
OSG_NOTICE<<std::endl<<"Stats before:"<<std::endl;
stats.print(osg::notify(osg::NOTICE));
}
if (options & FLATTEN_STATIC_TRANSFORMS)
{
OSG_INFO<<"Optimizer::optimize() doing FLATTEN_STATIC_TRANSFORMS"<<std::endl;
int i=0;
bool result = false;
do
{
OSG_DEBUG << "** RemoveStaticTransformsVisitor *** Pass "<<i<<std::endl;
FlattenStaticTransformsVisitor fstv(this);
node->accept(fstv);
result = fstv.removeTransforms(node);
++i;
} while (result);
// now combine any adjacent static transforms.
CombineStaticTransformsVisitor cstv(this);
node->accept(cstv);
cstv.removeTransforms(node);
}
if (options & SHARE_DUPLICATE_STATE && _sharedStateManager)
{
if (_sharedStateMutex) _sharedStateMutex->lock();
_sharedStateManager->share(node);
if (_sharedStateMutex) _sharedStateMutex->unlock();
}
if (options & REMOVE_REDUNDANT_NODES)
{
OSG_INFO<<"Optimizer::optimize() doing REMOVE_REDUNDANT_NODES"<<std::endl;
RemoveEmptyNodesVisitor renv(this);
node->accept(renv);
renv.removeEmptyNodes();
RemoveRedundantNodesVisitor rrnv(this);
node->accept(rrnv);
rrnv.removeRedundantNodes();
MergeGroupsVisitor mgrp(this);
node->accept(mgrp);
}
if (options & MERGE_GEOMETRY)
{
OSG_INFO<<"Optimizer::optimize() doing MERGE_GEOMETRY"<<std::endl;
osg::Timer_t startTick = osg::Timer::instance()->tick();
MergeGeometryVisitor mgv(this);
mgv.setTargetMaximumNumberOfVertices(1000000);
mgv.setMergeAlphaBlending(_mergeAlphaBlending);
mgv.setViewPoint(_viewPoint);
node->accept(mgv);
osg::Timer_t endTick = osg::Timer::instance()->tick();
OSG_INFO<<"MERGE_GEOMETRY took "<<osg::Timer::instance()->delta_s(startTick,endTick)<<std::endl;
}
if (options & VERTEX_POSTTRANSFORM)
{
OSG_INFO<<"Optimizer::optimize() doing VERTEX_POSTTRANSFORM"<<std::endl;
VertexCacheVisitor vcv;
node->accept(vcv);
vcv.optimizeVertices();
}
if (options & VERTEX_PRETRANSFORM)
{
OSG_INFO<<"Optimizer::optimize() doing VERTEX_PRETRANSFORM"<<std::endl;
VertexAccessOrderVisitor vaov;
node->accept(vaov);
vaov.optimizeOrder();
}
if (osg::getNotifyLevel()>=osg::INFO)
{
stats.reset();
node->accept(stats);
stats.totalUpStats();
OSG_NOTICE<<std::endl<<"Stats after:"<<std::endl;
stats.print(osg::notify(osg::NOTICE));
}
}
////////////////////////////////////////////////////////////////////////////
// Flatten static transforms
////////////////////////////////////////////////////////////////////////////
class CollectLowestTransformsVisitor : public BaseOptimizerVisitor
{
public:
CollectLowestTransformsVisitor(Optimizer* optimizer=0):
BaseOptimizerVisitor(optimizer,Optimizer::FLATTEN_STATIC_TRANSFORMS),
_transformFunctor(osg::Matrix())
{
setTraversalMode(osg::NodeVisitor::TRAVERSE_PARENTS);
}
void apply(osg::Group& node) override
{
if (node.getNumParents())
{
traverse(node);
}
else
{
// for all current objects mark a nullptr transform for them.
registerWithCurrentObjects(static_cast<osg::Transform*>(nullptr));
}
}
void apply(osg::LOD& lod) override
{
_currentObjectList.push_back(&lod);
traverse(lod);
_currentObjectList.pop_back();
}
void apply(osg::Transform& transform) override
{
// for all current objects associated this transform with them.
registerWithCurrentObjects(&transform);
}
void apply(osg::MatrixTransform& transform) override
{
// for all current objects associated this transform with them.
registerWithCurrentObjects(&transform);
}
void apply(osg::Node& node) override
{
traverse(node);
}
void apply(osg::Geometry& geometry) override
{
}
void collectDataFor(osg::Node* node)
{
_currentObjectList.push_back(node);
node->accept(*this);
_currentObjectList.pop_back();
}
void collectDataFor(osg::Billboard* billboard)
{
_currentObjectList.push_back(billboard);
billboard->accept(*this);
_currentObjectList.pop_back();
}
void collectDataFor(osg::Drawable* drawable)
{
_currentObjectList.push_back(drawable);
const osg::Drawable::ParentList& parents = drawable->getParents();
for(osg::Drawable::ParentList::const_iterator itr=parents.begin();
itr!=parents.end();
++itr)
{
(*itr)->accept(*this);
}
_currentObjectList.pop_back();
}
void setUpMaps();
void disableTransform(osg::Transform* transform);
bool removeTransforms(osg::Node* nodeWeCannotRemove);
inline bool isOperationPermissibleForObject(const osg::Object* object) const
{
const osg::Node* node = object->asNode();
if (node)
{
const osg::Drawable* drawable = node->asDrawable();
if (drawable)
return isOperationPermissibleForObject(drawable);
else
return isOperationPermissibleForObject(node);
}
return true;
}
inline bool isOperationPermissibleForObject(const osg::Drawable* drawable) const
{
return BaseOptimizerVisitor::isOperationPermissibleForObject(drawable);
}
inline bool isOperationPermissibleForObject(const osg::Node* node) const
{
return BaseOptimizerVisitor::isOperationPermissibleForObject(node);
}
protected:
struct TransformStruct
{
typedef std::set<osg::Object*> ObjectSet;
TransformStruct():_canBeApplied(true) {}
void add(osg::Object* obj)
{
_objectSet.insert(obj);
}
bool _canBeApplied;
ObjectSet _objectSet;
};
struct ObjectStruct
{
typedef std::set<osg::Transform*> TransformSet;
ObjectStruct():_canBeApplied(true),_moreThanOneMatrixRequired(false) {}
inline const osg::Matrix& getMatrix(osg::MatrixTransform* transform)
{
return transform->getMatrix();
}
osg::Matrix getMatrix(osg::Transform* transform)
{
osg::Matrix matrix;
transform->computeLocalToWorldMatrix(matrix, 0);
return matrix;
}
template<typename T>
void add(T* transform, bool canOptimize)
{
if (transform)
{
if (!canOptimize) _moreThanOneMatrixRequired=true;
else if (transform->getReferenceFrame()!=osg::Transform::RELATIVE_RF) _moreThanOneMatrixRequired=true;
else
{
if (_transformSet.empty()) _firstMatrix = getMatrix(transform);
else
{
if (_firstMatrix!=getMatrix(transform)) _moreThanOneMatrixRequired=true;
}
}
}
else
{
if (!_transformSet.empty())
{
if (!_firstMatrix.isIdentity()) _moreThanOneMatrixRequired=true;
}
}
_transformSet.insert(transform);
}
bool _canBeApplied;
bool _moreThanOneMatrixRequired;
osg::Matrix _firstMatrix;
TransformSet _transformSet;
};
template <typename T>
void registerWithCurrentObjects(T* transform)
{
for(ObjectList::iterator itr=_currentObjectList.begin();
itr!=_currentObjectList.end();
++itr)
{
_objectMap[*itr].add(transform, transform && isOperationPermissibleForObject(transform));
}
}
typedef std::map<osg::Transform*,TransformStruct> TransformMap;
typedef std::map<osg::Object*,ObjectStruct> ObjectMap;
typedef std::vector<osg::Object*> ObjectList;
void disableObject(osg::Object* object)
{
disableObject(_objectMap.find(object));
}
void disableObject(ObjectMap::iterator itr);
void doTransform(osg::Object* obj,osg::Matrix& matrix);
osgUtil::TransformAttributeFunctor _transformFunctor;
TransformMap _transformMap;
ObjectMap _objectMap;
ObjectList _currentObjectList;
};
void CollectLowestTransformsVisitor::doTransform(osg::Object* obj,osg::Matrix& matrix)
{
osg::Node* node = obj->asNode();
if (!node)
return;
osg::Drawable* drawable = node->asDrawable();
if (drawable)
{
osgUtil::TransformAttributeFunctor tf(matrix);
drawable->accept(tf);
osg::Geometry *geom = drawable->asGeometry();
osg::Vec4Array* tangents = geom ? dynamic_cast<osg::Vec4Array*>(geom->getTexCoordArray(7)) : nullptr;
if (tangents)
{
for (unsigned int i=0; i<tangents->size(); ++i)
{
osg::Vec4f& itr = (*tangents)[i];
osg::Vec3f vec3 (itr.x(), itr.y(), itr.z());
vec3 = osg::Matrix::transform3x3(tf._im, vec3);
vec3.normalize();
itr = osg::Vec4f(vec3.x(), vec3.y(), vec3.z(), itr.w());
}
}
drawable->dirtyBound();
drawable->dirtyDisplayList();
return;
}
osg::LOD* lod = dynamic_cast<osg::LOD*>(obj);
if (lod)
{
osg::Matrix matrix_no_trans = matrix;
matrix_no_trans.setTrans(0.0f,0.0f,0.0f);
osg::Vec3 v111(1.0f,1.0f,1.0f);
osg::Vec3 new_v111 = v111*matrix_no_trans;
float ratio = new_v111.length()/v111.length();
// move center point.
lod->setCenter(lod->getCenter()*matrix);
// adjust ranges to new scale.
for(unsigned int i=0;i<lod->getNumRanges();++i)
{
lod->setRange(i,lod->getMinRange(i)*ratio,lod->getMaxRange(i)*ratio);
}
lod->dirtyBound();
return;
}
osg::Billboard* billboard = dynamic_cast<osg::Billboard*>(obj);
if (billboard)
{
osg::Matrix matrix_no_trans = matrix;
matrix_no_trans.setTrans(0.0f,0.0f,0.0f);
osgUtil::TransformAttributeFunctor tf(matrix_no_trans);
osg::Vec3 axis = osg::Matrix::transform3x3(tf._im,billboard->getAxis());
axis.normalize();
billboard->setAxis(axis);
osg::Vec3 normal = osg::Matrix::transform3x3(tf._im,billboard->getNormal());
normal.normalize();
billboard->setNormal(normal);
for(unsigned int i=0;i<billboard->getNumDrawables();++i)
{
billboard->setPosition(i,billboard->getPosition(i)*matrix);
billboard->getDrawable(i)->accept(tf);
billboard->getDrawable(i)->dirtyBound();
}
billboard->dirtyBound();
return;
}
}
void CollectLowestTransformsVisitor::disableObject(ObjectMap::iterator itr)
{
if (itr==_objectMap.end())
{
return;
}
if (itr->second._canBeApplied)
{
// we haven't been disabled yet so we need to disable,
itr->second._canBeApplied = false;
// and then inform everybody we have been disabled.
for(ObjectStruct::TransformSet::iterator titr = itr->second._transformSet.begin();
titr != itr->second._transformSet.end();
++titr)
{
disableTransform(*titr);
}
}
}
void CollectLowestTransformsVisitor::disableTransform(osg::Transform* transform)
{
TransformMap::iterator itr=_transformMap.find(transform);
if (itr==_transformMap.end())
{
return;
}
if (itr->second._canBeApplied)
{
// we haven't been disabled yet so we need to disable,
itr->second._canBeApplied = false;
// and then inform everybody we have been disabled.
for(TransformStruct::ObjectSet::iterator oitr = itr->second._objectSet.begin();
oitr != itr->second._objectSet.end();
++oitr)
{
disableObject(*oitr);
}
}
}
void CollectLowestTransformsVisitor::setUpMaps()
{
// create the TransformMap from the ObjectMap
ObjectMap::iterator oitr;
for(oitr=_objectMap.begin();
oitr!=_objectMap.end();
++oitr)
{
osg::Object* object = oitr->first;
ObjectStruct& os = oitr->second;
for(ObjectStruct::TransformSet::iterator titr = os._transformSet.begin();
titr != os._transformSet.end();
++titr)
{
_transformMap[*titr].add(object);
}
}
// disable all the objects which have more than one matrix associated
// with them, and then disable all transforms which have an object associated
// them that can't be applied, and then disable all objects which have
// disabled transforms associated, recursing until all disabled
// associativity.
// and disable all objects that the operation is not permisable for)
for(oitr=_objectMap.begin();
oitr!=_objectMap.end();
++oitr)
{
osg::Object* object = oitr->first;
ObjectStruct& os = oitr->second;
if (os._canBeApplied)
{
if (os._moreThanOneMatrixRequired || !isOperationPermissibleForObject(object))
{
disableObject(oitr);
}
}
}
}
bool CollectLowestTransformsVisitor::removeTransforms(osg::Node* nodeWeCannotRemove)
{
// transform the objects that can be applied.
for(ObjectMap::iterator oitr=_objectMap.begin();
oitr!=_objectMap.end();
++oitr)
{
osg::Object* object = oitr->first;
ObjectStruct& os = oitr->second;
if (os._canBeApplied)
{
doTransform(object,os._firstMatrix);
}
}
bool transformRemoved = false;
// clean up the transforms.
for(TransformMap::iterator titr=_transformMap.begin();
titr!=_transformMap.end();
++titr)
{
if (titr->first!=0 && titr->second._canBeApplied)
{
if (titr->first!=nodeWeCannotRemove)
{
transformRemoved = true;
osg::ref_ptr<osg::Transform> transform = titr->first;
osg::ref_ptr<osg::Group> group = new osg::Group;
group->setName( transform->getName() );
group->setDataVariance(osg::Object::STATIC);
group->setNodeMask(transform->getNodeMask());
group->setStateSet(transform->getStateSet());
group->setUpdateCallback(transform->getUpdateCallback());
group->setEventCallback(transform->getEventCallback());
group->setCullCallback(transform->getCullCallback());
group->setUserDataContainer(transform->getUserDataContainer());
group->setDescriptions(transform->getDescriptions());
for(unsigned int i=0;i<transform->getNumChildren();++i)
{
group->addChild(transform->getChild(i));
}
for(int i2=transform->getNumParents()-1;i2>=0;--i2)
{
transform->getParent(i2)->replaceChild(transform.get(),group.get());
}
}
else
{
osg::MatrixTransform* mt = titr->first->asMatrixTransform();
if (mt) mt->setMatrix(osg::Matrix::identity());
else
{
osg::PositionAttitudeTransform* pat = titr->first->asPositionAttitudeTransform();
if (pat)
{
pat->setPosition(osg::Vec3(0.0f,0.0f,0.0f));
pat->setAttitude(osg::Quat());
pat->setPivotPoint(osg::Vec3(0.0f,0.0f,0.0f));
}
else
{
OSG_WARN<<"Warning:: during Optimize::CollectLowestTransformsVisitor::removeTransforms(Node*)"<<std::endl;
OSG_WARN<<" unhandled of setting of indentity matrix on "<< titr->first->className()<<std::endl;
OSG_WARN<<" model will appear in the incorrect position."<<std::endl;
}
}
}
}
}
_objectMap.clear();
_transformMap.clear();
return transformRemoved;
}
void Optimizer::FlattenStaticTransformsVisitor::apply(osg::Node& node)
{
traverse(node);
}
osg::Array* cloneArray(osg::Array* array, osg::VertexBufferObject*& vbo, const osg::Geometry* geom)
{
array = static_cast<osg::Array*>(array->clone(osg::CopyOp::DEEP_COPY_ALL));
if (!vbo) vbo = new osg::VertexBufferObject;
array->setVertexBufferObject(vbo);
return array;
}
void Optimizer::FlattenStaticTransformsVisitor::apply(osg::Geometry& geometry)
{
if(isOperationPermissibleForObject(&geometry))
{
osg::VertexBufferObject* vbo = nullptr;
if(geometry.getVertexArray() && geometry.getVertexArray()->referenceCount() > 1)
geometry.setVertexArray(cloneArray(geometry.getVertexArray(), vbo, &geometry));
if(geometry.getNormalArray() && geometry.getNormalArray()->referenceCount() > 1)
geometry.setNormalArray(cloneArray(geometry.getNormalArray(), vbo, &geometry));
if(geometry.getTexCoordArray(7) && geometry.getTexCoordArray(7)->referenceCount() > 1) // tangents
geometry.setTexCoordArray(7, cloneArray(geometry.getTexCoordArray(7), vbo, &geometry));
}
_drawableSet.insert(&geometry);
}
void Optimizer::FlattenStaticTransformsVisitor::apply(osg::Drawable& drawable)
{
_drawableSet.insert(&drawable);
}
void Optimizer::FlattenStaticTransformsVisitor::apply(osg::Billboard& billboard)
{
if (!_transformStack.empty())
{
_billboardSet.insert(&billboard);
}
}
void Optimizer::FlattenStaticTransformsVisitor::apply(osg::Transform& transform)
{
if (!_transformStack.empty())
{
// we need to disable any transform higher in the list.
_transformSet.insert(_transformStack.back());
}
_transformStack.push_back(&transform);
// simple traverse the children as if this Transform didn't exist.
traverse(transform);
_transformStack.pop_back();
}
void Optimizer::FlattenStaticTransformsVisitor::apply(osg::MatrixTransform& transform)
{
apply(static_cast<osg::Transform&>(transform));
}
bool Optimizer::FlattenStaticTransformsVisitor::removeTransforms(osg::Node* nodeWeCannotRemove)
{
CollectLowestTransformsVisitor cltv(_optimizer);
for(NodeSet::iterator nitr=_excludedNodeSet.begin();
nitr!=_excludedNodeSet.end();
++nitr)
{
cltv.collectDataFor(*nitr);
}
for(DrawableSet::iterator ditr=_drawableSet.begin();
ditr!=_drawableSet.end();
++ditr)
{
cltv.collectDataFor(*ditr);
}
for(BillboardSet::iterator bitr=_billboardSet.begin();
bitr!=_billboardSet.end();
++bitr)
{
cltv.collectDataFor(*bitr);
}
cltv.setUpMaps();
for(TransformSet::iterator titr=_transformSet.begin();
titr!=_transformSet.end();
++titr)
{
cltv.disableTransform(*titr);
}
return cltv.removeTransforms(nodeWeCannotRemove);
}
////////////////////////////////////////////////////////////////////////////
// CombineStaticTransforms
////////////////////////////////////////////////////////////////////////////
void Optimizer::CombineStaticTransformsVisitor::apply(osg::MatrixTransform& transform)
{
if (transform.getDataVariance()==osg::Object::STATIC &&
transform.getNumChildren()==1 &&
transform.getChild(0)->asTransform()!=0 &&
transform.getChild(0)->asTransform()->asMatrixTransform()!=0 &&
transform.getChild(0)->asTransform()->getDataVariance()==osg::Object::STATIC &&
isOperationPermissibleForObject(&transform) && isOperationPermissibleForObject(transform.getChild(0)))
{
_transformSet.insert(&transform);
}
traverse(transform);
}
bool Optimizer::CombineStaticTransformsVisitor::removeTransforms(osg::Node* nodeWeCannotRemove)
{
if (nodeWeCannotRemove && nodeWeCannotRemove->asTransform()!=0 && nodeWeCannotRemove->asTransform()->asMatrixTransform()!=0)
{
// remove topmost node from transform set if it exists there.
TransformSet::iterator itr = _transformSet.find(nodeWeCannotRemove->asTransform()->asMatrixTransform());
if (itr!=_transformSet.end()) _transformSet.erase(itr);
}
bool transformRemoved = false;
while (!_transformSet.empty())
{
// get the first available transform to combine.
osg::ref_ptr<osg::MatrixTransform> transform = *_transformSet.begin();
_transformSet.erase(_transformSet.begin());
if (transform->getNumChildren()==1 &&
transform->getChild(0)->asTransform()!=0 &&
transform->getChild(0)->asTransform()->asMatrixTransform()!=0 &&
(!transform->getChild(0)->getStateSet() || transform->getChild(0)->getStateSet()->referenceCount()==1) &&
transform->getChild(0)->getDataVariance()==osg::Object::STATIC)
{
// now combine with its child.
osg::MatrixTransform* child = transform->getChild(0)->asTransform()->asMatrixTransform();
osg::Matrix newMatrix = child->getMatrix()*transform->getMatrix();
child->setMatrix(newMatrix);
if (transform->getStateSet())
{
if(child->getStateSet()) child->getStateSet()->merge(*transform->getStateSet());
else child->setStateSet(transform->getStateSet());
}
transformRemoved = true;
osg::Node::ParentList parents = transform->getParents();
for(osg::Node::ParentList::iterator pitr=parents.begin();
pitr!=parents.end();
++pitr)
{
(*pitr)->replaceChild(transform.get(),child);
}
}
}
return transformRemoved;
}
////////////////////////////////////////////////////////////////////////////
// RemoveEmptyNodes.
////////////////////////////////////////////////////////////////////////////
void Optimizer::RemoveEmptyNodesVisitor::apply(osg::Group& group)
{
if (group.getNumParents()>0)
{
// only remove empty groups, but not empty occluders.
if (group.getNumChildren()==0 && isOperationPermissibleForObject(&group) &&
(typeid(group)==typeid(osg::Group) || (group.asTransform())) &&
(group.getNumChildrenRequiringUpdateTraversal()==0 && group.getNumChildrenRequiringEventTraversal()==0) )
{
_redundantNodeList.insert(&group);
}
}
traverse(group);
}
void Optimizer::RemoveEmptyNodesVisitor::removeEmptyNodes()
{
NodeList newEmptyGroups;
// keep iterator through until scene graph is cleaned of empty nodes.
while (!_redundantNodeList.empty())
{
for(NodeList::iterator itr=_redundantNodeList.begin();
itr!=_redundantNodeList.end();
++itr)
{
osg::ref_ptr<osg::Node> nodeToRemove = (*itr);
// take a copy of parents list since subsequent removes will modify the original one.
osg::Node::ParentList parents = nodeToRemove->getParents();
for(osg::Node::ParentList::iterator pitr=parents.begin();
pitr!=parents.end();
++pitr)
{
osg::Group* parent = *pitr;
if (!parent->asSwitch() && !dynamic_cast<osg::LOD*>(parent) && !dynamic_cast<osg::Sequence*>(parent))
{
parent->removeChild(nodeToRemove.get());
if (parent->getNumChildren()==0 && isOperationPermissibleForObject(parent)) newEmptyGroups.insert(parent);
}
}
}
_redundantNodeList.clear();
_redundantNodeList.swap(newEmptyGroups);
}
}
////////////////////////////////////////////////////////////////////////////
// RemoveRedundantNodes.
////////////////////////////////////////////////////////////////////////////
bool Optimizer::RemoveRedundantNodesVisitor::isOperationPermissible(osg::Node& node)
{
return node.getNumParents()>0 &&
!node.getStateSet() &&
!node.getCullCallback() &&
!node.getEventCallback() &&
!node.getUpdateCallback() &&
isOperationPermissibleForObject(&node);
}
void Optimizer::RemoveRedundantNodesVisitor::apply(osg::LOD& lod)
{
// don't remove any direct children of the LOD because they are used to define each LOD level.
for (unsigned int i=0; i<lod.getNumChildren(); ++i)
traverse(*lod.getChild(i));
}
void Optimizer::RemoveRedundantNodesVisitor::apply(osg::Switch& switchNode)
{
// We should keep all switch child nodes since they reflect different switch states.
for (unsigned int i=0; i<switchNode.getNumChildren(); ++i)
traverse(*switchNode.getChild(i));
}
void Optimizer::RemoveRedundantNodesVisitor::apply(osg::Sequence& sequenceNode)
{
// We should keep all sequence child nodes since they reflect different sequence states.
for (unsigned int i=0; i<sequenceNode.getNumChildren(); ++i)
traverse(*sequenceNode.getChild(i));
}
void Optimizer::RemoveRedundantNodesVisitor::apply(osg::Group& group)
{
if (typeid(group)==typeid(osg::Group) &&
isOperationPermissible(group))
{
_redundantNodeList.insert(&group);
}
traverse(group);
}
void Optimizer::RemoveRedundantNodesVisitor::apply(osg::Transform& transform)
{
if (transform.getDataVariance()==osg::Object::STATIC &&
isOperationPermissible(transform))
{
osg::Matrix matrix;
transform.computeWorldToLocalMatrix(matrix,nullptr);
if (matrix.isIdentity())
{
_redundantNodeList.insert(&transform);
}
}
traverse(transform);
}
void Optimizer::RemoveRedundantNodesVisitor::removeRedundantNodes()
{
for(NodeList::iterator itr=_redundantNodeList.begin();
itr!=_redundantNodeList.end();
++itr)
{
osg::ref_ptr<osg::Group> group = (*itr)->asGroup();
if (group.valid())
{
// take a copy of parents list since subsequent removes will modify the original one.
osg::Node::ParentList parents = group->getParents();
for(osg::Node::ParentList::iterator pitr=parents.begin();
pitr!=parents.end();
++pitr)
{
unsigned int childIndex = (*pitr)->getChildIndex(group);
for (unsigned int i=0; i<group->getNumChildren(); ++i)
{
if (i==0)
(*pitr)->setChild(childIndex, group->getChild(i));
else
(*pitr)->insertChild(childIndex+i, group->getChild(i));
}
}
group->removeChildren(0, group->getNumChildren());
}
else
{
OSG_WARN<<"Optimizer::RemoveRedundantNodesVisitor::removeRedundantNodes() - failed dynamic_cast"<<std::endl;
}
}
_redundantNodeList.clear();
}
////////////////////////////////////////////////////////////////////////////
// code to merge geometry object which share, state, and attribute bindings.
////////////////////////////////////////////////////////////////////////////
#define COMPARE_BINDING(lhs, rhs) \
if (osg::getBinding(lhs)<osg::getBinding(rhs)) return true; \
if (osg::getBinding(rhs)<osg::getBinding(lhs)) return false;
struct LessGeometry
{
bool operator() (const osg::ref_ptr<osg::Geometry>& lhs,const osg::ref_ptr<osg::Geometry>& rhs) const
{
if (lhs->getStateSet()<rhs->getStateSet()) return true;
if (rhs->getStateSet()<lhs->getStateSet()) return false;
COMPARE_BINDING(lhs->getNormalArray(), rhs->getNormalArray())
COMPARE_BINDING(lhs->getColorArray(), rhs->getColorArray())
COMPARE_BINDING(lhs->getSecondaryColorArray(), rhs->getSecondaryColorArray())
COMPARE_BINDING(lhs->getFogCoordArray(), rhs->getFogCoordArray())
if (lhs->getNumTexCoordArrays()<rhs->getNumTexCoordArrays()) return true;
if (rhs->getNumTexCoordArrays()<lhs->getNumTexCoordArrays()) return false;
// therefore lhs->getNumTexCoordArrays()==rhs->getNumTexCoordArrays()
unsigned int i;
for(i=0;i<lhs->getNumTexCoordArrays();++i)
{
if (rhs->getTexCoordArray(i))
{
if (!lhs->getTexCoordArray(i)) return true;
}
else if (lhs->getTexCoordArray(i)) return false;
}
for(i=0;i<lhs->getNumVertexAttribArrays();++i)
{
if (rhs->getVertexAttribArray(i))
{
if (!lhs->getVertexAttribArray(i)) return true;
}
else if (lhs->getVertexAttribArray(i)) return false;
}
if (osg::getBinding(lhs->getNormalArray())==osg::Array::BIND_OVERALL)
{
// assumes that the bindings and arrays are set up correctly, this
// should be the case after running computeCorrectBindingsAndArraySizes();
const osg::Array* lhs_normalArray = lhs->getNormalArray();
const osg::Array* rhs_normalArray = rhs->getNormalArray();
if (lhs_normalArray->getType()<rhs_normalArray->getType()) return true;
if (rhs_normalArray->getType()<lhs_normalArray->getType()) return false;
switch(lhs_normalArray->getType())
{
case(osg::Array::Vec3bArrayType):
if ((*static_cast<const osg::Vec3bArray*>(lhs_normalArray))[0]<(*static_cast<const osg::Vec3bArray*>(rhs_normalArray))[0]) return true;
if ((*static_cast<const osg::Vec3bArray*>(rhs_normalArray))[0]<(*static_cast<const osg::Vec3bArray*>(lhs_normalArray))[0]) return false;
break;
case(osg::Array::Vec3sArrayType):
if ((*static_cast<const osg::Vec3sArray*>(lhs_normalArray))[0]<(*static_cast<const osg::Vec3sArray*>(rhs_normalArray))[0]) return true;
if ((*static_cast<const osg::Vec3sArray*>(rhs_normalArray))[0]<(*static_cast<const osg::Vec3sArray*>(lhs_normalArray))[0]) return false;
break;
case(osg::Array::Vec3ArrayType):
if ((*static_cast<const osg::Vec3Array*>(lhs_normalArray))[0]<(*static_cast<const osg::Vec3Array*>(rhs_normalArray))[0]) return true;
if ((*static_cast<const osg::Vec3Array*>(rhs_normalArray))[0]<(*static_cast<const osg::Vec3Array*>(lhs_normalArray))[0]) return false;
break;
default:
break;
}
}
if (osg::getBinding(lhs->getColorArray())==osg::Array::BIND_OVERALL)
{
const osg::Array* lhs_colorArray = lhs->getColorArray();
const osg::Array* rhs_colorArray = rhs->getColorArray();
if (lhs_colorArray->getType()<rhs_colorArray->getType()) return true;
if (rhs_colorArray->getType()<lhs_colorArray->getType()) return false;
switch(lhs_colorArray->getType())
{
case(osg::Array::Vec4ubArrayType):
if ((*static_cast<const osg::Vec4ubArray*>(lhs_colorArray))[0]<(*static_cast<const osg::Vec4ubArray*>(rhs_colorArray))[0]) return true;
if ((*static_cast<const osg::Vec4ubArray*>(rhs_colorArray))[0]<(*static_cast<const osg::Vec4ubArray*>(lhs_colorArray))[0]) return false;
break;
case(osg::Array::Vec3ArrayType):
if ((*static_cast<const osg::Vec3Array*>(lhs_colorArray))[0]<(*static_cast<const osg::Vec3Array*>(rhs_colorArray))[0]) return true;
if ((*static_cast<const osg::Vec3Array*>(rhs_colorArray))[0]<(*static_cast<const osg::Vec3Array*>(lhs_colorArray))[0]) return false;
break;
case(osg::Array::Vec4ArrayType):
if ((*static_cast<const osg::Vec4Array*>(lhs_colorArray))[0]<(*static_cast<const osg::Vec4Array*>(rhs_colorArray))[0]) return true;
if ((*static_cast<const osg::Vec4Array*>(rhs_colorArray))[0]<(*static_cast<const osg::Vec4Array*>(lhs_colorArray))[0]) return false;
break;
default:
break;
}
}
return false;
}
};
struct LessGeometryViewPoint
{
osg::Vec3f _viewPoint;
bool operator() (const osg::ref_ptr<osg::Geometry>& lhs,const osg::ref_ptr<osg::Geometry>& rhs) const
{
float len1 = (lhs->getBoundingBox().center() - _viewPoint).length2();
float len2 = (rhs->getBoundingBox().center() - _viewPoint).length2();
return len2 < len1;
}
};
struct LessGeometryPrimitiveType
{
bool operator() (const osg::ref_ptr<osg::Geometry>& lhs,const osg::ref_ptr<osg::Geometry>& rhs) const
{
for(unsigned int i=0;
i<lhs->getNumPrimitiveSets() && i<rhs->getNumPrimitiveSets();
++i)
{
if (lhs->getPrimitiveSet(i)->getType()<rhs->getPrimitiveSet(i)->getType()) return true;
else if (rhs->getPrimitiveSet(i)->getType()<lhs->getPrimitiveSet(i)->getType()) return false;
if (lhs->getPrimitiveSet(i)->getMode()<rhs->getPrimitiveSet(i)->getMode()) return true;
else if (rhs->getPrimitiveSet(i)->getMode()<lhs->getPrimitiveSet(i)->getMode()) return false;
}
return lhs->getNumPrimitiveSets()<rhs->getNumPrimitiveSets();
}
};
/// Shortcut to get size of an array, even if pointer is nullptr.
inline unsigned int getSize(const osg::Array * a) { return a ? a->getNumElements() : 0; }
/// When merging geometries, tests if two arrays can be merged, regarding to their number of components, and the number of vertices.
bool isArrayCompatible(unsigned int numVertice1, unsigned int numVertice2, const osg::Array* compare1, const osg::Array* compare2)
{
// Sumed up truth table:
// If array (1 or 2) not empty and vertices empty => error, should not happen (allows simplification in formulae below)
// If one side has both vertices and array, and the other side has only vertices => then arrays cannot be merged
// Else, arrays can be merged
//assert(numVertice1 || !getSize(compare1));
//assert(numVertice2 || !getSize(compare2));
return !( (numVertice1 && !getSize(compare1) && getSize(compare2))
|| (numVertice2 && !getSize(compare2) && getSize(compare1)) );
}
/// Return true only if both geometries have same array type and if arrays (such as TexCoords) are compatible (i.e. both empty or both filled)
bool isAbleToMerge(const osg::Geometry& g1, const osg::Geometry& g2)
{
unsigned int numVertice1( getSize(g1.getVertexArray()) );
unsigned int numVertice2( getSize(g2.getVertexArray()) );
// first verify arrays size
if (!isArrayCompatible(numVertice1,numVertice2,g1.getNormalArray(),g2.getNormalArray()) ||
!isArrayCompatible(numVertice1,numVertice2,g1.getColorArray(),g2.getColorArray()) ||
!isArrayCompatible(numVertice1,numVertice2,g1.getSecondaryColorArray(),g2.getSecondaryColorArray()) ||
!isArrayCompatible(numVertice1,numVertice2,g1.getFogCoordArray(),g2.getFogCoordArray()) ||
g1.getNumTexCoordArrays()!=g2.getNumTexCoordArrays()) return false;
for (unsigned int eachTexCoordArray=0;eachTexCoordArray<g1.getNumTexCoordArrays();++eachTexCoordArray)
{
if (!isArrayCompatible(numVertice1,numVertice2,g1.getTexCoordArray(eachTexCoordArray),g2.getTexCoordArray(eachTexCoordArray))) return false;
}
// then verify data type compatibility
if (g1.getVertexArray() && g2.getVertexArray() && g1.getVertexArray()->getDataType()!=g2.getVertexArray()->getDataType()) return false;
if (g1.getNormalArray() && g2.getNormalArray() && g1.getNormalArray()->getDataType()!=g2.getNormalArray()->getDataType()) return false;
if (g1.getColorArray() && g2.getColorArray() && g1.getColorArray()->getDataType()!=g2.getColorArray()->getDataType()) return false;
if (g1.getSecondaryColorArray() && g2.getSecondaryColorArray() && g1.getSecondaryColorArray()->getDataType()!=g2.getSecondaryColorArray()->getDataType()) return false;
if (g1.getFogCoordArray() && g2.getNormalArray() && g1.getFogCoordArray()->getDataType()!=g2.getFogCoordArray()->getDataType()) return false;
return true;
}
bool Optimizer::MergeGeometryVisitor::pushStateSet(osg::StateSet *stateSet)
{
if (!stateSet || stateSet->getRenderBinMode() & osg::StateSet::INHERIT_RENDERBIN_DETAILS)
return false;
_stateSetStack.push_back(stateSet);
checkAlphaBlendingActive();
return true;
}
void Optimizer::MergeGeometryVisitor::popStateSet()
{
_stateSetStack.pop_back();
checkAlphaBlendingActive();
}
void Optimizer::MergeGeometryVisitor::checkAlphaBlendingActive()
{
int renderingHint = 0;
bool override = false;
for (std::vector<osg::StateSet*>::const_iterator it = _stateSetStack.begin(); it != _stateSetStack.end(); ++it)
{
osg::StateSet* stateSet = *it;
osg::StateSet::RenderBinMode mode = stateSet->getRenderBinMode();
if (override && !(mode & osg::StateSet::PROTECTED_RENDERBIN_DETAILS))
continue;
if (mode & osg::StateSet::USE_RENDERBIN_DETAILS)
renderingHint = stateSet->getRenderingHint();
if (mode & osg::StateSet::OVERRIDE_RENDERBIN_DETAILS)
override = true;
}
// Can't merge Geometry that are using a transparent sorting bin as that would cause the sorting to break.
_alphaBlendingActive = renderingHint == osg::StateSet::TRANSPARENT_BIN;
}
void Optimizer::MergeGeometryVisitor::apply(osg::Group &group)
{
bool pushed = pushStateSet(group.getStateSet());
if (!_alphaBlendingActive || _mergeAlphaBlending)
mergeGroup(group);
traverse(group);
if (pushed)
popStateSet();
}
osg::PrimitiveSet* clonePrimitive(osg::PrimitiveSet* ps, osg::ElementBufferObject*& ebo, const osg::Geometry* geom)
{
if (ps->referenceCount() <= 1)
return ps;
ps = static_cast<osg::PrimitiveSet*>(ps->clone(osg::CopyOp::DEEP_COPY_ALL));
osg::DrawElements* drawElements = ps->getDrawElements();
if (!drawElements) return ps;
if (!ebo) ebo = new osg::ElementBufferObject;
drawElements->setElementBufferObject(ebo);
return ps;
}
bool containsSharedPrimitives(const osg::Geometry* geom)
{
for (unsigned int i=0; i<geom->getNumPrimitiveSets(); ++i)
if (geom->getPrimitiveSet(i)->referenceCount() > 1) return true;
return false;
}
// clang-format on
namespace
{
unsigned getArraySizeOrZero(const osg::Array* array)
{
return array == nullptr ? 0 : array->getNumElements();
}
void fillArraySizes(const std::vector<osg::ref_ptr<osg::Array>>& arrays, std::vector<unsigned>& sizes)
{
sizes.reserve(arrays.size());
for (const auto& array : arrays)
sizes.push_back(getArraySizeOrZero(array));
}
void initArraySizes(const osg::Geometry& geometry, Optimizer::GeometryArraySizes& sizes)
{
sizes.mVertex = getArraySizeOrZero(geometry.getVertexArray());
sizes.mNormal = getArraySizeOrZero(geometry.getNormalArray());
sizes.mColor = getArraySizeOrZero(geometry.getColorArray());
sizes.mSecondaryColor = getArraySizeOrZero(geometry.getSecondaryColorArray());
sizes.mFogCoord = getArraySizeOrZero(geometry.getFogCoordArray());
sizes.mTexCoord.clear();
sizes.mVertexAttrib.clear();
fillArraySizes(geometry.getTexCoordArrayList(), sizes.mTexCoord);
fillArraySizes(geometry.getVertexAttribArrayList(), sizes.mVertexAttrib);
}
void addArraySize(const osg::Array* array, unsigned& size)
{
if (array != nullptr)
size += array->getNumElements();
}
void addArraySizes(const std::vector<osg::ref_ptr<osg::Array>>& dst,
const std::vector<osg::ref_ptr<osg::Array>>& src, std::vector<unsigned>& sizes)
{
assert(sizes.size() == dst.size());
for (std::size_t i = 0, n = std::min(dst.size(), src.size()); i < n; ++i)
if (osg::Array* const array = src[i])
sizes[i] += array->getNumElements();
}
void addArraysSizes(const osg::Geometry& dst, const osg::Geometry& src, Optimizer::GeometryArraySizes& sizes)
{
addArraySize(src.getVertexArray(), sizes.mVertex);
addArraySize(src.getNormalArray(), sizes.mNormal);
addArraySize(src.getColorArray(), sizes.mColor);
addArraySize(src.getSecondaryColorArray(), sizes.mSecondaryColor);
addArraySize(src.getFogCoordArray(), sizes.mFogCoord);
addArraySizes(dst.getTexCoordArrayList(), src.getTexCoordArrayList(), sizes.mTexCoord);
addArraySizes(dst.getVertexAttribArrayList(), src.getVertexAttribArrayList(), sizes.mVertexAttrib);
}
}
// clang-format off
bool Optimizer::MergeGeometryVisitor::mergeGroup(osg::Group& group)
{
if (!isOperationPermissibleForObject(&group)) return false;
if (group.getNumChildren()>=2)
{
typedef std::vector< osg::ref_ptr<osg::Geometry> > DuplicateList;
typedef std::vector< osg::ref_ptr<osg::Node> > Nodes;
typedef std::map< osg::ref_ptr<osg::Geometry> ,DuplicateList,LessGeometry> GeometryDuplicateMap;
typedef std::vector<DuplicateList> MergeList;
GeometryDuplicateMap geometryDuplicateMap;
Nodes standardChildren;
unsigned int i;
for(i=0;i<group.getNumChildren();++i)
{
osg::Node* child = group.getChild(i);
osg::Geometry* geom = child->asGeometry();
if (geom)
{
if (
geom->getDataVariance()!=osg::Object::DYNAMIC &&
isOperationPermissibleForObject(geom))
{
geometryDuplicateMap[geom].push_back(geom);
}
else
{
standardChildren.push_back(geom);
}
}
else
{
standardChildren.push_back(child);
}
}
// first try to group geometries with the same properties
// (i.e. array types) to avoid loss of data during merging
MergeList mergeListChecked; // List of drawables just before merging, grouped by "compatibility" and vertex limit
MergeList mergeList; // Intermediate list of drawables, grouped ony by "compatibility"
for(GeometryDuplicateMap::iterator itr=geometryDuplicateMap.begin();
itr!=geometryDuplicateMap.end();
++itr)
{
if (itr->second.empty()) continue;
if (itr->second.size()==1)
{
mergeList.push_back(DuplicateList());
DuplicateList* duplicateList = &mergeList.back();
duplicateList->push_back(itr->second[0]);
continue;
}
std::sort(itr->second.begin(),itr->second.end(),LessGeometryPrimitiveType());
// initialize the temporary list by pushing the first geometry
MergeList mergeListTmp;
mergeListTmp.push_back(DuplicateList());
DuplicateList* duplicateList = &mergeListTmp.back();
duplicateList->push_back(itr->second[0]);
for(DuplicateList::iterator dupItr=itr->second.begin()+1;
dupItr!=itr->second.end();
++dupItr)
{
osg::Geometry* geomToPush = dupItr->get();
// try to group geomToPush with another geometry
MergeList::iterator eachMergeList=mergeListTmp.begin();
for(;eachMergeList!=mergeListTmp.end();++eachMergeList)
{
if (!eachMergeList->empty() && eachMergeList->front()!=nullptr
&& isAbleToMerge(*eachMergeList->front(),*geomToPush))
{
eachMergeList->push_back(geomToPush);
break;
}
}
// if no suitable group was found, then a new one is created
if (eachMergeList==mergeListTmp.end())
{
mergeListTmp.push_back(DuplicateList());
duplicateList = &mergeListTmp.back();
duplicateList->push_back(geomToPush);
}
}
// copy the group in the mergeListChecked
for(MergeList::iterator eachMergeList=mergeListTmp.begin();eachMergeList!=mergeListTmp.end();++eachMergeList)
{
mergeListChecked.push_back(*eachMergeList);
}
}
// then build merge list using _targetMaximumNumberOfVertices
bool needToDoMerge = false;
// dequeue each DuplicateList when vertices limit is reached or when all elements has been checked
for(MergeList::iterator itr=mergeListChecked.begin(); itr!=mergeListChecked.end(); ++itr)
{
DuplicateList& duplicateList(*itr);
if (duplicateList.size()==0)
{
continue;
}
if (duplicateList.size()==1)
{
mergeList.push_back(duplicateList);
continue;
}
unsigned int totalNumberVertices = 0;
DuplicateList subset;
for(DuplicateList::iterator ditr = duplicateList.begin();
ditr != duplicateList.end();
++ditr)
{
osg::Geometry* geometry = ditr->get();
unsigned int numVertices = (geometry->getVertexArray() ? geometry->getVertexArray()->getNumElements() : 0);
if ((totalNumberVertices+numVertices)>_targetMaximumNumberOfVertices && !subset.empty())
{
mergeList.push_back(subset);
subset.clear();
totalNumberVertices = 0;
}
totalNumberVertices += numVertices;
subset.push_back(geometry);
if (subset.size()>1) needToDoMerge = true;
}
if (!subset.empty()) mergeList.push_back(subset);
}
if (needToDoMerge)
{
// to avoid performance issues associated with incrementally removing a large number children, we remove them all and add back the ones we need.
group.removeChildren(0, group.getNumChildren());
for(Nodes::iterator itr = standardChildren.begin();
itr != standardChildren.end();
++itr)
{
group.addChild(*itr);
}
// Place outside the loop to keep vectors allocated
GeometryArraySizes sizes;
// now do the merging of geometries
for(MergeList::iterator mitr = mergeList.begin();
mitr != mergeList.end();
++mitr)
{
DuplicateList& duplicateList = *mitr;
if (!duplicateList.empty())
{
if (_alphaBlendingActive)
{
LessGeometryViewPoint lgvp;
lgvp._viewPoint = _viewPoint;
std::sort(duplicateList.begin(), duplicateList.end(), lgvp);
}
DuplicateList::iterator ditr = duplicateList.begin();
osg::ref_ptr<osg::Geometry> lhs = *ditr++;
initArraySizes(*lhs, sizes);
for (auto it = ditr; it != duplicateList.end(); ++it)
addArraysSizes(*lhs, **it, sizes);
group.addChild(lhs.get());
for(;
ditr != duplicateList.end();
++ditr)
{
mergeGeometry(*lhs, **ditr, sizes);
}
}
}
}
}
// convert all polygon primitives which has 3 indices into TRIANGLES, 4 indices into QUADS.
unsigned int i;
for(i=0;i<group.getNumChildren();++i)
{
osg::Drawable* drawable = group.getChild(i)->asDrawable();
if (!drawable)
continue;
osg::Geometry* geom = drawable->asGeometry();
osg::ElementBufferObject* ebo = nullptr;
if (geom)
{
osg::Geometry::PrimitiveSetList& primitives = geom->getPrimitiveSetList();
for(osg::Geometry::PrimitiveSetList::iterator itr=primitives.begin();
itr!=primitives.end();
++itr)
{
osg::PrimitiveSet* prim = itr->get();
if (prim->getMode()==osg::PrimitiveSet::POLYGON)
{
if (prim->getNumIndices()==3)
{
prim = clonePrimitive(prim, ebo, geom); (*itr) = prim;
prim->setMode(osg::PrimitiveSet::TRIANGLES);
}
else if (prim->getNumIndices()==4)
{
prim = clonePrimitive(prim, ebo, geom); (*itr) = prim;
prim->setMode(osg::PrimitiveSet::QUADS);
}
}
}
}
}
// now merge any compatible primitives.
for(i=0;i<group.getNumChildren();++i)
{
osg::Drawable* drawable = group.getChild(i)->asDrawable();
if (!drawable)
continue;
osg::Geometry* geom = drawable->asGeometry();
osg::ElementBufferObject* ebo = nullptr;
if (geom)
{
if (geom->getNumPrimitiveSets()>0 &&
osg::getBinding(geom->getNormalArray())!=osg::Array::BIND_PER_PRIMITIVE_SET &&
osg::getBinding(geom->getColorArray())!=osg::Array::BIND_PER_PRIMITIVE_SET &&
osg::getBinding(geom->getSecondaryColorArray())!=osg::Array::BIND_PER_PRIMITIVE_SET &&
osg::getBinding(geom->getFogCoordArray())!=osg::Array::BIND_PER_PRIMITIVE_SET)
{
#if 1
bool doneCombine = false;
std::set<osg::PrimitiveSet*> toremove;
osg::Geometry::PrimitiveSetList& primitives = geom->getPrimitiveSetList();
unsigned int lhsNo=0;
unsigned int rhsNo=1;
while(rhsNo<primitives.size())
{
osg::PrimitiveSet* lhs = primitives[lhsNo].get();
osg::PrimitiveSet* rhs = primitives[rhsNo].get();
bool combine = false;
if (lhs->getType()==rhs->getType() &&
lhs->getMode()==rhs->getMode())
{
switch(lhs->getMode())
{
case(osg::PrimitiveSet::POINTS):
case(osg::PrimitiveSet::LINES):
case(osg::PrimitiveSet::TRIANGLES):
case(osg::PrimitiveSet::QUADS):
combine = true;
break;
}
}
if (combine)
{
lhs = clonePrimitive(lhs, ebo, geom);
primitives[lhsNo] = lhs;
switch(lhs->getType())
{
case(osg::PrimitiveSet::DrawArraysPrimitiveType):
combine = mergePrimitive(*(static_cast<osg::DrawArrays*>(lhs)),*(static_cast<osg::DrawArrays*>(rhs)));
break;
case(osg::PrimitiveSet::DrawArrayLengthsPrimitiveType):
combine = mergePrimitive(*(static_cast<osg::DrawArrayLengths*>(lhs)),*(static_cast<osg::DrawArrayLengths*>(rhs)));
break;
case(osg::PrimitiveSet::DrawElementsUBytePrimitiveType):
combine = mergePrimitive(*(static_cast<osg::DrawElementsUByte*>(lhs)),*(static_cast<osg::DrawElementsUByte*>(rhs)));
break;
case(osg::PrimitiveSet::DrawElementsUShortPrimitiveType):
combine = mergePrimitive(*(static_cast<osg::DrawElementsUShort*>(lhs)),*(static_cast<osg::DrawElementsUShort*>(rhs)));
break;
case(osg::PrimitiveSet::DrawElementsUIntPrimitiveType):
combine = mergePrimitive(*(static_cast<osg::DrawElementsUInt*>(lhs)),*(static_cast<osg::DrawElementsUInt*>(rhs)));
break;
default:
combine = false;
break;
}
}
if (combine)
{
// make this primitive set as invalid and needing cleaning up.
toremove.insert(rhs);
doneCombine = true;
++rhsNo;
}
else
{
lhsNo = rhsNo;
++rhsNo;
}
}
#if 1
if (doneCombine)
{
// now need to clean up primitiveset so it no longer contains the rhs combined primitives.
// first swap with a empty primitiveSet to empty it completely.
osg::Geometry::PrimitiveSetList oldPrimitives;
primitives.swap(oldPrimitives);
// now add the active primitive sets
for(osg::Geometry::PrimitiveSetList::iterator pitr = oldPrimitives.begin();
pitr != oldPrimitives.end();
++pitr)
{
if (!toremove.count(*pitr)) primitives.push_back(*pitr);
}
}
#endif
#else
osg::Geometry::PrimitiveSetList& primitives = geom->getPrimitiveSetList();
unsigned int primNo=0;
while(primNo+1<primitives.size())
{
osg::PrimitiveSet* lhs = primitives[primNo].get();
osg::PrimitiveSet* rhs = primitives[primNo+1].get();
bool combine = false;
if (lhs->getType()==rhs->getType() &&
lhs->getMode()==rhs->getMode())
{
switch(lhs->getMode())
{
case(osg::PrimitiveSet::POINTS):
case(osg::PrimitiveSet::LINES):
case(osg::PrimitiveSet::TRIANGLES):
case(osg::PrimitiveSet::QUADS):
combine = true;
break;
}
}
if (combine)
{
switch(lhs->getType())
{
case(osg::PrimitiveSet::DrawArraysPrimitiveType):
combine = mergePrimitive(*(static_cast<osg::DrawArrays*>(lhs)),*(static_cast<osg::DrawArrays*>(rhs)));
break;
case(osg::PrimitiveSet::DrawArrayLengthsPrimitiveType):
combine = mergePrimitive(*(static_cast<osg::DrawArrayLengths*>(lhs)),*(static_cast<osg::DrawArrayLengths*>(rhs)));
break;
case(osg::PrimitiveSet::DrawElementsUBytePrimitiveType):
combine = mergePrimitive(*(static_cast<osg::DrawElementsUByte*>(lhs)),*(static_cast<osg::DrawElementsUByte*>(rhs)));
break;
case(osg::PrimitiveSet::DrawElementsUShortPrimitiveType):
combine = mergePrimitive(*(static_cast<osg::DrawElementsUShort*>(lhs)),*(static_cast<osg::DrawElementsUShort*>(rhs)));
break;
case(osg::PrimitiveSet::DrawElementsUIntPrimitiveType):
combine = mergePrimitive(*(static_cast<osg::DrawElementsUInt*>(lhs)),*(static_cast<osg::DrawElementsUInt*>(rhs)));
break;
default:
break;
}
}
if (combine)
{
primitives.erase(primitives.begin()+primNo+1);
}
if (!combine)
{
primNo++;
}
}
#endif
if (doneCombine && !geom->containsSharedArrays() && !containsSharedPrimitives(geom))
{
// prefer to use vbo for merged geometries as vbo uses less memory than display lists.
geom->setUseVertexBufferObjects(true);
geom->setUseDisplayList(false);
}
if (_alphaBlendingActive && _mergeAlphaBlending && !geom->getStateSet())
{
osg::ref_ptr<osg::Depth> d = new SceneUtil::AutoDepth;
d->setWriteMask(false);
geom->getOrCreateStateSet()->setAttribute(d);
}
}
}
}
return false;
}
class MergeArrayVisitor : public osg::ArrayVisitor
{
protected:
osg::Array* _lhs;
public:
MergeArrayVisitor() :
_lhs(0) {}
/// try to merge the content of two arrays.
bool merge(osg::Array* lhs,osg::Array* rhs)
{
if (lhs==0 || rhs==0) return true;
if (lhs->getType()!=rhs->getType()) return false;
_lhs = lhs;
rhs->accept(*this);
return true;
}
template<typename T>
void _merge(T& rhs)
{
T* lhs = static_cast<T*>(_lhs);
lhs->insert(lhs->end(),rhs.begin(),rhs.end());
}
void apply(osg::Array&) override { OSG_WARN << "Warning: Optimizer's MergeArrayVisitor cannot merge Array type." << std::endl; }
void apply(osg::ByteArray& rhs) override { _merge(rhs); }
void apply(osg::ShortArray& rhs) override { _merge(rhs); }
void apply(osg::IntArray& rhs) override { _merge(rhs); }
void apply(osg::UByteArray& rhs) override { _merge(rhs); }
void apply(osg::UShortArray& rhs) override { _merge(rhs); }
void apply(osg::UIntArray& rhs) override { _merge(rhs); }
void apply(osg::Vec4ubArray& rhs) override { _merge(rhs); }
void apply(osg::Vec3ubArray& rhs) override{ _merge(rhs); }
void apply(osg::Vec2ubArray& rhs) override { _merge(rhs); }
void apply(osg::Vec4usArray& rhs) override { _merge(rhs); }
void apply(osg::Vec3usArray& rhs) override { _merge(rhs); }
void apply(osg::Vec2usArray& rhs) override { _merge(rhs); }
void apply(osg::FloatArray& rhs) override { _merge(rhs); }
void apply(osg::Vec2Array& rhs) override { _merge(rhs); }
void apply(osg::Vec3Array& rhs) override { _merge(rhs); }
void apply(osg::Vec4Array& rhs) override { _merge(rhs); }
void apply(osg::DoubleArray& rhs) override { _merge(rhs); }
void apply(osg::Vec2dArray& rhs) override { _merge(rhs); }
void apply(osg::Vec3dArray& rhs) override { _merge(rhs); }
void apply(osg::Vec4dArray& rhs) override { _merge(rhs); }
void apply(osg::Vec2bArray& rhs) override { _merge(rhs); }
void apply(osg::Vec3bArray& rhs) override { _merge(rhs); }
void apply(osg::Vec4bArray& rhs) override { _merge(rhs); }
void apply(osg::Vec2sArray& rhs) override { _merge(rhs); }
void apply(osg::Vec3sArray& rhs) override { _merge(rhs); }
void apply(osg::Vec4sArray& rhs) override { _merge(rhs); }
};
bool Optimizer::MergeGeometryVisitor::mergeGeometry(osg::Geometry& lhs, osg::Geometry& rhs, const GeometryArraySizes& sizes)
{
MergeArrayVisitor merger;
osg::VertexBufferObject* vbo = nullptr;
unsigned int base = 0;
if (lhs.getVertexArray() && rhs.getVertexArray())
{
base = lhs.getVertexArray()->getNumElements();
if (lhs.getVertexArray()->referenceCount() > 1)
lhs.setVertexArray(cloneArray(lhs.getVertexArray(), vbo, &lhs));
lhs.getVertexArray()->reserveArray(sizes.mVertex);
if (!merger.merge(lhs.getVertexArray(),rhs.getVertexArray()))
{
OSG_DEBUG << "MergeGeometry: vertex array not merged. Some data may be lost." <<std::endl;
}
}
else if (rhs.getVertexArray())
{
base = 0;
lhs.setVertexArray(rhs.getVertexArray());
}
if (lhs.getNormalArray() && rhs.getNormalArray() && lhs.getNormalArray()->getBinding()!=osg::Array::BIND_OVERALL)
{
if (lhs.getNormalArray()->referenceCount() > 1)
lhs.setNormalArray(cloneArray(lhs.getNormalArray(), vbo, &lhs));
lhs.getNormalArray()->reserveArray(sizes.mNormal);
if (!merger.merge(lhs.getNormalArray(),rhs.getNormalArray()))
{
OSG_DEBUG << "MergeGeometry: normal array not merged. Some data may be lost." <<std::endl;
}
}
else if (rhs.getNormalArray())
{
lhs.setNormalArray(rhs.getNormalArray());
}
if (lhs.getColorArray() && rhs.getColorArray() && lhs.getColorArray()->getBinding()!=osg::Array::BIND_OVERALL)
{
if (lhs.getColorArray()->referenceCount() > 1)
lhs.setColorArray(cloneArray(lhs.getColorArray(), vbo, &lhs));
lhs.getColorArray()->reserveArray(sizes.mColor);
if (!merger.merge(lhs.getColorArray(),rhs.getColorArray()))
{
OSG_DEBUG << "MergeGeometry: color array not merged. Some data may be lost." <<std::endl;
}
}
else if (rhs.getColorArray())
{
lhs.setColorArray(rhs.getColorArray());
}
if (lhs.getSecondaryColorArray() && rhs.getSecondaryColorArray() && lhs.getSecondaryColorArray()->getBinding()!=osg::Array::BIND_OVERALL)
{
if (lhs.getSecondaryColorArray()->referenceCount() > 1)
lhs.setSecondaryColorArray(cloneArray(lhs.getSecondaryColorArray(), vbo, &lhs));
lhs.getSecondaryColorArray()->reserveArray(static_cast<unsigned>(sizes.mSecondaryColor));
if (!merger.merge(lhs.getSecondaryColorArray(),rhs.getSecondaryColorArray()))
{
OSG_DEBUG << "MergeGeometry: secondary color array not merged. Some data may be lost." <<std::endl;
}
}
else if (rhs.getSecondaryColorArray())
{
lhs.setSecondaryColorArray(rhs.getSecondaryColorArray());
}
if (lhs.getFogCoordArray() && rhs.getFogCoordArray() && lhs.getFogCoordArray()->getBinding()!=osg::Array::BIND_OVERALL)
{
if (lhs.getFogCoordArray()->referenceCount() > 1)
lhs.setFogCoordArray(cloneArray(lhs.getFogCoordArray(), vbo, &lhs));
lhs.getFogCoordArray()->reserveArray(sizes.mFogCoord);
if (!merger.merge(lhs.getFogCoordArray(),rhs.getFogCoordArray()))
{
OSG_DEBUG << "MergeGeometry: fog coord array not merged. Some data may be lost." <<std::endl;
}
}
else if (rhs.getFogCoordArray())
{
lhs.setFogCoordArray(rhs.getFogCoordArray());
}
unsigned int unit;
for(unit=0;unit<lhs.getNumTexCoordArrays();++unit)
{
if (!lhs.getTexCoordArray(unit)) continue;
if (lhs.getTexCoordArray(unit)->referenceCount() > 1)
lhs.setTexCoordArray(unit, cloneArray(lhs.getTexCoordArray(unit), vbo, &lhs));
osg::Array* const lhsArray = lhs.getTexCoordArray(unit);
lhsArray->reserveArray(sizes.mTexCoord[unit]);
if (!merger.merge(lhsArray, rhs.getTexCoordArray(unit)))
{
OSG_DEBUG << "MergeGeometry: tex coord array not merged. Some data may be lost." <<std::endl;
}
}
for(unit=0;unit<lhs.getNumVertexAttribArrays();++unit)
{
if (!lhs.getVertexAttribArray(unit)) continue;
if (lhs.getVertexAttribArray(unit)->referenceCount() > 1)
lhs.setVertexAttribArray(unit, cloneArray(lhs.getVertexAttribArray(unit), vbo, &lhs));
osg::Array* const lhsArray = lhs.getVertexAttribArray(unit);
lhsArray->reserveArray(sizes.mVertexAttrib[unit]);
if (!merger.merge(lhsArray, rhs.getVertexAttribArray(unit)))
{
OSG_DEBUG << "MergeGeometry: vertex attrib array not merged. Some data may be lost." <<std::endl;
}
}
// shift the indices of the incoming primitives to account for the pre existing geometry.
osg::ElementBufferObject* ebo = nullptr;
osg::Geometry::PrimitiveSetList::iterator primItr;
for(primItr=rhs.getPrimitiveSetList().begin(); primItr!=rhs.getPrimitiveSetList().end(); ++primItr)
{
osg::PrimitiveSet* primitive = primItr->get();
switch(primitive->getType())
{
case(osg::PrimitiveSet::DrawElementsUBytePrimitiveType):
{
osg::DrawElementsUByte* primitiveUByte = static_cast<osg::DrawElementsUByte*>(primitive);
unsigned int currentMaximum = 0;
for(osg::DrawElementsUByte::iterator eitr=primitiveUByte->begin();
eitr!=primitiveUByte->end();
++eitr)
{
currentMaximum = osg::maximum(currentMaximum,(unsigned int)*eitr);
}
if ((base+currentMaximum)>=65536)
{
// must promote to a DrawElementsUInt
osg::DrawElementsUInt* new_primitive = new osg::DrawElementsUInt(primitive->getMode());
if (!ebo) ebo = new osg::ElementBufferObject;
new_primitive->setElementBufferObject(ebo);
std::copy(primitiveUByte->begin(),primitiveUByte->end(),std::back_inserter(*new_primitive));
new_primitive->offsetIndices(base);
(*primItr) = new_primitive;
} else if ((base+currentMaximum)>=256)
{
// must promote to a DrawElementsUShort
osg::DrawElementsUShort* new_primitive = new osg::DrawElementsUShort(primitive->getMode());
if (!ebo) ebo = new osg::ElementBufferObject;
new_primitive->setElementBufferObject(ebo);
std::copy(primitiveUByte->begin(),primitiveUByte->end(),std::back_inserter(*new_primitive));
new_primitive->offsetIndices(base);
(*primItr) = new_primitive;
}
else
{
(*primItr) = clonePrimitive(primitive, ebo, &lhs);
(*primItr)->offsetIndices(base);
}
}
break;
case(osg::PrimitiveSet::DrawElementsUShortPrimitiveType):
{
osg::DrawElementsUShort* primitiveUShort = static_cast<osg::DrawElementsUShort*>(primitive);
unsigned int currentMaximum = 0;
for(osg::DrawElementsUShort::iterator eitr=primitiveUShort->begin();
eitr!=primitiveUShort->end();
++eitr)
{
currentMaximum = osg::maximum(currentMaximum,(unsigned int)*eitr);
}
if ((base+currentMaximum)>=65536)
{
// must promote to a DrawElementsUInt
osg::DrawElementsUInt* new_primitive = new osg::DrawElementsUInt(primitive->getMode());
if (!ebo) ebo = new osg::ElementBufferObject;
new_primitive->setElementBufferObject(ebo);
std::copy(primitiveUShort->begin(),primitiveUShort->end(),std::back_inserter(*new_primitive));
new_primitive->offsetIndices(base);
(*primItr) = new_primitive;
}
else
{
(*primItr) = clonePrimitive(primitive, ebo, &lhs);
(*primItr)->offsetIndices(base);
}
}
break;
case(osg::PrimitiveSet::DrawArraysPrimitiveType):
case(osg::PrimitiveSet::DrawArrayLengthsPrimitiveType):
case(osg::PrimitiveSet::DrawElementsUIntPrimitiveType):
default:
(*primItr) = clonePrimitive(primitive, ebo, &lhs);
(*primItr)->offsetIndices(base);
break;
}
}
for(primItr=rhs.getPrimitiveSetList().begin(); primItr!=rhs.getPrimitiveSetList().end(); ++primItr)
{
lhs.addPrimitiveSet(primItr->get());
}
lhs.dirtyBound();
lhs.dirtyDisplayList();
if (osg::UserDataContainer* rhsUserData = rhs.getUserDataContainer())
for (unsigned int i=0; i<rhsUserData->getNumUserObjects(); ++i)
lhs.getOrCreateUserDataContainer()->addUserObject(rhsUserData->getUserObject(i));
return true;
}
bool Optimizer::MergeGeometryVisitor::mergePrimitive(osg::DrawArrays& lhs,osg::DrawArrays& rhs)
{
if (lhs.getFirst()+lhs.getCount()==rhs.getFirst())
{
lhs.setCount(lhs.getCount()+rhs.getCount());
return true;
}
return false;
}
bool Optimizer::MergeGeometryVisitor::mergePrimitive(osg::DrawArrayLengths& lhs,osg::DrawArrayLengths& rhs)
{
int lhs_count = std::accumulate(lhs.begin(),lhs.end(),0);
if (lhs.getFirst()+lhs_count==rhs.getFirst())
{
lhs.insert(lhs.end(),rhs.begin(),rhs.end());
return true;
}
return false;
}
bool Optimizer::MergeGeometryVisitor::mergePrimitive(osg::DrawElementsUByte& lhs,osg::DrawElementsUByte& rhs)
{
lhs.insert(lhs.end(),rhs.begin(),rhs.end());
return true;
}
bool Optimizer::MergeGeometryVisitor::mergePrimitive(osg::DrawElementsUShort& lhs,osg::DrawElementsUShort& rhs)
{
lhs.insert(lhs.end(),rhs.begin(),rhs.end());
return true;
}
bool Optimizer::MergeGeometryVisitor::mergePrimitive(osg::DrawElementsUInt& lhs,osg::DrawElementsUInt& rhs)
{
lhs.insert(lhs.end(),rhs.begin(),rhs.end());
return true;
}
bool Optimizer::MergeGroupsVisitor::isOperationPermissible(osg::Group& node)
{
return !node.getCullCallback() &&
!node.getEventCallback() &&
!node.getUpdateCallback() &&
typeid(node)==typeid(osg::Group) &&
isOperationPermissibleForObject(&node);
}
void Optimizer::MergeGroupsVisitor::apply(osg::LOD &lod)
{
// don't merge the direct children of the LOD because they are used to define each LOD level.
traverse(lod);
}
void Optimizer::MergeGroupsVisitor::apply(osg::Switch &switchNode)
{
// We should keep all switch child nodes since they reflect different switch states.
traverse(switchNode);
}
void Optimizer::MergeGroupsVisitor::apply(osg::Sequence &sequenceNode)
{
// We should keep all sequence child nodes since they reflect different sequence states.
traverse(sequenceNode);
}
void Optimizer::MergeGroupsVisitor::apply(osg::Group &group)
{
if (group.getNumChildren() <= 1)
traverse(group);
else
{
typedef std::map<osg::StateSet*, std::set<osg::Group*> > GroupMap;
GroupMap childGroups;
for (unsigned int i=0; i<group.getNumChildren(); ++i)
{
osg::Node* child = group.getChild(i);
osg::Group* childGroup = child->asGroup();
if (childGroup && isOperationPermissible(*childGroup))
{
childGroups[childGroup->getStateSet()].insert(childGroup);
}
}
for (GroupMap::iterator it = childGroups.begin(); it != childGroups.end(); ++it)
{
const std::set<osg::Group*>& groupSet = it->second;
if (groupSet.size() <= 1)
continue;
else
{
osg::Group* first = *groupSet.begin();
for (std::set<osg::Group*>::const_iterator groupIt = ++groupSet.begin(); groupIt != groupSet.end(); ++groupIt)
{
osg::Group* toMerge = *groupIt;
for (unsigned int i=0; i<toMerge->getNumChildren(); ++i)
first->addChild(toMerge->getChild(i));
toMerge->removeChildren(0, toMerge->getNumChildren());
group.removeChild(toMerge);
}
}
}
traverse(group);
}
}
}
// clang-format on
| 76,092
|
C++
|
.cpp
| 1,745
| 32.527221
| 171
| 0.581816
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,747
|
rtt.cpp
|
OpenMW_openmw/components/sceneutil/rtt.cpp
|
#include "rtt.hpp"
#include "util.hpp"
#include <osg/Texture2D>
#include <osg/Texture2DArray>
#include <osgUtil/CullVisitor>
#include <components/sceneutil/color.hpp>
#include <components/sceneutil/depth.hpp>
#include <components/sceneutil/nodecallback.hpp>
#include <components/stereo/multiview.hpp>
#include <components/stereo/stereomanager.hpp>
namespace SceneUtil
{
class CullCallback : public SceneUtil::NodeCallback<CullCallback, RTTNode*, osgUtil::CullVisitor*>
{
public:
void operator()(RTTNode* node, osgUtil::CullVisitor* cv) { node->cull(cv); }
};
RTTNode::RTTNode(uint32_t textureWidth, uint32_t textureHeight, uint32_t samples, bool generateMipmaps,
int renderOrderNum, StereoAwareness stereoAwareness, bool addMSAAIntermediateTarget)
: mTextureWidth(textureWidth)
, mTextureHeight(textureHeight)
, mSamples(samples)
, mGenerateMipmaps(generateMipmaps)
, mColorBufferInternalFormat(Color::colorInternalFormat())
, mDepthBufferInternalFormat(SceneUtil::AutoDepth::depthInternalFormat())
, mRenderOrderNum(renderOrderNum)
, mStereoAwareness(stereoAwareness)
, mAddMSAAIntermediateTarget(addMSAAIntermediateTarget)
{
addCullCallback(new CullCallback);
setCullingActive(false);
}
RTTNode::~RTTNode()
{
for (auto& vdd : mViewDependentDataMap)
{
auto* camera = vdd.second->mCamera.get();
if (camera)
{
camera->removeChildren(0, camera->getNumChildren());
}
}
mViewDependentDataMap.clear();
}
void RTTNode::cull(osgUtil::CullVisitor* cv)
{
auto frameNumber = cv->getFrameStamp()->getFrameNumber();
auto* vdd = getViewDependentData(cv);
if (frameNumber > vdd->mFrameNumber)
{
apply(vdd->mCamera);
if (Stereo::getStereo())
{
auto& sm = Stereo::Manager::instance();
if (sm.getEye(cv) == Stereo::Eye::Left)
applyLeft(vdd->mCamera);
if (sm.getEye(cv) == Stereo::Eye::Right)
applyRight(vdd->mCamera);
}
vdd->mCamera->accept(*cv);
}
vdd->mFrameNumber = frameNumber;
}
void RTTNode::setColorBufferInternalFormat(GLint internalFormat)
{
mColorBufferInternalFormat = internalFormat;
}
void RTTNode::setDepthBufferInternalFormat(GLint internalFormat)
{
mDepthBufferInternalFormat = internalFormat;
}
bool RTTNode::shouldDoPerViewMapping()
{
if (mStereoAwareness != StereoAwareness::Aware)
return false;
if (!Stereo::getMultiview())
return true;
return false;
}
bool RTTNode::shouldDoTextureArray()
{
if (mStereoAwareness == StereoAwareness::Unaware)
return false;
if (Stereo::getMultiview())
return true;
return false;
}
bool RTTNode::shouldDoTextureView()
{
if (mStereoAwareness != StereoAwareness::Unaware_MultiViewShaders)
return false;
if (Stereo::getMultiview())
return true;
return false;
}
osg::Texture2DArray* RTTNode::createTextureArray(GLint internalFormat)
{
osg::Texture2DArray* textureArray = new osg::Texture2DArray;
textureArray->setTextureSize(mTextureWidth, mTextureHeight, 2);
textureArray->setInternalFormat(internalFormat);
GLenum sourceFormat = 0;
GLenum sourceType = 0;
if (SceneUtil::isDepthFormat(internalFormat))
{
SceneUtil::getDepthFormatSourceFormatAndType(internalFormat, sourceFormat, sourceType);
}
else
{
SceneUtil::getColorFormatSourceFormatAndType(internalFormat, sourceFormat, sourceType);
}
textureArray->setSourceFormat(sourceFormat);
textureArray->setSourceType(sourceType);
textureArray->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
textureArray->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
textureArray->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
textureArray->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
textureArray->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
return textureArray;
}
osg::Texture2D* RTTNode::createTexture(GLint internalFormat)
{
osg::Texture2D* texture = new osg::Texture2D;
texture->setTextureSize(mTextureWidth, mTextureHeight);
texture->setInternalFormat(internalFormat);
GLenum sourceFormat = 0;
GLenum sourceType = 0;
if (SceneUtil::isDepthFormat(internalFormat))
{
SceneUtil::getDepthFormatSourceFormatAndType(internalFormat, sourceFormat, sourceType);
}
else
{
SceneUtil::getColorFormatSourceFormatAndType(internalFormat, sourceFormat, sourceType);
}
texture->setSourceFormat(sourceFormat);
texture->setSourceType(sourceType);
texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
return texture;
}
osg::Texture* RTTNode::getColorTexture(osgUtil::CullVisitor* cv)
{
return getViewDependentData(cv)->mColorTexture;
}
osg::Texture* RTTNode::getDepthTexture(osgUtil::CullVisitor* cv)
{
return getViewDependentData(cv)->mDepthTexture;
}
osg::Camera* RTTNode::getCamera(osgUtil::CullVisitor* cv)
{
return getViewDependentData(cv)->mCamera;
}
RTTNode::ViewDependentData* RTTNode::getViewDependentData(osgUtil::CullVisitor* cv)
{
if (!shouldDoPerViewMapping())
// Always setting it to null is an easy way to disable per-view mapping when mDoPerViewMapping is false.
// This is safe since the visitor is never dereferenced.
cv = nullptr;
if (mViewDependentDataMap.count(cv) == 0)
{
auto camera = new osg::Camera();
auto vdd = std::make_shared<ViewDependentData>();
mViewDependentDataMap[cv] = vdd;
mViewDependentDataMap[cv]->mCamera = camera;
camera->setRenderOrder(osg::Camera::PRE_RENDER, mRenderOrderNum);
camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
camera->setViewport(0, 0, mTextureWidth, mTextureHeight);
SceneUtil::setCameraClearDepth(camera);
setDefaults(camera);
if (camera->getBufferAttachmentMap().count(osg::Camera::COLOR_BUFFER))
vdd->mColorTexture = camera->getBufferAttachmentMap()[osg::Camera::COLOR_BUFFER]._texture;
if (camera->getBufferAttachmentMap().count(osg::Camera::PACKED_DEPTH_STENCIL_BUFFER))
vdd->mDepthTexture
= camera->getBufferAttachmentMap()[osg::Camera::PACKED_DEPTH_STENCIL_BUFFER]._texture;
if (shouldDoTextureArray())
{
// Create any buffer attachments not added in setDefaults
if (camera->getBufferAttachmentMap().count(osg::Camera::COLOR_BUFFER) == 0)
{
vdd->mColorTexture = createTextureArray(mColorBufferInternalFormat);
camera->attach(osg::Camera::COLOR_BUFFER, vdd->mColorTexture, 0,
Stereo::osgFaceControlledByMultiviewShader(), mGenerateMipmaps, mSamples);
SceneUtil::attachAlphaToCoverageFriendlyFramebufferToCamera(camera, osg::Camera::COLOR_BUFFER,
vdd->mColorTexture, 0, Stereo::osgFaceControlledByMultiviewShader(), mGenerateMipmaps,
mAddMSAAIntermediateTarget);
}
if (camera->getBufferAttachmentMap().count(osg::Camera::PACKED_DEPTH_STENCIL_BUFFER) == 0)
{
vdd->mDepthTexture = createTextureArray(mDepthBufferInternalFormat);
camera->attach(osg::Camera::PACKED_DEPTH_STENCIL_BUFFER, vdd->mDepthTexture, 0,
Stereo::osgFaceControlledByMultiviewShader(), false, mSamples);
}
if (shouldDoTextureView())
{
// In this case, shaders being set to multiview forces us to render to a multiview framebuffer even
// though we don't need that. This forces us to make Texture2DArray. To make this possible to sample
// as a Texture2D, make a Texture2D view into the texture array.
vdd->mColorTexture = Stereo::createTextureView_Texture2DFromTexture2DArray(
static_cast<osg::Texture2DArray*>(vdd->mColorTexture.get()), 0);
vdd->mDepthTexture = Stereo::createTextureView_Texture2DFromTexture2DArray(
static_cast<osg::Texture2DArray*>(vdd->mDepthTexture.get()), 0);
}
}
else
{
// Create any buffer attachments not added in setDefaults
if (camera->getBufferAttachmentMap().count(osg::Camera::COLOR_BUFFER) == 0)
{
vdd->mColorTexture = createTexture(mColorBufferInternalFormat);
camera->attach(osg::Camera::COLOR_BUFFER, vdd->mColorTexture, 0, 0, mGenerateMipmaps, mSamples);
SceneUtil::attachAlphaToCoverageFriendlyFramebufferToCamera(camera, osg::Camera::COLOR_BUFFER,
vdd->mColorTexture, 0, 0, mGenerateMipmaps, mAddMSAAIntermediateTarget);
}
if (camera->getBufferAttachmentMap().count(osg::Camera::PACKED_DEPTH_STENCIL_BUFFER) == 0)
{
vdd->mDepthTexture = createTexture(mDepthBufferInternalFormat);
camera->attach(osg::Camera::PACKED_DEPTH_STENCIL_BUFFER, vdd->mDepthTexture, 0, 0, false, mSamples);
}
}
// OSG appears not to properly initialize this metadata. So when multisampling is enabled, OSG will use
// incorrect formats for the resolve buffers.
if (mSamples > 1)
{
camera->getBufferAttachmentMap()[osg::Camera::COLOR_BUFFER]._internalFormat
= mColorBufferInternalFormat;
camera->getBufferAttachmentMap()[osg::Camera::COLOR_BUFFER]._mipMapGeneration = mGenerateMipmaps;
camera->getBufferAttachmentMap()[osg::Camera::PACKED_DEPTH_STENCIL_BUFFER]._internalFormat
= mDepthBufferInternalFormat;
camera->getBufferAttachmentMap()[osg::Camera::PACKED_DEPTH_STENCIL_BUFFER]._mipMapGeneration
= mGenerateMipmaps;
}
}
return mViewDependentDataMap[cv].get();
}
}
| 11,345
|
C++
|
.cpp
| 239
| 36.380753
| 120
| 0.637151
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,748
|
depth.cpp
|
OpenMW_openmw/components/sceneutil/depth.cpp
|
#include "depth.hpp"
#include <algorithm>
#include <array>
#include <components/debug/debuglog.hpp>
#include <components/sceneutil/glextensions.hpp>
#include <components/settings/values.hpp>
namespace SceneUtil
{
void setCameraClearDepth(osg::Camera* camera)
{
camera->setClearDepth(AutoDepth::isReversed() ? 0.0 : 1.0);
}
osg::Matrix getReversedZProjectionMatrixAsPerspectiveInf(double fov, double aspect, double near)
{
double A = 1.0 / std::tan(osg::DegreesToRadians(fov) / 2.0);
return osg::Matrix(A / aspect, 0, 0, 0, 0, A, 0, 0, 0, 0, 0, -1, 0, 0, near, 0);
}
osg::Matrix getReversedZProjectionMatrixAsPerspective(double fov, double aspect, double near, double far)
{
double A = 1.0 / std::tan(osg::DegreesToRadians(fov) / 2.0);
return osg::Matrix(
A / aspect, 0, 0, 0, 0, A, 0, 0, 0, 0, near / (far - near), -1, 0, 0, (far * near) / (far - near), 0);
}
osg::Matrix getReversedZProjectionMatrixAsOrtho(
double left, double right, double bottom, double top, double near, double far)
{
return osg::Matrix(2 / (right - left), 0, 0, 0, 0, 2 / (top - bottom), 0, 0, 0, 0, 1 / (far - near), 0,
(right + left) / (left - right), (top + bottom) / (bottom - top), far / (far - near), 1);
}
bool isDepthFormat(GLenum format)
{
constexpr std::array<GLenum, 8> formats = {
GL_DEPTH_COMPONENT32F,
GL_DEPTH_COMPONENT32F_NV,
GL_DEPTH_COMPONENT16,
GL_DEPTH_COMPONENT24,
GL_DEPTH_COMPONENT32,
GL_DEPTH32F_STENCIL8,
GL_DEPTH32F_STENCIL8_NV,
GL_DEPTH24_STENCIL8,
};
return std::find(formats.cbegin(), formats.cend(), format) != formats.cend();
}
bool isDepthStencilFormat(GLenum format)
{
constexpr std::array<GLenum, 8> formats = {
GL_DEPTH32F_STENCIL8,
GL_DEPTH32F_STENCIL8_NV,
GL_DEPTH24_STENCIL8,
};
return std::find(formats.cbegin(), formats.cend(), format) != formats.cend();
}
void getDepthFormatSourceFormatAndType(GLenum internalFormat, GLenum& sourceFormat, GLenum& sourceType)
{
switch (internalFormat)
{
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_DEPTH_COMPONENT32:
sourceType = GL_UNSIGNED_INT;
sourceFormat = GL_DEPTH_COMPONENT;
break;
case GL_DEPTH_COMPONENT32F:
case GL_DEPTH_COMPONENT32F_NV:
sourceType = GL_FLOAT;
sourceFormat = GL_DEPTH_COMPONENT;
break;
case GL_DEPTH24_STENCIL8:
sourceType = GL_UNSIGNED_INT_24_8_EXT;
sourceFormat = GL_DEPTH_STENCIL_EXT;
break;
case GL_DEPTH32F_STENCIL8:
case GL_DEPTH32F_STENCIL8_NV:
sourceType = GL_FLOAT_32_UNSIGNED_INT_24_8_REV;
sourceFormat = GL_DEPTH_STENCIL_EXT;
break;
default:
sourceType = GL_UNSIGNED_INT;
sourceFormat = GL_DEPTH_COMPONENT;
break;
}
}
GLenum getDepthFormatOfDepthStencilFormat(GLenum internalFormat)
{
switch (internalFormat)
{
case GL_DEPTH24_STENCIL8:
return GL_DEPTH_COMPONENT24;
break;
case GL_DEPTH32F_STENCIL8:
return GL_DEPTH_COMPONENT32F;
break;
case GL_DEPTH32F_STENCIL8_NV:
return GL_DEPTH_COMPONENT32F_NV;
break;
default:
return internalFormat;
break;
}
}
void SelectDepthFormatOperation::operator()(osg::GraphicsContext* graphicsContext)
{
bool enableReverseZ = false;
if (Settings::camera().mReverseZ)
{
if (SceneUtil::getGLExtensions().isClipControlSupported)
{
enableReverseZ = true;
Log(Debug::Info) << "Using reverse-z depth buffer";
}
else
Log(Debug::Warning) << "GL_ARB_clip_control not supported: disabling reverse-z depth buffer";
}
else
Log(Debug::Info) << "Using standard depth buffer";
SceneUtil::AutoDepth::setReversed(enableReverseZ);
constexpr char errPreamble[] = "Postprocessing and floating point depth buffers disabled: ";
std::vector<GLenum> requestedFormats;
unsigned int contextID = graphicsContext->getState()->getContextID();
if (SceneUtil::AutoDepth::isReversed())
{
if (osg::isGLExtensionSupported(contextID, "GL_ARB_depth_buffer_float"))
{
requestedFormats.push_back(GL_DEPTH32F_STENCIL8);
}
else if (osg::isGLExtensionSupported(contextID, "GL_NV_depth_buffer_float"))
{
requestedFormats.push_back(GL_DEPTH32F_STENCIL8_NV);
}
else
{
Log(Debug::Warning) << errPreamble
<< "'GL_ARB_depth_buffer_float' and 'GL_NV_depth_buffer_float' unsupported.";
}
}
requestedFormats.push_back(GL_DEPTH24_STENCIL8);
if (mSupportedFormats.empty())
{
SceneUtil::AutoDepth::setDepthFormat(requestedFormats.front());
}
else
{
for (auto requestedFormat : requestedFormats)
{
if (std::find(mSupportedFormats.cbegin(), mSupportedFormats.cend(), requestedFormat)
!= mSupportedFormats.cend())
{
SceneUtil::AutoDepth::setDepthFormat(requestedFormat);
break;
}
}
}
}
void AutoDepth::setDepthFormat(GLenum format)
{
sDepthInternalFormat = format;
getDepthFormatSourceFormatAndType(sDepthInternalFormat, sDepthSourceFormat, sDepthSourceType);
}
}
| 6,137
|
C++
|
.cpp
| 159
| 27.572327
| 114
| 0.57349
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,749
|
riggeometryosgaextension.cpp
|
OpenMW_openmw/components/sceneutil/riggeometryosgaextension.cpp
|
#include "riggeometryosgaextension.hpp"
#include <osgAnimation/RigGeometry>
#include <osg/Drawable>
#include <osg/NodeVisitor>
#include <osgUtil/CullVisitor>
#include <components/debug/debuglog.hpp>
#include <components/resource/scenemanager.hpp>
namespace SceneUtil
{
OsgaRigGeometry::OsgaRigGeometry()
: osgAnimation::RigGeometry()
{
setDataVariance(osg::Object::STATIC);
}
OsgaRigGeometry::OsgaRigGeometry(const osgAnimation::RigGeometry& copy, const osg::CopyOp& copyop)
: osgAnimation::RigGeometry(copy, copyop)
{
setDataVariance(osg::Object::STATIC);
}
OsgaRigGeometry::OsgaRigGeometry(const OsgaRigGeometry& copy, const osg::CopyOp& copyop)
: osgAnimation::RigGeometry(copy, copyop)
{
setDataVariance(osg::Object::STATIC);
}
void OsgaRigGeometry::computeMatrixFromRootSkeleton(osg::MatrixList mtxList)
{
if (!_root.valid())
{
Log(Debug::Warning) << "Warning " << className()
<< "::computeMatrixFromRootSkeleton if you have this message it means you miss to call "
"buildTransformer(Skeleton* root), or your RigGeometry ("
<< getName() << ") is not attached to a Skeleton subgraph";
return;
}
osg::Matrix notRoot = _root->getMatrix();
_matrixFromSkeletonToGeometry = mtxList[0] * osg::Matrix::inverse(notRoot);
_invMatrixFromSkeletonToGeometry = osg::Matrix::inverse(_matrixFromSkeletonToGeometry);
_needToComputeMatrix = false;
}
RigGeometryHolder::RigGeometryHolder()
: mBackToOrigin(nullptr)
, mLastFrameNumber(0)
, mIsBodyPart(false)
{
}
RigGeometryHolder::RigGeometryHolder(const RigGeometryHolder& copy, const osg::CopyOp& copyop)
: Drawable(copy, copyop)
, mBackToOrigin(copy.mBackToOrigin)
, mLastFrameNumber(0)
, mIsBodyPart(copy.mIsBodyPart)
{
setUseVertexBufferObjects(true);
if (!copy.getSourceRigGeometry())
{
Log(Debug::Error) << "copy constructor of RigGeometryHolder partially failed (no source RigGeometry)";
return;
}
osg::ref_ptr<OsgaRigGeometry> rigGeometry = new OsgaRigGeometry(*copy.getSourceRigGeometry(), copyop);
setSourceRigGeometry(std::move(rigGeometry));
}
RigGeometryHolder::RigGeometryHolder(const osgAnimation::RigGeometry& copy, const osg::CopyOp& copyop)
: mBackToOrigin(nullptr)
, mLastFrameNumber(0)
, mIsBodyPart(false)
{
setUseVertexBufferObjects(true);
osg::ref_ptr<OsgaRigGeometry> rigGeometry = new OsgaRigGeometry(copy, copyop);
setSourceRigGeometry(std::move(rigGeometry));
}
void RigGeometryHolder::setSourceRigGeometry(osg::ref_ptr<OsgaRigGeometry> sourceRigGeometry)
{
for (unsigned int i = 0; i < 2; ++i)
mGeometry.at(i) = nullptr;
mSourceRigGeometry = sourceRigGeometry;
_boundingBox = mSourceRigGeometry->getComputeBoundingBoxCallback()->computeBound(*mSourceRigGeometry);
_boundingSphere = osg::BoundingSphere(_boundingBox);
for (unsigned int i = 0; i < 2; ++i)
{
const OsgaRigGeometry& from = *sourceRigGeometry;
// DO NOT COPY AND PASTE THIS CODE. Cloning osg::Geometry without also cloning its contained Arrays is
// generally unsafe. In this specific case the operation is safe under the following two assumptions:
// - When Arrays are removed or replaced in the cloned geometry, the original Arrays in their place must
// outlive the cloned geometry regardless. (ensured by mSourceRigGeometry, possibly also
// RigGeometry._geometry)
// - Arrays that we add or replace in the cloned geometry must be explicitely forbidden from reusing
// BufferObjects of the original geometry.
mGeometry.at(i) = new OsgaRigGeometry(from, osg::CopyOp::SHALLOW_COPY);
mGeometry.at(i)->getOrCreateUserDataContainer()->addUserObject(
new Resource::TemplateRef(mSourceRigGeometry));
OsgaRigGeometry& to = *mGeometry.at(i);
to.setSupportsDisplayList(false);
to.setUseVertexBufferObjects(true);
to.setCullingActive(false); // make sure to disable culling since that's handled by this class
to.setDataVariance(osg::Object::STATIC);
to.setNeedToComputeMatrix(true);
// vertices and normals are modified every frame, so we need to deep copy them.
// assign a dedicated VBO to make sure that modifications don't interfere with source geometry's VBO.
osg::ref_ptr<osg::VertexBufferObject> vbo(new osg::VertexBufferObject);
vbo->setUsage(GL_DYNAMIC_DRAW_ARB);
osg::ref_ptr<osg::Array> vertexArray
= static_cast<osg::Array*>(from.getVertexArray()->clone(osg::CopyOp::DEEP_COPY_ALL));
if (vertexArray)
{
vertexArray->setVertexBufferObject(vbo);
to.setVertexArray(vertexArray);
}
if (const osg::Array* normals = from.getNormalArray())
{
osg::ref_ptr<osg::Array> normalArray
= static_cast<osg::Array*>(normals->clone(osg::CopyOp::DEEP_COPY_ALL));
if (normalArray)
{
normalArray->setVertexBufferObject(vbo);
to.setNormalArray(normalArray, osg::Array::BIND_PER_VERTEX);
}
}
if (const osg::Vec4Array* tangents = dynamic_cast<const osg::Vec4Array*>(from.getTexCoordArray(7)))
{
osg::ref_ptr<osg::Array> tangentArray
= static_cast<osg::Array*>(tangents->clone(osg::CopyOp::DEEP_COPY_ALL));
tangentArray->setVertexBufferObject(vbo);
to.setTexCoordArray(7, tangentArray, osg::Array::BIND_PER_VERTEX);
}
}
}
osg::ref_ptr<OsgaRigGeometry> RigGeometryHolder::getSourceRigGeometry() const
{
return mSourceRigGeometry;
}
void RigGeometryHolder::updateRigGeometry(OsgaRigGeometry* geom, osg::NodeVisitor* nv)
{
if (!geom)
return;
if (!geom->getSkeleton() && !this->getParents().empty())
{
osgAnimation::RigGeometry::FindNearestParentSkeleton finder;
if (this->getParents().size() > 1)
Log(Debug::Warning) << "A RigGeometry should not have multi parent ( " << geom->getName() << " )";
this->getParents()[0]->accept(finder);
if (!finder._root.valid())
{
Log(Debug::Warning) << "A RigGeometry did not find a parent skeleton for RigGeometry ( "
<< geom->getName() << " )";
return;
}
geom->getRigTransformImplementation()->prepareData(*geom);
geom->setSkeleton(finder._root.get());
}
if (!geom->getSkeleton())
return;
if (geom->getNeedToComputeMatrix())
{
osgAnimation::Skeleton* root = geom->getSkeleton();
if (!root)
{
Log(Debug::Warning)
<< "Warning: if you have this message it means you miss to call buildTransformer(Skeleton* root), "
"or your RigGeometry is not attached to a Skeleton subgraph";
return;
}
osg::MatrixList mtxList
= root->getWorldMatrices(root); // We always assume that RigGeometries have origin at their root
geom->computeMatrixFromRootSkeleton(std::move(mtxList));
if (mIsBodyPart && mBackToOrigin)
updateBackToOriginTransform(geom);
}
if (geom->getSourceGeometry())
{
osg::Drawable::UpdateCallback* up
= dynamic_cast<osg::Drawable::UpdateCallback*>(geom->getSourceGeometry()->getUpdateCallback());
if (up)
{
up->update(nv, geom->getSourceGeometry());
}
}
geom->update();
}
OsgaRigGeometry* RigGeometryHolder::getGeometry(int geometry)
{
return mGeometry.at(geometry).get();
}
void RigGeometryHolder::updateBackToOriginTransform(OsgaRigGeometry* geometry)
{
osgAnimation::Skeleton* skeleton = geometry->getSkeleton();
if (skeleton)
{
osg::MatrixList mtxList = mBackToOrigin->getParents()[0]->getWorldMatrices(skeleton);
osg::Matrix skeletonMatrix = skeleton->getMatrix();
osg::Matrixf matrixFromSkeletonToGeometry = mtxList[0] * osg::Matrix::inverse(skeletonMatrix);
osg::Matrixf invMatrixFromSkeletonToGeometry = osg::Matrix::inverse(matrixFromSkeletonToGeometry);
mBackToOrigin->setMatrix(invMatrixFromSkeletonToGeometry);
}
}
void RigGeometryHolder::accept(osg::NodeVisitor& nv)
{
if (!nv.validNodeMask(*this))
return;
nv.pushOntoNodePath(this);
if (nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR && mSourceRigGeometry.get())
{
// The cull visitor won't be applied to the node itself,
// but we want to use its state to render the child geometry.
osg::StateSet* stateset = getStateSet();
osgUtil::CullVisitor* cv = static_cast<osgUtil::CullVisitor*>(&nv);
if (stateset)
cv->pushStateSet(stateset);
unsigned int traversalNumber = nv.getTraversalNumber();
if (mLastFrameNumber == traversalNumber)
{
OsgaRigGeometry& geom = *getRigGeometryPerFrame(mLastFrameNumber);
nv.pushOntoNodePath(&geom);
nv.apply(geom);
nv.popFromNodePath();
}
else
{
mLastFrameNumber = traversalNumber;
OsgaRigGeometry& geom = *getRigGeometryPerFrame(mLastFrameNumber);
if (mIsBodyPart)
{
if (mBackToOrigin)
updateBackToOriginTransform(&geom);
else
{
osg::MatrixTransform* matrixTransform
= dynamic_cast<osg::MatrixTransform*>(this->getParents()[0]);
if (matrixTransform)
{
mBackToOrigin = matrixTransform;
updateBackToOriginTransform(&geom);
}
}
}
updateRigGeometry(&geom, &nv);
nv.pushOntoNodePath(&geom);
nv.apply(geom);
nv.popFromNodePath();
}
if (stateset)
cv->popStateSet();
}
else if (nv.getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR)
{
}
else
nv.apply(*this);
nv.popFromNodePath();
}
void RigGeometryHolder::accept(osg::PrimitiveFunctor& func) const
{
getRigGeometryPerFrame(mLastFrameNumber)->accept(func);
}
OsgaRigGeometry* RigGeometryHolder::getRigGeometryPerFrame(unsigned int frame) const
{
return mGeometry.at(frame % 2).get();
}
}
| 11,570
|
C++
|
.cpp
| 257
| 33.136187
| 120
| 0.601048
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,750
|
application.cpp
|
OpenMW_openmw/components/platform/application.cpp
|
#include "application.hpp"
#include <QFile>
#include <QOperatingSystemVersion>
#include <QStyle>
#include <QStyleHints>
#include <components/debug/debuglog.hpp>
#include <components/misc/scalableicon.hpp>
namespace Platform
{
Application::Application(int& argc, char* argv[])
: QApplication(argc, argv)
{
#if defined(WIN32) && QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
init();
}
static QString getStyleSheetPath()
{
QString qssPath(":/dark/dark_win10.qss");
if (QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows11)
qssPath = ":/dark/dark_win11.qss";
return qssPath;
}
void Application::init()
{
connect(this, &Application::darkModeChanged, this, &Application::updateStyle);
const auto* hints = QGuiApplication::styleHints();
const auto currentStyle = QApplication::style()->objectName();
mInitialStyle = currentStyle.toStdString();
mCurrentStyle = currentStyle.toStdString();
if (hints->colorScheme() == Qt::ColorScheme::Dark)
{
mDarkMode = true;
if (currentStyle == "windowsvista")
{
mCurrentStyle = "windows";
setStyle("windows");
QFile file(getStyleSheetPath());
if (!file.open(QIODevice::ReadOnly))
{
qDebug() << "Failed to open style sheet file:" << getStyleSheetPath();
return;
}
setStyleSheet(file.readAll());
}
}
}
void Application::updateStyle(bool isDark)
{
if (mInitialStyle != "windowsvista")
return;
if (isDark)
{
mCurrentStyle = "windows";
setStyle("windows");
QFile file(getStyleSheetPath());
if (!file.open(QIODevice::ReadOnly))
{
qDebug() << "Failed to open style sheet file:" << getStyleSheetPath();
return;
}
setStyleSheet(file.readAll());
}
else
{
mCurrentStyle = mInitialStyle;
setStyleSheet("");
setStyle(mInitialStyle.c_str());
}
#endif
}
bool Application::notify(QObject* receiver, QEvent* event)
{
try
{
if (event->type() == QEvent::ThemeChange || event->type() == QEvent::PaletteChange)
{
#if defined(WIN32) && QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
const auto* hints = QGuiApplication::styleHints();
const auto currentStyle = QApplication::style()->objectName();
bool isDark = hints->colorScheme() == Qt::ColorScheme::Dark;
if (isDark != mDarkMode)
{
mDarkMode = isDark;
bool result = QApplication::notify(receiver, event);
emit darkModeChanged(isDark);
return result;
}
#endif
Misc::ScalableIcon::updateAllIcons();
}
return QApplication::notify(receiver, event);
}
catch (const std::exception& exception)
{
Log(Debug::Error) << "An exception has been caught: " << exception.what();
}
return false;
}
}
| 3,373
|
C++
|
.cpp
| 99
| 23.747475
| 95
| 0.549923
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,751
|
file.stdio.cpp
|
OpenMW_openmw/components/platform/file.stdio.cpp
|
#include "file.hpp"
#include <cassert>
#include <errno.h>
#include <stdexcept>
#include <string.h>
#include <string>
#include <components/files/conversion.hpp>
namespace Platform::File
{
static auto getNativeHandle(Handle handle)
{
assert(handle != Handle::Invalid);
return reinterpret_cast<FILE*>(static_cast<intptr_t>(handle));
}
static int getNativeSeekType(SeekType seek)
{
if (seek == SeekType::Begin)
return SEEK_SET;
if (seek == SeekType::Current)
return SEEK_CUR;
if (seek == SeekType::End)
return SEEK_END;
return -1;
}
Handle open(const std::filesystem::path& filename)
{
FILE* handle = fopen(filename.c_str(), "rb");
if (handle == nullptr)
{
throw std::system_error(errno, std::generic_category(),
std::string("Failed to open '") + Files::pathToUnicodeString(filename) + "' for reading");
}
return static_cast<Handle>(reinterpret_cast<intptr_t>(handle));
}
void close(Handle handle)
{
auto nativeHandle = getNativeHandle(handle);
fclose(nativeHandle);
}
void seek(Handle handle, size_t position, SeekType type /*= SeekType::Begin*/)
{
const auto nativeHandle = getNativeHandle(handle);
const auto nativeSeekType = getNativeSeekType(type);
if (fseek(nativeHandle, position, nativeSeekType) != 0)
{
throw std::system_error(errno, std::generic_category(), std::string("An fseek() call failed"));
}
}
size_t size(Handle handle)
{
auto nativeHandle = getNativeHandle(handle);
const auto oldPos = tell(handle);
seek(handle, 0, SeekType::End);
const auto fileSize = tell(handle);
seek(handle, oldPos, SeekType::Begin);
return static_cast<size_t>(fileSize);
}
size_t tell(Handle handle)
{
auto nativeHandle = getNativeHandle(handle);
long position = ftell(nativeHandle);
if (position == -1)
{
throw std::system_error(errno, std::generic_category(), std::string("An ftell() call failed"));
}
return static_cast<size_t>(position);
}
size_t read(Handle handle, void* data, size_t size)
{
auto nativeHandle = getNativeHandle(handle);
int amount = fread(data, 1, size, nativeHandle);
if (amount == 0 && ferror(nativeHandle))
{
throw std::system_error(errno, std::generic_category(),
std::string("An attempt to read ") + std::to_string(size) + " bytes failed");
}
return static_cast<size_t>(amount);
}
}
| 2,718
|
C++
|
.cpp
| 79
| 26.860759
| 107
| 0.610603
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,752
|
platform.cpp
|
OpenMW_openmw/components/platform/platform.cpp
|
#include "platform.hpp"
#ifdef WIN32
#include <stdio.h>
#endif
namespace Platform
{
static void increaseFileHandleLimit()
{
#ifdef WIN32
// Increase limit for open files at the stream I/O level, see
// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setmaxstdio?view=msvc-170#remarks
_setmaxstdio(8192);
#else
// No-op on any other platform.
#endif
}
void init()
{
increaseFileHandleLimit();
}
}
| 482
|
C++
|
.cpp
| 21
| 18.666667
| 109
| 0.679825
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,753
|
file.posix.cpp
|
OpenMW_openmw/components/platform/file.posix.cpp
|
#include "file.hpp"
#include <cassert>
#include <errno.h>
#include <fcntl.h>
#include <stdexcept>
#include <string.h>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <components/files/conversion.hpp>
namespace Platform::File
{
static auto getNativeHandle(Handle handle)
{
assert(handle != Handle::Invalid);
return static_cast<int>(handle);
}
static int getNativeSeekType(SeekType seek)
{
if (seek == SeekType::Begin)
return SEEK_SET;
if (seek == SeekType::Current)
return SEEK_CUR;
if (seek == SeekType::End)
return SEEK_END;
return -1;
}
Handle open(const std::filesystem::path& filename)
{
#ifdef O_BINARY
static const int openFlags = O_RDONLY | O_BINARY;
#else
static const int openFlags = O_RDONLY;
#endif
auto handle = ::open(filename.c_str(), openFlags, 0);
if (handle == -1)
{
throw std::system_error(errno, std::generic_category(),
std::string("Failed to open '") + Files::pathToUnicodeString(filename) + "' for reading");
}
return static_cast<Handle>(handle);
}
void close(Handle handle)
{
auto nativeHandle = getNativeHandle(handle);
::close(nativeHandle);
}
void seek(Handle handle, size_t position, SeekType type /*= SeekType::Begin*/)
{
const auto nativeHandle = getNativeHandle(handle);
const auto nativeSeekType = getNativeSeekType(type);
if (::lseek(nativeHandle, position, nativeSeekType) == -1)
{
throw std::system_error(errno, std::generic_category(), "An lseek() call failed");
}
}
size_t size(Handle handle)
{
const auto oldPos = tell(handle);
seek(handle, 0, SeekType::End);
const auto fileSize = tell(handle);
seek(handle, oldPos, SeekType::Begin);
return static_cast<size_t>(fileSize);
}
size_t tell(Handle handle)
{
auto nativeHandle = getNativeHandle(handle);
size_t position = ::lseek(nativeHandle, 0, SEEK_CUR);
if (position == size_t(-1))
{
throw std::system_error(errno, std::generic_category(), "An lseek() call failed");
}
return position;
}
size_t read(Handle handle, void* data, size_t size)
{
auto nativeHandle = getNativeHandle(handle);
int amount = ::read(nativeHandle, data, size);
if (amount == -1)
{
throw std::system_error(
errno, std::generic_category(), "An attempt to read " + std::to_string(size) + " bytes failed");
}
return amount;
}
}
| 2,733
|
C++
|
.cpp
| 86
| 24.639535
| 112
| 0.604111
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,754
|
file.win32.cpp
|
OpenMW_openmw/components/platform/file.win32.cpp
|
#include "file.hpp"
#include <cassert>
#include <components/misc/windows.hpp>
#include <stdexcept>
#include <string>
#include <components/files/conversion.hpp>
namespace Platform::File
{
static auto getNativeHandle(Handle handle)
{
assert(handle != Handle::Invalid);
return reinterpret_cast<HANDLE>(static_cast<intptr_t>(handle));
}
static int getNativeSeekType(SeekType seek)
{
if (seek == SeekType::Begin)
return FILE_BEGIN;
if (seek == SeekType::Current)
return FILE_CURRENT;
if (seek == SeekType::End)
return FILE_END;
return -1;
}
Handle open(const std::filesystem::path& filename)
{
HANDLE handle = CreateFileW(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
if (handle == INVALID_HANDLE_VALUE)
{
throw std::runtime_error(std::string("Failed to open '") + Files::pathToUnicodeString(filename)
+ "' for reading: " + std::to_string(GetLastError()));
}
return static_cast<Handle>(reinterpret_cast<intptr_t>(handle));
}
void close(Handle handle)
{
auto nativeHandle = getNativeHandle(handle);
CloseHandle(nativeHandle);
}
void seek(Handle handle, size_t position, SeekType type /*= SeekType::Begin*/)
{
const auto nativeHandle = getNativeHandle(handle);
const auto nativeSeekType = getNativeSeekType(type);
LARGE_INTEGER li;
li.QuadPart = static_cast<LONGLONG>(position);
if (!SetFilePointerEx(nativeHandle, li, nullptr, nativeSeekType))
{
if (auto errCode = GetLastError(); errCode != ERROR_SUCCESS)
{
throw std::runtime_error(std::string("An fseek() call failed: ") + std::to_string(errCode));
}
}
}
size_t size(Handle handle)
{
auto nativeHandle = getNativeHandle(handle);
BY_HANDLE_FILE_INFORMATION info;
if (!GetFileInformationByHandle(nativeHandle, &info))
throw std::runtime_error("A query operation on a file failed.");
if (info.nFileSizeHigh != 0)
throw std::runtime_error("Files greater that 4GB are not supported.");
return info.nFileSizeLow;
}
size_t tell(Handle handle)
{
auto nativeHandle = getNativeHandle(handle);
DWORD value = SetFilePointer(nativeHandle, 0, nullptr, SEEK_CUR);
if (value == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR)
throw std::runtime_error("A query operation on a file failed.");
return value;
}
size_t read(Handle handle, void* data, size_t size)
{
auto nativeHandle = getNativeHandle(handle);
DWORD bytesRead{};
if (!ReadFile(nativeHandle, data, static_cast<DWORD>(size), &bytesRead, nullptr))
throw std::runtime_error(
std::string("A read operation on a file failed: ") + std::to_string(GetLastError()));
return bytesRead;
}
}
| 3,070
|
C++
|
.cpp
| 80
| 30.35
| 109
| 0.629043
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,755
|
messagebundles.cpp
|
OpenMW_openmw/components/l10n/messagebundles.cpp
|
#include "messagebundles.hpp"
#include <cstring>
#include <unicode/calendar.h>
#include <unicode/errorcode.h>
#include <yaml-cpp/yaml.h>
#include <components/debug/debuglog.hpp>
namespace l10n
{
MessageBundles::MessageBundles(const std::vector<icu::Locale>& preferredLocales, icu::Locale& fallbackLocale)
: mFallbackLocale(fallbackLocale)
{
setPreferredLocales(preferredLocales);
}
void MessageBundles::setPreferredLocales(const std::vector<icu::Locale>& preferredLocales)
{
mPreferredLocales.clear();
mPreferredLocaleStrings.clear();
for (const icu::Locale& loc : preferredLocales)
{
mPreferredLocales.push_back(loc);
mPreferredLocaleStrings.emplace_back(loc.getName());
// Try without variant or country if they are specified, starting with the most specific
if (strcmp(loc.getVariant(), "") != 0)
{
icu::Locale withoutVariant(loc.getLanguage(), loc.getCountry());
mPreferredLocales.push_back(withoutVariant);
mPreferredLocaleStrings.emplace_back(withoutVariant.getName());
}
if (strcmp(loc.getCountry(), "") != 0)
{
icu::Locale withoutCountry(loc.getLanguage());
mPreferredLocales.push_back(withoutCountry);
mPreferredLocaleStrings.emplace_back(withoutCountry.getName());
}
}
}
std::string getErrorText(const UParseError& parseError)
{
icu::UnicodeString preContext(parseError.preContext), postContext(parseError.postContext);
std::string parseErrorString;
preContext.toUTF8String(parseErrorString);
postContext.toUTF8String(parseErrorString);
return parseErrorString;
}
static bool checkSuccess(
const icu::ErrorCode& status, const std::string& message, const UParseError parseError = UParseError())
{
if (status.isFailure())
{
std::string errorText = getErrorText(parseError);
if (!errorText.empty())
{
Log(Debug::Error) << message << ": " << status.errorName() << " in \"" << errorText << "\"";
}
else
{
Log(Debug::Error) << message << ": " << status.errorName();
}
}
return status.isSuccess();
}
void MessageBundles::load(std::istream& input, const icu::Locale& lang)
{
YAML::Node data = YAML::Load(input);
std::string localeName = lang.getName();
const icu::Locale& langOrEn = localeName == "gmst" ? icu::Locale::getEnglish() : lang;
for (const auto& it : data)
{
const auto key = it.first.as<std::string>();
const auto value = it.second.as<std::string>();
icu::UnicodeString pattern
= icu::UnicodeString::fromUTF8(icu::StringPiece(value.data(), static_cast<std::int32_t>(value.size())));
icu::ErrorCode status;
UParseError parseError;
icu::MessageFormat message(pattern, langOrEn, parseError, status);
if (checkSuccess(status, std::string("Failed to create message ") + key + " for locale " + lang.getName(),
parseError))
{
mBundles[localeName].insert(std::make_pair(key, message));
}
}
}
const icu::MessageFormat* MessageBundles::findMessage(std::string_view key, const std::string& localeName) const
{
auto iter = mBundles.find(localeName);
if (iter != mBundles.end())
{
auto message = iter->second.find(key.data());
if (message != iter->second.end())
{
return &(message->second);
}
}
return nullptr;
}
std::string MessageBundles::formatMessage(
std::string_view key, const std::map<std::string, icu::Formattable>& args) const
{
std::vector<icu::UnicodeString> argNames;
std::vector<icu::Formattable> argValues;
for (auto& [k, v] : args)
{
argNames.push_back(
icu::UnicodeString::fromUTF8(icu::StringPiece(k.data(), static_cast<std::int32_t>(k.size()))));
argValues.push_back(v);
}
return formatMessage(key, argNames, argValues);
}
static std::string loadGmst(
const std::function<std::string(std::string_view)> gmstLoader, const icu::MessageFormat* message)
{
icu::UnicodeString gmstNameUnicode;
std::string gmstName;
icu::ErrorCode success;
message->format(nullptr, nullptr, 0, gmstNameUnicode, success);
gmstNameUnicode.toUTF8String(gmstName);
if (gmstLoader)
return gmstLoader(gmstName);
else
return "GMST:" + gmstName;
}
std::string MessageBundles::formatMessage(std::string_view key, const std::vector<icu::UnicodeString>& argNames,
const std::vector<icu::Formattable>& args) const
{
icu::UnicodeString result;
std::string resultString;
icu::ErrorCode success;
const icu::MessageFormat* message = nullptr;
for (auto& loc : mPreferredLocaleStrings)
{
message = findMessage(key, loc);
if (message)
{
if (loc == "gmst")
return loadGmst(mGmstLoader, message);
break;
}
}
// If no requested locales included the message, try the fallback locale
if (!message)
message = findMessage(key, mFallbackLocale.getName());
if (message)
{
if (!args.empty() && !argNames.empty())
message->format(argNames.data(), args.data(), static_cast<std::int32_t>(args.size()), result, success);
else
message->format(nullptr, nullptr, static_cast<std::int32_t>(args.size()), result, success);
checkSuccess(success, std::string("Failed to format message ") + key.data());
result.toUTF8String(resultString);
return resultString;
}
icu::Locale defaultLocale(nullptr);
if (!mPreferredLocales.empty())
{
defaultLocale = mPreferredLocales[0];
}
UParseError parseError;
icu::MessageFormat defaultMessage(
icu::UnicodeString::fromUTF8(icu::StringPiece(key.data(), static_cast<std::int32_t>(key.size()))),
defaultLocale, parseError, success);
if (!checkSuccess(success, std::string("Failed to create message ") + key.data(), parseError))
// If we can't parse the key as a pattern, just return the key
return std::string(key);
if (!args.empty() && !argNames.empty())
defaultMessage.format(
argNames.data(), args.data(), static_cast<std::int32_t>(args.size()), result, success);
else
defaultMessage.format(nullptr, nullptr, static_cast<std::int32_t>(args.size()), result, success);
checkSuccess(success, std::string("Failed to format message ") + key.data());
result.toUTF8String(resultString);
return resultString;
}
}
| 7,276
|
C++
|
.cpp
| 173
| 31.936416
| 120
| 0.600085
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,756
|
manager.cpp
|
OpenMW_openmw/components/l10n/manager.cpp
|
#include "manager.hpp"
#include <set>
#include <unicode/errorcode.h>
#include <components/debug/debuglog.hpp>
#include <components/vfs/manager.hpp>
namespace l10n
{
void Manager::setPreferredLocales(const std::vector<std::string>& langs, bool gmstHasPriority)
{
mPreferredLocales.clear();
if (gmstHasPriority)
mPreferredLocales.push_back(icu::Locale("gmst"));
std::set<std::string> langSet;
for (const auto& lang : langs)
{
if (langSet.contains(lang))
continue;
langSet.insert(lang);
mPreferredLocales.push_back(icu::Locale(lang.c_str()));
}
if (!gmstHasPriority)
mPreferredLocales.push_back(icu::Locale("gmst"));
{
Log msg(Debug::Info);
msg << "Preferred locales:";
for (const icu::Locale& l : mPreferredLocales)
msg << " " << l.getName();
}
for (auto& [key, context] : mCache)
updateContext(key.first, *context);
}
void Manager::readLangData(const std::string& name, MessageBundles& ctx, const icu::Locale& lang)
{
std::string langName(lang.getName());
langName += ".yaml";
VFS::Path::Normalized path("l10n");
path /= name;
path /= langName;
const Files::IStreamPtr stream = mVFS->find(path);
if (stream == nullptr)
return;
try
{
ctx.load(*stream, lang);
}
catch (const std::exception& e)
{
Log(Debug::Error) << "Cannot load message bundles from " << path << ": " << e.what();
}
}
void Manager::updateContext(const std::string& name, MessageBundles& ctx)
{
icu::Locale fallbackLocale = ctx.getFallbackLocale();
ctx.setPreferredLocales(mPreferredLocales);
int localeCount = 0;
bool fallbackLocaleInPreferred = false;
for (const icu::Locale& loc : ctx.getPreferredLocales())
{
if (!ctx.isLoaded(loc))
readLangData(name, ctx, loc);
if (ctx.isLoaded(loc))
{
localeCount++;
Log(Debug::Verbose) << "Language file \"l10n/" << name << "/" << loc.getName() << ".yaml\" is enabled";
if (loc == ctx.getFallbackLocale())
fallbackLocaleInPreferred = true;
}
}
if (!ctx.isLoaded(ctx.getFallbackLocale()))
readLangData(name, ctx, ctx.getFallbackLocale());
if (ctx.isLoaded(ctx.getFallbackLocale()) && !fallbackLocaleInPreferred)
Log(Debug::Verbose) << "Fallback language file \"l10n/" << name << "/" << ctx.getFallbackLocale().getName()
<< ".yaml\" is enabled";
if (localeCount == 0)
{
Log(Debug::Warning) << "No language files for the preferred languages found in \"l10n/" << name << "\"";
}
}
std::shared_ptr<const MessageBundles> Manager::getContext(
const std::string& contextName, const std::string& fallbackLocaleName)
{
std::pair<std::string, std::string> key(contextName, fallbackLocaleName);
auto it = mCache.find(key);
if (it != mCache.end())
return it->second;
auto allowedChar = [](char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_';
};
bool valid = !contextName.empty();
for (char c : contextName)
valid = valid && allowedChar(c);
if (!valid)
throw std::runtime_error(std::string("Invalid l10n context name: ") + contextName);
icu::Locale fallbackLocale(fallbackLocaleName.c_str());
std::shared_ptr<MessageBundles> ctx = std::make_shared<MessageBundles>(mPreferredLocales, fallbackLocale);
ctx->setGmstLoader(mGmstLoader);
updateContext(contextName, *ctx);
mCache.emplace(key, ctx);
return ctx;
}
}
| 4,037
|
C++
|
.cpp
| 101
| 30.207921
| 119
| 0.563854
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,757
|
qttranslations.cpp
|
OpenMW_openmw/components/l10n/qttranslations.cpp
|
#include "qttranslations.hpp"
#include <QLibraryInfo>
#include <QLocale>
namespace l10n
{
QTranslator AppTranslator{};
QTranslator ComponentsTranslator{};
QTranslator QtBaseAppTranslator{};
void installQtTranslations(QApplication& app, const QString& appName, const QString& resourcesPath)
{
// Try to load OpenMW translations from resources folder first.
// If we loaded them, try to load Qt translations from both
// resources folder and default translations folder as well.
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
auto qtPath = QLibraryInfo::path(QLibraryInfo::TranslationsPath);
#else
auto qtPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#endif
auto localPath = resourcesPath + "/translations";
if (AppTranslator.load(QLocale::system(), appName, "_", localPath)
&& ComponentsTranslator.load(QLocale::system(), "components", "_", localPath))
{
app.installTranslator(&AppTranslator);
app.installTranslator(&ComponentsTranslator);
if (QtBaseAppTranslator.load(QLocale::system(), "qtbase", "_", localPath)
|| QtBaseAppTranslator.load(QLocale::system(), "qt", "_", localPath)
|| QtBaseAppTranslator.load(QLocale::system(), "qtbase", "_", qtPath)
|| QtBaseAppTranslator.load(QLocale::system(), "qt", "_", qtPath))
app.installTranslator(&QtBaseAppTranslator);
}
}
}
| 1,534
|
C++
|
.cpp
| 32
| 39.125
| 104
| 0.656166
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,758
|
fontloader.cpp
|
OpenMW_openmw/components/fontloader/fontloader.cpp
|
#include "fontloader.hpp"
#include <array>
#include <stdexcept>
#include <string_view>
#include <osg/Image>
#include <osgDB/WriteFile>
#include <MyGUI_FactoryManager.h>
#include <MyGUI_RenderManager.h>
#include <MyGUI_ResourceManager.h>
#include <MyGUI_ResourceManualFont.h>
#include <MyGUI_ResourceTrueTypeFont.h>
#include <MyGUI_XmlDocument.h>
#include <components/debug/debuglog.hpp>
#include <components/fallback/fallback.hpp>
#include <components/vfs/manager.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/myguiplatform/scalinglayer.hpp>
#include <components/settings/values.hpp>
namespace
{
MyGUI::xml::ElementPtr getProperty(MyGUI::xml::ElementPtr resourceNode, std::string_view propertyName)
{
MyGUI::xml::ElementPtr propertyNode = nullptr;
MyGUI::xml::ElementEnumerator propertyIterator = resourceNode->getElementEnumerator();
while (propertyIterator.next("Property"))
{
if (propertyIterator->findAttribute("key") == propertyName)
{
propertyNode = propertyIterator.current();
break;
}
}
return propertyNode;
}
MyGUI::IntSize getBookSize(MyGUI::IDataStream* layersStream)
{
MyGUI::xml::Document xmlDocument;
xmlDocument.open(layersStream);
MyGUI::xml::ElementPtr root = xmlDocument.getRoot();
MyGUI::xml::ElementEnumerator layersIterator = root->getElementEnumerator();
while (layersIterator.next("Layer"))
{
if (layersIterator->findAttribute("name") == "JournalBooks")
{
MyGUI::xml::ElementPtr sizeProperty = getProperty(layersIterator.current(), "Size");
if (sizeProperty != nullptr)
{
auto sizeValue = sizeProperty->findAttribute("value");
if (!sizeValue.empty())
return MyGUI::IntSize::parse(sizeValue);
}
}
}
return MyGUI::RenderManager::getInstance().getViewSize();
}
unsigned long utf8ToUnicode(std::string_view utf8)
{
if (utf8.empty())
return 0;
size_t i = 0;
unsigned long unicode;
size_t numbytes;
unsigned char ch = utf8[i++];
if (ch <= 0x7F)
{
unicode = ch;
numbytes = 0;
}
else if (ch <= 0xBF)
{
throw std::logic_error("not a UTF-8 string");
}
else if (ch <= 0xDF)
{
unicode = ch & 0x1F;
numbytes = 1;
}
else if (ch <= 0xEF)
{
unicode = ch & 0x0F;
numbytes = 2;
}
else if (ch <= 0xF7)
{
unicode = ch & 0x07;
numbytes = 3;
}
else
{
throw std::logic_error("not a UTF-8 string");
}
for (size_t j = 0; j < numbytes; ++j)
{
ch = utf8[i++];
if (ch < 0x80 || ch > 0xBF)
throw std::logic_error("not a UTF-8 string");
unicode <<= 6;
unicode += ch & 0x3F;
}
if (unicode >= 0xD800 && unicode <= 0xDFFF)
throw std::logic_error("not a UTF-8 string");
if (unicode > 0x10FFFF)
throw std::logic_error("not a UTF-8 string");
return unicode;
}
/// This is a hack for Polish font
unsigned char mapUtf8Char(unsigned char c)
{
switch (c)
{
case 0x80:
return 0xc6;
case 0x81:
return 0x9c;
case 0x82:
return 0xe6;
case 0x83:
return 0xb3;
case 0x84:
return 0xf1;
case 0x85:
return 0xb9;
case 0x86:
return 0xbf;
case 0x87:
return 0x9f;
case 0x88:
return 0xea;
case 0x89:
return 0xea;
case 0x8a:
return 0x00; // not contained in win1250
case 0x8b:
return 0x00; // not contained in win1250
case 0x8c:
return 0x8f;
case 0x8d:
return 0xaf;
case 0x8e:
return 0xa5;
case 0x8f:
return 0x8c;
case 0x90:
return 0xca;
case 0x93:
return 0xa3;
case 0x94:
return 0xf6;
case 0x95:
return 0xf3;
case 0x96:
return 0xaf;
case 0x97:
return 0x8f;
case 0x99:
return 0xd3;
case 0x9a:
return 0xd1;
case 0x9c:
return 0x00; // not contained in win1250
case 0xa0:
return 0xb9;
case 0xa1:
return 0xaf;
case 0xa2:
return 0xf3;
case 0xa3:
return 0xbf;
case 0xa4:
return 0x00; // not contained in win1250
case 0xe1:
return 0x8c;
case 0xe3:
return 0x00; // not contained in win1250
case 0xf5:
return 0x00; // not contained in win1250
default:
return c;
}
}
// getUnicode includes various hacks for dealing with Morrowind's .fnt files that are *mostly*
// in the expected win12XX encoding, but also have randomly swapped characters sometimes.
// Looks like the Morrowind developers found standard encodings too boring and threw in some twists for fun.
unsigned long getUnicode(unsigned char c, ToUTF8::Utf8Encoder& encoder, ToUTF8::FromType encoding)
{
if (encoding == ToUTF8::WINDOWS_1250) // Hack for polish font
{
const std::array<char, 2> str{ static_cast<char>(mapUtf8Char(c)), '\0' };
return utf8ToUnicode(encoder.getUtf8(std::string_view(str.data(), 1)));
}
else
{
const std::array<char, 2> str{ static_cast<char>(c), '\0' };
return utf8ToUnicode(encoder.getUtf8(std::string_view(str.data(), 1)));
}
}
[[noreturn]] void fail(std::istream& stream, std::string_view fileName, std::string_view message)
{
std::stringstream error;
error << "Font loading error: " << message;
error << "\n File: " << fileName;
error << "\n Offset: 0x" << std::hex << stream.tellg();
throw std::runtime_error(error.str());
}
}
namespace Gui
{
FontLoader::FontLoader(ToUTF8::FromType encoding, const VFS::Manager* vfs, float scalingFactor)
: mVFS(vfs)
, mScalingFactor(scalingFactor)
{
if (encoding == ToUTF8::WINDOWS_1252)
mEncoding = ToUTF8::CP437;
else
mEncoding = encoding;
MyGUI::ResourceManager::getInstance().unregisterLoadXmlDelegate("Resource");
MyGUI::ResourceManager::getInstance().registerLoadXmlDelegate("Resource")
= MyGUI::newDelegate(this, &FontLoader::overrideLineHeight);
loadFonts();
}
void FontLoader::loadFonts()
{
std::string defaultFont{ Fallback::Map::getString("Fonts_Font_0") };
std::string scrollFont{ Fallback::Map::getString("Fonts_Font_2") };
loadFont(defaultFont, "DefaultFont");
loadFont(scrollFont, "ScrollFont");
loadFont("DejaVuLGCSansMono",
"MonoFont"); // We need to use a TrueType monospace font to display debug texts properly.
// Use our TrueType fonts as a fallback.
if (!MyGUI::ResourceManager::getInstance().isExist("DefaultFont")
&& !Misc::StringUtils::ciEqual(defaultFont, "MysticCards"))
loadFont("MysticCards", "DefaultFont");
if (!MyGUI::ResourceManager::getInstance().isExist("ScrollFont")
&& !Misc::StringUtils::ciEqual(scrollFont, "DemonicLetters"))
loadFont("DemonicLetters", "ScrollFont");
}
void FontLoader::loadFont(const std::string& fileName, const std::string& fontId)
{
if (mVFS->exists("fonts/" + fileName + ".fnt"))
loadBitmapFont(fileName + ".fnt", fontId);
else if (mVFS->exists("fonts/" + fileName + ".omwfont"))
loadTrueTypeFont(fileName + ".omwfont", fontId);
else
Log(Debug::Error) << "Font '" << fileName << "' is not found.";
}
void FontLoader::loadTrueTypeFont(const std::string& fileName, const std::string& fontId)
{
Log(Debug::Info) << "Loading font file " << fileName;
osgMyGUI::DataManager* dataManager
= dynamic_cast<osgMyGUI::DataManager*>(&osgMyGUI::DataManager::getInstance());
if (!dataManager)
{
Log(Debug::Error) << "Can not load TrueType font " << fontId << ": osgMyGUI::DataManager is not available.";
return;
}
// TODO: it may be worth to take in account resolution change, but it is not safe to replace used assets
std::unique_ptr<MyGUI::IDataStream> layersStream(dataManager->getData("openmw_layers.xml"));
MyGUI::IntSize bookSize = getBookSize(layersStream.get());
float bookScale = osgMyGUI::ScalingLayer::getScaleFactor(bookSize);
const auto oldDataPath = dataManager->getDataPath({});
dataManager->setResourcePath("fonts");
std::unique_ptr<MyGUI::IDataStream> dataStream(dataManager->getData(fileName));
MyGUI::xml::Document xmlDocument;
xmlDocument.open(dataStream.get());
MyGUI::xml::ElementPtr root = xmlDocument.getRoot();
MyGUI::xml::ElementEnumerator resourceNode = root->getElementEnumerator();
bool valid = false;
if (resourceNode.next("Resource"))
{
valid = resourceNode->findAttribute("type") == "ResourceTrueTypeFont";
}
if (valid == false)
{
dataManager->setResourcePath(oldDataPath);
Log(Debug::Error) << "Can not load TrueType font " << fontId << ": " << fileName << " is invalid.";
return;
}
int resolution = 70;
MyGUI::xml::ElementPtr resolutionNode = getProperty(resourceNode.current(), "Resolution");
if (resolutionNode == nullptr)
{
resolutionNode = resourceNode->createChild("Property");
resolutionNode->addAttribute("key", "Resolution");
}
else
resolution = MyGUI::utility::parseInt(resolutionNode->findAttribute("value"));
resolutionNode->setAttribute("value", MyGUI::utility::toString(resolution * std::ceil(mScalingFactor)));
MyGUI::xml::ElementPtr sizeNode = resourceNode->createChild("Property");
sizeNode->addAttribute("key", "Size");
sizeNode->addAttribute("value", std::to_string(Settings::gui().mFontSize));
MyGUI::ResourceTrueTypeFont* font = static_cast<MyGUI::ResourceTrueTypeFont*>(
MyGUI::FactoryManager::getInstance().createObject("Resource", "ResourceTrueTypeFont"));
font->deserialization(resourceNode.current(), MyGUI::Version(3, 2, 0));
font->setResourceName(fontId);
MyGUI::ResourceManager::getInstance().addResource(font);
resolutionNode->setAttribute(
"value", MyGUI::utility::toString(static_cast<int>(resolution * bookScale * mScalingFactor)));
MyGUI::ResourceTrueTypeFont* bookFont = static_cast<MyGUI::ResourceTrueTypeFont*>(
MyGUI::FactoryManager::getInstance().createObject("Resource", "ResourceTrueTypeFont"));
bookFont->deserialization(resourceNode.current(), MyGUI::Version(3, 2, 0));
bookFont->setResourceName("Journalbook " + fontId);
MyGUI::ResourceManager::getInstance().addResource(bookFont);
dataManager->setResourcePath(oldDataPath);
if (resourceNode.next("Resource"))
Log(Debug::Warning) << "Font file " << fileName
<< " contains multiple Resource entries, only first one will be used.";
}
typedef struct
{
float x;
float y;
} Point;
typedef struct
{
float u1; // appears unused, always 0
Point top_left;
Point top_right;
Point bottom_left;
Point bottom_right;
float width;
float height;
float u2; // appears unused, always 0
float kerning;
float ascent;
} GlyphInfo;
void FontLoader::loadBitmapFont(const std::string& fileName, const std::string& fontId)
{
Log(Debug::Info) << "Loading font file " << fileName;
Files::IStreamPtr file = mVFS->get("fonts/" + fileName);
float fontSize;
file->read((char*)&fontSize, sizeof(fontSize));
if (!file->good())
fail(*file, fileName, "File too small to be a valid font");
int one;
file->read((char*)&one, sizeof(one));
if (!file->good())
fail(*file, fileName, "File too small to be a valid font");
if (one != 1)
fail(*file, fileName, "Unexpected value");
file->read((char*)&one, sizeof(one));
if (!file->good())
fail(*file, fileName, "File too small to be a valid font");
if (one != 1)
fail(*file, fileName, "Unexpected value");
char name_[284];
file->read(name_, sizeof(name_));
if (!file->good())
fail(*file, fileName, "File too small to be a valid font");
GlyphInfo data[256];
file->read((char*)data, sizeof(data));
if (!file->good())
fail(*file, fileName, "File too small to be a valid font");
file.reset();
// Create the font texture
std::string bitmapFilename = "fonts/" + std::string(name_) + ".tex";
Files::IStreamPtr bitmapFile = mVFS->get(bitmapFilename);
int width, height;
bitmapFile->read((char*)&width, sizeof(int));
bitmapFile->read((char*)&height, sizeof(int));
if (!bitmapFile->good())
fail(*bitmapFile, bitmapFilename, "File too small to be a valid bitmap");
if (width <= 0 || height <= 0)
fail(*bitmapFile, bitmapFilename, "Width and height must be positive");
std::vector<char> textureData;
textureData.resize(width * height * 4);
bitmapFile->read(textureData.data(), width * height * 4);
if (!bitmapFile->good())
fail(*bitmapFile, bitmapFilename, "File too small to be a valid bitmap");
bitmapFile.reset();
MyGUI::ITexture* tex = MyGUI::RenderManager::getInstance().createTexture(bitmapFilename);
tex->createManual(width, height, MyGUI::TextureUsage::Write, MyGUI::PixelFormat::R8G8B8A8);
unsigned char* texData = reinterpret_cast<unsigned char*>(tex->lock(MyGUI::TextureUsage::Write));
memcpy(texData, textureData.data(), textureData.size());
tex->unlock();
// We need to emulate loading from XML because the data members are private as of mygui 3.2.0
MyGUI::xml::Document xmlDocument;
MyGUI::xml::ElementPtr root = xmlDocument.createRoot("ResourceManualFont");
root->addAttribute("name", fontId);
MyGUI::xml::ElementPtr defaultHeight = root->createChild("Property");
defaultHeight->addAttribute("key", "DefaultHeight");
defaultHeight->addAttribute("value", fontSize);
MyGUI::xml::ElementPtr source = root->createChild("Property");
source->addAttribute("key", "Source");
source->addAttribute("value", bitmapFilename);
MyGUI::xml::ElementPtr codes = root->createChild("Codes");
// Fall back from unavailable Windows-1252 encoding symbols to similar characters available in the game
// fonts
std::multimap<int, int> additional; // fallback glyph index, unicode
additional.emplace(156, 0x00A2); // cent sign
additional.emplace(89, 0x00A5); // yen sign
additional.emplace(221, 0x00A6); // broken bar
additional.emplace(99, 0x00A9); // copyright sign
additional.emplace(97, 0x00AA); // prima ordinal indicator
additional.emplace(60, 0x00AB); // double left-pointing angle quotation mark
additional.emplace(45, 0x00AD); // soft hyphen
additional.emplace(114, 0x00AE); // registered trademark symbol
additional.emplace(45, 0x00AF); // macron
additional.emplace(241, 0x00B1); // plus-minus sign
additional.emplace(50, 0x00B2); // superscript two
additional.emplace(51, 0x00B3); // superscript three
additional.emplace(44, 0x00B8); // cedilla
additional.emplace(49, 0x00B9); // superscript one
additional.emplace(111, 0x00BA); // primo ordinal indicator
additional.emplace(62, 0x00BB); // double right-pointing angle quotation mark
additional.emplace(63, 0x00BF); // inverted question mark
additional.emplace(65, 0x00C6); // latin capital ae ligature
additional.emplace(79, 0x00D8); // latin capital o with stroke
additional.emplace(97, 0x00E6); // latin small ae ligature
additional.emplace(111, 0x00F8); // latin small o with stroke
additional.emplace(79, 0x0152); // latin capital oe ligature
additional.emplace(111, 0x0153); // latin small oe ligature
additional.emplace(83, 0x015A); // latin capital s with caron
additional.emplace(115, 0x015B); // latin small s with caron
additional.emplace(89, 0x0178); // latin capital y with diaresis
additional.emplace(90, 0x017D); // latin capital z with caron
additional.emplace(122, 0x017E); // latin small z with caron
additional.emplace(102, 0x0192); // latin small f with hook
additional.emplace(94, 0x02C6); // circumflex modifier
additional.emplace(126, 0x02DC); // small tilde
additional.emplace(69, 0x0401); // cyrillic capital io (no diaeresis latin e is available)
additional.emplace(137, 0x0451); // cyrillic small io
additional.emplace(45, 0x2012); // figure dash
additional.emplace(45, 0x2013); // en dash
additional.emplace(45, 0x2014); // em dash
additional.emplace(39, 0x2018); // left single quotation mark
additional.emplace(39, 0x2019); // right single quotation mark
additional.emplace(44, 0x201A); // single low quotation mark
additional.emplace(39, 0x201B); // single high quotation mark (reversed)
additional.emplace(34, 0x201C); // left double quotation mark
additional.emplace(34, 0x201D); // right double quotation mark
additional.emplace(44, 0x201E); // double low quotation mark
additional.emplace(34, 0x201F); // double high quotation mark (reversed)
additional.emplace(43, 0x2020); // dagger
additional.emplace(216, 0x2021); // double dagger (note: this glyph is not available)
additional.emplace(46, 0x2026); // ellipsis
additional.emplace(37, 0x2030); // per mille sign
additional.emplace(60, 0x2039); // single left-pointing angle quotation mark
additional.emplace(62, 0x203A); // single right-pointing angle quotation mark
additional.emplace(101, 0x20AC); // euro sign
additional.emplace(84, 0x2122); // trademark sign
additional.emplace(45, 0x2212); // minus sign
for (int i = 0; i < 256; i++)
{
float x1 = data[i].top_left.x * width;
float y1 = data[i].top_left.y * height;
float w = data[i].top_right.x * width - x1;
float h = data[i].bottom_left.y * height - y1;
ToUTF8::Utf8Encoder encoder(mEncoding);
unsigned long unicodeVal = getUnicode(i, encoder, mEncoding);
MyGUI::xml::ElementPtr code = codes->createChild("Code");
code->addAttribute("index", unicodeVal);
code->addAttribute("coord",
MyGUI::utility::toString(x1) + " " + MyGUI::utility::toString(y1) + " " + MyGUI::utility::toString(w)
+ " " + MyGUI::utility::toString(h));
code->addAttribute("advance", data[i].width);
code->addAttribute("bearing",
MyGUI::utility::toString(data[i].kerning) + " "
+ MyGUI::utility::toString((fontSize - data[i].ascent)));
code->addAttribute(
"size", MyGUI::IntSize(static_cast<int>(data[i].width), static_cast<int>(data[i].height)));
for (auto [it, end] = additional.equal_range(i); it != end; ++it)
{
code = codes->createChild("Code");
code->addAttribute("index", it->second);
code->addAttribute("coord",
MyGUI::utility::toString(x1) + " " + MyGUI::utility::toString(y1) + " "
+ MyGUI::utility::toString(w) + " " + MyGUI::utility::toString(h));
code->addAttribute("advance", data[i].width);
code->addAttribute("bearing",
MyGUI::utility::toString(data[i].kerning) + " "
+ MyGUI::utility::toString((fontSize - data[i].ascent)));
code->addAttribute(
"size", MyGUI::IntSize(static_cast<int>(data[i].width), static_cast<int>(data[i].height)));
}
// ASCII vertical bar, use this as text input cursor
if (i == 124)
{
MyGUI::xml::ElementPtr cursorCode = codes->createChild("Code");
cursorCode->addAttribute("index", MyGUI::FontCodeType::Cursor);
cursorCode->addAttribute("coord",
MyGUI::utility::toString(x1) + " " + MyGUI::utility::toString(y1) + " "
+ MyGUI::utility::toString(w) + " " + MyGUI::utility::toString(h));
cursorCode->addAttribute("advance", data[i].width);
cursorCode->addAttribute("bearing",
MyGUI::utility::toString(data[i].kerning) + " "
+ MyGUI::utility::toString((fontSize - data[i].ascent)));
cursorCode->addAttribute(
"size", MyGUI::IntSize(static_cast<int>(data[i].width), static_cast<int>(data[i].height)));
}
// Question mark, use for NotDefined marker (used for glyphs not existing in the font)
if (i == 63)
{
MyGUI::xml::ElementPtr cursorCode = codes->createChild("Code");
cursorCode->addAttribute("index", MyGUI::FontCodeType::NotDefined);
cursorCode->addAttribute("coord",
MyGUI::utility::toString(x1) + " " + MyGUI::utility::toString(y1) + " "
+ MyGUI::utility::toString(w) + " " + MyGUI::utility::toString(h));
cursorCode->addAttribute("advance", data[i].width);
cursorCode->addAttribute("bearing",
MyGUI::utility::toString(data[i].kerning) + " "
+ MyGUI::utility::toString((fontSize - data[i].ascent)));
cursorCode->addAttribute(
"size", MyGUI::IntSize(static_cast<int>(data[i].width), static_cast<int>(data[i].height)));
}
}
// These are required as well, but the fonts don't provide them
for (int i = 0; i < 2; ++i)
{
MyGUI::FontCodeType::Enum type;
if (i == 0)
type = MyGUI::FontCodeType::Selected;
else // if (i == 1)
type = MyGUI::FontCodeType::SelectedBack;
MyGUI::xml::ElementPtr cursorCode = codes->createChild("Code");
cursorCode->addAttribute("index", type);
cursorCode->addAttribute("coord", "0 0 0 0");
cursorCode->addAttribute("advance", "0");
cursorCode->addAttribute("bearing", "0 0");
cursorCode->addAttribute("size", "0 0");
}
// Register the font with MyGUI
MyGUI::ResourceManualFont* font = static_cast<MyGUI::ResourceManualFont*>(
MyGUI::FactoryManager::getInstance().createObject("Resource", "ResourceManualFont"));
font->deserialization(root, MyGUI::Version(3, 2, 0));
MyGUI::ResourceManualFont* bookFont = static_cast<MyGUI::ResourceManualFont*>(
MyGUI::FactoryManager::getInstance().createObject("Resource", "ResourceManualFont"));
bookFont->deserialization(root, MyGUI::Version(3, 2, 0));
bookFont->setResourceName("Journalbook " + fontId);
MyGUI::ResourceManager::getInstance().addResource(font);
MyGUI::ResourceManager::getInstance().addResource(bookFont);
}
void FontLoader::overrideLineHeight(MyGUI::xml::ElementPtr _node, std::string_view _file, MyGUI::Version _version)
{
// We should adjust line height for MyGUI widgets depending on font size
MyGUI::xml::ElementEnumerator resourceNode = _node->getElementEnumerator();
while (resourceNode.next("Resource"))
{
auto type = resourceNode->findAttribute("type");
if (Misc::StringUtils::ciEqual(type, "ResourceLayout"))
{
MyGUI::xml::ElementEnumerator resourceRootNode = resourceNode->getElementEnumerator();
while (resourceRootNode.next("Widget"))
{
if (resourceRootNode->findAttribute("name") != "Root")
continue;
MyGUI::xml::ElementPtr heightNode = resourceRootNode->createChild("UserString");
heightNode->addAttribute("key", "HeightLine");
heightNode->addAttribute("value", std::to_string(Settings::gui().mFontSize + 2));
break;
}
}
}
MyGUI::ResourceManager::getInstance().loadFromXmlNode(_node, _file, _version);
}
std::string_view FontLoader::getFontForFace(std::string_view face)
{
if (Misc::StringUtils::ciEqual(face, "daedric"))
return "ScrollFont";
return "DefaultFont";
}
}
| 26,281
|
C++
|
.cpp
| 561
| 35.802139
| 120
| 0.592503
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,759
|
transaction.cpp
|
OpenMW_openmw/components/sqlite3/transaction.cpp
|
#include "transaction.hpp"
#include <components/debug/debuglog.hpp>
#include <sqlite3.h>
#include <stdexcept>
#include <string>
namespace Sqlite3
{
namespace
{
const char* getBeginStatement(TransactionMode mode)
{
switch (mode)
{
case TransactionMode::Default:
return "BEGIN";
case TransactionMode::Deferred:
return "BEGIN DEFERRED";
case TransactionMode::Immediate:
return "BEGIN IMMEDIATE";
case TransactionMode::Exclusive:
return "BEGIN EXCLUSIVE";
}
throw std::logic_error("Invalid transaction mode: "
+ std::to_string(static_cast<std::underlying_type_t<TransactionMode>>(mode)));
}
}
void Rollback::operator()(sqlite3* db) const
{
if (db == nullptr)
return;
if (const int ec = sqlite3_exec(db, "ROLLBACK", nullptr, nullptr, nullptr); ec != SQLITE_OK)
Log(Debug::Debug) << "Failed to rollback SQLite3 transaction: " << sqlite3_errmsg(db) << " (" << ec << ")";
}
Transaction::Transaction(sqlite3& db, TransactionMode mode)
: mDb(&db)
{
if (const int ec = sqlite3_exec(&db, getBeginStatement(mode), nullptr, nullptr, nullptr); ec != SQLITE_OK)
{
(void)mDb.release();
throw std::runtime_error(
"Failed to start transaction: " + std::string(sqlite3_errmsg(&db)) + " (" + std::to_string(ec) + ")");
}
}
void Transaction::commit()
{
if (const int ec = sqlite3_exec(mDb.get(), "COMMIT", nullptr, nullptr, nullptr); ec != SQLITE_OK)
throw std::runtime_error("Failed to commit transaction: " + std::string(sqlite3_errmsg(mDb.get())) + " ("
+ std::to_string(ec) + ")");
(void)mDb.release();
}
}
| 1,932
|
C++
|
.cpp
| 51
| 28.196078
| 119
| 0.559232
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,760
|
statement.cpp
|
OpenMW_openmw/components/sqlite3/statement.cpp
|
#include "statement.hpp"
#include <sqlite3.h>
#include <stdexcept>
#include <string>
#include <string_view>
namespace Sqlite3
{
void CloseSqlite3Stmt::operator()(sqlite3_stmt* handle) const noexcept
{
sqlite3_finalize(handle);
}
StatementHandle makeStatementHandle(sqlite3& db, std::string_view query)
{
sqlite3_stmt* stmt = nullptr;
if (const int ec = sqlite3_prepare_v2(&db, query.data(), static_cast<int>(query.size()), &stmt, nullptr);
ec != SQLITE_OK)
throw std::runtime_error("Failed to prepare statement for query \"" + std::string(query)
+ "\": " + std::string(sqlite3_errmsg(&db)));
return StatementHandle(stmt);
}
}
| 726
|
C++
|
.cpp
| 21
| 28.809524
| 113
| 0.649073
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,761
|
db.cpp
|
OpenMW_openmw/components/sqlite3/db.cpp
|
#include "db.hpp"
#include <sqlite3.h>
#include <stdexcept>
#include <string>
#include <string_view>
namespace Sqlite3
{
void CloseSqlite3::operator()(sqlite3* handle) const noexcept
{
sqlite3_close_v2(handle);
}
Db makeDb(std::string_view path, const char* schema)
{
sqlite3* handle = nullptr;
// All uses of NavMeshDb are protected by a mutex (navmeshtool) or serialized in a single thread (DbWorker)
// so additional synchronization between threads is not required and SQLITE_OPEN_NOMUTEX can be used.
// This is unsafe to use NavMeshDb without external synchronization because of internal state.
const int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
if (const int ec = sqlite3_open_v2(std::string(path).c_str(), &handle, flags, nullptr); ec != SQLITE_OK)
{
const std::string message(sqlite3_errmsg(handle));
sqlite3_close(handle);
throw std::runtime_error("Failed to open database: " + message);
}
Db result(handle);
if (const int ec = sqlite3_exec(result.get(), schema, nullptr, nullptr, nullptr); ec != SQLITE_OK)
throw std::runtime_error("Failed create database schema: " + std::string(sqlite3_errmsg(handle)));
return result;
}
}
| 1,340
|
C++
|
.cpp
| 30
| 37.933333
| 115
| 0.668453
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,762
|
loadscrl.cpp
|
OpenMW_openmw/components/esm4/loadscrl.cpp
|
/*
Copyright (C) 2019-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadscrl.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Scroll::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("DESC"):
reader.getLocalizedString(mText);
break;
case ESM::fourCC("DATA"):
reader.get(mData.value);
reader.get(mData.weight);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("YNAM"):
reader.getFormId(mPickUpSound);
break;
case ESM::fourCC("ZNAM"):
reader.getFormId(mDropSound);
break;
// case ESM::fourCC("MODB"): reader.get(mBoundRadius); break;
case ESM::fourCC("OBND"):
case ESM::fourCC("CTDA"):
case ESM::fourCC("EFID"):
case ESM::fourCC("EFIT"):
case ESM::fourCC("ETYP"):
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("MDOB"):
case ESM::fourCC("MODT"):
case ESM::fourCC("SPIT"):
case ESM::fourCC("CIS2"):
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::SCRL::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Scroll::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Scroll::blank()
//{
// }
| 3,126
|
C++
|
.cpp
| 80
| 30.075
| 114
| 0.613382
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,763
|
loadmato.cpp
|
OpenMW_openmw/components/esm4/loadmato.cpp
|
/*
Copyright (C) 2016, 2018 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadmato.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Material::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("DNAM"):
case ESM::fourCC("DATA"):
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::MATO::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Material::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Material::blank()
//{
// }
| 2,314
|
C++
|
.cpp
| 58
| 33.172414
| 114
| 0.667112
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,764
|
loadfurn.cpp
|
OpenMW_openmw/components/esm4/loadfurn.cpp
|
/*
Copyright (C) 2016, 2018, 2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadfurn.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Furniture::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
{
std::string name;
reader.getLocalizedString(name);
// FIXME: subsequent FULL subrecords name object combinations (FO4)
if (mFullName.empty())
mFullName = std::move(name);
break;
}
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("MNAM"):
reader.get(mActiveMarkerFlags);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("DAMC"): // Destructible
case ESM::fourCC("DEST"):
case ESM::fourCC("DMDC"):
case ESM::fourCC("DMDL"):
case ESM::fourCC("DMDT"):
case ESM::fourCC("DMDS"):
case ESM::fourCC("DSTA"):
case ESM::fourCC("DSTD"):
case ESM::fourCC("DSTF"): // Destructible end
case ESM::fourCC("ENAM"):
case ESM::fourCC("FNAM"):
case ESM::fourCC("FNMK"):
case ESM::fourCC("FNPR"):
case ESM::fourCC("KNAM"):
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("NAM0"):
case ESM::fourCC("OBND"):
case ESM::fourCC("PNAM"):
case ESM::fourCC("VMAD"):
case ESM::fourCC("WBDT"):
case ESM::fourCC("XMRK"):
case ESM::fourCC("PRPS"):
case ESM::fourCC("CTDA"):
case ESM::fourCC("CIS1"):
case ESM::fourCC("CIS2"):
case ESM::fourCC("APPR"): // FO4
case ESM::fourCC("ATTX"): // FO4
case ESM::fourCC("CITC"): // FO4
case ESM::fourCC("CNTO"): // FO4
case ESM::fourCC("COCT"): // FO4
case ESM::fourCC("COED"): // FO4
case ESM::fourCC("FTYP"): // FO4
case ESM::fourCC("NAM1"): // FO4
case ESM::fourCC("NTRM"): // FO4
case ESM::fourCC("NVNM"): // FO4
case ESM::fourCC("PTRN"): // FO4
case ESM::fourCC("SNAM"): // FO4
case ESM::fourCC("WNAM"): // FO4
case ESM::fourCC("OBTE"): // FO4 object template start
case ESM::fourCC("OBTF"):
case ESM::fourCC("OBTS"):
case ESM::fourCC("STOP"): // FO4 object template end
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::FURN::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Furniture::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Furniture::blank()
//{
// }
| 4,726
|
C++
|
.cpp
| 117
| 30.059829
| 114
| 0.565586
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,765
|
loadpwat.cpp
|
OpenMW_openmw/components/esm4/loadpwat.cpp
|
/*
Copyright (C) 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
Also see https://tes5edit.github.io/fopdoc/ for FO3/FONV specific details.
*/
#include "loadpwat.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::PlaceableWater::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("OBND"):
case ESM::fourCC("MODL"):
case ESM::fourCC("DNAM"):
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::PWAT::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::PlaceableWater::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::PlaceableWater::blank()
//{
// }
| 2,154
|
C++
|
.cpp
| 53
| 34.830189
| 114
| 0.69636
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,766
|
loadhair.cpp
|
OpenMW_openmw/components/esm4/loadhair.cpp
|
/*
Copyright (C) 2016, 2018, 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadhair.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Hair::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getZString(mFullName);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("ICON"):
reader.getZString(mIcon);
break;
case ESM::fourCC("DATA"):
reader.get(mData);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("MODT"):
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::HAIR::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Hair::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Hair::blank()
//{
// }
| 2,495
|
C++
|
.cpp
| 65
| 30.492308
| 114
| 0.641853
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,767
|
loadidlm.cpp
|
OpenMW_openmw/components/esm4/loadidlm.cpp
|
/*
Copyright (C) 2019, 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadidlm.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::IdleMarker::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
std::uint32_t esmVer = reader.esmVersion();
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("IDLF"):
reader.get(mIdleFlags);
break;
case ESM::fourCC("IDLC"):
if (subHdr.dataSize != 1) // FO3 can have 4?
{
reader.skipSubRecordData();
break;
}
reader.get(mIdleCount);
break;
case ESM::fourCC("IDLT"):
reader.get(mIdleTimer);
break;
case ESM::fourCC("IDLA"):
{
bool isFONV = esmVer == ESM::VER_132 || esmVer == ESM::VER_133 || esmVer == ESM::VER_134;
if (esmVer == ESM::VER_094 || isFONV) // FO3? 4 or 8 bytes
{
reader.skipSubRecordData();
break;
}
mIdleAnim.resize(mIdleCount);
for (ESM::FormId& value : mIdleAnim)
reader.getFormId(value);
break;
}
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("OBND"): // object bounds
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("QNAM"):
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::IDLM::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::IdleMarker::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::IdleMarker::blank()
//{
// }
| 3,464
|
C++
|
.cpp
| 88
| 29.375
| 114
| 0.586433
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,768
|
loadtes4.cpp
|
OpenMW_openmw/components/esm4/loadtes4.cpp
|
/*
Copyright (C) 2015-2016, 2018, 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadtes4.hpp"
#include <stdexcept>
#include "common.hpp"
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Header::load(ESM4::Reader& reader)
{
mFlags = reader.hdr().record.flags; // 0x01 = Rec_ESM, 0x80 = Rec_Localized
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("HEDR"):
{
if (!reader.getExact(mData.version) || !reader.getExact(mData.records)
|| !reader.getExact(mData.nextObjectId))
throw std::runtime_error("TES4 HEDR data read error");
if ((size_t)subHdr.dataSize
!= sizeof(mData.version) + sizeof(mData.records) + sizeof(mData.nextObjectId))
throw std::runtime_error("TES4 HEDR data size mismatch");
break;
}
case ESM::fourCC("CNAM"):
reader.getZString(mAuthor);
break;
case ESM::fourCC("SNAM"):
reader.getZString(mDesc);
break;
case ESM::fourCC("MAST"): // multiple
{
ESM::MasterData m;
if (!reader.getZString(m.name))
throw std::runtime_error("TES4 MAST data read error");
// NOTE: some mods do not have DATA following MAST so can't read DATA here
m.size = 0;
mMaster.push_back(m);
break;
}
case ESM::fourCC("DATA"):
{
if (mMaster.empty())
throw std::runtime_error(
"Failed to read TES4 DATA subrecord: there is no preceding MAST subrecord");
// WARNING: assumes DATA always follows MAST
if (!reader.getExact(mMaster.back().size))
throw std::runtime_error("TES4 DATA data read error");
break;
}
case ESM::fourCC("ONAM"):
{
mOverrides.resize(subHdr.dataSize / sizeof(ESM::FormId32));
for (ESM::FormId& mOverride : mOverrides)
{
uint32_t v;
if (!reader.getExact(v))
throw std::runtime_error("TES4 ONAM data read error");
mOverride = ESM::FormId::fromUint32(v);
#if 0
std::string padding;
padding.insert(0, reader.stackSize()*2, ' ');
std::cout << padding << "ESM4::Header::ONAM overrides: " << formIdToString(mOverride) << std::endl;
#endif
}
break;
}
case ESM::fourCC("INTV"):
case ESM::fourCC("INCC"):
case ESM::fourCC("OFST"): // Oblivion only?
case ESM::fourCC("DELE"): // Oblivion only?
case ESM::fourCC("TNAM"): // Fallout 4 (CK only)
case ESM::fourCC("MMSB"): // Fallout 76
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::Header::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Header::save(ESM4::Writer& writer)
//{
// }
| 4,474
|
C++
|
.cpp
| 102
| 32.392157
| 120
| 0.576835
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,769
|
loadcont.cpp
|
OpenMW_openmw/components/esm4/loadcont.cpp
|
/*
Copyright (C) 2016, 2018, 2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadcont.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Container::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("DATA"):
reader.get(mDataFlags);
reader.get(mWeight);
break;
case ESM::fourCC("CNTO"):
{
InventoryItem inv; // FIXME: use unique_ptr here?
reader.get(inv);
reader.adjustFormId(inv.item);
mInventory.push_back(inv);
break;
}
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("SNAM"):
reader.getFormId(mOpenSound);
break;
case ESM::fourCC("QNAM"):
reader.getFormId(mCloseSound);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("VMAD"): // TES5 only
case ESM::fourCC("OBND"): // TES5 only
case ESM::fourCC("COCT"): // TES5 only
case ESM::fourCC("COED"): // TES5 only
case ESM::fourCC("DAMC"): // Destructible
case ESM::fourCC("DEST"):
case ESM::fourCC("DMDC"):
case ESM::fourCC("DMDL"):
case ESM::fourCC("DMDT"):
case ESM::fourCC("DMDS"):
case ESM::fourCC("DSTA"):
case ESM::fourCC("DSTD"):
case ESM::fourCC("DSTF"): // Destructible end
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("ONAM"):
case ESM::fourCC("RNAM"): // FONV
case ESM::fourCC("TNAM"):
case ESM::fourCC("FTYP"): // FO4
case ESM::fourCC("NTRM"): // FO4
case ESM::fourCC("PRPS"): // FO4
case ESM::fourCC("PTRN"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::CONT::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Container::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Container::blank()
//{
// }
| 4,162
|
C++
|
.cpp
| 105
| 29.419048
| 114
| 0.576514
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,770
|
loadinfo.cpp
|
OpenMW_openmw/components/esm4/loadinfo.cpp
|
/*
Copyright (C) 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadinfo.hpp"
#include <cstring>
#include <stdexcept>
#include <components/esm/refid.hpp>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::DialogInfo::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
mEditorId = ESM::RefId(mId).serializeText(); // FIXME: quick workaround to use existing code
bool ignore = false;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("QSTI"):
reader.getFormId(mQuest);
break; // FormId quest id
case ESM::fourCC("SNDD"):
reader.getFormId(mSound);
break; // FO3 (not used in FONV?)
case ESM::fourCC("TRDT"):
{
if (subHdr.dataSize == 16) // TES4
reader.get(&mResponseData, 16);
else if (subHdr.dataSize == 20) // FO3
reader.get(&mResponseData, 20);
else // FO3/FONV
{
reader.get(mResponseData);
if (mResponseData.sound)
reader.adjustFormId(mResponseData.sound);
}
break;
}
case ESM::fourCC("NAM1"):
reader.getLocalizedString(mResponse);
break; // response text
case ESM::fourCC("NAM2"):
reader.getZString(mNotes);
break; // actor notes
case ESM::fourCC("NAM3"):
reader.getZString(mEdits);
break; // not in TES4
case ESM::fourCC("CTDA"): // FIXME: how to detect if 1st/2nd param is a formid?
{
if (subHdr.dataSize == 24) // TES4
reader.get(&mTargetCondition, 24);
else if (subHdr.dataSize == 20) // FO3
reader.get(&mTargetCondition, 20);
else if (subHdr.dataSize == 28)
{
reader.get(mTargetCondition); // FO3/FONV
if (mTargetCondition.reference)
reader.adjustFormId(mTargetCondition.reference);
}
else // TES5
{
reader.get(&mTargetCondition, 20);
if (subHdr.dataSize == 36)
reader.getFormId(mParam3);
reader.get(mTargetCondition.runOn);
reader.get(mTargetCondition.reference);
if (mTargetCondition.reference)
reader.adjustFormId(mTargetCondition.reference);
reader.skipSubRecordData(4); // unknown
}
break;
}
case ESM::fourCC("SCHR"):
{
if (!ignore)
reader.get(mScript.scriptHeader);
else
reader.skipSubRecordData(); // TODO: does the second one ever used?
break;
}
case ESM::fourCC("SCDA"):
reader.skipSubRecordData();
break; // compiled script data
case ESM::fourCC("SCTX"):
reader.getString(mScript.scriptSource);
break;
case ESM::fourCC("SCRO"):
reader.getFormId(mScript.globReference);
break;
case ESM::fourCC("SLSD"):
{
ScriptLocalVariableData localVar;
reader.get(localVar.index);
reader.get(localVar.unknown1);
reader.get(localVar.unknown2);
reader.get(localVar.unknown3);
reader.get(localVar.type);
reader.get(localVar.unknown4);
mScript.localVarData.push_back(std::move(localVar));
// WARN: assumes SCVR will follow immediately
break;
}
case ESM::fourCC("SCVR"): // assumed always pair with SLSD
{
if (!mScript.localVarData.empty())
reader.getZString(mScript.localVarData.back().variableName);
else
reader.skipSubRecordData();
break;
}
case ESM::fourCC("SCRV"):
{
std::uint32_t index;
reader.get(index);
mScript.localRefVarIndex.push_back(index);
break;
}
case ESM::fourCC("NEXT"): // FO3/FONV marker for next script header
{
ignore = true;
break;
}
case ESM::fourCC("DATA"): // always 3 for TES4 ?
{
if (subHdr.dataSize == 4) // FO3/FONV
{
reader.get(mDialType);
reader.get(mNextSpeaker);
reader.get(mInfoFlags);
}
else
reader.skipSubRecordData(); // FIXME
break;
}
case ESM::fourCC("NAME"): // FormId add topic (not always present)
case ESM::fourCC("CTDT"): // older version of CTDA? 20 bytes
case ESM::fourCC("SCHD"): // 28 bytes
case ESM::fourCC("TCLT"): // FormId choice
case ESM::fourCC("TCLF"): // FormId
case ESM::fourCC("PNAM"): // TES4 DLC
case ESM::fourCC("TPIC"): // TES4 DLC
case ESM::fourCC("ANAM"): // FO3 speaker formid
case ESM::fourCC("DNAM"): // FO3 speech challenge
case ESM::fourCC("KNAM"): // FO3 formid
case ESM::fourCC("LNAM"): // FONV
case ESM::fourCC("TCFU"): // FONV
case ESM::fourCC("TIFC"): // TES5
case ESM::fourCC("TWAT"): // TES5
case ESM::fourCC("CIS1"): // TES5
case ESM::fourCC("CIS2"): // TES5
case ESM::fourCC("CNAM"): // TES5
case ESM::fourCC("ENAM"): // TES5
case ESM::fourCC("EDID"): // TES5
case ESM::fourCC("VMAD"): // TES5
case ESM::fourCC("BNAM"): // TES5
case ESM::fourCC("SNAM"): // TES5
case ESM::fourCC("ONAM"): // TES5
case ESM::fourCC("QNAM"): // TES5 for mScript
case ESM::fourCC("RNAM"): // TES5
case ESM::fourCC("ALFA"): // FO4
case ESM::fourCC("GNAM"): // FO4
case ESM::fourCC("GREE"): // FO4
case ESM::fourCC("INAM"): // FO4
case ESM::fourCC("INCC"): // FO4
case ESM::fourCC("INTV"): // FO4
case ESM::fourCC("IOVR"): // FO4
case ESM::fourCC("MODQ"): // FO4
case ESM::fourCC("NAM0"): // FO4
case ESM::fourCC("NAM4"): // FO4
case ESM::fourCC("NAM9"): // FO4
case ESM::fourCC("SRAF"): // FO4
case ESM::fourCC("TIQS"): // FO4
case ESM::fourCC("TNAM"): // FO4
case ESM::fourCC("TRDA"): // FO4
case ESM::fourCC("TSCE"): // FO4
case ESM::fourCC("WZMD"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::INFO::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::DialogInfo::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::DialogInfo::blank()
//{
// }
| 8,687
|
C++
|
.cpp
| 208
| 28.538462
| 114
| 0.523061
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,771
|
loadhdpt.cpp
|
OpenMW_openmw/components/esm4/loadhdpt.cpp
|
/*
Copyright (C) 2019-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadhdpt.hpp"
#include <cstdint>
#include <optional>
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::HeadPart::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
mExtraFlags2 = 0;
mData = 0;
mType = 0;
std::optional<std::uint32_t> type;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("XALG"): // FO76
reader.get(mExtraFlags2);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("DATA"):
reader.get(mData);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("HNAM"):
reader.getFormId(mExtraParts.emplace_back());
break;
case ESM::fourCC("NAM0"): // TES5
{
std::uint32_t value;
reader.get(value);
type = value;
break;
}
case ESM::fourCC("NAM1"): // TES5
{
std::string file;
reader.getZString(file);
if (!type.has_value())
throw std::runtime_error(
"Failed to read ESM4 HDPT record: subrecord NAM0 does not precede subrecord NAM1: file type is "
"unknown");
if (*type >= mTriFile.size())
throw std::runtime_error(
"Failed to read ESM4 HDPT record: invalid file type: " + std::to_string(*type));
mTriFile[*type] = std::move(file);
break;
}
case ESM::fourCC("TNAM"):
reader.getFormId(mBaseTexture);
break;
case ESM::fourCC("CNAM"):
reader.getFormId(mColor);
break;
case ESM::fourCC("RNAM"):
reader.getFormId(mValidRaces.emplace_back());
break;
case ESM::fourCC("PNAM"):
reader.get(mType);
break;
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"):
case ESM::fourCC("ENLM"):
case ESM::fourCC("XFLG"):
case ESM::fourCC("ENLT"):
case ESM::fourCC("ENLS"):
case ESM::fourCC("AUUV"):
case ESM::fourCC("MODD"): // Model data end
case ESM::fourCC("CTDA"):
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::HDPT::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::HeadPart::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::HeadPart::blank()
//{
// }
| 4,374
|
C++
|
.cpp
| 114
| 27.649123
| 120
| 0.565975
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,772
|
loadimod.cpp
|
OpenMW_openmw/components/esm4/loadimod.cpp
|
/*
Copyright (C) 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
Also see https://tes5edit.github.io/fopdoc/ for FO3/FONV specific details.
*/
#include "loadimod.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::ItemMod::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("DESC"):
reader.getLocalizedString(mText);
break;
case ESM::fourCC("ICON"):
reader.getZString(mIcon);
break;
case ESM::fourCC("MICO"):
reader.getZString(mMiniIcon);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("YNAM"):
reader.getFormId(mPickUpSound);
break;
case ESM::fourCC("ZNAM"):
reader.getFormId(mDropSound);
break;
case ESM::fourCC("DATA"):
reader.get(mData.mValue);
reader.get(mData.mWeight);
break;
case ESM::fourCC("OBND"):
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODS"):
case ESM::fourCC("MODD"): // Model data end
case ESM::fourCC("DAMC"): // Destructible
case ESM::fourCC("DEST"):
case ESM::fourCC("DMDC"):
case ESM::fourCC("DMDL"):
case ESM::fourCC("DMDT"):
case ESM::fourCC("DMDS"):
case ESM::fourCC("DSTA"):
case ESM::fourCC("DSTD"):
case ESM::fourCC("DSTF"): // Destructible end
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::IMOD::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::ItemMod::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::ItemMod::blank()
//{
// }
| 3,692
|
C++
|
.cpp
| 94
| 29.43617
| 114
| 0.596653
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,773
|
loadwrld.cpp
|
OpenMW_openmw/components/esm4/loadwrld.cpp
|
/*
Copyright (C) 2015-2016, 2018-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadwrld.hpp"
#include <stdexcept>
#include "reader.hpp"
// #include "writer.hpp"
void ESM4::World::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
// It should be possible to save the current world formId automatically while reading in
// the record header rather than doing it manually here but possibly less efficient (may
// need to check each record?).
//
// Alternatively it may be possible to figure it out by examining the group headers, but
// apparently the label field is not reliable so the parent world formid may have been
// corrupted by the use of ignore flag (TODO: should check to verify).
reader.setCurrWorld(mId); // save for CELL later
std::uint32_t esmVer = reader.esmVersion();
// bool isTES4 = (esmVer == ESM::VER_080 || esmVer == ESM::VER_100);
// bool isFONV = (esmVer == ESM::VER_132 || esmVer == ESM::VER_133 || esmVer == ESM::VER_134);
bool isTES5 = (esmVer == ESM::VER_094 || esmVer == ESM::VER_170); // WARN: FO3 is also VER_094
bool usingDefaultLevels = true;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("WCTR"): // TES5+
reader.get(mCenterCell);
break;
case ESM::fourCC("WNAM"):
reader.getFormId(mParent);
break;
case ESM::fourCC("SNAM"):
reader.get(mSound);
break; // sound, Oblivion only?
case ESM::fourCC("ICON"):
reader.getZString(mMapFile);
break;
case ESM::fourCC("CNAM"):
reader.getFormId(mClimate);
break;
case ESM::fourCC("NAM2"):
reader.getFormId(mWater);
break;
case ESM::fourCC("NAM0"):
{
reader.get(mMinX);
reader.get(mMinY);
break;
}
case ESM::fourCC("NAM9"):
{
reader.get(mMaxX);
reader.get(mMaxY);
break;
}
case ESM::fourCC("DATA"):
reader.get(mWorldFlags);
break;
case ESM::fourCC("MNAM"):
{
reader.get(mMap.width);
reader.get(mMap.height);
reader.get(mMap.NWcellX);
reader.get(mMap.NWcellY);
reader.get(mMap.SEcellX);
reader.get(mMap.SEcellY);
if (subHdr.dataSize == 28) // Skyrim?
{
reader.get(mMap.minHeight);
reader.get(mMap.maxHeight);
reader.get(mMap.initialPitch);
}
break;
}
case ESM::fourCC("DNAM"): // defaults
{
reader.get(mLandLevel); // -2700.f for TES5
reader.get(mWaterLevel); // -14000.f for TES5
usingDefaultLevels = false;
break;
}
// Only a few worlds in FO3 have music (I'm guessing 00090908 "explore" is the default?)
// 00090906 public WRLD: 00000A74 MegatonWorld
// 00090CE7 base WRLD: 0001A25D DCWorld18 (Arlington National Cemeteray)
// 00090CE7 base WRLD: 0001A266 DCWorld09 (The Mall)
// 00090CE7 base WRLD: 0001A267 DCWorld08 (Pennsylvania Avenue)
// 000BAD30 tranquilitylane WRLD: 000244A7 TranquilityLane
// 00090CE7 base WRLD: 000271C0 MonumentWorld (The Washington Monument)
// 00090907 dungeon WRLD: 0004C4D1 MamaDolcesWorld (Mama Dolce's Loading Yard)
//
// FONV has only 3 (note the different format, also can't find the files?):
// 00119D2E freeside\freeside_01.mp3 0010BEEA FreesideWorld (Freeside)
// 00119D2E freeside\freeside_01.mp3 0012D94D FreesideNorthWorld (Freeside)
// 00119D2E freeside\freeside_01.mp3 0012D94E FreesideFortWorld (Old Mormon Fort)
// NOTE: FONV DefaultObjectManager has 00090908 "explore" as the default music
case ESM::fourCC("ZNAM"):
reader.getFormId(mMusic);
break;
case ESM::fourCC("PNAM"):
reader.get(mParentUseFlags);
break;
case ESM::fourCC("OFST"):
case ESM::fourCC("RNAM"): // multiple
case ESM::fourCC("MHDT"):
case ESM::fourCC("LTMP"):
case ESM::fourCC("XEZN"):
case ESM::fourCC("XLCN"):
case ESM::fourCC("NAM3"):
case ESM::fourCC("NAM4"):
case ESM::fourCC("NAMA"):
case ESM::fourCC("ONAM"):
case ESM::fourCC("TNAM"):
case ESM::fourCC("UNAM"):
case ESM::fourCC("XWEM"):
case ESM::fourCC("MODL"): // Model data start
case ESM::fourCC("MODT"):
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("INAM"): // FO3
case ESM::fourCC("NNAM"): // FO3
case ESM::fourCC("XNAM"): // FO3
case ESM::fourCC("IMPS"): // FO3 Anchorage
case ESM::fourCC("IMPF"): // FO3 Anchorage
case ESM::fourCC("CLSZ"): // FO4
case ESM::fourCC("WLEV"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::WRLD::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
if (usingDefaultLevels)
{
if (isTES5)
{
mLandLevel = -2700.f;
mWaterLevel = -14000.f;
}
else
{
mLandLevel = 0.f; // FIXME: not sure that this value is correct
mWaterLevel = 0.f;
}
}
// TES4 doesn't define PNAM. Exact parent worldspace behavior needs research
if (!reader.hasFormVersion())
mParentUseFlags = 0xFFFF;
}
}
// void ESM4::World::save(ESM4::Writer& writer) const
//{
// }
| 7,730
|
C++
|
.cpp
| 179
| 31.603352
| 114
| 0.568565
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,774
|
loadaloc.cpp
|
OpenMW_openmw/components/esm4/loadaloc.cpp
|
/*
Copyright (C) 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadaloc.hpp"
#include <cstring>
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::MediaLocationController::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getZString(mFullName);
break;
case ESM::fourCC("GNAM"):
reader.getFormId(mBattleSets.emplace_back());
break;
case ESM::fourCC("LNAM"):
reader.getFormId(mLocationSets.emplace_back());
break;
case ESM::fourCC("YNAM"):
reader.getFormId(mEnemySets.emplace_back());
break;
case ESM::fourCC("HNAM"):
reader.getFormId(mNeutralSets.emplace_back());
break;
case ESM::fourCC("XNAM"):
reader.getFormId(mFriendSets.emplace_back());
break;
case ESM::fourCC("ZNAM"):
reader.getFormId(mAllySets.emplace_back());
break;
case ESM::fourCC("RNAM"):
reader.getFormId(mConditionalFaction);
break;
case ESM::fourCC("NAM1"):
{
reader.get(mMediaFlags);
std::uint8_t flags = mMediaFlags.loopingOptions;
mMediaFlags.loopingOptions = (flags & 0xF0) >> 4;
mMediaFlags.factionNotFound = flags & 0x0F; // WARN: overwriting data
break;
}
case ESM::fourCC("NAM4"):
reader.get(mLocationDelay);
break;
case ESM::fourCC("NAM7"):
reader.get(mRetriggerDelay);
break;
case ESM::fourCC("NAM5"):
reader.get(mDayStart);
break;
case ESM::fourCC("NAM6"):
reader.get(mNightStart);
break;
case ESM::fourCC("NAM2"): // always 0? 4 bytes
case ESM::fourCC("NAM3"): // always 0? 4 bytes
case ESM::fourCC("FNAM"): // always 0? 4 bytes
{
#if 0
std::vector<unsigned char> mDataBuf(subHdr.dataSize);
reader.get(mDataBuf.data(), subHdr.dataSize);
std::ostringstream ss;
ss << mEditorId << " " << ESM::printName(subHdr.typeId) << ":size " << subHdr.dataSize << "\n";
for (std::size_t i = 0; i < subHdr.dataSize; ++i)
{
//if (mDataBuf[i] > 64 && mDataBuf[i] < 91) // looks like printable ascii char
//ss << (char)(mDataBuf[i]) << " ";
//else
ss << std::setfill('0') << std::setw(2) << std::hex << (int)(mDataBuf[i]);
if ((i & 0x000f) == 0xf) // wrap around
ss << "\n";
else if (i < subHdr.dataSize-1)
ss << " ";
}
std::cout << ss.str() << std::endl;
#else
reader.skipSubRecordData();
#endif
break;
}
default:
throw std::runtime_error("ESM4::ALOC::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::MediaLocationController::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::MediaLocationController::blank()
//{
// }
| 4,864
|
C++
|
.cpp
| 118
| 29.838983
| 114
| 0.559265
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,775
|
loadcrea.cpp
|
OpenMW_openmw/components/esm4/loadcrea.cpp
|
/*
Copyright (C) 2016, 2018, 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadcrea.hpp"
#include <cstring>
#include <stdexcept>
#include <string>
#include <components/debug/debuglog.hpp>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Creature::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getZString(mFullName);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("CNTO"):
{
InventoryItem inv; // FIXME: use unique_ptr here?
reader.get(inv);
reader.adjustFormId(inv.item);
mInventory.push_back(inv);
break;
}
case ESM::fourCC("SPLO"):
reader.getFormId(mSpell.emplace_back());
break;
case ESM::fourCC("PKID"):
reader.getFormId(mAIPackages.emplace_back());
break;
case ESM::fourCC("SNAM"):
reader.get(mFaction);
reader.adjustFormId(mFaction.faction);
break;
case ESM::fourCC("INAM"):
reader.getFormId(mDeathItem);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("AIDT"):
if (subHdr.dataSize == 20) // FO3
reader.skipSubRecordData();
else
reader.get(mAIData); // 12 bytes
break;
case ESM::fourCC("ACBS"):
// if (esmVer == ESM::VER_094 || esmVer == ESM::VER_170 || mIsFONV)
if (subHdr.dataSize == 24)
reader.get(mBaseConfig);
else
reader.get(&mBaseConfig, 16); // TES4
break;
case ESM::fourCC("DATA"):
if (subHdr.dataSize == 17) // FO3
reader.skipSubRecordData();
else
reader.get(mData);
break;
case ESM::fourCC("ZNAM"):
reader.getFormId(mCombatStyle);
break;
case ESM::fourCC("CSCR"):
reader.getFormId(mSoundBase);
break;
case ESM::fourCC("CSDI"):
reader.getFormId(mSound);
break;
case ESM::fourCC("CSDC"):
reader.get(mSoundChance);
break;
case ESM::fourCC("BNAM"):
reader.get(mBaseScale);
break;
case ESM::fourCC("TNAM"):
reader.get(mTurningSpeed);
break;
case ESM::fourCC("WNAM"):
reader.get(mFootWeight);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("NAM0"):
reader.getZString(mBloodSpray);
break;
case ESM::fourCC("NAM1"):
reader.getZString(mBloodDecal);
break;
case ESM::fourCC("NIFZ"):
if (!reader.getZeroTerminatedStringArray(mNif))
throw std::runtime_error("CREA NIFZ data read error");
break;
case ESM::fourCC("NIFT"):
{
if (subHdr.dataSize != 4) // FIXME: FO3
{
reader.skipSubRecordData();
break;
}
if (subHdr.dataSize != 4)
throw std::runtime_error("CREA NIFT datasize error");
std::uint32_t nift;
reader.get(nift);
if (nift)
Log(Debug::Verbose) << "CREA NIFT " << mId << ", non-zero " << nift;
break;
}
case ESM::fourCC("KFFZ"):
if (!reader.getZeroTerminatedStringArray(mKf))
throw std::runtime_error("CREA KFFZ data read error");
break;
case ESM::fourCC("TPLT"):
reader.getFormId(mBaseTemplate);
break; // FO3
case ESM::fourCC("PNAM"): // FO3/FONV/TES5
reader.getFormId(mBodyParts.emplace_back());
break;
case ESM::fourCC("MODT"):
case ESM::fourCC("RNAM"):
case ESM::fourCC("CSDT"):
case ESM::fourCC("OBND"): // FO3
case ESM::fourCC("EAMT"): // FO3
case ESM::fourCC("VTCK"): // FO3
case ESM::fourCC("NAM4"): // FO3
case ESM::fourCC("NAM5"): // FO3
case ESM::fourCC("CNAM"): // FO3
case ESM::fourCC("LNAM"): // FO3
case ESM::fourCC("EITM"): // FO3
case ESM::fourCC("DEST"): // FO3
case ESM::fourCC("DSTD"): // FO3
case ESM::fourCC("DSTF"): // FO3
case ESM::fourCC("DMDL"): // FO3
case ESM::fourCC("DMDT"): // FO3
case ESM::fourCC("COED"): // FO3
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::CREA::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Creature::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Creature::blank()
//{
// }
| 6,908
|
C++
|
.cpp
| 177
| 26.288136
| 114
| 0.521215
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,776
|
loadotft.cpp
|
OpenMW_openmw/components/esm4/loadotft.cpp
|
/*
Copyright (C) 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadotft.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Outfit::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("INAM"):
{
mInventory.resize(subHdr.dataSize / sizeof(ESM::FormId32));
for (ESM::FormId& formId : mInventory)
reader.getFormId(formId);
break;
}
default:
throw std::runtime_error("ESM4::OTFT::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Outfit::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Outfit::blank()
//{
// }
| 2,137
|
C++
|
.cpp
| 54
| 33.240741
| 114
| 0.680831
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,777
|
loadclot.cpp
|
OpenMW_openmw/components/esm4/loadclot.cpp
|
/*
Copyright (C) 2016, 2018, 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadclot.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Clothing::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getZString(mFullName);
break;
case ESM::fourCC("DATA"):
reader.get(mData);
break;
case ESM::fourCC("BMDT"):
reader.get(mClothingFlags);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("ENAM"):
reader.getFormId(mEnchantment);
break;
case ESM::fourCC("ANAM"):
reader.get(mEnchantmentPoints);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModelMale);
break;
case ESM::fourCC("MOD2"):
reader.getZString(mModelMaleWorld);
break;
case ESM::fourCC("MOD3"):
reader.getZString(mModelFemale);
break;
case ESM::fourCC("MOD4"):
reader.getZString(mModelFemaleWorld);
break;
case ESM::fourCC("ICON"):
reader.getZString(mIconMale);
break;
case ESM::fourCC("ICO2"):
reader.getZString(mIconFemale);
break;
case ESM::fourCC("MODT"):
case ESM::fourCC("MO2B"):
case ESM::fourCC("MO3B"):
case ESM::fourCC("MO4B"):
case ESM::fourCC("MO2T"):
case ESM::fourCC("MO3T"):
case ESM::fourCC("MO4T"):
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::CLOT::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
// if ((mClothingFlags&0xffff) == 0x02) // only hair
// std::cout << "only hair " << mEditorId << std::endl;
}
// void ESM4::Clothing::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Clothing::blank()
//{
// }
| 3,736
|
C++
|
.cpp
| 97
| 28.443299
| 114
| 0.588641
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,778
|
loadstat.cpp
|
OpenMW_openmw/components/esm4/loadstat.cpp
|
/*
Copyright (C) 2015-2016, 2018 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadstat.hpp"
#include <stdexcept>
#include "reader.hpp"
// #include "writer.hpp"
void ESM4::Static::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("MODT"):
{
// version is only availabe in TES5 (seems to be 27 or 28?)
// if (reader.esmVersion() == ESM::VER_094 || reader.esmVersion() == ESM::VER_170)
// std::cout << "STAT MODT ver: " << std::hex << reader.hdr().record.version << std::endl;
// for TES4 these are just a sequence of bytes
mMODT.resize(subHdr.dataSize / sizeof(std::uint8_t));
for (std::vector<std::uint8_t>::iterator it = mMODT.begin(); it != mMODT.end(); ++it)
{
reader.get(*it);
#if 0
std::string padding;
padding.insert(0, reader.stackSize()*2, ' ');
std::cout << padding << "MODT: " << std::hex << *it << std::endl;
#endif
}
break;
}
case ESM::fourCC("MNAM"):
{
for (std::string& level : mLOD)
{
level.resize(260);
reader.get(level.data(), 260);
size_t end = level.find('\0');
if (end != std::string::npos)
level.erase(end);
}
break;
}
case ESM::fourCC("MODC"): // More model data
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("OBND"):
case ESM::fourCC("DNAM"):
case ESM::fourCC("BRUS"): // FONV
case ESM::fourCC("RNAM"): // FONV
case ESM::fourCC("FTYP"): // FO4
case ESM::fourCC("NVNM"): // FO4
case ESM::fourCC("PRPS"): // FO4
case ESM::fourCC("PTRN"): // FO4
case ESM::fourCC("VMAD"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::STAT::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Static::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Static::blank()
//{
// }
| 4,109
|
C++
|
.cpp
| 100
| 30.52
| 114
| 0.561562
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,779
|
loadregn.cpp
|
OpenMW_openmw/components/esm4/loadregn.cpp
|
/*
Copyright (C) 2015-2016, 2018, 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadregn.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Region::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("RCLR"):
reader.get(mColour);
break;
case ESM::fourCC("WNAM"):
reader.getFormId(mWorldId);
break;
case ESM::fourCC("ICON"):
reader.getZString(mShader);
break;
case ESM::fourCC("RPLI"):
reader.get(mEdgeFalloff);
break;
case ESM::fourCC("RPLD"):
{
mRPLD.resize(subHdr.dataSize / sizeof(std::uint32_t));
for (std::vector<std::uint32_t>::iterator it = mRPLD.begin(); it != mRPLD.end(); ++it)
{
reader.get(*it);
#if 0
std::string padding;
padding.insert(0, reader.stackSize()*2, ' ');
std::cout << padding << "RPLD: 0x" << std::hex << *it << std::endl;
#endif
}
break;
}
case ESM::fourCC("RDAT"):
reader.get(mData);
break;
case ESM::fourCC("RDMP"):
{
if (mData.type != RDAT_Map)
throw std::runtime_error("REGN unexpected data type");
reader.getLocalizedString(mMapName);
break;
}
// FO3 only 2: DemoMegatonSound and DC01 (both 0 RDMD)
// FONV none
case ESM::fourCC("RDMD"): // music type; 0 default, 1 public, 2 dungeon
{
#if 0
int dummy;
reader.get(dummy);
std::cout << "REGN " << mEditorId << " " << dummy << std::endl;
#else
reader.skipSubRecordData();
#endif
break;
}
case ESM::fourCC("RDMO"): // not seen in FO3/FONV?
{
// std::cout << "REGN " << ESM::printName(subHdr.typeId) << " skipping..."
// << subHdr.dataSize << std::endl;
reader.skipSubRecordData();
break;
}
case ESM::fourCC("RDSD"): // Possibly the same as RDSA
{
if (mData.type != RDAT_Sound)
throw std::runtime_error(
"ESM4::REGN::load - unexpected data type " + ESM::printName(subHdr.typeId));
std::size_t numSounds = subHdr.dataSize / sizeof(RegionSound);
mSounds.resize(numSounds);
for (std::size_t i = 0; i < numSounds; ++i)
reader.get(mSounds.at(i));
break;
}
case ESM::fourCC("RDGS"): // Only in Oblivion? (ToddTestRegion1) // formId
case ESM::fourCC("RDSA"):
case ESM::fourCC("RDWT"): // formId
case ESM::fourCC("RDOT"): // formId
case ESM::fourCC("RDID"): // FONV
case ESM::fourCC("RDSB"): // FONV
case ESM::fourCC("RDSI"): // FONV
case ESM::fourCC("NVMI"): // TES5
case ESM::fourCC("ANAM"): // FO4
case ESM::fourCC("RLDM"): // FO4
// RDAT skipping... following is a map
// RDMP skipping... map name
//
// RDAT skipping... following is weather
// RDWT skipping... weather data
//
// RDAT skipping... following is sound
// RDMD skipping... unknown, maybe music data
//
// RDSD skipping... unknown, maybe sound data
//
// RDAT skipping... following is grass
// RDGS skipping... unknown, maybe grass
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::REGN::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Region::save(ESM4::Writer& writer) const
//{
// }
void ESM4::Region::blank() {}
| 5,609
|
C++
|
.cpp
| 137
| 29.080292
| 114
| 0.53684
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,780
|
loadeyes.cpp
|
OpenMW_openmw/components/esm4/loadeyes.cpp
|
/*
Copyright (C) 2016, 2018, 2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadeyes.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Eyes::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("ICON"):
reader.getZString(mIcon);
break;
case ESM::fourCC("DATA"):
reader.get(mData);
break;
default:
throw std::runtime_error("ESM4::EYES::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Eyes::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Eyes::blank()
//{
// }
| 2,191
|
C++
|
.cpp
| 56
| 32.482143
| 114
| 0.672633
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,781
|
loaddoor.cpp
|
OpenMW_openmw/components/esm4/loaddoor.cpp
|
/*
Copyright (C) 2016, 2018, 2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loaddoor.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Door::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("SNAM"):
reader.getFormId(mOpenSound);
break;
case ESM::fourCC("ANAM"):
reader.getFormId(mCloseSound);
break;
case ESM::fourCC("BNAM"):
reader.getFormId(mLoopSound);
break;
case ESM::fourCC("FNAM"):
reader.get(mDoorFlags);
break;
case ESM::fourCC("TNAM"):
reader.getFormId(mRandomTeleport);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("OBND"):
case ESM::fourCC("VMAD"):
case ESM::fourCC("DAMC"): // Destructible
case ESM::fourCC("DEST"):
case ESM::fourCC("DMDC"):
case ESM::fourCC("DMDL"):
case ESM::fourCC("DMDT"):
case ESM::fourCC("DMDS"):
case ESM::fourCC("DSTA"):
case ESM::fourCC("DSTD"):
case ESM::fourCC("DSTF"): // Destructible end
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("CNAM"): // FO4
case ESM::fourCC("NTRM"): // FO4
case ESM::fourCC("ONAM"): // FO4
case ESM::fourCC("PTRN"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::DOOR::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Door::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Door::blank()
//{
// }
| 3,801
|
C++
|
.cpp
| 97
| 29.278351
| 114
| 0.58559
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,782
|
loadlvln.cpp
|
OpenMW_openmw/components/esm4/loadlvln.cpp
|
/*
Copyright (C) 2019-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadlvln.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::LevelledNpc::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
// std::uint32_t esmVer = reader.esmVersion(); // currently unused
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("LLCT"):
reader.get(mListCount);
break;
case ESM::fourCC("LVLD"):
reader.get(mChanceNone);
break;
case ESM::fourCC("LVLF"):
reader.get(mLvlActorFlags);
break;
case ESM::fourCC("LVLO"):
{
LVLO lvlo;
if (subHdr.dataSize != 12)
{
if (subHdr.dataSize == 8)
{
reader.get(lvlo.level);
reader.get(lvlo.item);
reader.get(lvlo.count);
break;
}
else
throw std::runtime_error("ESM4::LVLN::load - " + mEditorId + " LVLO size error");
}
// else if (esmVer == ESM::VER_094 || esmVer == ESM::VER_170 || isFONV)
// {
// std::uint32_t level;
// reader.get(level);
// lvlo.level = static_cast<std::uint16_t>(level);
// reader.get(lvlo.item);
// std::uint32_t count;
// reader.get(count);
// lvlo.count = static_cast<std::uint16_t>(count);
// }
else
reader.get(lvlo);
reader.adjustFormId(lvlo.item);
mLvlObject.push_back(lvlo);
break;
}
case ESM::fourCC("COED"): // owner
case ESM::fourCC("OBND"): // object bounds
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("LLKC"): // FO4
case ESM::fourCC("LVLG"): // FO4
case ESM::fourCC("LVLM"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::LVLN::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::LevelledNpc::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::LevelledNpc::blank()
//{
// }
| 4,224
|
C++
|
.cpp
| 102
| 30.127451
| 114
| 0.532733
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,783
|
loadidle.cpp
|
OpenMW_openmw/components/esm4/loadidle.cpp
|
/*
Copyright (C) 2016, 2018 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadidle.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::IdleAnimation::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("DNAM"):
reader.getZString(mCollision);
break;
case ESM::fourCC("ENAM"):
reader.getZString(mEvent);
break;
case ESM::fourCC("ANAM"):
{
switch (subHdr.dataSize)
{
case 1: // TES4
{
// Animation group section
uint8_t dummy;
reader.get(dummy);
break;
}
case 8: // Everything else
{
// These IDs go into DATA for TES4
reader.getFormId(mParent);
reader.getFormId(mPrevious);
break;
}
default:
reader.skipSubRecordData();
break;
}
break;
}
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("CTDA"): // formId
case ESM::fourCC("CTDT"):
case ESM::fourCC("CIS1"):
case ESM::fourCC("CIS2"):
case ESM::fourCC("DATA"):
case ESM::fourCC("MODD"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODT"):
case ESM::fourCC("GNAM"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::IDLE::load - Unknown subrecord " + std::to_string(subHdr.typeId) + " "
+ ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::IdleAnimation::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::IdleAnimation::blank()
//{
// }
| 3,608
|
C++
|
.cpp
| 95
| 26.452632
| 118
| 0.554413
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,784
|
loadbook.cpp
|
OpenMW_openmw/components/esm4/loadbook.cpp
|
/*
Copyright (C) 2016, 2018, 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadbook.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Book::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
// std::uint32_t esmVer = reader.esmVersion(); // currently unused
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("DESC"):
reader.getLocalizedString(mText);
break;
case ESM::fourCC("DATA"):
{
switch (subHdr.dataSize)
{
case 10: // TES4, FO3, FNV
reader.get(mData.flags);
reader.get(mData.bookSkill);
reader.get(mData.value);
reader.get(mData.weight);
break;
case 16: // TES5
{
reader.get(mData.flags);
reader.get(mData.type);
std::uint16_t dummy;
reader.get(dummy);
reader.get(mData.teaches);
reader.get(mData.value);
reader.get(mData.weight);
break;
}
case 8: // FO4
reader.get(mData.value);
reader.get(mData.weight);
break;
default:
reader.skipSubRecordData();
break;
}
break;
}
case ESM::fourCC("ICON"):
reader.getZString(mIcon);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("ANAM"):
reader.get(mEnchantmentPoints);
break;
case ESM::fourCC("ENAM"):
reader.getFormId(mEnchantment);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("YNAM"):
reader.getFormId(mPickUpSound);
break;
case ESM::fourCC("ZNAM"):
reader.getFormId(mDropSound);
break;
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("OBND"):
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("CNAM"):
case ESM::fourCC("INAM"):
case ESM::fourCC("VMAD"):
case ESM::fourCC("DAMC"): // Destructible
case ESM::fourCC("DEST"):
case ESM::fourCC("DMDC"):
case ESM::fourCC("DMDL"):
case ESM::fourCC("DMDT"):
case ESM::fourCC("DMDS"):
case ESM::fourCC("DSTA"):
case ESM::fourCC("DSTD"):
case ESM::fourCC("DSTF"): // Destructible end
case ESM::fourCC("DNAM"): // FO4
case ESM::fourCC("FIMD"): // FO4
case ESM::fourCC("MICO"): // FO4
case ESM::fourCC("PTRN"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::BOOK::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Book::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Book::blank()
//{
// }
| 5,235
|
C++
|
.cpp
| 134
| 26.216418
| 114
| 0.525054
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,785
|
loadgmst.cpp
|
OpenMW_openmw/components/esm4/loadgmst.cpp
|
#include "loadgmst.hpp"
#include <cstdint>
#include <stdexcept>
#include <string>
#include "reader.hpp"
namespace ESM4
{
namespace
{
GameSetting::Data readData(ESM::FormId formId, std::string_view editorId, Reader& reader)
{
if (editorId.empty())
{
reader.skipSubRecordData();
return std::monostate{};
}
const char type = editorId[0];
switch (type)
{
case 'b':
{
std::uint32_t value = 0;
reader.get(value);
return value != 0;
}
case 'i':
{
std::int32_t value = 0;
reader.get(value);
return value;
}
case 'f':
{
float value = 0;
reader.get(value);
return value;
}
case 's':
{
std::string value;
reader.getLocalizedString(value);
return value;
}
case 'u':
{
std::uint32_t value = 0;
reader.get(value);
return value;
}
default:
throw std::runtime_error(
"Unsupported ESM4 GMST (" + formId.toString() + ") data type: " + std::string(editorId));
}
}
}
void GameSetting::load(Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("DATA"):
mData = readData(mId, mEditorId, reader);
break;
default:
throw std::runtime_error(
"Unknown ESM4 GMST (" + mId.toString() + ") subrecord " + ESM::printName(subHdr.typeId));
}
}
}
}
| 2,388
|
C++
|
.cpp
| 77
| 16.636364
| 113
| 0.412148
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,786
|
loadmstt.cpp
|
OpenMW_openmw/components/esm4/loadmstt.cpp
|
/*
Copyright (C) 2019, 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadmstt.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::MovableStatic::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("DATA"):
reader.get(mData);
break;
case ESM::fourCC("SNAM"):
reader.getFormId(mLoopingSound);
break;
case ESM::fourCC("DAMC"): // Destructible
case ESM::fourCC("DEST"):
case ESM::fourCC("DMDC"):
case ESM::fourCC("DMDL"):
case ESM::fourCC("DMDT"):
case ESM::fourCC("DMDS"):
case ESM::fourCC("DSTA"):
case ESM::fourCC("DSTD"):
case ESM::fourCC("DSTF"): // Destructible end
case ESM::fourCC("OBND"): // object bounds
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("VMAD"):
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("MODB"):
case ESM::fourCC("PRPS"):
case ESM::fourCC("PTRN"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::MSTT::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::MovableStatic::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::MovableStatic::blank()
//{
// }
| 3,242
|
C++
|
.cpp
| 81
| 31.222222
| 114
| 0.613846
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,787
|
loadqust.cpp
|
OpenMW_openmw/components/esm4/loadqust.cpp
|
/*
Copyright (C) 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadqust.hpp"
#include <cstring>
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Quest::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getZString(mQuestName);
break;
case ESM::fourCC("ICON"):
reader.getZString(mFileName);
break; // TES4 (none in FO3/FONV)
case ESM::fourCC("DATA"):
{
if (subHdr.dataSize == 2) // TES4
{
reader.get(&mData, 2);
mData.questDelay = 0.f; // unused in TES4 but keep it clean
// if ((mData.flags & Flag_StartGameEnabled) != 0)
// std::cout << "start quest " << mEditorId << std::endl;
}
else
reader.get(mData); // FO3
break;
}
case ESM::fourCC("SCRI"):
reader.getFormId(mQuestScript);
break;
case ESM::fourCC("CTDA"): // FIXME: how to detect if 1st/2nd param is a formid?
{
if (subHdr.dataSize == 24) // TES4
{
TargetCondition cond;
reader.get(&cond, 24);
cond.reference = 0; // unused in TES4 but keep it clean
mTargetConditions.push_back(cond);
}
else if (subHdr.dataSize == 28)
{
TargetCondition cond;
reader.get(cond); // FO3/FONV
if (cond.reference)
reader.adjustFormId(cond.reference);
mTargetConditions.push_back(cond);
}
else
{
// one record with size 20: EDID GenericSupMutBehemoth
reader.skipSubRecordData(); // FIXME
}
// FIXME: support TES5
break;
}
case ESM::fourCC("SCHR"):
reader.get(mScript.scriptHeader);
break;
case ESM::fourCC("SCDA"):
reader.skipSubRecordData();
break; // compiled script data
case ESM::fourCC("SCTX"):
reader.getString(mScript.scriptSource);
break;
case ESM::fourCC("SCRO"):
reader.getFormId(mScript.globReference);
break;
case ESM::fourCC("INDX"):
case ESM::fourCC("QSDT"):
case ESM::fourCC("CNAM"):
case ESM::fourCC("QSTA"):
case ESM::fourCC("NNAM"): // FO3
case ESM::fourCC("QOBJ"): // FO3
case ESM::fourCC("NAM0"): // FO3
case ESM::fourCC("ANAM"): // TES5
case ESM::fourCC("DNAM"): // TES5
case ESM::fourCC("ENAM"): // TES5
case ESM::fourCC("FNAM"): // TES5
case ESM::fourCC("NEXT"): // TES5
case ESM::fourCC("ALCA"): // TES5
case ESM::fourCC("ALCL"): // TES5
case ESM::fourCC("ALCO"): // TES5
case ESM::fourCC("ALDN"): // TES5
case ESM::fourCC("ALEA"): // TES5
case ESM::fourCC("ALED"): // TES5
case ESM::fourCC("ALEQ"): // TES5
case ESM::fourCC("ALFA"): // TES5
case ESM::fourCC("ALFC"): // TES5
case ESM::fourCC("ALFD"): // TES5
case ESM::fourCC("ALFE"): // TES5
case ESM::fourCC("ALFI"): // TES5
case ESM::fourCC("ALFL"): // TES5
case ESM::fourCC("ALFR"): // TES5
case ESM::fourCC("ALID"): // TES5
case ESM::fourCC("ALLS"): // TES5
case ESM::fourCC("ALNA"): // TES5
case ESM::fourCC("ALNT"): // TES5
case ESM::fourCC("ALPC"): // TES5
case ESM::fourCC("ALRT"): // TES5
case ESM::fourCC("ALSP"): // TES5
case ESM::fourCC("ALST"): // TES5
case ESM::fourCC("ALUA"): // TES5
case ESM::fourCC("CIS1"): // TES5
case ESM::fourCC("CIS2"): // TES5
case ESM::fourCC("CNTO"): // TES5
case ESM::fourCC("COCT"): // TES5
case ESM::fourCC("ECOR"): // TES5
case ESM::fourCC("FLTR"): // TES5
case ESM::fourCC("KNAM"): // TES5
case ESM::fourCC("KSIZ"): // TES5
case ESM::fourCC("KWDA"): // TES5
case ESM::fourCC("QNAM"): // TES5
case ESM::fourCC("QTGL"): // TES5
case ESM::fourCC("SPOR"): // TES5
case ESM::fourCC("VMAD"): // TES5
case ESM::fourCC("VTCK"): // TES5
case ESM::fourCC("ALCC"): // FO4
case ESM::fourCC("ALCS"): // FO4
case ESM::fourCC("ALDI"): // FO4
case ESM::fourCC("ALFV"): // FO4
case ESM::fourCC("ALLA"): // FO4
case ESM::fourCC("ALMI"): // FO4
case ESM::fourCC("GNAM"): // FO4
case ESM::fourCC("GWOR"): // FO4
case ESM::fourCC("LNAM"): // FO4
case ESM::fourCC("NAM2"): // FO4
case ESM::fourCC("OCOR"): // FO4
case ESM::fourCC("SNAM"): // FO4
case ESM::fourCC("XNAM"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::QUST::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
// if (mEditorId == "DAConversations")
// std::cout << mEditorId << std::endl;
}
// void ESM4::Quest::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Quest::blank()
//{
// }
| 7,199
|
C++
|
.cpp
| 173
| 29.450867
| 114
| 0.519469
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,788
|
loadslgm.cpp
|
OpenMW_openmw/components/esm4/loadslgm.cpp
|
/*
Copyright (C) 2016, 2018, 2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadslgm.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::SoulGem::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("ICON"):
reader.getZString(mIcon);
break;
case ESM::fourCC("DATA"):
reader.get(mData);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("SOUL"):
reader.get(mSoul);
break;
case ESM::fourCC("SLCP"):
reader.get(mSoulCapacity);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("MODT"):
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("NAM0"):
case ESM::fourCC("OBND"):
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::SLGM::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::SoulGem::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::SoulGem::blank()
//{
// }
| 2,970
|
C++
|
.cpp
| 78
| 29.025641
| 114
| 0.612153
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,789
|
loadalch.cpp
|
OpenMW_openmw/components/esm4/loadalch.cpp
|
/*
Copyright (C) 2016, 2018, 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadalch.hpp"
#include <cstring>
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Potion::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("ICON"):
reader.getZString(mIcon);
break;
case ESM::fourCC("MICO"):
reader.getZString(mMiniIcon);
break; // FO3
case ESM::fourCC("DATA"):
reader.get(mData);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("SCIT"):
reader.get(mEffect);
reader.adjustFormId(mEffect.formId);
break;
case ESM::fourCC("ENIT"):
if (subHdr.dataSize == 8) // TES4
{
reader.get(&mItem, 8);
mItem.withdrawl = 0;
mItem.sound = 0;
break;
}
reader.get(mItem);
reader.adjustFormId(mItem.withdrawl);
reader.adjustFormId(mItem.sound);
break;
case ESM::fourCC("YNAM"):
reader.getFormId(mPickUpSound);
break;
case ESM::fourCC("ZNAM"):
reader.getFormId(mDropSound);
break;
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("EFID"):
case ESM::fourCC("EFIT"):
case ESM::fourCC("CTDA"):
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("OBND"):
case ESM::fourCC("ETYP"): // FO3
case ESM::fourCC("DESC"):
case ESM::fourCC("DAMC"): // Destructible
case ESM::fourCC("DEST"):
case ESM::fourCC("DMDC"):
case ESM::fourCC("DMDL"):
case ESM::fourCC("DMDT"):
case ESM::fourCC("DMDS"):
case ESM::fourCC("DSTA"):
case ESM::fourCC("DSTD"):
case ESM::fourCC("DSTF"): // Destructible end
case ESM::fourCC("DNAM"): // FO4
case ESM::fourCC("PTRN"): // FO4
case ESM::fourCC("CUSD"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::ALCH::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Potion::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Potion::blank()
//{
// }
| 4,524
|
C++
|
.cpp
| 117
| 27.717949
| 114
| 0.559499
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,790
|
reader.cpp
|
OpenMW_openmw/components/esm4/reader.cpp
|
/*
Copyright (C) 2015-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
*/
#include "reader.hpp"
#undef DEBUG_GROUPSTACK
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <optional>
#include <span>
#include <sstream>
#include <stdexcept>
#include <zlib.h>
#include <components/bsa/memorystream.hpp>
#include <components/debug/debuglog.hpp>
#include <components/esm/refid.hpp>
#include <components/files/constrainedfilestream.hpp>
#include <components/files/conversion.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/to_utf8/to_utf8.hpp>
#include <components/vfs/manager.hpp>
#include "grouptype.hpp"
namespace ESM4
{
namespace
{
using FormId = ESM::FormId;
using FormId32 = ESM::FormId32;
std::string getError(const std::string& header, const int errorCode, const char* msg)
{
return header + ": code " + std::to_string(errorCode) + ", " + std::string(msg != nullptr ? msg : "(null)");
}
std::u8string_view getStringsSuffix(LocalizedStringType type)
{
switch (type)
{
case LocalizedStringType::Strings:
return u8".STRINGS";
case LocalizedStringType::ILStrings:
return u8".ILSTRINGS";
case LocalizedStringType::DLStrings:
return u8".DLSTRINGS";
}
throw std::logic_error("Unsupported LocalizedStringType: " + std::to_string(static_cast<int>(type)));
}
struct InflateEnd
{
void operator()(z_stream* stream) const { inflateEnd(stream); }
};
std::optional<std::string> tryDecompressAll(std::span<char> compressed, std::span<char> decompressed)
{
z_stream stream{};
stream.next_in = reinterpret_cast<Bytef*>(compressed.data());
stream.next_out = reinterpret_cast<Bytef*>(decompressed.data());
stream.avail_in = static_cast<uInt>(compressed.size());
stream.avail_out = static_cast<uInt>(decompressed.size());
if (const int ec = inflateInit(&stream); ec != Z_OK)
return getError("inflateInit error", ec, stream.msg);
const std::unique_ptr<z_stream, InflateEnd> streamPtr(&stream);
if (const int ec = inflate(&stream, Z_NO_FLUSH); ec != Z_STREAM_END)
return getError("inflate error", ec, stream.msg);
return std::nullopt;
}
std::optional<std::string> tryDecompressByBlock(
std::span<char> compressed, std::span<char> decompressed, std::size_t blockSize)
{
z_stream stream{};
if (const int ec = inflateInit(&stream); ec != Z_OK)
return getError("inflateInit error", ec, stream.msg);
const std::unique_ptr<z_stream, InflateEnd> streamPtr(&stream);
while (!compressed.empty() && !decompressed.empty())
{
const auto prevTotalIn = stream.total_in;
const auto prevTotalOut = stream.total_out;
stream.next_in = reinterpret_cast<Bytef*>(compressed.data());
stream.avail_in = static_cast<uInt>(std::min(blockSize, compressed.size()));
stream.next_out = reinterpret_cast<Bytef*>(decompressed.data());
stream.avail_out = static_cast<uInt>(std::min(blockSize, decompressed.size()));
const int ec = inflate(&stream, Z_NO_FLUSH);
if (ec == Z_STREAM_END)
break;
if (ec != Z_OK)
return getError(
"inflate error after reading " + std::to_string(stream.total_in) + " bytes", ec, stream.msg);
compressed = compressed.subspan(stream.total_in - prevTotalIn);
decompressed = decompressed.subspan(stream.total_out - prevTotalOut);
}
return std::nullopt;
}
std::unique_ptr<Bsa::MemoryInputStream> decompress(
std::streamoff position, std::span<char> compressed, std::uint32_t uncompressedSize)
{
auto result = std::make_unique<Bsa::MemoryInputStream>(uncompressedSize);
const std::span decompressed(result->getRawData(), uncompressedSize);
const auto allError = tryDecompressAll(compressed, decompressed);
if (!allError.has_value())
return result;
Log(Debug::Warning) << "Failed to decompress record data at 0x" << std::hex << position
<< std::resetiosflags(std::ios_base::hex) << " compressed size = " << compressed.size()
<< " uncompressed size = " << uncompressedSize << ": " << *allError
<< ". Trying to decompress by block...";
std::memset(result->getRawData(), 0, uncompressedSize);
constexpr std::size_t blockSize = 4;
const auto blockError = tryDecompressByBlock(compressed, decompressed, blockSize);
if (!blockError.has_value())
return result;
std::ostringstream s;
s << "Failed to decompress record data by block of " << blockSize << " bytes at 0x" << std::hex << position
<< std::resetiosflags(std::ios_base::hex) << " compressed size = " << compressed.size()
<< " uncompressed size = " << uncompressedSize << ": " << *blockError;
throw std::runtime_error(s.str());
}
}
ReaderContext::ReaderContext()
: modIndex(0)
, recHeaderSize(sizeof(RecordHeader))
, filePos(0)
, fileRead(0)
, recordRead(0)
, currWorld({ 0, 0 })
, currCell({ 0, 0 })
, currCellGrid(FormId{ 0, 0 })
, cellGridValid(false)
{
recordHeader = {};
subRecordHeader = {};
}
Reader::Reader(Files::IStreamPtr&& esmStream, const std::filesystem::path& filename, VFS::Manager const* vfs,
const ToUTF8::StatelessUtf8Encoder* encoder, bool ignoreMissingLocalizedStrings)
: mVFS(vfs)
, mEncoder(encoder)
, mFileSize(0)
, mStream(std::move(esmStream))
, mIgnoreMissingLocalizedStrings(ignoreMissingLocalizedStrings)
{
// used by ESMReader only?
mCtx.filename = filename;
mCtx.fileRead = 0;
mStream->seekg(0, mStream->end);
mFileSize = mStream->tellg();
mStream->seekg(20); // go to the start but skip the "TES4" record header
mSavedStream.reset();
// determine header size
std::uint32_t subRecName = 0;
mStream->read((char*)&subRecName, sizeof(subRecName));
if (subRecName == 0x52444548) // "HEDR"
mCtx.recHeaderSize = sizeof(RecordHeader) - 4; // TES4 header size is 4 bytes smaller than TES5 header
else
mCtx.recHeaderSize = sizeof(RecordHeader);
// restart from the beginning (i.e. "TES4" record header)
mStream->seekg(0, mStream->beg);
getRecordHeader();
if (mCtx.recordHeader.record.typeId == REC_TES4)
{
mHeader.load(*this);
mCtx.fileRead += mCtx.recordHeader.record.dataSize;
buildLStringIndex(); // for localised strings in Skyrim
}
else
fail("Unknown file format");
}
Reader::~Reader()
{
close();
}
// Since the record data may have been compressed, it is not always possible to use seek() to
// go to a position of a sub record.
//
// The record header needs to be saved in the context or the header needs to be re-loaded after
// restoring the context. The latter option was chosen.
ReaderContext Reader::getContext()
{
mCtx.filePos = mStream->tellg();
if (mCtx.filePos == std::streampos(-1))
return mCtx;
mCtx.filePos -= mCtx.recHeaderSize; // update file position
return mCtx;
}
// NOTE: Assumes that the caller has reopened the file if necessary
bool Reader::restoreContext(const ReaderContext& ctx)
{
if (mSavedStream) // TODO: doesn't seem to ever happen
{
mStream = std::move(mSavedStream);
}
mCtx.groupStack.clear(); // probably not necessary since it will be overwritten
mCtx = ctx;
mStream->seekg(ctx.filePos); // update file position
return getRecordHeader();
}
void Reader::close()
{
mStream.reset();
// clearCtx();
// mHeader.blank();
}
void Reader::openRaw(Files::IStreamPtr&& stream, const std::filesystem::path& filename)
{
close();
mStream = std::move(stream);
mCtx.filename = filename;
mCtx.fileRead = 0;
mStream->seekg(0, mStream->end);
mFileSize = mStream->tellg();
mStream->seekg(0, mStream->beg);
}
void Reader::open(Files::IStreamPtr&& stream, const std::filesystem::path& filename)
{
openRaw(std::move(stream), filename);
// should at least have the size of ESM3 record header (20 or 24 bytes for ESM4)
if (mFileSize < 16)
throw std::runtime_error("File too small");
std::uint32_t modVer = 0;
if (getExact(modVer)) // get the first 4 bytes of the record header only
{
// FIXME: need to setup header/context
if (modVer == REC_TES4)
{
}
else
{
}
}
throw std::runtime_error("Unknown file format"); // can't yet use fail() as mCtx is not setup
}
void Reader::open(const std::filesystem::path& filename)
{
open(Files::openConstrainedFileStream(filename), filename);
}
void Reader::setRecHeaderSize(const std::size_t size)
{
mCtx.recHeaderSize = size;
}
void Reader::buildLStringIndex()
{
if ((mHeader.mFlags & Rec_ESM) == 0 || (mHeader.mFlags & Rec_Localized) == 0)
return;
const std::u8string prefix = mCtx.filename.stem().filename().u8string();
buildLStringIndex(LocalizedStringType::Strings, prefix);
buildLStringIndex(LocalizedStringType::ILStrings, prefix);
buildLStringIndex(LocalizedStringType::DLStrings, prefix);
}
void Reader::buildLStringIndex(LocalizedStringType stringType, const std::u8string& prefix)
{
static const std::filesystem::path strings("Strings");
const std::u8string language(u8"_En");
const std::u8string altLanguage(u8"_English");
const std::u8string suffix(getStringsSuffix(stringType));
std::filesystem::path path = strings / (prefix + language + suffix);
if (mVFS != nullptr)
{
VFS::Path::Normalized vfsPath(Files::pathToUnicodeString(path));
Files::IStreamPtr stream = mVFS->find(vfsPath);
if (stream == nullptr)
{
path = strings / (prefix + altLanguage + suffix);
vfsPath = VFS::Path::Normalized(Files::pathToUnicodeString(path));
stream = mVFS->find(vfsPath);
}
if (stream != nullptr)
{
buildLStringIndex(stringType, *stream);
return;
}
if (mIgnoreMissingLocalizedStrings)
{
Log(Debug::Warning) << "Ignore missing VFS strings file: " << vfsPath;
return;
}
}
std::filesystem::path fsPath = mCtx.filename.parent_path() / path;
if (!std::filesystem::exists(fsPath))
{
path = strings / (prefix + altLanguage + suffix);
fsPath = mCtx.filename.parent_path() / path;
}
if (std::filesystem::exists(fsPath))
{
const Files::IStreamPtr stream = Files::openConstrainedFileStream(fsPath);
buildLStringIndex(stringType, *stream);
return;
}
if (mIgnoreMissingLocalizedStrings)
Log(Debug::Warning) << "Ignore missing strings file: " << fsPath;
}
void Reader::buildLStringIndex(LocalizedStringType stringType, std::istream& stream)
{
stream.seekg(0, std::ios::end);
const std::istream::pos_type fileSize = stream.tellg();
stream.seekg(0, std::ios::beg);
std::uint32_t numEntries = 0;
stream.read(reinterpret_cast<char*>(&numEntries), sizeof(numEntries));
std::uint32_t dataSize = 0;
stream.read(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));
const std::istream::pos_type dataStart = fileSize - static_cast<std::istream::pos_type>(dataSize);
struct LocalizedString
{
std::uint32_t mOffset = 0;
std::uint32_t mStringId = 0;
};
std::vector<LocalizedString> strings;
strings.reserve(numEntries);
for (std::uint32_t i = 0; i < numEntries; ++i)
{
LocalizedString string;
stream.read(reinterpret_cast<char*>(&string.mStringId), sizeof(string.mStringId));
stream.read(reinterpret_cast<char*>(&string.mOffset), sizeof(string.mOffset));
strings.push_back(string);
}
std::sort(strings.begin(), strings.end(),
[](const LocalizedString& l, const LocalizedString& r) { return l.mOffset < r.mOffset; });
std::uint32_t lastOffset = 0;
std::string_view lastValue;
for (const LocalizedString& string : strings)
{
if (string.mOffset == lastOffset)
{
mLStringIndex.emplace(FormId::fromUint32(string.mStringId), lastValue);
continue;
}
const std::istream::pos_type offset = string.mOffset + dataStart;
const std::istream::pos_type pos = stream.tellg();
if (pos != offset)
{
char buffer[4096];
if (pos < offset && offset - pos < static_cast<std::istream::pos_type>(sizeof(buffer)))
stream.read(buffer, offset - pos);
else
stream.seekg(offset);
}
const auto it
= mLStringIndex.emplace(FormId::fromUint32(string.mStringId), readLocalizedString(stringType, stream))
.first;
lastOffset = string.mOffset;
lastValue = it->second;
}
}
std::string Reader::readLocalizedString(LocalizedStringType type, std::istream& stream)
{
if (type == LocalizedStringType::Strings)
{
std::string data;
while (true)
{
char ch = 0;
stream.read(&ch, sizeof(ch));
if (ch == 0)
break;
data.push_back(ch);
}
return data;
}
std::uint32_t size = 0;
stream.read(reinterpret_cast<char*>(&size), sizeof(size));
std::string result;
getStringImpl(result, size, stream, true); // expect null terminated string
return result;
}
void Reader::getLocalizedString(std::string& str)
{
if (!hasLocalizedStrings())
return (void)getZString(str);
std::uint32_t stringId; // FormId
get(stringId);
if (stringId) // TES5 FoxRace, BOOK
getLocalizedStringImpl(FormId::fromUint32(stringId), str);
}
// FIXME: very messy and probably slow/inefficient
void Reader::getLocalizedStringImpl(const FormId stringId, std::string& str)
{
const auto it = mLStringIndex.find(stringId);
if (it == mLStringIndex.end())
{
if (mIgnoreMissingLocalizedStrings)
return;
throw std::runtime_error("ESM4::Reader::getLocalizedString localized string not found for "
+ ESM::RefId(stringId).toDebugString());
}
str = it->second;
}
bool Reader::getRecordHeader()
{
// FIXME: this seems very hacky but we may have skipped subrecords from within an inflated data block
if (/*mStream->eof() && */ mSavedStream)
{
mStream = std::move(mSavedStream);
}
mStream->read((char*)&mCtx.recordHeader, mCtx.recHeaderSize);
std::size_t bytesRead = (std::size_t)mStream->gcount();
// keep track of data left to read from the file
mCtx.fileRead += mCtx.recHeaderSize;
mCtx.recordRead = 0; // for keeping track of sub records
// After reading the record header we can cache a WRLD or CELL formId for convenient access later.
// FIXME: currently currWorld and currCell are set manually when loading the WRLD and CELL records
// HACK: mCtx.groupStack.back() is updated before the record data are read/skipped
// N.B. the data must be fully read/skipped for this to work
if (mCtx.recordHeader.record.typeId != REC_GRUP && !mCtx.groupStack.empty())
{
mCtx.groupStack.back().second += (std::uint32_t)mCtx.recHeaderSize + mCtx.recordHeader.record.dataSize;
// keep track of data left to read from the file
mCtx.fileRead += mCtx.recordHeader.record.dataSize;
}
return bytesRead == mCtx.recHeaderSize;
}
void Reader::getRecordData(bool dump)
{
std::uint32_t uncompressedSize = 0;
if ((mCtx.recordHeader.record.flags & Rec_Compressed) != 0)
{
mStream->read(reinterpret_cast<char*>(&uncompressedSize), sizeof(std::uint32_t));
const std::streamoff position = mStream->tellg();
const std::uint32_t recordSize = mCtx.recordHeader.record.dataSize - sizeof(std::uint32_t);
std::vector<char> compressed(recordSize);
mStream->read(compressed.data(), recordSize);
mSavedStream = std::move(mStream);
mCtx.recordHeader.record.dataSize = uncompressedSize - sizeof(uncompressedSize);
auto memoryStreamPtr = decompress(position, compressed, uncompressedSize);
// For debugging only
// #if 0
if (dump)
{
std::ostringstream ss;
char* data = memoryStreamPtr->getRawData();
for (unsigned int i = 0; i < uncompressedSize; ++i)
{
if (data[i] > 64 && data[i] < 91)
ss << (char)(data[i]) << " ";
else
ss << std::setfill('0') << std::setw(2) << std::hex << (int)(data[i]);
if ((i & 0x000f) == 0xf)
ss << "\n";
else if (i < uncompressedSize - 1)
ss << " ";
}
std::cout << ss.str() << std::endl;
}
// #endif
mStream = std::make_unique<Files::StreamWithBuffer<Bsa::MemoryInputStream>>(std::move(memoryStreamPtr));
}
}
void Reader::skipRecordData()
{
if (mCtx.recordRead > mCtx.recordHeader.record.dataSize)
throw std::runtime_error("Skipping after reading more than available");
mStream->ignore(mCtx.recordHeader.record.dataSize - mCtx.recordRead);
mCtx.recordRead = mCtx.recordHeader.record.dataSize; // for getSubRecordHeader()
}
bool Reader::getSubRecordHeader()
{
bool result = false;
// NOTE: some SubRecords have 0 dataSize (e.g. SUB_RDSD in one of REC_REGN records in Oblivion.esm).
if (mCtx.recordHeader.record.dataSize - mCtx.recordRead >= sizeof(mCtx.subRecordHeader))
{
result = getExact(mCtx.subRecordHeader);
// HACK: below assumes sub-record data will be read or skipped in full;
// this hack aims to avoid updating mCtx.recordRead each time anything is read
mCtx.recordRead += (sizeof(mCtx.subRecordHeader) + mCtx.subRecordHeader.dataSize);
}
else if (mCtx.recordRead > mCtx.recordHeader.record.dataSize)
{
// try to correct any overshoot, seek to the end of the expected data
// this will only work if mCtx.subRecordHeader.dataSize was fully read or skipped
// (i.e. it will only correct mCtx.subRecordHeader.dataSize being incorrect)
// TODO: not tested
std::uint32_t overshoot = (std::uint32_t)mCtx.recordRead - mCtx.recordHeader.record.dataSize;
std::size_t pos = mStream->tellg();
mStream->seekg(pos - overshoot);
return false;
}
// Extended storage subrecord redefines the following subrecord's size.
// Would need to redesign the loader to support that, so skip over both subrecords.
if (result && mCtx.subRecordHeader.typeId == ESM::fourCC("XXXX"))
{
std::uint32_t extDataSize;
get(extDataSize);
if (!getSubRecordHeader())
return false;
skipSubRecordData(extDataSize);
mCtx.recordRead += extDataSize - mCtx.subRecordHeader.dataSize;
return getSubRecordHeader();
}
return result;
}
void Reader::skipSubRecordData()
{
mStream->ignore(mCtx.subRecordHeader.dataSize);
}
void Reader::skipSubRecordData(std::uint32_t size)
{
mStream->ignore(size);
}
void Reader::enterGroup()
{
#ifdef DEBUG_GROUPSTACK
std::string padding; // FIXME: debugging only
padding.insert(0, mCtx.groupStack.size() * 2, ' ');
std::cout << padding << "Starting record group "
<< printLabel(mCtx.recordHeader.group.label, mCtx.recordHeader.group.type) << std::endl;
#endif
// empty group if the group size is same as the header size
if (mCtx.recordHeader.group.groupSize == (std::uint32_t)mCtx.recHeaderSize)
{
#ifdef DEBUG_GROUPSTACK
std::cout << padding << "Ignoring record group " // FIXME: debugging only
<< printLabel(mCtx.recordHeader.group.label, mCtx.recordHeader.group.type) << " (empty)"
<< std::endl;
#endif
if (!mCtx.groupStack.empty()) // top group may be empty (e.g. HAIR in Skyrim)
{
// don't put on the stack, exitGroupCheck() may not get called before recursing into this method
mCtx.groupStack.back().second += mCtx.recordHeader.group.groupSize;
exitGroupCheck();
}
return; // don't push an empty group, just return
}
// push group
mCtx.groupStack.push_back(std::make_pair(mCtx.recordHeader.group, (std::uint32_t)mCtx.recHeaderSize));
}
void Reader::exitGroupCheck()
{
if (mCtx.groupStack.empty())
return;
// pop finished groups (note reading too much is allowed here)
std::uint32_t lastGroupSize = mCtx.groupStack.back().first.groupSize;
while (mCtx.groupStack.back().second >= lastGroupSize)
{
#ifdef DEBUG_GROUPSTACK
GroupTypeHeader grp = mCtx.groupStack.back().first; // FIXME: grp is for debugging only
#endif
// try to correct any overshoot
// TODO: not tested
std::uint32_t overshoot = mCtx.groupStack.back().second - lastGroupSize;
if (overshoot > 0)
{
std::size_t pos = mStream->tellg();
mStream->seekg(pos - overshoot);
}
mCtx.groupStack.pop_back();
#ifdef DEBUG_GROUPSTACK
std::string padding; // FIXME: debugging only
padding.insert(0, mCtx.groupStack.size() * 2, ' ');
std::cout << padding << "Finished record group " << printLabel(grp.label, grp.type) << std::endl;
#endif
// if the previous group was the final one no need to do below
if (mCtx.groupStack.empty())
return;
mCtx.groupStack.back().second += lastGroupSize;
lastGroupSize = mCtx.groupStack.back().first.groupSize;
if (lastGroupSize < mCtx.groupStack.back().second)
throw std::runtime_error("Read more records than available");
// #if 0
if (mCtx.groupStack.back().second > lastGroupSize) // FIXME: debugging only
std::cerr << printLabel(mCtx.groupStack.back().first.label, mCtx.groupStack.back().first.type)
<< " read more records than available" << std::endl;
// #endif
}
}
// WARNING: this method should be used after first calling enterGroup()
// else the method may try to dereference an element that does not exist
const GroupTypeHeader& Reader::grp(std::size_t pos) const
{
if (mCtx.groupStack.size() == 0)
throw std::runtime_error("ESM4::Reader::grp mCtx.groupStack.size is zero");
if (pos > mCtx.groupStack.size() - 1)
throw std::runtime_error("ESM4::Reader::grp - exceeded stack depth");
return (*(mCtx.groupStack.end() - pos - 1)).first;
}
void Reader::skipGroupData()
{
if (mCtx.groupStack.empty())
throw std::runtime_error("Skipping group with an empty stack");
// subtract what was already read/skipped
std::uint32_t skipSize = mCtx.groupStack.back().first.groupSize - mCtx.groupStack.back().second;
mStream->ignore(skipSize);
// keep track of data left to read from the file
mCtx.fileRead += skipSize;
mCtx.groupStack.back().second = mCtx.groupStack.back().first.groupSize;
}
void Reader::skipGroup()
{
#ifdef DEBUG_GROUPSTACK
std::string padding; // FIXME: debugging only
padding.insert(0, mCtx.groupStack.size() * 2, ' ');
std::cout << padding << "Skipping record group "
<< printLabel(mCtx.recordHeader.group.label, mCtx.recordHeader.group.type) << std::endl;
#endif
// subtract the size of header already read before skipping
std::uint32_t skipSize = mCtx.recordHeader.group.groupSize - (std::uint32_t)mCtx.recHeaderSize;
mStream->ignore(skipSize);
// keep track of data left to read from the file
mCtx.fileRead += skipSize;
// NOTE: mCtx.groupStack.back().second already has mCtx.recHeaderSize from enterGroup()
if (!mCtx.groupStack.empty())
mCtx.groupStack.back().second += mCtx.recordHeader.group.groupSize;
}
const CellGrid& Reader::currCellGrid() const
{
if (!mCtx.cellGridValid)
throw std::runtime_error("Attempt to use an invalid cell grid");
return mCtx.currCellGrid;
}
void Reader::updateModIndices(const std::map<std::string, int>& fileToModIndex)
{
mCtx.parentFileIndices.resize(mHeader.mMaster.size());
for (unsigned int i = 0; i < mHeader.mMaster.size(); ++i)
{
// locate the position of the dependency in already loaded files
auto it = fileToModIndex.find(Misc::StringUtils::lowerCase(mHeader.mMaster[i].name));
if (it != fileToModIndex.end())
mCtx.parentFileIndices[i] = it->second;
else
throw std::runtime_error(
"ESM4::Reader::updateModIndices required dependency '" + mHeader.mMaster[i].name + "' not found");
}
}
// ModIndex adjusted formId according to master file dependencies
// (see http://www.uesp.net/wiki/Tes4Mod:FormID_Fixup)
// NOTE: need to update modindex to parentFileIndices.size() before saving
//
// FIXME: probably should add a parameter to check for mCtx.header::mOverrides
// (ACHR, LAND, NAVM, PGRE, PHZD, REFR), but not sure what exactly overrides mean
// i.e. use the modindx of its master?
// FIXME: Apparently ModIndex '00' in an ESP means the object is defined in one of its masters.
// This means we may need to search multiple times to get the correct id.
// (see https://www.uesp.net/wiki/Tes4Mod:Formid#ModIndex_Zero)
void Reader::adjustFormId(FormId& id) const
{
if (id.hasContentFile() && id.mContentFile < static_cast<int>(mCtx.parentFileIndices.size()))
id.mContentFile = mCtx.parentFileIndices[id.mContentFile];
else
id.mContentFile = mCtx.modIndex;
}
void Reader::adjustFormId(FormId32& id) const
{
FormId formId = FormId::fromUint32(id);
adjustFormId(formId);
id = formId.toUint32();
}
bool Reader::getFormId(FormId& id)
{
FormId32 v;
if (!getExact(v))
return false;
id = FormId::fromUint32(v);
adjustFormId(id);
return true;
}
ESM::FormId Reader::getFormIdFromHeader() const
{
FormId formId = hdr().record.getFormId();
adjustFormId(formId);
return formId;
}
void Reader::adjustGRUPFormId()
{
adjustFormId(mCtx.recordHeader.group.label.value);
}
[[noreturn]] void Reader::fail(const std::string& msg)
{
std::stringstream ss;
ss << "ESM Error: " << msg;
ss << "\n File: " << Files::pathToUnicodeString(mCtx.filename);
ss << "\n Record: " << ESM::printName(mCtx.recordHeader.record.typeId);
ss << "\n Subrecord: " << ESM::printName(mCtx.subRecordHeader.typeId);
if (mStream.get())
ss << "\n Offset: 0x" << std::hex << mStream->tellg();
throw std::runtime_error(ss.str());
}
bool Reader::getStringImpl(std::string& str, std::size_t size, std::istream& stream, bool hasNull)
{
std::size_t newSize = size;
if (mEncoder != nullptr)
{
std::string input(size, '\0');
stream.read(input.data(), size);
if (stream.gcount() == static_cast<std::streamsize>(size))
{
const std::string_view result
= mEncoder->getUtf8(input, ToUTF8::BufferAllocationPolicy::FitToRequiredSize, str);
if (str.empty() && !result.empty())
{
str = std::move(input);
str.resize(result.size());
}
return true;
}
}
else
{
if (hasNull)
newSize -= 1; // don't read the null terminator yet
str.resize(newSize); // assumed C++11
stream.read(str.data(), newSize);
if (static_cast<std::size_t>(stream.gcount()) == newSize)
{
if (hasNull)
{
char ch;
stream.read(&ch, 1); // read the null terminator
if (ch != '\0')
throw std::runtime_error("ESM4::Reader::getString string is not terminated with a null");
}
#if 0
else
{
// NOTE: normal ESMs don't but omwsave has locals or spells with null terminator
assert (str[newSize - 1] != '\0'
&& "ESM4::Reader::getString string is unexpectedly terminated with a null");
}
#endif
return true;
}
}
str.clear();
return false; // FIXME: throw instead?
}
bool Reader::getZeroTerminatedStringArray(std::vector<std::string>& values)
{
const std::size_t size = mCtx.subRecordHeader.dataSize;
std::string input(size, '\0');
mStream->read(input.data(), size);
if (mStream->gcount() != static_cast<std::streamsize>(size))
return false;
std::string_view inputView(input.data(), input.size());
std::string buffer;
while (true)
{
std::string_view value(inputView.data());
const std::size_t next = inputView.find_first_not_of('\0', value.size());
if (mEncoder != nullptr)
value = mEncoder->getUtf8(value, ToUTF8::BufferAllocationPolicy::UseGrowFactor, buffer);
values.emplace_back(value);
if (next == std::string_view::npos)
break;
inputView = inputView.substr(next);
}
return true;
}
namespace
{
constexpr std::string_view sGroupType[] = {
"Record Type",
"World Child",
"Interior Cell",
"Interior Sub Cell",
"Exterior Cell",
"Exterior Sub Cell",
"Cell Child",
"Topic Child",
"Cell Persistent Child",
"Cell Temporary Child",
"Cell Visible Dist Child",
"Unknown",
};
}
std::string printLabel(const GroupLabel& label, const std::uint32_t type)
{
std::ostringstream ss;
ss << sGroupType[std::min<std::size_t>(type, std::size(sGroupType))]; // avoid out of range
switch (type)
{
case ESM4::Grp_RecordType:
{
ss << ": " << std::string((char*)label.recordType, 4);
break;
}
case ESM4::Grp_ExteriorCell:
case ESM4::Grp_ExteriorSubCell:
{
// short x, y;
// y = label & 0xff;
// x = (label >> 16) & 0xff;
ss << ": grid (x, y) " << std::dec << label.grid[1] << ", " << label.grid[0];
break;
}
case ESM4::Grp_InteriorCell:
case ESM4::Grp_InteriorSubCell:
{
ss << ": block 0x" << std::hex << label.value;
break;
}
case ESM4::Grp_WorldChild:
case ESM4::Grp_CellChild:
case ESM4::Grp_TopicChild:
case ESM4::Grp_CellPersistentChild:
case ESM4::Grp_CellTemporaryChild:
case ESM4::Grp_CellVisibleDistChild:
{
ss << ": " << ESM::RefId(FormId::fromUint32(label.value));
break;
}
default:
break;
}
return ss.str();
}
}
| 35,124
|
C++
|
.cpp
| 811
| 32.720099
| 120
| 0.58651
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,791
|
loadsndr.cpp
|
OpenMW_openmw/components/esm4/loadsndr.cpp
|
/*
Copyright (C) 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadsndr.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::SoundReference::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("CTDA"):
reader.get(&mTargetCondition, 20);
reader.get(mTargetCondition.runOn);
reader.get(mTargetCondition.reference);
if (mTargetCondition.reference)
reader.adjustFormId(mTargetCondition.reference);
reader.skipSubRecordData(4); // unknown
break;
case ESM::fourCC("GNAM"):
reader.getFormId(mSoundCategory);
break;
case ESM::fourCC("SNAM"):
reader.getFormId(mSoundId);
break;
case ESM::fourCC("ONAM"):
reader.getFormId(mOutputModel);
break;
case ESM::fourCC("ANAM"):
reader.getZString(mSoundFile);
break;
case ESM::fourCC("LNAM"):
reader.get(mLoopInfo);
break;
case ESM::fourCC("BNAM"):
{
if (subHdr.dataSize == 6)
reader.get(mData);
else if (subHdr.dataSize == 4)
reader.getFormId(mBaseDescriptor);
else
reader.skipSubRecordData();
break;
}
case ESM::fourCC("CIS1"):
case ESM::fourCC("CIS2"):
case ESM::fourCC("CNAM"): // CRC32 hash
case ESM::fourCC("DNAM"): // FO4
case ESM::fourCC("FNAM"): // unknown
case ESM::fourCC("INTV"): // FO4
case ESM::fourCC("ITMC"): // FO4
case ESM::fourCC("ITME"): // FO4
case ESM::fourCC("ITMS"): // FO4
case ESM::fourCC("NNAM"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::SNDR::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::SoundReference::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::SoundReference::blank()
//{
// }
| 3,676
|
C++
|
.cpp
| 92
| 29.782609
| 114
| 0.595185
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,792
|
loadsgst.cpp
|
OpenMW_openmw/components/esm4/loadsgst.cpp
|
/*
Copyright (C) 2016, 2018, 2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadsgst.hpp"
#include <cstring>
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::SigilStone::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
{
if (mFullName.empty())
{
if (!reader.getZString(mFullName))
throw std::runtime_error("SGST FULL data read error");
}
else
{
// FIXME: should be part of a struct?
std::string scriptEffectName;
if (!reader.getZString(scriptEffectName))
throw std::runtime_error("SGST FULL data read error");
mScriptEffect.push_back(scriptEffectName);
}
break;
}
case ESM::fourCC("DATA"):
{
reader.get(mData.uses);
reader.get(mData.value);
reader.get(mData.weight);
break;
}
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("ICON"):
reader.getZString(mIcon);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("SCIT"):
{
reader.get(mEffect);
reader.adjustFormId(mEffect.formId);
break;
}
case ESM::fourCC("MODT"):
case ESM::fourCC("EFID"):
case ESM::fourCC("EFIT"):
{
reader.skipSubRecordData();
break;
}
default:
throw std::runtime_error("ESM4::SGST::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::SigilStone::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::SigilStone::blank()
//{
// }
| 3,597
|
C++
|
.cpp
| 97
| 26.474227
| 114
| 0.573968
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,793
|
loadgras.cpp
|
OpenMW_openmw/components/esm4/loadgras.cpp
|
/*
Copyright (C) 2016, 2018 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadgras.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Grass::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("DATA"):
reader.get(mData);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("OBND"):
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::GRAS::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Grass::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Grass::blank()
//{
// }
| 2,466
|
C++
|
.cpp
| 63
| 31.666667
| 114
| 0.648264
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,794
|
loadlvli.cpp
|
OpenMW_openmw/components/esm4/loadlvli.cpp
|
/*
Copyright (C) 2016, 2018-2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadlvli.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::LevelledItem::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("LVLD"):
reader.get(mChanceNone);
break;
case ESM::fourCC("LVLF"):
reader.get(mLvlItemFlags);
mHasLvlItemFlags = true;
break;
case ESM::fourCC("DATA"):
reader.get(mData);
break;
case ESM::fourCC("LVLO"):
{
LVLO lvlo;
if (subHdr.dataSize != 12)
{
if (subHdr.dataSize == 8)
{
reader.get(lvlo.level);
reader.get(lvlo.item);
reader.get(lvlo.count);
break;
}
else
throw std::runtime_error("ESM4::LVLI::load - " + mEditorId + " LVLO size error");
}
else
reader.get(lvlo);
reader.adjustFormId(lvlo.item);
mLvlObject.push_back(lvlo);
break;
}
case ESM::fourCC("LLCT"):
case ESM::fourCC("OBND"): // FO3/FONV
case ESM::fourCC("COED"): // FO3/FONV
case ESM::fourCC("LVLG"): // FO3/FONV
case ESM::fourCC("LLKC"): // FO4
case ESM::fourCC("LVLM"): // FO4
case ESM::fourCC("LVSG"): // FO4
case ESM::fourCC("ONAM"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::LVLI::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
// FIXME: testing
// if (mHasLvlItemFlags && mChanceNone >= 90)
// std::cout << "LVLI " << mEditorId << " chance none " << int(mChanceNone) << std::endl;
}
bool ESM4::LevelledItem::calcAllLvlLessThanPlayer() const
{
if (mHasLvlItemFlags)
return (mLvlItemFlags & 0x01) != 0;
else
return (mChanceNone & 0x80) != 0; // FIXME: 0x80 is just a guess
}
bool ESM4::LevelledItem::calcEachItemInCount() const
{
if (mHasLvlItemFlags)
return (mLvlItemFlags & 0x02) != 0;
else
return mData != 0;
}
std::int8_t ESM4::LevelledItem::chanceNone() const
{
if (mHasLvlItemFlags)
return mChanceNone;
else
return (mChanceNone & 0x7f); // FIXME: 0x80 is just a guess
}
bool ESM4::LevelledItem::useAll() const
{
if (mHasLvlItemFlags)
return (mLvlItemFlags & 0x04) != 0;
else
return false;
}
// void ESM4::LevelledItem::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::LevelledItem::blank()
//{
// }
| 4,299
|
C++
|
.cpp
| 119
| 27.07563
| 114
| 0.587458
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,795
|
loadammo.cpp
|
OpenMW_openmw/components/esm4/loadammo.cpp
|
/*
Copyright (C) 2016, 2018-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadammo.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Ammunition::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("DATA"):
switch (subHdr.dataSize)
{
case 18: // TES4
case 13: // FO3/FNV
{
reader.get(mData.mSpeed);
reader.get(mData.mFlags);
mData.mFlags &= 0xFF;
reader.get(mData.mValue);
if (subHdr.dataSize == 13)
reader.get(mData.mClipRounds);
else
{
reader.get(mData.mWeight);
std::uint16_t damageInt;
reader.get(damageInt);
mData.mDamage = static_cast<float>(damageInt);
}
break;
}
case 16: // TES5
case 20: // SSE
reader.getFormId(mData.mProjectile);
reader.get(mData.mFlags);
reader.get(mData.mDamage);
reader.get(mData.mValue);
if (subHdr.dataSize == 20)
reader.get(mData.mWeight);
break;
case 8:
reader.get(mData.mValue);
reader.get(mData.mWeight);
break;
default:
reader.skipSubRecordData();
break;
}
break;
case ESM::fourCC("DAT2"):
if (subHdr.dataSize == 20)
{
reader.get(mData.mProjPerShot);
reader.getFormId(mData.mProjectile);
reader.get(mData.mWeight);
reader.getFormId(mData.mConsumedAmmo);
reader.get(mData.mConsumedPercentage);
}
else
{
reader.skipSubRecordData();
}
break;
case ESM::fourCC("DNAM"):
reader.getFormId(mData.mProjectile);
reader.get(mData.mFlags);
mData.mFlags &= 0xFF;
reader.get(mData.mDamage);
reader.get(mData.mHealth);
break;
case ESM::fourCC("ICON"):
reader.getZString(mIcon);
break;
case ESM::fourCC("MICO"):
reader.getZString(mMiniIcon);
break; // FO3
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("ANAM"):
reader.get(mEnchantmentPoints);
break;
case ESM::fourCC("ENAM"):
reader.getFormId(mEnchantment);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("DESC"):
reader.getLocalizedString(mText);
break;
case ESM::fourCC("YNAM"):
reader.getFormId(mPickUpSound);
break;
case ESM::fourCC("ZNAM"):
reader.getFormId(mDropSound);
break;
case ESM::fourCC("ONAM"):
reader.getLocalizedString(mShortName);
break;
case ESM::fourCC("QNAM"): // FONV
reader.getLocalizedString(mAbbrev);
break;
case ESM::fourCC("RCIL"):
reader.getFormId(mAmmoEffects.emplace_back());
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScript);
break;
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("OBND"):
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("DAMC"): // Destructible
case ESM::fourCC("DEST"):
case ESM::fourCC("DMDC"):
case ESM::fourCC("DMDL"):
case ESM::fourCC("DMDT"):
case ESM::fourCC("DMDS"):
case ESM::fourCC("DSTA"):
case ESM::fourCC("DSTD"):
case ESM::fourCC("DSTF"): // Destructible end
case ESM::fourCC("PTRN"): // FO4
case ESM::fourCC("NAM1"): // FO4 casing model data
case ESM::fourCC("NAM2"): //
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::AMMO::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Ammunition::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Ammunition::blank()
//{
// }
| 6,739
|
C++
|
.cpp
| 170
| 25.135294
| 114
| 0.502669
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,796
|
loadsoun.cpp
|
OpenMW_openmw/components/esm4/loadsoun.cpp
|
/*
Copyright (C) 2016, 2018, 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadsoun.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Sound::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FNAM"):
reader.getZString(mSoundFile);
break;
case ESM::fourCC("SNDX"):
reader.get(mData);
break;
case ESM::fourCC("SNDD"):
if (subHdr.dataSize == 8)
reader.get(&mData, 8);
else
{
reader.get(mData);
reader.get(mExtra);
}
break;
case ESM::fourCC("OBND"): // TES5 only
case ESM::fourCC("SDSC"): // TES5 only
case ESM::fourCC("ANAM"): // FO3
case ESM::fourCC("GNAM"): // FO3
case ESM::fourCC("HNAM"): // FO3
case ESM::fourCC("RNAM"): // FONV
case ESM::fourCC("REPT"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::SOUN::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Sound::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Sound::blank()
//{
// }
| 2,761
|
C++
|
.cpp
| 71
| 30.28169
| 114
| 0.615011
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,797
|
loadpgre.cpp
|
OpenMW_openmw/components/esm4/loadpgre.cpp
|
/*
Copyright (C) 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
Also see https://tes5edit.github.io/fopdoc/ for FO3/FONV specific details.
*/
#include "loadpgre.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::PlacedGrenade::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("NAME"):
case ESM::fourCC("XEZN"):
case ESM::fourCC("XRGD"):
case ESM::fourCC("XRGB"):
case ESM::fourCC("XPRD"):
case ESM::fourCC("XPPA"):
case ESM::fourCC("INAM"):
case ESM::fourCC("TNAM"):
case ESM::fourCC("XOWN"):
case ESM::fourCC("XRNK"):
case ESM::fourCC("XCNT"):
case ESM::fourCC("XRDS"):
case ESM::fourCC("XHLP"):
case ESM::fourCC("XPWR"):
case ESM::fourCC("XDCR"):
case ESM::fourCC("XLKR"):
case ESM::fourCC("XLKT"): // FO4
case ESM::fourCC("XCLP"):
case ESM::fourCC("XAPD"):
case ESM::fourCC("XAPR"):
case ESM::fourCC("XATO"):
case ESM::fourCC("XESP"):
case ESM::fourCC("XEMI"):
case ESM::fourCC("XMBR"):
case ESM::fourCC("XIBS"):
case ESM::fourCC("XSCL"):
case ESM::fourCC("DATA"):
case ESM::fourCC("VMAD"):
case ESM::fourCC("MNAM"): // FO4
case ESM::fourCC("XAMC"): // FO4
case ESM::fourCC("XASP"): // FO4
case ESM::fourCC("XATP"): // FO4
case ESM::fourCC("XCVR"): // FO4
case ESM::fourCC("XFVC"): // FO4
case ESM::fourCC("XHTW"): // FO4
case ESM::fourCC("XIS2"): // FO4
case ESM::fourCC("XLOD"): // FO4
case ESM::fourCC("XLRL"): // FO4
case ESM::fourCC("XLRT"): // FO4
case ESM::fourCC("XLYR"): // FO4
case ESM::fourCC("XMSP"): // FO4
case ESM::fourCC("XRFG"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::PGRE::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::PlacedGrenade::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::PlacedGrenade::blank()
//{
// }
| 3,738
|
C++
|
.cpp
| 92
| 31.771739
| 114
| 0.594275
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,798
|
loadscpt.cpp
|
OpenMW_openmw/components/esm4/loadscpt.cpp
|
/*
Copyright (C) 2019-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadscpt.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Script::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
{
reader.getZString(mEditorId);
break;
}
case ESM::fourCC("SCHR"):
{
// For debugging only
#if 0
unsigned char mDataBuf[256/*bufSize*/];
reader.get(mDataBuf, subHdr.dataSize);
std::ostringstream ss;
for (unsigned int i = 0; i < subHdr.dataSize; ++i)
{
//if (mDataBuf[i] > 64 && mDataBuf[i] < 91)
//ss << (char)(mDataBuf[i]) << " ";
//else
ss << std::setfill('0') << std::setw(2) << std::hex << (int)(mDataBuf[i]);
if ((i & 0x000f) == 0xf)
ss << "\n";
else if (i < 256/*bufSize*/-1)
ss << " ";
}
std::cout << ss.str() << std::endl;
#else
reader.get(mScript.scriptHeader);
#endif
break;
}
case ESM::fourCC("SCTX"):
reader.getString(mScript.scriptSource);
// if (mEditorId == "CTrapLogs01SCRIPT")
// std::cout << mScript.scriptSource << std::endl;
break;
case ESM::fourCC("SCDA"): // compiled script data
{
// For debugging only
#if 0
if (subHdr.dataSize >= 4096)
{
std::cout << "Skipping " << mEditorId << std::endl;
reader.skipSubRecordData();
break;
}
std::cout << mEditorId << std::endl;
unsigned char mDataBuf[4096/*bufSize*/];
reader.get(mDataBuf, subHdr.dataSize);
std::ostringstream ss;
for (unsigned int i = 0; i < subHdr.dataSize; ++i)
{
//if (mDataBuf[i] > 64 && mDataBuf[i] < 91)
//ss << (char)(mDataBuf[i]) << " ";
//else
ss << std::setfill('0') << std::setw(2) << std::hex << (int)(mDataBuf[i]);
if ((i & 0x000f) == 0xf)
ss << "\n";
else if (i < 4096/*bufSize*/-1)
ss << " ";
}
std::cout << ss.str() << std::endl;
#else
reader.skipSubRecordData();
#endif
break;
}
case ESM::fourCC("SCRO"):
reader.getFormId(mScript.globReference);
break;
case ESM::fourCC("SLSD"):
{
ScriptLocalVariableData localVar;
reader.get(localVar.index);
reader.get(localVar.unknown1);
reader.get(localVar.unknown2);
reader.get(localVar.unknown3);
reader.get(localVar.type);
reader.get(localVar.unknown4);
mScript.localVarData.push_back(std::move(localVar));
// WARN: assumes SCVR will follow immediately
break;
}
case ESM::fourCC("SCVR"): // assumed always pair with SLSD
if (!mScript.localVarData.empty())
reader.getZString(mScript.localVarData.back().variableName);
else
reader.skipSubRecordData();
break;
case ESM::fourCC("SCRV"):
{
std::uint32_t index;
reader.get(index);
mScript.localRefVarIndex.push_back(index);
break;
}
default:
throw std::runtime_error("ESM4::SCPT::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Script::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Script::blank()
//{
// }
| 5,466
|
C++
|
.cpp
| 138
| 27.028986
| 114
| 0.517702
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,799
|
loadcell.cpp
|
OpenMW_openmw/components/esm4/loadcell.cpp
|
/*
Copyright (C) 2015-2016, 2018-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadcell.hpp"
#include <cfloat> // FLT_MAX for gcc
#include <limits>
#include <stdexcept>
#include "grouptype.hpp"
#include "reader.hpp"
// #include "writer.hpp"
#include <components/esm/refid.hpp>
float ESM4::Cell::sInvalidWaterLevel = -200000.f;
// TODO: Try loading only EDID and XCLC (along with mFormId, mFlags and mParent)
//
// But, for external cells we may be scanning the whole record since we don't know if there is
// going to be an EDID subrecord. And the vast majority of cells are these kinds.
//
// So perhaps some testing needs to be done to see if scanning and skipping takes
// longer/shorter/same as loading the subrecords.
void ESM4::Cell::load(ESM4::Reader& reader)
{
ESM::FormId formId = reader.getFormIdFromHeader();
mId = formId;
mFlags = reader.hdr().record.flags;
mParent = reader.currWorld();
mWaterHeight = sInvalidWaterLevel;
reader.clearCellGrid(); // clear until XCLC FIXME: somehow do this automatically?
// Sometimes cell 0,0 does not have an XCLC sub record (e.g. ToddLand 000009BF)
// To workaround this issue put a default value if group is "exterior sub cell" and its
// grid from label is "0 0". Note the reversed X/Y order (no matter since they're both 0
// anyway).
if (reader.grp().type == ESM4::Grp_ExteriorSubCell && reader.grp().label.grid[1] == 0
&& reader.grp().label.grid[0] == 0)
{
ESM4::CellGrid currCellGrid;
currCellGrid = Grid{ 0, 0 };
reader.setCurrCellGrid(currCellGrid); // side effect: sets mCellGridValid true
}
// WARN: we need to call setCurrCell (and maybe setCurrCellGrid?) again before loading
// cell child groups if we are loading them after restoring the context
// (may be easier to update the context before saving?)
reader.setCurrCell(formId); // save for LAND (and other children) to access later
std::uint32_t esmVer = reader.esmVersion();
bool isSkyrim = (esmVer == ESM::VER_170 || esmVer == ESM::VER_094);
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
{
if (!reader.getZString(mEditorId))
throw std::runtime_error("CELL EDID data read error");
#if 0
std::string padding;
padding.insert(0, reader.stackSize()*2, ' ');
std::cout << padding << "CELL Editor ID: " << mEditorId << std::endl;
#endif
break;
}
case ESM::fourCC("XCLC"):
{
//(X, Y) grid location of the cell followed by flags. Always in
// exterior cells and never in interior cells.
//
// int32 - X
// int32 - Y
// uint32 - flags (high bits look random)
//
// 0x1 - Force Hide Land Quad 1
// 0x2 - Force Hide Land Quad 2
// 0x4 - Force Hide Land Quad 3
// 0x8 - Force Hide Land Quad 4
uint32_t flags;
reader.get(mX);
reader.get(mY);
if (subHdr.dataSize == 12)
reader.get(flags);
// Remember cell grid for later (loading LAND, NAVM which should be CELL temporary children)
// Note that grids only apply for external cells. For interior cells use the cell's formid.
reader.setCurrCellGrid(Grid{ static_cast<int16_t>(mX), static_cast<int16_t>(mY) });
break;
}
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("DATA"):
{
if (subHdr.dataSize == 2)
reader.get(mCellFlags);
else
{
if (subHdr.dataSize != 1)
throw std::runtime_error("CELL unexpected DATA flag size");
std::uint8_t value = 0;
reader.get(value);
mCellFlags = value;
}
break;
}
case ESM::fourCC("XCLR"): // for exterior cells
{
mRegions.resize(subHdr.dataSize / sizeof(ESM::FormId32));
for (std::vector<ESM::FormId>::iterator it = mRegions.begin(); it != mRegions.end(); ++it)
{
reader.getFormId(*it);
#if 0
std::string padding;
padding.insert(0, reader.stackSize()*2, ' ');
std::cout << padding << "region: " << std::hex << *it << std::endl;
#endif
}
break;
}
case ESM::fourCC("XOWN"):
{
switch (subHdr.dataSize)
{
case 4:
reader.getFormId(mOwner);
break;
case 12:
{
reader.getFormId(mOwner);
std::uint32_t dummy;
reader.get(dummy); // Unknown
reader.get(dummy); // No crime flag, FO4
break;
}
default:
reader.skipSubRecordData();
break;
}
break;
}
case ESM::fourCC("XGLB"):
reader.getFormId(mGlobal);
break; // Oblivion only?
case ESM::fourCC("XCCM"):
reader.getFormId(mClimate);
break;
case ESM::fourCC("XCWT"):
reader.getFormId(mWater);
break;
case ESM::fourCC("XCLW"):
reader.get(mWaterHeight);
break;
case ESM::fourCC("XCLL"):
{
switch (subHdr.dataSize)
{
case 36: // TES4
reader.get(&mLighting, 36);
break;
case 40: // FO3/FNV
case 92: // TES5 (FIXME)
case 136: // FO4 (FIXME)
reader.get(mLighting);
reader.skipSubRecordData(subHdr.dataSize - 40);
break;
default:
reader.skipSubRecordData();
break;
}
break;
}
case ESM::fourCC("XCMT"):
reader.get(mMusicType);
break; // Oblivion only?
case ESM::fourCC("LTMP"):
reader.getFormId(mLightingTemplate);
break;
case ESM::fourCC("LNAM"):
reader.get(mLightingTemplateFlags);
break; // seems to always follow LTMP
case ESM::fourCC("XCMO"):
reader.getFormId(mMusic);
break;
case ESM::fourCC("XCAS"):
reader.getFormId(mAcousticSpace);
break;
case ESM::fourCC("TVDT"):
case ESM::fourCC("MHDT"):
case ESM::fourCC("XCGD"):
case ESM::fourCC("XNAM"):
case ESM::fourCC("XLCN"):
case ESM::fourCC("XWCS"):
case ESM::fourCC("XWCU"):
case ESM::fourCC("XWCN"):
case ESM::fourCC("XCIM"):
case ESM::fourCC("XEZN"):
case ESM::fourCC("XWEM"):
case ESM::fourCC("XILL"):
case ESM::fourCC("XRNK"):
case ESM::fourCC("XCET"): // FO3
case ESM::fourCC("IMPF"): // FO3 Zeta
case ESM::fourCC("CNAM"): // FO4
case ESM::fourCC("PCMB"): // FO4
case ESM::fourCC("RVIS"): // FO4
case ESM::fourCC("VISI"): // FO4
case ESM::fourCC("XGDR"): // FO4
case ESM::fourCC("XILW"): // FO4
case ESM::fourCC("XCRI"): // FO4
case ESM::fourCC("XPRI"): // FO4
case ESM::fourCC("ZNAM"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::CELL::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
if (isSkyrim) // Skyrim seems to have broken water level records. But the subrecord exists so it
// shouldn't be skipped.
{
mWaterHeight = sInvalidWaterLevel;
}
mReaderContext = reader.getContext();
}
// void ESM4::Cell::save(ESM4::Writer& writer) const
//{
// }
void ESM4::Cell::blank() {}
| 9,966
|
C++
|
.cpp
| 239
| 29.133891
| 114
| 0.53126
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,800
|
loadscol.cpp
|
OpenMW_openmw/components/esm4/loadscol.cpp
|
/*
Copyright (C) 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
Also see https://tes5edit.github.io/fopdoc/ for FO3/FONV specific details.
*/
#include "loadscol.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::StaticCollection::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("MODL"): // Model data start
reader.getZString(mModel);
break;
case ESM::fourCC("MODT"):
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("OBND"):
case ESM::fourCC("ONAM"):
case ESM::fourCC("DATA"):
case ESM::fourCC("FLTR"): // FO4
case ESM::fourCC("PTRN"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::SCOL::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::StaticCollection::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::StaticCollection::blank()
//{
// }
| 2,659
|
C++
|
.cpp
| 65
| 33.523077
| 114
| 0.655947
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,801
|
loadpack.cpp
|
OpenMW_openmw/components/esm4/loadpack.cpp
|
/*
Copyright (C) 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadpack.hpp"
#include <cstring>
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::AIPackage::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("PKDT"):
{
if (subHdr.dataSize != sizeof(PKDT) && subHdr.dataSize == 4)
{
// std::cout << "skip fallout" << mEditorId << std::endl; // FIXME
reader.get(mData.flags);
mData.type = 0; // FIXME
}
else if (subHdr.dataSize != sizeof(mData))
reader.skipSubRecordData(); // FIXME: FO3
else
reader.get(mData);
break;
}
case ESM::fourCC("PSDT"): // reader.get(mSchedule); break;
{
if (subHdr.dataSize != sizeof(mSchedule))
reader.skipSubRecordData(); // FIXME:
else
reader.get(mSchedule); // TES4
break;
}
case ESM::fourCC("PLDT"):
{
if (subHdr.dataSize != sizeof(mLocation))
reader.skipSubRecordData(); // FIXME:
else
{
reader.get(mLocation); // TES4
if (mLocation.type != 5)
reader.adjustFormId(mLocation.location);
}
break;
}
case ESM::fourCC("PTDT"):
{
if (subHdr.dataSize != sizeof(mTarget))
reader.skipSubRecordData(); // FIXME: FO3
else
{
reader.get(mTarget); // TES4
if (mLocation.type != 2)
reader.adjustFormId(mTarget.target);
}
break;
}
case ESM::fourCC("CTDA"):
{
if (subHdr.dataSize != sizeof(CTDA))
{
reader.skipSubRecordData(); // FIXME: FO3
break;
}
CTDA condition;
reader.get(condition);
// FIXME: how to "unadjust" if not FormId?
// adjustFormId(condition.param1);
// adjustFormId(condition.param2);
mConditions.push_back(condition);
break;
}
case ESM::fourCC("CTDT"): // always 20 for TES4
case ESM::fourCC("TNAM"): // FO3
case ESM::fourCC("INAM"): // FO3
case ESM::fourCC("CNAM"): // FO3
case ESM::fourCC("SCHR"): // FO3
case ESM::fourCC("POBA"): // FO3
case ESM::fourCC("POCA"): // FO3
case ESM::fourCC("POEA"): // FO3
case ESM::fourCC("SCTX"): // FO3
case ESM::fourCC("SCDA"): // FO3
case ESM::fourCC("SCRO"): // FO3
case ESM::fourCC("IDLA"): // FO3
case ESM::fourCC("IDLC"): // FO3
case ESM::fourCC("IDLF"): // FO3
case ESM::fourCC("IDLT"): // FO3
case ESM::fourCC("PKDD"): // FO3
case ESM::fourCC("PKD2"): // FO3
case ESM::fourCC("PKPT"): // FO3
case ESM::fourCC("PKED"): // FO3
case ESM::fourCC("PKE2"): // FO3
case ESM::fourCC("PKAM"): // FO3
case ESM::fourCC("PUID"): // FO3
case ESM::fourCC("PKW3"): // FO3
case ESM::fourCC("PTD2"): // FO3
case ESM::fourCC("PLD2"): // FO3
case ESM::fourCC("PKFD"): // FO3
case ESM::fourCC("SLSD"): // FO3
case ESM::fourCC("SCVR"): // FO3
case ESM::fourCC("SCRV"): // FO3
case ESM::fourCC("IDLB"): // FO3
case ESM::fourCC("ANAM"): // TES5
case ESM::fourCC("BNAM"): // TES5
case ESM::fourCC("FNAM"): // TES5
case ESM::fourCC("PNAM"): // TES5
case ESM::fourCC("QNAM"): // TES5
case ESM::fourCC("UNAM"): // TES5
case ESM::fourCC("XNAM"): // TES5
case ESM::fourCC("PDTO"): // TES5
case ESM::fourCC("PTDA"): // TES5
case ESM::fourCC("PFOR"): // TES5
case ESM::fourCC("PFO2"): // TES5
case ESM::fourCC("PRCB"): // TES5
case ESM::fourCC("PKCU"): // TES5
case ESM::fourCC("PKC2"): // TES5
case ESM::fourCC("CITC"): // TES5
case ESM::fourCC("CIS1"): // TES5
case ESM::fourCC("CIS2"): // TES5
case ESM::fourCC("VMAD"): // TES5
case ESM::fourCC("TPIC"): // TES5
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::PACK::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::AIPackage::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::AIPackage::blank()
//{
// }
| 6,477
|
C++
|
.cpp
| 160
| 28.21875
| 114
| 0.514526
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,802
|
loadachr.cpp
|
OpenMW_openmw/components/esm4/loadachr.cpp
|
/*
Copyright (C) 2016, 2018, 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadachr.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::ActorCharacter::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
mParent = reader.currCell();
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getZString(mFullName);
break;
case ESM::fourCC("NAME"):
reader.getFormId(mBaseObj);
break;
case ESM::fourCC("DATA"):
reader.get(mPos);
break;
case ESM::fourCC("XSCL"):
reader.get(mScale);
break;
case ESM::fourCC("XOWN"):
{
switch (subHdr.dataSize)
{
case 4:
reader.getFormId(mOwner);
break;
case 12:
{
reader.getFormId(mOwner);
std::uint32_t dummy;
reader.get(dummy); // Unknown
reader.get(dummy); // No crime flag, FO4
break;
}
default:
reader.skipSubRecordData();
break;
}
break;
}
case ESM::fourCC("XESP"):
reader.getFormId(mEsp.parent);
reader.get(mEsp.flags);
break;
case ESM::fourCC("XCNT"):
{
reader.get(mCount);
break;
}
case ESM::fourCC("XRGD"): // ragdoll
case ESM::fourCC("XRGB"): // ragdoll biped
case ESM::fourCC("XHRS"): // horse formId
case ESM::fourCC("XMRC"): // merchant container formId
// TES5
case ESM::fourCC("XAPD"): // activation parent
case ESM::fourCC("XAPR"): // active parent
case ESM::fourCC("XEZN"): // encounter zone
case ESM::fourCC("XHOR"):
case ESM::fourCC("XLCM"): // levelled creature
case ESM::fourCC("XLCN"): // location
case ESM::fourCC("XLKR"): // location route?
case ESM::fourCC("XLRT"): // location type
//
case ESM::fourCC("XPRD"):
case ESM::fourCC("XPPA"):
case ESM::fourCC("INAM"):
case ESM::fourCC("PDTO"):
//
case ESM::fourCC("XIS2"):
case ESM::fourCC("XPCI"): // formId
case ESM::fourCC("XLOD"):
case ESM::fourCC("VMAD"):
case ESM::fourCC("XLRL"): // Unofficial Skyrim Patch
case ESM::fourCC("XRDS"): // FO3
case ESM::fourCC("XIBS"): // FO3
case ESM::fourCC("SCHR"): // FO3
case ESM::fourCC("TNAM"): // FO3
case ESM::fourCC("XATO"): // FONV
case ESM::fourCC("MNAM"): // FO4
case ESM::fourCC("XATP"): // FO4
case ESM::fourCC("XEMI"): // FO4
case ESM::fourCC("XFVC"): // FO4
case ESM::fourCC("XHLT"): // FO4
case ESM::fourCC("XHTW"): // FO4
case ESM::fourCC("XLKT"): // FO4
case ESM::fourCC("XLYR"): // FO4
case ESM::fourCC("XMBR"): // FO4
case ESM::fourCC("XMSP"): // FO4
case ESM::fourCC("XPLK"): // FO4
case ESM::fourCC("XRFG"): // FO4
case ESM::fourCC("XRNK"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4 ACHR/ACRE load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::ActorCharacter::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::ActorCharacter::blank()
//{
// }
| 5,291
|
C++
|
.cpp
| 134
| 27.708955
| 117
| 0.533139
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,803
|
loadtree.cpp
|
OpenMW_openmw/components/esm4/loadtree.cpp
|
/*
Copyright (C) 2016, 2018 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadtree.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Tree::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("ICON"):
reader.getZString(mLeafTexture);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("CNAM"):
case ESM::fourCC("BNAM"):
case ESM::fourCC("SNAM"):
case ESM::fourCC("FULL"):
case ESM::fourCC("OBND"):
case ESM::fourCC("PFIG"):
case ESM::fourCC("PFPC"):
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::TREE::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Tree::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Tree::blank()
//{
// }
| 2,705
|
C++
|
.cpp
| 69
| 31.246377
| 114
| 0.633765
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,804
|
loadland.cpp
|
OpenMW_openmw/components/esm4/loadland.cpp
|
/*
Copyright (C) 2015-2016, 2018, 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadland.hpp"
#include <cstdint>
#include <stdexcept>
#include <components/debug/debuglog.hpp>
#include "reader.hpp"
// #include "writer.hpp"
// overlap north
//
// 32
// 31
// 30
// overlap .
// west .
// .
// 2
// 1
// 0
// 0 1 2 ... 30 31 32
//
// overlap south
//
void ESM4::Land::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
mDataTypes = 0;
mCell = reader.currCell();
TxtLayer layer;
std::int8_t currentAddQuad = -1; // for VTXT following ATXT
// std::map<FormId, int> uniqueTextures; // FIXME: for temp testing only
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("DATA"):
{
reader.get(mLandFlags);
break;
}
case ESM::fourCC("VNML"): // vertex normals, 33x33x(1+1+1) = 3267
{
reader.get(mVertNorm);
mDataTypes |= LAND_VNML;
break;
}
case ESM::fourCC("VHGT"): // vertex height gradient, 4+33x33+3 = 4+1089+3 = 1096
{
#if 0
reader.get(mHeightMap.heightOffset);
reader.get(mHeightMap.gradientData);
reader.get(mHeightMap.unknown1);
reader.get(mHeightMap.unknown2);
#endif
reader.get(mHeightMap);
mDataTypes |= LAND_VHGT;
break;
}
case ESM::fourCC("VCLR"): // vertex colours, 24bit RGB, 33x33x(1+1+1) = 3267
{
reader.get(mVertColr);
mDataTypes |= LAND_VCLR;
break;
}
case ESM::fourCC("BTXT"):
{
BTXT base;
if (reader.getExact(base))
{
if (base.quadrant >= 4)
throw std::runtime_error("base texture quadrant index error");
reader.adjustFormId(base.formId);
mTextures[base.quadrant].base = std::move(base);
#if 0
std::cout << "Base Texture formid: 0x"
<< std::hex << mTextures[base.quadrant].base.formId
<< ", quad " << std::dec << (int)base.quadrant << std::endl;
#endif
}
break;
}
case ESM::fourCC("ATXT"):
{
if (currentAddQuad != -1)
{
// FIXME: sometimes there are no VTXT following an ATXT? Just add a dummy one for now
Log(Debug::Verbose) << "ESM4::Land VTXT empty layer " << layer.texture.layerIndex;
mTextures[currentAddQuad].layers.push_back(layer);
}
reader.get(layer.texture);
reader.adjustFormId(layer.texture.formId);
if (layer.texture.quadrant >= 4)
throw std::runtime_error("additional texture quadrant index error");
#if 0
FormId txt = layer.texture.formId;
std::map<FormId, int>::iterator lb = uniqueTextures.lower_bound(txt);
if (lb != uniqueTextures.end() && !(uniqueTextures.key_comp()(txt, lb->first)))
{
lb->second += 1;
}
else
uniqueTextures.insert(lb, std::make_pair(txt, 1));
#endif
#if 0
std::cout << "Additional Texture formId: 0x"
<< std::hex << layer.texture.formId
<< ", quad " << std::dec << (int)layer.texture.quadrant << std::endl;
std::cout << "Additional Texture layer: "
<< std::dec << (int)layer.texture.layerIndex << std::endl;
#endif
currentAddQuad = layer.texture.quadrant;
break;
}
case ESM::fourCC("VTXT"):
{
if (currentAddQuad == -1)
throw std::runtime_error("VTXT without ATXT found");
const std::uint16_t count = reader.subRecordHeader().dataSize / sizeof(ESM4::Land::VTXT);
if ((reader.subRecordHeader().dataSize % sizeof(ESM4::Land::VTXT)) != 0)
throw std::runtime_error("ESM4::LAND VTXT data size error");
if (count)
{
layer.data.resize(count);
std::vector<ESM4::Land::VTXT>::iterator it = layer.data.begin();
for (; it != layer.data.end(); ++it)
{
reader.get(*it);
// FIXME: debug only
// std::cout << "pos: " << std::dec << (int)(*it).position << std::endl;
}
}
mTextures[currentAddQuad].layers.push_back(layer);
// Assumed that the layers are added in the correct sequence
// FIXME: Knights.esp doesn't seem to observe this - investigate more
// assert(layer.texture.layerIndex == mTextures[currentAddQuad].layers.size()-1
//&& "additional texture layer index error");
currentAddQuad = -1;
layer.data.clear();
// FIXME: debug only
// std::cout << "VTXT: count " << std::dec << count << std::endl;
break;
}
case ESM::fourCC("VTEX"): // only in Oblivion?
{
const std::uint16_t count = reader.subRecordHeader().dataSize / sizeof(ESM::FormId32);
if ((reader.subRecordHeader().dataSize % sizeof(ESM::FormId32)) != 0)
throw std::runtime_error("ESM4::LAND VTEX data size error");
if (count)
{
mIds.resize(count);
for (ESM::FormId& id : mIds)
reader.getFormId(id);
}
break;
}
case ESM::fourCC("MPCD"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::LAND::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
if (currentAddQuad != -1)
{
// FIXME: not sure if it happens here as well
Log(Debug::Verbose) << "ESM4::Land VTXT empty layer " << layer.texture.layerIndex << " quad "
<< static_cast<unsigned>(layer.texture.quadrant);
mTextures[currentAddQuad].layers.push_back(layer);
}
bool missing = false;
for (int i = 0; i < 4; ++i)
{
if (mTextures[i].base.formId == 0)
{
// std::cout << "ESM4::LAND " << ESM4::formIdToString(mFormId) << " missing base, quad " << i << std::endl;
// std::cout << "layers " << mTextures[i].layers.size() << std::endl;
// NOTE: can't set the default here since FO3/FONV may have different defaults
// mTextures[i].base.formId = 0x000008C0; // TerrainHDDirt01.dds
missing = true;
}
// else
//{
// std::cout << "ESM4::LAND " << ESM4::formIdToString(mFormId) << " base, quad " << i << std::endl;
// std::cout << "layers " << mTextures[i].layers.size() << std::endl;
// }
}
// at least one of the quadrants do not have a base texture, return without setting the flag
if (!missing)
mDataTypes |= LAND_VTEX;
}
// void ESM4::Land::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Land::blank()
//{
// }
| 8,961
|
C++
|
.cpp
| 216
| 29.939815
| 119
| 0.529405
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,805
|
loadroad.cpp
|
OpenMW_openmw/components/esm4/loadroad.cpp
|
/*
Copyright (C) 2020 - 2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadroad.hpp"
#include <stdexcept>
#include "reader.hpp"
#include <components/esm/refid.hpp> // FIXME: for workaround
//#include "writer.hpp"
void ESM4::Road::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
mParent = reader.currWorld();
mEditorId = ESM::RefId(mId).serializeText(); // FIXME: quick workaround to use existing code
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("PGRP"):
{
std::size_t numNodes = subHdr.dataSize / sizeof(PGRP);
mNodes.resize(numNodes);
for (std::size_t i = 0; i < numNodes; ++i)
{
reader.get(mNodes.at(i));
}
break;
}
case ESM::fourCC("PGRR"):
{
PGRR link;
RDRP linkPt;
for (std::size_t i = 0; i < mNodes.size(); ++i)
{
for (std::size_t j = 0; j < mNodes[i].numLinks; ++j)
{
link.startNode = std::int16_t(i);
reader.get(linkPt);
// FIXME: instead of looping each time, maybe use a map?
bool found = false;
for (std::size_t k = 0; k < mNodes.size(); ++k)
{
if (linkPt.x != mNodes[k].x || linkPt.y != mNodes[k].y || linkPt.z != mNodes[k].z)
continue;
else
{
link.endNode = std::int16_t(k);
mLinks.push_back(link);
found = true;
break;
}
}
if (!found)
throw std::runtime_error("ESM4::ROAD::PGRR - Unknown link point " + std::to_string(j)
+ "at node " + std::to_string(i) + ".");
}
}
break;
}
default:
throw std::runtime_error("ESM4::ROAD::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Road::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Road::blank()
//{
// }
| 3,695
|
C++
|
.cpp
| 88
| 29.340909
| 114
| 0.533742
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,806
|
loadtact.cpp
|
OpenMW_openmw/components/esm4/loadtact.cpp
|
/*
Copyright (C) 2019-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadtact.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::TalkingActivator::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("VNAM"):
reader.getFormId(mVoiceType);
break;
case ESM::fourCC("SNAM"):
reader.getFormId(mLoopSound);
break;
case ESM::fourCC("INAM"):
reader.getFormId(mRadioTemplate);
break; // FONV
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("DAMC"): // Destructible
case ESM::fourCC("DEST"):
case ESM::fourCC("DMDC"):
case ESM::fourCC("DMDL"):
case ESM::fourCC("DMDT"):
case ESM::fourCC("DMDS"):
case ESM::fourCC("DSTA"):
case ESM::fourCC("DSTD"):
case ESM::fourCC("DSTF"): // Destructible end
case ESM::fourCC("FNAM"):
case ESM::fourCC("PNAM"):
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("OBND"):
case ESM::fourCC("VMAD"):
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::TACT::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::TalkingActivator::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::TalkingActivator::blank()
//{
// }
| 3,345
|
C++
|
.cpp
| 84
| 30.678571
| 114
| 0.610957
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,807
|
loadflor.cpp
|
OpenMW_openmw/components/esm4/loadflor.cpp
|
/*
Copyright (C) 2016, 2018, 2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadflor.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Flora::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("PFIG"):
reader.getFormId(mIngredient);
break;
case ESM::fourCC("PFPC"):
reader.get(mPercentHarvest);
break;
case ESM::fourCC("SNAM"):
reader.getFormId(mSound);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("FNAM"):
case ESM::fourCC("OBND"):
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("PNAM"):
case ESM::fourCC("RNAM"):
case ESM::fourCC("VMAD"):
case ESM::fourCC("DAMC"): // Destructible
case ESM::fourCC("DEST"):
case ESM::fourCC("DMDC"):
case ESM::fourCC("DMDL"):
case ESM::fourCC("DMDT"):
case ESM::fourCC("DMDS"):
case ESM::fourCC("DSTA"):
case ESM::fourCC("DSTD"):
case ESM::fourCC("DSTF"): // Destructible end
case ESM::fourCC("PRPS"): // FO4
case ESM::fourCC("PTRN"): // FO4
case ESM::fourCC("ATTX"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::FLOR::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Flora::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Flora::blank()
//{
// }
| 3,655
|
C++
|
.cpp
| 93
| 29.698925
| 114
| 0.590986
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,808
|
loadmusc.cpp
|
OpenMW_openmw/components/esm4/loadmusc.cpp
|
/*
Copyright (C) 2020 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
Also see https://tes5edit.github.io/fopdoc/ for FO3/FONV specific details.
*/
#include "loadmusc.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Music::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FNAM"):
reader.getZString(mMusicFile);
break;
case ESM::fourCC("ANAM"): // FONV float (attenuation in db? loop if positive?)
case ESM::fourCC("WNAM"): // TES5
case ESM::fourCC("PNAM"): // TES5
case ESM::fourCC("TNAM"): // TES5
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::MUSC::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Music::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Music::blank()
//{
// }
| 2,350
|
C++
|
.cpp
| 57
| 34.77193
| 114
| 0.676316
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,809
|
loadkeym.cpp
|
OpenMW_openmw/components/esm4/loadkeym.cpp
|
/*
Copyright (C) 2016, 2018, 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadkeym.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Key::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("ICON"):
reader.getZString(mIcon);
break;
case ESM::fourCC("MICO"):
reader.getZString(mMiniIcon);
break; // FO3
case ESM::fourCC("DATA"):
reader.get(mData);
break;
case ESM::fourCC("SCRI"):
reader.getFormId(mScriptId);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("YNAM"):
reader.getFormId(mPickUpSound);
break;
case ESM::fourCC("ZNAM"):
reader.getFormId(mDropSound);
break;
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("KSIZ"):
case ESM::fourCC("KWDA"):
case ESM::fourCC("OBND"):
case ESM::fourCC("VMAD"):
case ESM::fourCC("DAMC"): // Destructible
case ESM::fourCC("DEST"):
case ESM::fourCC("DMDC"):
case ESM::fourCC("DMDL"):
case ESM::fourCC("DMDT"):
case ESM::fourCC("DMDS"):
case ESM::fourCC("DSTA"):
case ESM::fourCC("DSTD"):
case ESM::fourCC("DSTF"): // Destructible end
case ESM::fourCC("PTRN"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::KEYM::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Key::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Key::blank()
//{
// }
| 3,662
|
C++
|
.cpp
| 94
| 29.148936
| 114
| 0.588583
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,810
|
loadnote.cpp
|
OpenMW_openmw/components/esm4/loadnote.cpp
|
/*
Copyright (C) 2019-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadnote.hpp"
#include <stdexcept>
#include "reader.hpp"
//#include "writer.hpp"
void ESM4::Note::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("EDID"):
reader.getZString(mEditorId);
break;
case ESM::fourCC("FULL"):
reader.getLocalizedString(mFullName);
break;
case ESM::fourCC("MODL"):
reader.getZString(mModel);
break;
case ESM::fourCC("ICON"):
reader.getZString(mIcon);
break;
case ESM::fourCC("MODB"):
reader.get(mBoundRadius);
break;
case ESM::fourCC("YNAM"):
reader.getFormId(mPickUpSound);
break;
case ESM::fourCC("ZNAM"):
reader.getFormId(mDropSound);
break;
case ESM::fourCC("DATA"):
case ESM::fourCC("MODT"): // Model data
case ESM::fourCC("MODC"):
case ESM::fourCC("MODS"):
case ESM::fourCC("MODF"): // Model data end
case ESM::fourCC("ONAM"):
case ESM::fourCC("SNAM"):
case ESM::fourCC("TNAM"):
case ESM::fourCC("XNAM"):
case ESM::fourCC("OBND"):
case ESM::fourCC("VMAD"):
case ESM::fourCC("DNAM"): // FO4
case ESM::fourCC("PNAM"): // FO4
case ESM::fourCC("PTRN"): // FO4
reader.skipSubRecordData();
break;
default:
throw std::runtime_error("ESM4::NOTE::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Note::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Note::blank()
//{
// }
| 3,163
|
C++
|
.cpp
| 81
| 30.049383
| 114
| 0.608143
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
34,811
|
loadpgrd.cpp
|
OpenMW_openmw/components/esm4/loadpgrd.cpp
|
/*
Copyright (C) 2020-2021 cc9cii
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
cc9cii cc9c@iinet.net.au
Much of the information on the data structures are based on the information
from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by
trial & error. See http://en.uesp.net/wiki for details.
*/
#include "loadpgrd.hpp"
#include <stdexcept>
#include "reader.hpp"
#include <components/esm/refid.hpp> // FIXME: for mEditorId workaround
//#include "writer.hpp"
void ESM4::Pathgrid::load(ESM4::Reader& reader)
{
mId = reader.getFormIdFromHeader();
mFlags = reader.hdr().record.flags;
mEditorId = ESM::RefId(mId).serializeText(); // FIXME: quick workaround to use existing code
while (reader.getSubRecordHeader())
{
const ESM4::SubRecordHeader& subHdr = reader.subRecordHeader();
switch (subHdr.typeId)
{
case ESM::fourCC("DATA"):
reader.get(mData);
break;
case ESM::fourCC("PGRP"):
{
std::size_t numNodes = subHdr.dataSize / sizeof(PGRP);
if (numNodes != std::size_t(mData)) // keep gcc quiet
throw std::runtime_error("ESM4::PGRD::load numNodes mismatch");
mNodes.resize(numNodes);
for (std::size_t i = 0; i < numNodes; ++i)
{
reader.get(mNodes.at(i));
if (int(mNodes.at(i).z) % 2 == 0)
mNodes.at(i).priority = 0;
else
mNodes.at(i).priority = 1;
}
break;
}
case ESM::fourCC("PGRR"):
{
PGRR link;
for (std::size_t i = 0; i < std::size_t(mData); ++i) // keep gcc quiet
{
for (std::size_t j = 0; j < mNodes[i].numLinks; ++j)
{
link.startNode = std::int16_t(i);
reader.get(link.endNode);
if (link.endNode == -1)
continue;
// ICMarketDistrictTheBestDefenseBasement doesn't have a PGRR sub-record
// CELL formId 00049E2A
// PGRD formId 000304B7
// if (mFormId == 0x0001C2C8)
// std::cout << link.startNode << "," << link.endNode << std::endl;
mLinks.push_back(link);
}
}
break;
}
case ESM::fourCC("PGRI"):
{
std::size_t numForeign = subHdr.dataSize / sizeof(PGRI);
mForeign.resize(numForeign);
for (std::size_t i = 0; i < numForeign; ++i)
{
reader.get(mForeign.at(i));
// mForeign.at(i).localNode;// &= 0xffff; // some have junk high bits (maybe flags?)
}
break;
}
case ESM::fourCC("PGRL"):
{
PGRL objLink;
reader.getFormId(objLink.object);
// object linkedNode
std::size_t numNodes = (subHdr.dataSize - sizeof(int32_t)) / sizeof(int32_t);
objLink.linkedNodes.resize(numNodes);
for (std::size_t i = 0; i < numNodes; ++i)
reader.get(objLink.linkedNodes.at(i));
mObjects.push_back(objLink);
break;
}
case ESM::fourCC("PGAG"):
{
#if 0
std::vector<unsigned char> mDataBuf(subHdr.dataSize);
reader.get(mDataBuf.data(), subHdr.dataSize);
std::ostringstream ss;
ss << mEditorId << " " << ESM::printName(subHdr.typeId) << ":size " << subHdr.dataSize << "\n";
for (std::size_t i = 0; i < subHdr.dataSize; ++i)
{
//if (mDataBuf[i] > 64 && mDataBuf[i] < 91) // looks like printable ascii char
//ss << (char)(mDataBuf[i]) << " ";
//else
ss << std::setfill('0') << std::setw(2) << std::hex << (int)(mDataBuf[i]);
if ((i & 0x000f) == 0xf) // wrap around
ss << "\n";
else if (i < subHdr.dataSize-1)
ss << " ";
}
std::cout << ss.str() << std::endl;
#else
reader.skipSubRecordData();
#endif
break;
}
default:
throw std::runtime_error("ESM4::PGRD::load - Unknown subrecord " + ESM::printName(subHdr.typeId));
}
}
}
// void ESM4::Pathgrid::save(ESM4::Writer& writer) const
//{
// }
// void ESM4::Pathgrid::blank()
//{
// }
| 5,748
|
C++
|
.cpp
| 133
| 30
| 114
| 0.51127
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.