本文整理汇总了C++中assimp::Importer::SetPropertyInteger方法的典型用法代码示例。如果您正苦于以下问题:C++ Importer::SetPropertyInteger方法的具体用法?C++ Importer::SetPropertyInteger怎么用?C++ Importer::SetPropertyInteger使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类assimp::Importer
的用法示例。
在下文中一共展示了Importer::SetPropertyInteger方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1:
std::vector<Ygg::ConverterData>* Ygg::Loader::LoadScene(const std::string filename, std::vector<Entity> *entity_list)
{
Assimp::Importer importer;
importer.SetPropertyInteger(AI_CONFIG_PP_SLM_VERTEX_LIMIT, 65536);
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT | aiPrimitiveType_LINE);
const aiScene* ascene = importer.ReadFile(filename,
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_FindDegenerates |
aiProcess_SplitLargeMeshes |
aiProcess_JoinIdenticalVertices |
aiProcess_SortByPType);
if (!ascene)
{
std::fprintf(stderr, "%s\n", importer.GetErrorString());
return &this->results;
}
// Get path for relative textures
int split = (int)filename.rfind("/");
std::string path = filename.substr(0, split + 1);
// Now we can access the file's contents.
this->ParseScene(ascene, entity_list);
return &this->results;
}
示例2: exit
Node *Model::load(Scene &scene, Node &root, const std::string &prefix, const std::string &filename, const unsigned int options)
{
unsigned int pflags;
unsigned int remove_flags;
std::string full_name = prefix + "/" + filename;
this->prefix = prefix;
if (!file_exists(full_name)) {
std::cout << "Model file '" << full_name << "' does not exist. Exiting ..." << std::endl;
exit(-1);
}
pflags = aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_CalcTangentSpace |
aiProcess_FindDegenerates | aiProcess_JoinIdenticalVertices | aiProcess_FlipUVs |
aiProcess_LimitBoneWeights | aiProcess_RemoveComponent | aiProcess_FixInfacingNormals;
remove_flags = aiComponent_COLORS | aiComponent_LIGHTS | aiComponent_CAMERAS;
if (options & MODEL_IMPORT_OPTIMIZED) {
pflags |= aiProcess_OptimizeGraph | aiProcess_OptimizeMeshes | aiProcess_RemoveComponent | aiProcess_FindInstances;
}
if (options & MODEL_IMPORT_LIGHTS) {
remove_flags = aiComponent_COLORS | aiComponent_CAMERAS;
}
Assimp::Importer importer;
importer.SetPropertyInteger(AI_CONFIG_PP_LBW_MAX_WEIGHTS, 3);
importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, remove_flags);
assimp_scene = importer.ReadFile(full_name.c_str(), pflags);
if (!assimp_scene) {
std::cout << "Error parsing '" << full_name.c_str() << "': " << importer.GetErrorString() << std::endl;
exit(-1);
}
Node *rootPtr = node_map_create(scene, *assimp_scene->mRootNode, &root, root.tree_level_get(), options);
// rootPtr->transform_update_global_recursive(*rootPtr);
BoneForAssimpBone boneForAssimpBone;
bone_map_create(scene, boneForAssimpBone, options);
materials_parse(scene);
lights_parse(scene);
mesh_create_all(scene, *assimp_scene->mRootNode, boneForAssimpBone);
key_frames_parse();
return rootPtr;
}
示例3: LoadScene
int LoadScene(tchar const *filename, aiScene const **scene)
{
if(scene == null || filename == null)
{
return E_POINTER;
}
Assimp::Importer *importer = new Assimp::Importer();
importer->SetIOHandler(new MyIOSystem());
importer->SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT);
#if defined(_DEBUG)
DefaultLogger::create("", Logger::VERBOSE, aiDefaultLogStream_DEBUGGER);
#endif
importer->ReadFile(filename, aiProcess_Triangulate | aiProcess_SortByPType);
#if defined(_DEBUG)
DefaultLogger::kill();
#endif
if(importer->GetScene() == null)
{
TRACE("Error loading %s: %s\n", filename, importer->GetErrorString());
return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
}
*scene = importer->GetScene();
return S_OK;
}
示例4:
////////////////////////////////////////////////////////////////////////
///
/// @fn void Modele3D::charger(Path cheminFichier)
///
/// Cette fonction charge un modèle 3D à partir d'un fichier supporté
/// par la librairie 'assimp'. Les textures OpenGL afférentes sont
/// également chargées.
///
/// @param[in] nomFichier : nom du fichier modèle (normalement .obj
/// ou .dae)
///
/// @return Aucune.
///
////////////////////////////////////////////////////////////////////////
void Modele3D::charger(Path cheminFichier)
{
/// Ne pas charger le même fichier inutilement
if (cheminFichier_ == cheminFichier)
return;
cheminFichier_ = std::move(cheminFichier);
/// Ne pas conserver les identifiants de texture d'un ancien modèle
libererTextures();
Assimp::Importer importer;
/// Lors de l'importation, ne pas conserver les lignes et les points.
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT);
/// Le flag aiProcess_Triangulate, inclus dans aiProcessPreset_TargetRealtime_Quality,
/// fera en sorte que les mesh ne comporteront que des triangles.
const aiScene* scene{ importer.ReadFile(cheminFichier_, aiProcessPreset_TargetRealtime_Quality) };
if (scene == nullptr) {
utilitaire::afficherErreur(std::string{ "Impossible de charger l'objet 3d : " } +cheminFichier.filename() + std::string{ "." });
return;
}
/// Charger l'ensemble des textures contenues dans le modèle :
chargerTexturesExternes(scene);
chargerTexturesIntegrees(scene);
/// Chargement des données du modèle 3D
racine_ = Noeud{ scene, scene->mRootNode };
}
示例5: fin
SharedPointer< Group > SceneImporter::import( std::string filename )
{
// check if file exists
std::ifstream fin( filename );
bool exists = !fin.fail();
fin.close();
if ( !exists ) {
// Is it ok to throw exceptions?
throw FileNotFoundException( filename );
}
Assimp::Importer importer;
importer.SetPropertyInteger( AI_CONFIG_PP_SLM_VERTEX_LIMIT, 15000 );
const aiScene* importedScene = importer.ReadFile( filename, aiProcessPreset_TargetRealtime_MaxQuality );
if ( importedScene == nullptr ) {
Log::error( CRIMILD_CURRENT_CLASS_NAME, "Error importing file ", filename, "\n", importer.GetErrorString() );
return nullptr;
}
auto skinnedMesh = crimild::alloc< SkinnedMesh >();
loadAnimations( importedScene, skinnedMesh );
auto root = crimild::alloc< Group >( filename );
auto basePath = FileSystem::getInstance().extractDirectory( filename ) + "/";
recursiveSceneBuilder( root, importedScene, importedScene->mRootNode, basePath, skinnedMesh );
if ( _skeleton != nullptr ) {
Transformation globalInverseTransform;
computeTransform( importedScene->mRootNode->mTransformation.Inverse(), globalInverseTransform );
_skeleton->setGlobalInverseTransform( globalInverseTransform );
root->attachComponent( _skeleton );
}
return root;
}
示例6: LoadScene
bool SceneLoader::LoadScene(const std::string& file_name, Scene& scene,
std::string& status) {
Assimp::Importer importer;
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE,
aiPrimitiveType_POINT | aiPrimitiveType_LINE);
const aiScene* assimp_scene = importer.ReadFile(file_name,
aiProcess_Triangulate | aiProcess_JoinIdenticalVertices
| aiProcess_FixInfacingNormals | aiProcess_FindDegenerates
| aiProcess_ValidateDataStructure);
// | aiProcess_ImproveCacheLocality
// | aiProcess_RemoveRedundantMaterials
// | aiProcess_FixInfacingNormals | aiProcess_FindDegenerates
// | aiProcess_OptimizeGraph | aiProcess_OptimizeMeshes);
status = std::string(importer.GetErrorString());
if (!status.empty() || NULL == assimp_scene) {
return false;
}
status = "OK";
for (uint32_t i = 0; i < assimp_scene->mNumCameras; ++i) {
ImportCamera(scene, assimp_scene->mCameras[i]);
}
for (uint32_t i = 0; i < assimp_scene->mNumLights; ++i) {
ImportLight(scene, assimp_scene->mLights[i]);
}
std::cout << "mNumMaterials = " << assimp_scene->mNumMaterials << std::endl;
for (uint32_t i = 0; i < assimp_scene->mNumMaterials; ++i) {
ImportMaterial(scene, assimp_scene->mMaterials[i]);
}
std::cout << "mNumMeshes = " << assimp_scene->mNumMeshes << std::endl;
for (uint32_t i = 0; i < assimp_scene->mNumMeshes; ++i) {
ImportMesh(scene, assimp_scene->mMeshes[i]);
}
return true;
}
示例7: LoadMeshFromColladaAssimp
void LoadMeshFromColladaAssimp(const char* relativeFileName, btAlignedObjectArray<GLInstanceGraphicsShape>& visualShapes, btAlignedObjectArray<ColladaGraphicsInstance>& visualShapeInstances,btTransform& upAxisTrans, float& unitMeterScaling)
{
upAxisTrans.setIdentity();
unitMeterScaling=1;
GLInstanceGraphicsShape* shape = 0;
FILE* file = fopen(relativeFileName,"rb");
if (file)
{
int size=0;
if (fseek(file, 0, SEEK_END) || (size = ftell(file)) == EOF || fseek(file, 0, SEEK_SET))
{
printf("Error: Cannot access file to determine size of %s\n", relativeFileName);
} else
{
if (size)
{
printf("Open DAE file of %d bytes\n",size);
Assimp::Importer importer;
//importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, aiComponent_NORMALS | aiComponent_COLORS);
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT);
// importer.SetPropertyInteger(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, 1);
aiScene const* scene = importer.ReadFile(relativeFileName,
aiProcess_JoinIdenticalVertices |
//aiProcess_RemoveComponent |
aiProcess_SortByPType |
aiProcess_Triangulate);
if (scene)
{
shape = &visualShapes.expand();
shape->m_scaling[0] = 1;
shape->m_scaling[1] = 1;
shape->m_scaling[2] = 1;
shape->m_scaling[3] = 1;
int index = 0;
shape->m_indices = new b3AlignedObjectArray<int>();
shape->m_vertices = new b3AlignedObjectArray<GLInstanceVertex>();
aiMatrix4x4 ident;
addMeshParts(scene, scene->mRootNode, shape, ident);
shape->m_numIndices = shape->m_indices->size();
shape->m_numvertices = shape->m_vertices->size();
ColladaGraphicsInstance& instance = visualShapeInstances.expand();
instance.m_shapeIndex = visualShapes.size()-1;
}
}
}
}
}
示例8: loadModelFromFile
// Loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector.
void Model::loadModelFromFile(std::string path, bool flipUVs, bool forDistField)
{
_filename = path.substr(path.find_last_of('/'), path.length());
// Read file via ASSIMP
Assimp::Importer importer;
unsigned int flags = aiProcessPreset_TargetRealtime_Fast;
if (forDistField)
{
flags = aiProcess_JoinIdenticalVertices |
aiProcess_Triangulate |
aiProcess_PreTransformVertices |
aiProcess_ValidateDataStructure |
aiProcess_RemoveRedundantMaterials |
aiProcess_FindDegenerates |
aiProcess_SortByPType |
aiProcess_FixInfacingNormals |
aiProcess_GenSmoothNormals;
//This with aiProcess_FindDegenerates and aiProcess_SortByPType will get rid of all degenerate triangles and not create lines or points.
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType::aiPrimitiveType_POINT | aiPrimitiveType::aiPrimitiveType_LINE);
//Configures the #aiProcess_PretransformVertices step to normalize all vertex components into the[-1, 1] range.
//importer.SetPropertyInteger(AI_CONFIG_PP_PTV_NORMALIZE, 1);
}
if (flipUVs)
{
flags |= aiProcess_FlipUVs;
}
const aiScene* scene = importer.ReadFile(path, flags);
// Check for errors
if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero
{
std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl;
return;
}
// Retrieve the directory path of the filepath
this->_directory = path.substr(0, path.find_last_of('/'));
//Process the materials
this->processMaterials(scene);
// Process ASSIMP's root node recursively
glm::mat4 identity;
this->processNode(scene->mRootNode, scene, identity);
for (auto m : _meshes)
{
m->bindAttributesToVAO();
}
}
示例9: QString
ModelInterface::ModelInterface(TextureManager* manager, const QString filename)
: has_animations(false)
, meshes(0)
, animations(0)
, bones(0)
, textureManager(manager)
{
if(filename.contains("/"))
{
int index = filename.lastIndexOf("/") + 1;
filePath = filename.left(index);
fileName = filename.right(filename.size() - index);
}
else
fileName = filename;
Assimp::Importer importer;
importer.SetPropertyInteger(AI_CONFIG_PP_LBW_MAX_WEIGHTS, 4);
const aiScene* scene = importer.ReadFile(filename.toStdString(), aiProcess_GenSmoothNormals | aiProcess_Triangulate | aiProcess_CalcTangentSpace/* | aiProcess_FlipUVs*/);
if(!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
{
throw QString("The file wasn't successfuly opened");
return;
}
if(scene->HasAnimations())
{
has_animations = true;
bones = loadBones(scene);
buildSkeleton(scene->mRootNode, NULL);
animations = new Animations();
animations->setBones(bones);
for(uint i = 0; i < scene->mNumAnimations; ++i)
animations->add(loadAnimation(scene->mAnimations[i], i));
}
meshes = new Meshes();
for(uint i = 0; i < scene->mNumMeshes; ++i)
meshes->add(loadMesh(scene->mMeshes[i], scene->mMaterials[scene->mMeshes[i]->mMaterialIndex], i));
initialize(scene);
// try delete scene probably crash
}
示例10: LoadMesh
std::vector<std::shared_ptr<RenderingObject>> LoadMesh(std::shared_ptr<ShaderProgram> inputShader, const std::string& filename, std::vector<std::shared_ptr<aiMaterial>>* outputMaterials)
{
#ifndef ASSET_PATH
static_assert(false, "ASSET_PATH is not defined. Check to make sure your projects are setup correctly");
#endif
Assimp::Importer importer;
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT);
const std::string completeFilename = std::string(STRINGIFY(ASSET_PATH)) + "/" + filename;
const aiScene* scene = importer.ReadFile(completeFilename.c_str(),
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_JoinIdenticalVertices |
aiProcess_FixInfacingNormals |
aiProcess_SortByPType);
if (!scene) {
std::cerr << "ERROR: Assimp failed -- " << importer.GetErrorString() << std::endl;
return {};
}
std::vector<std::shared_ptr<aiMaterial>> sceneMaterials;
if (outputMaterials) {
sceneMaterials.resize(scene->mNumMaterials);
for (unsigned int m = 0; m < scene->mNumMaterials; ++m) {
aiMaterial* material = scene->mMaterials[m];
std::shared_ptr<aiMaterial> dstMaterial = std::make_shared<aiMaterial>();
aiMaterial::CopyPropertyList(dstMaterial.get(), material);
sceneMaterials[m] = dstMaterial;
}
}
std::vector<std::shared_ptr<RenderingObject>> loadedMeshes;
for (decltype(scene->mNumMeshes) i = 0; i < scene->mNumMeshes; ++i) {
const aiMesh* mesh = scene->mMeshes[i];
if (!mesh->HasPositions()) {
std::cerr << "WARNING: A mesh in " << filename << " does not have positions. Skipping." << std::endl;
continue;
}
auto totalVertices = mesh->mNumVertices;
std::unique_ptr<RenderingObject::PositionArray> positions = make_unique<RenderingObject::PositionArray>(totalVertices);
std::unique_ptr<RenderingObject::NormalArray> normals = mesh->HasNormals() ? make_unique<RenderingObject::NormalArray>(totalVertices) : nullptr;
std::unique_ptr<RenderingObject::UVArray> uv = mesh->HasTextureCoords(0) ? make_unique<RenderingObject::UVArray>(totalVertices) : nullptr;
std::unique_ptr<RenderingObject::ColorArray> colors = mesh->HasVertexColors(0) ? make_unique<RenderingObject::ColorArray>(totalVertices) : nullptr;
std::unique_ptr<RenderingObject::IndexArray> indices = mesh->HasFaces() ? make_unique<RenderingObject::IndexArray>(mesh->mNumFaces * 3) : nullptr;
for (decltype(totalVertices) v = 0; v < totalVertices; ++v) {
positions->at(v) = glm::vec4(mesh->mVertices[v].x, mesh->mVertices[v].y, mesh->mVertices[v].z, 1.f);
if (normals) {
normals->at(v) = glm::vec3(mesh->mNormals[v].x, mesh->mNormals[v].y, mesh->mNormals[v].z);
}
if (uv) {
uv->at(v) = glm::vec2(mesh->mTextureCoords[0][v].x, mesh->mTextureCoords[0][v].y);
}
if (colors) {
colors->at(v) = glm::vec4(mesh->mColors[0][v].r, mesh->mColors[0][v].g, mesh->mColors[0][v].b, mesh->mColors[0][v].a);
}
}
for (decltype(mesh->mNumFaces) f = 0; f < mesh->mNumFaces && indices; ++f) {
const aiFace& face = mesh->mFaces[f];
if (face.mNumIndices != 3) {
std::cerr << "WARNING: Input mesh may not be triangulated. Skipping face with: " << face.mNumIndices << " vertices." << std::endl;
continue;
}
for (int j = 0; j < 3; ++j) {
indices->at(f * 3 + j) = face.mIndices[j];
}
}
std::shared_ptr<RenderingObject> createdMesh = std::make_shared<RenderingObject>(inputShader, std::move(positions), std::move(indices),
std::move(normals), std::move(uv), std::move(colors));
loadedMeshes.push_back(std::move(createdMesh));
if (outputMaterials) {
outputMaterials->push_back(sceneMaterials[mesh->mMaterialIndex]);
}
}
return loadedMeshes;
}
示例11: Load
S3DModel* CAssParser::Load(const std::string& modelFilePath)
{
LOG_SL(LOG_SECTION_MODEL, L_INFO, "Loading model: %s", modelFilePath.c_str());
const std::string& modelPath = FileSystem::GetDirectory(modelFilePath);
const std::string& modelName = FileSystem::GetBasename(modelFilePath);
// Load the lua metafile. This contains properties unique to Spring models and must return a table
std::string metaFileName = modelFilePath + ".lua";
if (!CFileHandler::FileExists(metaFileName, SPRING_VFS_ZIP)) {
// Try again without the model file extension
metaFileName = modelPath + '/' + modelName + ".lua";
}
if (!CFileHandler::FileExists(metaFileName, SPRING_VFS_ZIP)) {
LOG_SL(LOG_SECTION_MODEL, L_INFO, "No meta-file '%s'. Using defaults.", metaFileName.c_str());
}
LuaParser metaFileParser(metaFileName, SPRING_VFS_MOD_BASE, SPRING_VFS_ZIP);
if (!metaFileParser.Execute()) {
LOG_SL(LOG_SECTION_MODEL, L_INFO, "'%s': %s. Using defaults.", metaFileName.c_str(), metaFileParser.GetErrorLog().c_str());
}
// Get the (root-level) model table
const LuaTable& modelTable = metaFileParser.GetRoot();
if (!modelTable.IsValid()) {
LOG_SL(LOG_SECTION_MODEL, L_INFO, "No valid model metadata in '%s' or no meta-file", metaFileName.c_str());
}
// Create a model importer instance
Assimp::Importer importer;
// Give the importer an IO class that handles Spring's VFS
importer.SetIOHandler(new AssVFSSystem());
// Speed-up processing by skipping things we don't need
importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, ASS_IMPORTER_OPTIONS);
#ifndef BITMAP_NO_OPENGL
{
importer.SetPropertyInteger(AI_CONFIG_PP_SLM_VERTEX_LIMIT, maxVertices);
importer.SetPropertyInteger(AI_CONFIG_PP_SLM_TRIANGLE_LIMIT, maxIndices / 3);
}
#endif
// Read the model file to build a scene object
LOG_SL(LOG_SECTION_MODEL, L_INFO, "Importing model file: %s", modelFilePath.c_str());
const aiScene* scene = nullptr;
{
// ASSIMP spams many SIGFPEs atm in normal & tangent generation
ScopedDisableFpuExceptions fe;
scene = importer.ReadFile(modelFilePath, ASS_POSTPROCESS_OPTIONS);
}
if (scene != nullptr) {
LOG_SL(LOG_SECTION_MODEL, L_INFO,
"Processing scene for model: %s (%d meshes / %d materials / %d textures)",
modelFilePath.c_str(), scene->mNumMeshes, scene->mNumMaterials,
scene->mNumTextures);
} else {
throw content_error("[AssimpParser] Model Import: " + std::string(importer.GetErrorString()));
}
ModelPieceMap pieceMap;
ParentNameMap parentMap;
S3DModel* model = new S3DModel();
model->name = modelFilePath;
model->type = MODELTYPE_ASS;
// Load textures
FindTextures(model, scene, modelTable, modelPath, modelName);
LOG_SL(LOG_SECTION_MODEL, L_INFO, "Loading textures. Tex1: '%s' Tex2: '%s'", model->texs[0].c_str(), model->texs[1].c_str());
texturehandlerS3O->PreloadTexture(model, modelTable.GetBool("fliptextures", true), modelTable.GetBool("invertteamcolor", true));
// Load all pieces in the model
LOG_SL(LOG_SECTION_MODEL, L_INFO, "Loading pieces from root node '%s'", scene->mRootNode->mName.data);
LoadPiece(model, scene->mRootNode, scene, modelTable, pieceMap, parentMap);
// Update piece hierarchy based on metadata
BuildPieceHierarchy(model, pieceMap, parentMap);
CalculateModelProperties(model, modelTable);
// Verbose logging of model properties
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->name: %s", model->name.c_str());
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->numobjects: %d", model->numPieces);
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->radius: %f", model->radius);
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->height: %f", model->height);
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->mins: (%f,%f,%f)", model->mins[0], model->mins[1], model->mins[2]);
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->maxs: (%f,%f,%f)", model->maxs[0], model->maxs[1], model->maxs[2]);
LOG_SL(LOG_SECTION_MODEL, L_INFO, "Model %s Imported.", model->name.c_str());
return model;
}
示例12: acSpecular
std::shared_ptr<GeometryData::GenericObject> AssimpWrapper::LoadModel(std::string sFilename)
{
Assimp::Importer importer;
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT | aiPrimitiveType_LINE );
const aiScene* scene = importer.ReadFile(sFilename,
aiProcess_CalcTangentSpace |
aiProcess_ValidateDataStructure |
aiProcess_Triangulate |
aiProcess_PreTransformVertices |
//aiProcess_JoinIdenticalVertices |
aiProcess_GenSmoothNormals |
aiProcess_ImproveCacheLocality |
aiProcess_FindInvalidData |
//aiProcess_MakeLeftHanded |
//aiProcess_OptimizeMeshes |
//aiProcess_OptimizeGraph |
aiProcess_GenUVCoords |
aiProcess_TransformUVCoords |
aiProcess_FlipUVs |
aiProcess_FindDegenerates |
aiProcess_SortByPType
);
// If the import failed, report it
if( !scene)
Logger::error() << importer.GetErrorString() << Logger::endl;
else
Logger::debug() << "Loaded file " << sFilename << " with assimp" << Logger::endl;
//bool bModelHasMeshes = scene->HasMeshes();
//bool bModelHasMaterials = scene->HasMaterials();
//bool bModelHasTextures = scene->HasTextures();
unsigned int nNumMeshes = scene->mNumMeshes;
assert (nNumMeshes > 0);
GeometryData::GenericObject *pObject = new GeometryData::GenericObject(nNumMeshes);
std::shared_ptr<GeometryData::GenericObject> spObject(pObject);
for (unsigned int i=0; i < nNumMeshes; i++)
{
aiMesh *pMesh = scene->mMeshes[i];
GeometryData::GenericMesh *pGenericMesh = std::shared_ptr<GeometryData::GenericMesh>(pObject->GetMesh(i)).get();
unsigned int nMaterialIndex = pMesh->mMaterialIndex;
aiMaterial *pUsedMaterial = scene->mMaterials[nMaterialIndex];
// now fetch the material properties
/* aiColor3D acDiffuse (0.f,0.f,0.f);
bool bGotColorDiffuse = (AI_SUCCESS == pUsedMaterial->Get(AI_MATKEY_COLOR_DIFFUSE, acDiffuse));
float pfDiffuseColor[3] = { acDiffuse.r, acDiffuse.g, acDiffuse.b };
if (bGotColorDiffuse)
{
// pGenericMesh->AddAttributeValues(GeometryData::GenericData::DATA_MATERIAL_COLOR_DIFFUSE, 3, pfDiffuseColor);
unsigned int nNumVertices = pMesh->mNumVertices;
std::vector<float> vfFakedColor;
//get vertices
for (unsigned int ii=0; ii < nNumVertices; ii++)
{
vfFakedColor.push_back(pfDiffuseColor[0]);
vfFakedColor.push_back(pfDiffuseColor[1]);
vfFakedColor.push_back(pfDiffuseColor[2]);
}
pGenericMesh->AddAttributeValues(GeometryData::GenericData::DATA_COLORS,
3 * nNumVertices,
&vfFakedColor[0]);
}
aiColor3D acSpecular (0.f, 0.f, 0.f);
bool bGotSpecularColor = (AI_SUCCESS == pUsedMaterial->Get(AI_MATKEY_COLOR_SPECULAR, acSpecular));
float pfSpecularColor[3] = { acSpecular.r, acSpecular.g, acSpecular.b };
if (bGotSpecularColor)
pGenericMesh->AddAttributeValues(GeometryData::GenericData::DATA_MATERIAL_COLOR_SPECULAR, 3, pfSpecularColor);
float fShininess = 0.0f;
bool bGotShininess = (AI_SUCCESS == pUsedMaterial->Get(AI_MATKEY_SHININESS, fShininess));
if (bGotShininess)
pGenericMesh->AddAttributeValues(GeometryData::GenericData::DATA_MATERIAL_SHININESS, 1, &fShininess);
float fShininessStrength = 0.0f;
bool bGotShininessStrength = (AI_SUCCESS == pUsedMaterial->Get(AI_MATKEY_SHININESS_STRENGTH, fShininessStrength));
if (bGotShininessStrength)
pGenericMesh->AddAttributeValues(GeometryData::GenericData::DATA_MATERIAL_SHININESS_STRENGTH, 1, &fShininessStrength);*/
assert (pMesh->HasPositions());
if (pMesh->HasPositions())
{
// get vertices
//.........这里部分代码省略.........
示例13: LoadAssimp
bool Model::LoadAssimp(const char *filename)
{
Assimp::Importer importer;
// remove unused data
importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS,
aiComponent_COLORS | aiComponent_LIGHTS | aiComponent_CAMERAS);
// max triangles and vertices per mesh, splits above this threshold
importer.SetPropertyInteger(AI_CONFIG_PP_SLM_TRIANGLE_LIMIT, INT_MAX);
importer.SetPropertyInteger(AI_CONFIG_PP_SLM_VERTEX_LIMIT, 0xfffe); // avoid the primitive restart index
// remove points and lines
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT | aiPrimitiveType_LINE);
const aiScene *scene = importer.ReadFile(filename,
aiProcess_CalcTangentSpace |
aiProcess_JoinIdenticalVertices |
aiProcess_Triangulate |
aiProcess_RemoveComponent |
aiProcess_GenSmoothNormals |
aiProcess_SplitLargeMeshes |
aiProcess_ValidateDataStructure |
//aiProcess_ImproveCacheLocality | // handled by optimizePostTransform()
aiProcess_RemoveRedundantMaterials |
aiProcess_SortByPType |
aiProcess_FindInvalidData |
aiProcess_GenUVCoords |
aiProcess_TransformUVCoords |
aiProcess_OptimizeMeshes |
aiProcess_OptimizeGraph);
if (scene == nullptr)
return false;
if (scene->HasTextures())
{
// embedded textures...
}
if (scene->HasAnimations())
{
// todo
}
m_Header.materialCount = scene->mNumMaterials;
m_pMaterial = new Material [m_Header.materialCount];
memset(m_pMaterial, 0, sizeof(Material) * m_Header.materialCount);
for (unsigned int materialIndex = 0; materialIndex < scene->mNumMaterials; materialIndex++)
{
const aiMaterial *srcMat = scene->mMaterials[materialIndex];
Material *dstMat = m_pMaterial + materialIndex;
aiColor3D diffuse(1.0f, 1.0f, 1.0f);
aiColor3D specular(1.0f, 1.0f, 1.0f);
aiColor3D ambient(1.0f, 1.0f, 1.0f);
aiColor3D emissive(0.0f, 0.0f, 0.0f);
aiColor3D transparent(1.0f, 1.0f, 1.0f);
float opacity = 1.0f;
float shininess = 0.0f;
float specularStrength = 1.0f;
aiString texDiffusePath;
aiString texSpecularPath;
aiString texEmissivePath;
aiString texNormalPath;
aiString texLightmapPath;
aiString texReflectionPath;
srcMat->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse);
srcMat->Get(AI_MATKEY_COLOR_SPECULAR, specular);
srcMat->Get(AI_MATKEY_COLOR_AMBIENT, ambient);
srcMat->Get(AI_MATKEY_COLOR_EMISSIVE, emissive);
srcMat->Get(AI_MATKEY_COLOR_TRANSPARENT, transparent);
srcMat->Get(AI_MATKEY_OPACITY, opacity);
srcMat->Get(AI_MATKEY_SHININESS, shininess);
srcMat->Get(AI_MATKEY_SHININESS_STRENGTH, specularStrength);
srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), texDiffusePath);
srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), texSpecularPath);
srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_EMISSIVE, 0), texEmissivePath);
srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), texNormalPath);
srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), texLightmapPath);
srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_REFLECTION, 0), texReflectionPath);
dstMat->diffuse = Vector3(diffuse.r, diffuse.g, diffuse.b);
dstMat->specular = Vector3(specular.r, specular.g, specular.b);
dstMat->ambient = Vector3(ambient.r, ambient.g, ambient.b);
dstMat->emissive = Vector3(emissive.r, emissive.g, emissive.b);
dstMat->transparent = Vector3(transparent.r, transparent.g, transparent.b);
dstMat->opacity = opacity;
dstMat->shininess = shininess;
dstMat->specularStrength = specularStrength;
char *pRem = nullptr;
strncpy_s(dstMat->texDiffusePath, "models/", Material::maxTexPath - 1);
strncat_s(dstMat->texDiffusePath, texDiffusePath.C_Str(), Material::maxTexPath - 1);
pRem = strrchr(dstMat->texDiffusePath, '.');
while (pRem != nullptr && *pRem != 0) *(pRem++) = 0; // remove extension
strncpy_s(dstMat->texSpecularPath, "models/", Material::maxTexPath - 1);
strncat_s(dstMat->texSpecularPath, texSpecularPath.C_Str(), Material::maxTexPath - 1);
//.........这里部分代码省略.........
示例14: load
/**
* Load the model.
* Return true on success, false on failure.
**/
bool AssimpModel::load(Render3D* render, bool meshdata, AssimpLoadFlags flags)
{
Assimp::Importer importer;
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT | aiPrimitiveType_LINE);
importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, aiComponent_COLORS | aiComponent_LIGHTS | aiComponent_CAMERAS);
importer.SetPropertyInteger(AI_CONFIG_PP_SLM_VERTEX_LIMIT, 65535);
importer.SetPropertyInteger(AI_CONFIG_PP_SLM_TRIANGLE_LIMIT, 65535);
unsigned int assflags = aiProcess_CalcTangentSpace
| aiProcess_Triangulate
| aiProcess_JoinIdenticalVertices
| aiProcess_SortByPType
| aiProcess_FlipUVs
| aiProcess_FindDegenerates
| aiProcess_ImproveCacheLocality
| aiProcess_RemoveComponent;
// For map meshes we flatten geometry
if (flags & ALM_FlattenGeometry) {
assflags |= aiProcess_PreTransformVertices;
assflags |= aiProcess_RemoveRedundantMaterials;
assflags |= aiProcess_OptimizeMeshes;
assflags |= aiProcess_FindInvalidData;
assflags |= aiProcess_SplitLargeMeshes;
}
// Normally models are re-centered; this isn't always deisred.
if (flags & ALF_NoRecenter) {
this->recenter = false;
}
// Read the file from the mod
Sint64 len;
Uint8 * data = this->mod->loadBinary("models/" + this->name, &len);
if (! data) {
this->mod->setLoadErr("Failed to load %s; file read failed", this->name.c_str());
return false;
}
// Check we aren't larger than size_t
if (len > MAX_FILE_SIZE) {
this->mod->setLoadErr("Failed to load %s; file too large", this->name.c_str());
return false;
}
// Do the import
const struct aiScene* sc = importer.ReadFileFromMemory((const void*) data, (size_t)len, assflags, this->name.c_str());
if (!sc) {
this->mod->setLoadErr("Failed to load %s; file read failed; %s", this->name.c_str(), importer.GetErrorString());
return false;
}
free(data);
if (debug_enabled("loadbones")) {
cout << endl << this->name << endl;
}
if (render != NULL && render->is3D()) {
this->loadMeshes(true, sc);
this->loadMaterials(render, sc);
} else {
this->loadMeshes(false, sc);
}
if (meshdata) {
this->loadMeshdata(render != NULL, sc);
}
this->loadNodes(sc);
this->loadAnimations(sc);
this->calcBoundingBox(sc);
this->setBoneNodes();
return true;
}
示例15: switch
void
Mesh::bind()
{
Assimp::Importer importer;
unsigned int flags = aiProcess_Triangulate | aiProcess_JoinIdenticalVertices;
if (generateVertexNormals) {
importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, aiComponent_NORMALS);
importer.SetPropertyFloat(AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE, 30.0f);
// ignore normals in file and generate per vertex normals
flags |= aiProcess_RemoveComponent | aiProcess_GenSmoothNormals;
} else {
// generate face normals if not already present in the file
flags |= aiProcess_GenNormals;
}
const aiScene* scene = importer.ReadFile(fileName, flags);
if (!scene) {
return;
}
std::vector<float> vertices;
std::vector<float> normals;
std::vector<float> textureCoordinates;
min.x = 1e38;
min.y = 1e38;
min.z = 1e38;
max.x = -1e38;
max.y = -1e38;
max.z = -1e38;
const struct aiNode* nd = scene->mRootNode;
for (unsigned int n = 0; n < nd->mNumMeshes; ++n) {
const struct aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]];
std::cout << "vertices: " << mesh->mNumVertices << ", faces: " << mesh->mNumFaces << std::endl;
for (unsigned int t = 0; t < mesh->mNumFaces; ++t) {
const struct aiFace* face = &mesh->mFaces[t];
switch (face->mNumIndices) {
case 3:
break;
default:
std::cout << "ignored" << std::endl;
continue;
}
for (unsigned int idx= 0;idx < face->mNumIndices;idx++) {
float x = mesh->mVertices[face->mIndices[idx]].x;
float y = mesh->mVertices[face->mIndices[idx]].y;
float z = mesh->mVertices[face->mIndices[idx]].z;
float nx = mesh->mNormals[face->mIndices[idx]].x;
float ny = mesh->mNormals[face->mIndices[idx]].y;
float nz = mesh->mNormals[face->mIndices[idx]].z;
if (x < min.x) {
min.x = x;
}
if (y < min.y) {
min.y = y;
}
if (z < min.z) {
min.z = z;
}
if (x > max.x) {
max.x = x;
}
if (y > max.y) {
max.y = y;
}
if (z > max.z) {
max.z = z;
}
vertices.push_back(x);
vertices.push_back(y);
vertices.push_back(z);
vertices.push_back(1.0f);
normals.push_back(nx);
normals.push_back(ny);
normals.push_back(nz);
normals.push_back(0.0f);
textureCoordinates.push_back(x / 8);
textureCoordinates.push_back(z / 8);
}
}
}
std::cout << "bounding box: min = "
<< min.x << ", " << min.y << ", " << min.z
<< " - max = "
<< max.x << ", " << max.y << ", " << max.z
<< std::endl;
// vertices.clear();
// normals.clear();
// quad(vertices, normals, 0, 1, 2, 3);
// quad(vertices, normals, 0, 4, 5, 1);
// quad(vertices, normals, 1, 5, 6, 2);
//.........这里部分代码省略.........