1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
|
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2012, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
#include "AssimpPCH.h"
#ifndef ASSIMP_BUILD_NO_OBJ_IMPORTER
#include "DefaultIOSystem.h"
#include "ObjFileImporter.h"
#include "ObjFileParser.h"
#include "ObjFileData.h"
namespace Assimp {
using namespace std;
// ------------------------------------------------------------------------------------------------
// Default constructor
ObjFileImporter::ObjFileImporter() :
m_Buffer(),
m_pRootObject( NULL ),
m_strAbsPath( "" )
{
DefaultIOSystem io;
m_strAbsPath = io.getOsSeparator();
}
// ------------------------------------------------------------------------------------------------
// Destructor.
ObjFileImporter::~ObjFileImporter()
{
// Release root object instance
if (NULL != m_pRootObject)
{
delete m_pRootObject;
m_pRootObject = NULL;
}
}
// ------------------------------------------------------------------------------------------------
// Returns true, if file is an obj file.
bool ObjFileImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler , bool checkSig ) const
{
if(!checkSig) //Check File Extension
{
return SimpleExtensionCheck(pFile,"obj");
}
else //Check file Header
{
static const char *pTokens[] = { "mtllib", "usemtl", "v ", "vt ", "vn ", "o ", "g ", "s ", "f " };
return BaseImporter::SearchFileHeaderForToken(pIOHandler, pFile, pTokens, 9 );
}
}
// ------------------------------------------------------------------------------------------------
// Obj-file import implementation
void ObjFileImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
{
DefaultIOSystem io;
// Read file into memory
const std::string mode = "rb";
boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, mode));
if (NULL == file.get())
throw DeadlyImportError( "Failed to open file " + pFile + ".");
// Get the file-size and validate it, throwing an exception when fails
size_t fileSize = file->FileSize();
if( fileSize < 16)
throw DeadlyImportError( "OBJ-file is too small.");
// Allocate buffer and read file into it
TextFileToBuffer(file.get(),m_Buffer);
// Get the model name
std::string strModelName;
std::string::size_type pos = pFile.find_last_of( "\\/" );
if ( pos != std::string::npos )
{
strModelName = pFile.substr(pos+1, pFile.size() - pos - 1);
}
else
{
strModelName = pFile;
}
// parse the file into a temporary representation
ObjFileParser parser(m_Buffer, strModelName, pIOHandler);
// And create the proper return structures out of it
CreateDataFromImport(parser.GetModel(), pScene);
// Clean up allocated storage for the next import
m_Buffer.clear();
}
// ------------------------------------------------------------------------------------------------
// Create the data from parsed obj-file
void ObjFileImporter::CreateDataFromImport(const ObjFile::Model* pModel, aiScene* pScene)
{
if (0L == pModel)
return;
// Create the root node of the scene
pScene->mRootNode = new aiNode;
if ( !pModel->m_ModelName.empty() )
{
// Set the name of the scene
pScene->mRootNode->mName.Set(pModel->m_ModelName);
}
else
{
// This is an error, so break down the application
ai_assert(false);
}
// Create nodes for the whole scene
std::vector<aiMesh*> MeshArray;
for (size_t index = 0; index < pModel->m_Objects.size(); index++)
{
createNodes(pModel, pModel->m_Objects[ index ], index, pScene->mRootNode, pScene, MeshArray);
}
// Create mesh pointer buffer for this scene
if (pScene->mNumMeshes > 0)
{
pScene->mMeshes = new aiMesh*[ MeshArray.size() ];
for (size_t index =0; index < MeshArray.size(); index++)
{
pScene->mMeshes [ index ] = MeshArray[ index ];
}
}
// Create all materials
createMaterials( pModel, pScene );
}
// ------------------------------------------------------------------------------------------------
// Creates all nodes of the model
aiNode *ObjFileImporter::createNodes(const ObjFile::Model* pModel, const ObjFile::Object* pObject,
unsigned int /*uiMeshIndex*/,
aiNode *pParent, aiScene* pScene,
std::vector<aiMesh*> &MeshArray )
{
ai_assert( NULL != pModel );
if ( NULL == pObject )
return NULL;
// Store older mesh size to be able to computes mesh offsets for new mesh instances
const size_t oldMeshSize = MeshArray.size();
aiNode *pNode = new aiNode;
pNode->mName = pObject->m_strObjName;
// If we have a parent node, store it
if (pParent != NULL)
appendChildToParentNode(pParent, pNode);
for ( unsigned int i=0; i< pObject->m_Meshes.size(); i++ )
{
unsigned int meshId = pObject->m_Meshes[ i ];
aiMesh *pMesh = new aiMesh;
createTopology( pModel, pObject, meshId, pMesh );
if ( pMesh->mNumVertices > 0 )
{
MeshArray.push_back( pMesh );
}
else
{
delete pMesh;
}
}
// Create all nodes from the sub-objects stored in the current object
if ( !pObject->m_SubObjects.empty() )
{
size_t numChilds = pObject->m_SubObjects.size();
pNode->mNumChildren = static_cast<unsigned int>( numChilds );
pNode->mChildren = new aiNode*[ numChilds ];
pNode->mNumMeshes = 1;
pNode->mMeshes = new unsigned int[ 1 ];
}
// Set mesh instances into scene- and node-instances
const size_t meshSizeDiff = MeshArray.size()- oldMeshSize;
if ( meshSizeDiff > 0 )
{
pNode->mMeshes = new unsigned int[ meshSizeDiff ];
pNode->mNumMeshes = static_cast<unsigned int>( meshSizeDiff );
size_t index = 0;
for (size_t i = oldMeshSize; i < MeshArray.size(); i++)
{
pNode->mMeshes[ index ] = pScene->mNumMeshes;
pScene->mNumMeshes++;
index++;
}
}
return pNode;
}
// ------------------------------------------------------------------------------------------------
// Create topology data
void ObjFileImporter::createTopology(const ObjFile::Model* pModel,
const ObjFile::Object* pData,
unsigned int uiMeshIndex,
aiMesh* pMesh )
{
// Checking preconditions
ai_assert( NULL != pModel );
if (NULL == pData)
return;
// Create faces
ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
ai_assert( NULL != pObjMesh );
pMesh->mNumFaces = 0;
for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++)
{
ObjFile::Face* const inp = pObjMesh->m_Faces[ index ];
if (inp->m_PrimitiveType == aiPrimitiveType_LINE) {
pMesh->mNumFaces += inp->m_pVertices->size() - 1;
}
else if (inp->m_PrimitiveType == aiPrimitiveType_POINT) {
pMesh->mNumFaces += inp->m_pVertices->size();
}
else {
++pMesh->mNumFaces;
}
}
unsigned int uiIdxCount = 0u;
if ( pMesh->mNumFaces > 0 )
{
pMesh->mFaces = new aiFace[ pMesh->mNumFaces ];
if ( pObjMesh->m_uiMaterialIndex != ObjFile::Mesh::NoMaterial )
{
pMesh->mMaterialIndex = pObjMesh->m_uiMaterialIndex;
}
unsigned int outIndex = 0;
// Copy all data from all stored meshes
for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++)
{
ObjFile::Face* const inp = pObjMesh->m_Faces[ index ];
if (inp->m_PrimitiveType == aiPrimitiveType_LINE) {
for(size_t i = 0; i < inp->m_pVertices->size() - 1; ++i) {
aiFace& f = pMesh->mFaces[ outIndex++ ];
uiIdxCount += f.mNumIndices = 2;
f.mIndices = new unsigned int[2];
}
continue;
}
else if (inp->m_PrimitiveType == aiPrimitiveType_POINT) {
for(size_t i = 0; i < inp->m_pVertices->size(); ++i) {
aiFace& f = pMesh->mFaces[ outIndex++ ];
uiIdxCount += f.mNumIndices = 1;
f.mIndices = new unsigned int[1];
}
continue;
}
aiFace *pFace = &pMesh->mFaces[ outIndex++ ];
const unsigned int uiNumIndices = (unsigned int) pObjMesh->m_Faces[ index ]->m_pVertices->size();
uiIdxCount += pFace->mNumIndices = (unsigned int) uiNumIndices;
if (pFace->mNumIndices > 0) {
pFace->mIndices = new unsigned int[ uiNumIndices ];
}
}
}
// Create mesh vertices
createVertexArray(pModel, pData, uiMeshIndex, pMesh, uiIdxCount);
}
// ------------------------------------------------------------------------------------------------
// Creates a vertex array
void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel,
const ObjFile::Object* pCurrentObject,
unsigned int uiMeshIndex,
aiMesh* pMesh,
unsigned int uiIdxCount)
{
// Checking preconditions
ai_assert( NULL != pCurrentObject );
// Break, if no faces are stored in object
if ( pCurrentObject->m_Meshes.empty() )
return;
// Get current mesh
ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
if ( NULL == pObjMesh || pObjMesh->m_uiNumIndices < 1)
return;
// Copy vertices of this mesh instance
pMesh->mNumVertices = uiIdxCount;
pMesh->mVertices = new aiVector3D[ pMesh->mNumVertices ];
// Allocate buffer for normal vectors
if ( !pModel->m_Normals.empty() && pObjMesh->m_hasNormals )
pMesh->mNormals = new aiVector3D[ pMesh->mNumVertices ];
// Allocate buffer for texture coordinates
if ( !pModel->m_TextureCoord.empty() && pObjMesh->m_uiUVCoordinates[0] )
{
pMesh->mNumUVComponents[ 0 ] = 2;
pMesh->mTextureCoords[ 0 ] = new aiVector3D[ pMesh->mNumVertices ];
}
// Copy vertices, normals and textures into aiMesh instance
unsigned int newIndex = 0, outIndex = 0;
for ( size_t index=0; index < pObjMesh->m_Faces.size(); index++ )
{
// Get source face
ObjFile::Face *pSourceFace = pObjMesh->m_Faces[ index ];
// Copy all index arrays
for ( size_t vertexIndex = 0, outVertexIndex = 0; vertexIndex < pSourceFace->m_pVertices->size(); vertexIndex++ )
{
const unsigned int vertex = pSourceFace->m_pVertices->at( vertexIndex );
if ( vertex >= pModel->m_Vertices.size() )
throw DeadlyImportError( "OBJ: vertex index out of range" );
pMesh->mVertices[ newIndex ] = pModel->m_Vertices[ vertex ];
// Copy all normals
if ( !pSourceFace->m_pNormals->empty() && !pModel->m_Normals.empty())
{
const unsigned int normal = pSourceFace->m_pNormals->at( vertexIndex );
if ( normal >= pModel->m_Normals.size() )
throw DeadlyImportError("OBJ: vertex normal index out of range");
pMesh->mNormals[ newIndex ] = pModel->m_Normals[ normal ];
}
// Copy all texture coordinates
if ( !pModel->m_TextureCoord.empty() )
{
if ( !pSourceFace->m_pTexturCoords->empty() )
{
const unsigned int tex = pSourceFace->m_pTexturCoords->at( vertexIndex );
ai_assert( tex < pModel->m_TextureCoord.size() );
for ( size_t i=0; i < pMesh->GetNumUVChannels(); i++ )
{
if ( tex >= pModel->m_TextureCoord.size() )
throw DeadlyImportError("OBJ: texture coord index out of range");
aiVector2D coord2d = pModel->m_TextureCoord[ tex ];
pMesh->mTextureCoords[ i ][ newIndex ] = aiVector3D( coord2d.x, coord2d.y, 0.0 );
}
}
}
ai_assert( pMesh->mNumVertices > newIndex );
// Get destination face
aiFace *pDestFace = &pMesh->mFaces[ outIndex ];
const bool last = ( vertexIndex == pSourceFace->m_pVertices->size() - 1 );
if (pSourceFace->m_PrimitiveType != aiPrimitiveType_LINE || !last)
{
pDestFace->mIndices[ outVertexIndex ] = newIndex;
outVertexIndex++;
}
if (pSourceFace->m_PrimitiveType == aiPrimitiveType_POINT)
{
outIndex++;
outVertexIndex = 0;
}
else if (pSourceFace->m_PrimitiveType == aiPrimitiveType_LINE)
{
outVertexIndex = 0;
if(!last)
outIndex++;
if (vertexIndex) {
if(!last) {
pMesh->mVertices[ newIndex+1 ] = pMesh->mVertices[ newIndex ];
if ( !pSourceFace->m_pNormals->empty() && !pModel->m_Normals.empty()) {
pMesh->mNormals[ newIndex+1 ] = pMesh->mNormals[newIndex ];
}
if ( !pModel->m_TextureCoord.empty() ) {
for ( size_t i=0; i < pMesh->GetNumUVChannels(); i++ ) {
pMesh->mTextureCoords[ i ][ newIndex+1 ] = pMesh->mTextureCoords[ i ][ newIndex ];
}
}
++newIndex;
}
pDestFace[-1].mIndices[1] = newIndex;
}
}
else if (last) {
outIndex++;
}
++newIndex;
}
}
}
// ------------------------------------------------------------------------------------------------
// Counts all stored meshes
void ObjFileImporter::countObjects(const std::vector<ObjFile::Object*> &rObjects, int &iNumMeshes)
{
iNumMeshes = 0;
if ( rObjects.empty() )
return;
iNumMeshes += static_cast<unsigned int>( rObjects.size() );
for (std::vector<ObjFile::Object*>::const_iterator it = rObjects.begin();
it != rObjects.end();
++it)
{
if (!(*it)->m_SubObjects.empty())
{
countObjects((*it)->m_SubObjects, iNumMeshes);
}
}
}
// ------------------------------------------------------------------------------------------------
// Creates the material
void ObjFileImporter::createMaterials(const ObjFile::Model* pModel, aiScene* pScene )
{
ai_assert( NULL != pScene );
if ( NULL == pScene )
return;
const unsigned int numMaterials = (unsigned int) pModel->m_MaterialLib.size();
pScene->mNumMaterials = 0;
if ( pModel->m_MaterialLib.empty() ) {
DefaultLogger::get()->debug("OBJ: no materials specified");
return;
}
pScene->mMaterials = new aiMaterial*[ numMaterials ];
for ( unsigned int matIndex = 0; matIndex < numMaterials; matIndex++ )
{
// Store material name
std::map<std::string, ObjFile::Material*>::const_iterator it;
it = pModel->m_MaterialMap.find( pModel->m_MaterialLib[ matIndex ] );
// No material found, use the default material
if ( pModel->m_MaterialMap.end() == it )
continue;
aiMaterial* mat = new aiMaterial;
ObjFile::Material *pCurrentMaterial = (*it).second;
mat->AddProperty( &pCurrentMaterial->MaterialName, AI_MATKEY_NAME );
// convert illumination model
int sm = 0;
switch (pCurrentMaterial->illumination_model)
{
case 0:
sm = aiShadingMode_NoShading;
break;
case 1:
sm = aiShadingMode_Gouraud;
break;
case 2:
sm = aiShadingMode_Phong;
break;
default:
sm = aiShadingMode_Gouraud;
DefaultLogger::get()->error("OBJ: unexpected illumination model (0-2 recognized)");
}
mat->AddProperty<int>( &sm, 1, AI_MATKEY_SHADING_MODEL);
// multiplying the specular exponent with 2 seems to yield better results
pCurrentMaterial->shineness *= 4.f;
// Adding material colors
mat->AddProperty( &pCurrentMaterial->ambient, 1, AI_MATKEY_COLOR_AMBIENT );
mat->AddProperty( &pCurrentMaterial->diffuse, 1, AI_MATKEY_COLOR_DIFFUSE );
mat->AddProperty( &pCurrentMaterial->specular, 1, AI_MATKEY_COLOR_SPECULAR );
mat->AddProperty( &pCurrentMaterial->shineness, 1, AI_MATKEY_SHININESS );
mat->AddProperty( &pCurrentMaterial->alpha, 1, AI_MATKEY_OPACITY );
// Adding refraction index
mat->AddProperty( &pCurrentMaterial->ior, 1, AI_MATKEY_REFRACTI );
// Adding textures
if ( 0 != pCurrentMaterial->texture.length )
mat->AddProperty( &pCurrentMaterial->texture, AI_MATKEY_TEXTURE_DIFFUSE(0));
if ( 0 != pCurrentMaterial->textureAmbient.length )
mat->AddProperty( &pCurrentMaterial->textureAmbient, AI_MATKEY_TEXTURE_AMBIENT(0));
if ( 0 != pCurrentMaterial->textureSpecular.length )
mat->AddProperty( &pCurrentMaterial->textureSpecular, AI_MATKEY_TEXTURE_SPECULAR(0));
if ( 0 != pCurrentMaterial->textureBump.length )
mat->AddProperty( &pCurrentMaterial->textureBump, AI_MATKEY_TEXTURE_HEIGHT(0));
if ( 0 != pCurrentMaterial->textureOpacity.length )
mat->AddProperty( &pCurrentMaterial->textureOpacity, AI_MATKEY_TEXTURE_OPACITY(0));
if ( 0 != pCurrentMaterial->textureSpecularity.length )
mat->AddProperty( &pCurrentMaterial->textureSpecularity, AI_MATKEY_TEXTURE_SHININESS(0));
// Store material property info in material array in scene
pScene->mMaterials[ pScene->mNumMaterials ] = mat;
pScene->mNumMaterials++;
}
// Test number of created materials.
ai_assert( pScene->mNumMaterials == numMaterials );
}
// ------------------------------------------------------------------------------------------------
// Appends this node to the parent node
void ObjFileImporter::appendChildToParentNode(aiNode *pParent, aiNode *pChild)
{
// Checking preconditions
ai_assert( NULL != pParent );
ai_assert( NULL != pChild );
// Assign parent to child
pChild->mParent = pParent;
size_t sNumChildren = 0;
(void)sNumChildren; // remove warning on release build
// If already children was assigned to the parent node, store them in a
std::vector<aiNode*> temp;
if (pParent->mChildren != NULL)
{
sNumChildren = pParent->mNumChildren;
ai_assert( 0 != sNumChildren );
for (size_t index = 0; index < pParent->mNumChildren; index++)
{
temp.push_back(pParent->mChildren [ index ] );
}
delete [] pParent->mChildren;
}
// Copy node instances into parent node
pParent->mNumChildren++;
pParent->mChildren = new aiNode*[ pParent->mNumChildren ];
for (size_t index = 0; index < pParent->mNumChildren-1; index++)
{
pParent->mChildren[ index ] = temp [ index ];
}
pParent->mChildren[ pParent->mNumChildren-1 ] = pChild;
}
// ------------------------------------------------------------------------------------------------
} // Namespace Assimp
#endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER
|