예제 #1
0
static Lib3dsFile *qgl3ds_lib3ds_file_load(QIODevice *iod)
{
    Lib3dsFile *file;
    Lib3dsIo *io;
    Q_ASSERT(iod->isOpen() && iod->isReadable());
    file = lib3ds_file_new();
    if (!file) {
        iod->close();
        return(0);
    }
    IODevice3ds io3d;
    io3d.dev = iod;
    io3d.errorState = false;
    io = lib3ds_io_new(
            &io3d,
            qgl3ds_fileio_error_func,
            qgl3ds_fileio_seek_func,
            qgl3ds_fileio_tell_func,
            qgl3ds_fileio_read_func,
            qgl3ds_fileio_write_func
            );
    if (!io) {
        lib3ds_file_free(file);
        iod->close();
        return(0);
    }
    if (!lib3ds_file_read(file, io)) {
        lib3ds_file_free(file);
        iod->close();
        return(0);
    }
    lib3ds_io_free(io);
    iod->close();
    return(file);
}
예제 #2
0
    /*!
     * See \ref Loader3ds::loadFromFile
     */
    dcollide::Proxy* Loader3dsInternal::loadFromFile(dcollide::World* world, const char* fileName, dcollide::ProxyTypes proxyType) {
        mData->mProxy2Transformation.clear();
        mData->mProxy2TextureInformation.clear();
        if (!fileName) {
            // TODO: exception?
            return 0;
        }

        mFile = lib3ds_file_load(fileName);
        if (!mFile) {
            std::cout << dc_funcinfo << "unable to load " << fileName << std::endl;
            return 0;
        }

        // AB: some files don't store nodes and just want exactly one node per mesh.
        //     atm we don't support that.
        if (!mFile->nodes) {
            std::cout << dc_funcinfo << "File " << fileName << " does not contain any nodes. mesh-only files not supported currently." << std::endl;
            lib3ds_file_free(mFile);
            mFile = 0;
            return 0;
        }

        // 3ds stores several frames, we want the first
        lib3ds_file_eval(mFile, 0);

        if (!checkUniqueMeshMaterial()) {
            std::cerr << dc_funcinfo << "the file " << fileName << " contains at least one mesh with different materials. this is not supported by this modelloader, only the first material will be used!" << std::endl;
        }

        dcollide::Proxy* topObject = world->createProxy(proxyType);
        mData->mProxy2Transformation.insert(std::make_pair(topObject, Loader3ds::TransformationNode()));

        Lib3dsMatrix identityMatrix;
        lib3ds_matrix_identity(identityMatrix);
        Lib3dsNode* node = mFile->nodes;
        while (node) {
            // node->type can be object, light, camera, ...
            // -> only object nodes are relevant to us
            if (node->type == LIB3DS_OBJECT_NODE) {
                if (!loadNode(world, topObject, node, &identityMatrix)) {
                    std::cerr << dc_funcinfo << "Loading node from " << fileName << " failed" << std::endl;
                    // TODO: is MyObjectNode::mProxy being deleted?
                    delete topObject;
                    lib3ds_file_free(mFile);
                    mFile = 0;
                    return 0;
                }
            }

            node = node->next;
        }

        lib3ds_file_free(mFile);
        mFile = 0;
        return topObject;
    }
예제 #3
0
	x3ds_definition::~x3ds_definition()
	{
		if (m_file)
		{
			lib3ds_file_free(m_file);
		}
	}
예제 #4
0
// clear 3dsToWorld allocate memory and reset member
void GLC_3dsToWorld::clear()
{
	if (NULL != m_pCurrentMesh)
	{
		delete m_pCurrentMesh;
		m_pCurrentMesh= NULL;
	}
	m_pWorld= NULL;
	m_FileName.clear();
	if (NULL != m_pLib3dsFile)
	{
		lib3ds_file_free(m_pLib3dsFile);
		m_pLib3dsFile= NULL;
	}

	// Remove unused material
	QHash<QString, GLC_Material*>::iterator i;
	for (i= m_Materials.begin(); i != m_Materials.end(); ++i)
	{
		if (i.value()->isUnused()) delete i.value();
	}
	m_Materials.clear();
	m_NextMaterialIndex= 0;
	// Clear the loaded meshes Set
	m_LoadedMeshes.clear();
	// Progress indicator
	m_CurrentQuantumValue= 0;
	m_PreviousQuantumValue= 0;
	m_NumberOfMeshes= 0;
	m_CurrentMeshNumber= 0;
	m_ListOfAttachedFileName.clear();
}
예제 #5
0
Scene *load_scene(const char *fname) {

	Lib3dsFile *file;
	if(!(file = lib3ds_file_load(fname))) {
		error("%s: could not load %s", __func__, fname);
		return 0;
	}
	lib3ds_file_eval(file, 0);

	Scene *scene = new Scene;

	load_objects(file, scene);
	load_lights(file, scene);
	load_cameras(file, scene);

	construct_hierarchy(file, scene);

	/*
	std::list<Object*> *obj_list = scene->get_objects_list();
	std::list<Object*>::iterator iter = obj_list->begin();
	while(iter != obj_list->end()) {
		fix_hierarchy(*iter++);
	}
	*/
	
	lib3ds_file_free(file);

	return scene;
}
예제 #6
0
int main(int argc, char **argv)
{
	Lib3dsFile *f = NULL;
	FILE *o = NULL;

	parse_args(argc, argv);
	f = lib3ds_file_load(input_file);
	if (!f)
	{
		fprintf(stderr, "***ERROR***\nLoading file %s failed\n", input_file);
		exit(1);
	}
	o = fopen(output_file, "w+");
	if (!o)
	{
		fprintf(stderr, "***ERROR***\nCan't open %s for writing\n", output_file);
		exit(1);
	}
	dump_wzm_file(f, o, swapYZ, invertUV, reverseWinding, baseTexFlags, scaleFactor);
	fclose(o);

	lib3ds_file_free(f);

	return 0;
}
void SkeletalObject::CreateVBO()
{
	assert(m_model != NULL);
	// Calculate the number of faces we have in total
	GetFaces();
	// Allocate memory for our vertices and normals
	Lib3dsVector * vertices = new Lib3dsVector[m_TotalFaces * 3];
	Lib3dsVector * normals = new Lib3dsVector[m_TotalFaces * 3];
	Lib3dsTexel* texCoords = new Lib3dsTexel[m_TotalFaces * 3];

	Lib3dsMesh * mesh;
	unsigned int FinishedFaces = 0;
	// Loop through all the meshes
	for(mesh = m_model->meshes;mesh != NULL;mesh = mesh->next)
	{

		lib3ds_mesh_calculate_normals(mesh, &normals[FinishedFaces*3]);
		// Loop through every face
		for(unsigned int cur_face = 0; cur_face < mesh->faces;cur_face++)
		{

			Lib3dsFace * face = &mesh->faceL[cur_face];
			for(unsigned int i = 0;i < 3;i++)
			{

				if(mesh->texels)
				{
					memcpy(&texCoords[FinishedFaces*2 + i], mesh->texelL[face->points[ i ]], sizeof(Lib3dsTexel));
				}
				memcpy(&vertices[FinishedFaces*3 + i], mesh->pointL[face->points[ i ]].pos, sizeof(Lib3dsVector));

			}

			FinishedFaces++;
		}

	}

	// Generate a Vertex Buffer SkeletalObject and store it with our vertices
	glGenBuffers(1, &m_VertexVBO);
	glBindBuffer(GL_ARRAY_BUFFER, m_VertexVBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsVector) * 3 * m_TotalFaces, vertices, GL_STATIC_DRAW);
	// Generate another Vertex Buffer SkeletalObject and store the normals in it
	glGenBuffers(1, &m_NormalVBO);
	glBindBuffer(GL_ARRAY_BUFFER, m_NormalVBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsVector) * 3 * m_TotalFaces, normals, GL_STATIC_DRAW);
	// Generate a third VBO and store the texture coordinates in it.
	glGenBuffers(1, &m_TexCoordVBO);
	glBindBuffer(GL_ARRAY_BUFFER, m_TexCoordVBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsTexel) * 3 * m_TotalFaces, texCoords, GL_STATIC_DRAW);

	// Clean up our allocated memory
	delete vertices;
	delete normals;
	delete texCoords;

	// We no longer need lib3ds
	lib3ds_file_free(m_model);
	m_model = NULL;
}
예제 #8
0
파일: 3ds2m.c 프로젝트: kasicass/frustum
int
main(int argc, char **argv)
{
  Lib3dsFile *f=0;

  parse_args(argc, argv);
  f=lib3ds_file_load(filename);
  if (!f) {
    fprintf(stderr, "***ERROR***\nLoading file %s failed\n", filename);
    exit(1);
  }
  if (output) {
    FILE *o=fopen(output, "w+");
    if (!o) {
      fprintf(stderr, "***ERROR***\nCan't open %s for writing\n", output);
      exit(1);
    }
    dump_m_file(f,o);
    fclose(o);
  }
  else {
    dump_m_file(f,stdout);
  }

  lib3ds_file_free(f);
  return(0);
}
예제 #9
0
int
main(int argc, char **argv)
{
  Lib3dsFile *f=0;

  parse_args(argc, argv);
  f=lib3ds_file_load(filename);
  if (!f)
  {
    fprintf(stderr, "***ERROR***\nLoading file %s failed\n", filename);
    exit(1);
  }
  if (output)
  {
    dump_m_file(f,output);
  }
  else
  {
    fprintf(stderr, "***ERROR***\nNo output file specified.\n");
    exit(1);
  }

  lib3ds_file_free(f);
  return(0);
}
예제 #10
0
// destructor, free up memory and disable texture generation
Model::~Model()
{
	if(file) // if the file isn't freed yet
		lib3ds_file_free(file); //free up memory
	 //disable texture generation
	for(unsigned int i = 0;i < textureIndices.size();i++)
		glDeleteTextures(1, &textureIndices.at(i));
}
예제 #11
0
파일: m3ds.cpp 프로젝트: anirul/3DStereo
m3ds::~m3ds() {
	if (m_file)
		lib3ds_file_free(m_file);
	s_count--;
	// unload textures
	if (s_count == 0) {
		texlib::release();
	}
}
예제 #12
0
// Destructor
CModel3DS::~CModel3DS()
{
	glDeleteBuffers(1, &m_VertexVBO);
	glDeleteBuffers(1, &m_NormalVBO);
	
	if(m_model != NULL)
	{
		lib3ds_file_free(m_model);
	}
}
예제 #13
0
int main(int argc, char **argv)
{
	Lib3dsFile *f=0;
	FILE	*inputM2,*outputM2;

	if(argc<3)
	{
		printf("3ds To M2 Converter v1.1 (July 29th, 2006)\n");
		printf(" (Original Version July 23rd, 2006)\n");
		printf(" by John \"Cryect\" Rittenhouse\n\n");
		printf(" 3dsToM2 <3ds File Name> <M2 File Name> <Optional Scale>\n");
		return 0;
	}
	
	f=lib3ds_file_load(argv[1]);

	if(!f)
	{
		printf("ERROR: Unable to load 3ds file %s\n",argv[1]);
		return 0;
	}

	outputM2=fopen(argv[2],"wb");
	if(!outputM2)
	{
		printf("ERROR: Unable to open M2 file for writing %s\n",argv[2]);
		lib3ds_file_free(f);
		return 0;
	}
	
	if(argc>3)
		Scale=atof(argv[3]);
	else
		Scale=1;

	convert3ds(outputM2, f);
	fclose(outputM2);
	lib3ds_file_free(f);

	printf("3ds to M2 conversion completed\n");
}
예제 #14
0
파일: 3dsdump.c 프로젝트: 34985086/meshlab
int
main(int argc, char **argv)
{
  Lib3dsFile *f=0;

  parse_args(argc, argv);

  lib3ds_chunk_enable_dump(flags&LIB3DSDUMP_STRUCTURE, flags&LIB3DSDUMP_UNKNOWN);
  f=lib3ds_file_load(filename);
  if (!f) {
    fprintf(stderr, "***ERROR***\nLoading file %s failed\n", filename);
    exit(1);
  }

  if (flags&LIB3DSDUMP_MATERIALS) {
    printf("Dumping materials:\n");
    lib3ds_file_dump_materials(f);
    printf("\n");
  }
  if (flags&LIB3DSDUMP_TRIMESHES) {
    printf("Dumping meshes:\n");
    lib3ds_file_dump_meshes(f);
    printf("\n");
  }
  if (flags&LIB3DSDUMP_INSTANCES) {
    printf("Dumping instances:\n");
    lib3ds_file_dump_instances(f);
    printf("\n");
  }
  if (flags&LIB3DSDUMP_CAMERAS) {
    printf("Dumping cameras:\n");
    lib3ds_file_dump_cameras(f);
    printf("\n");
  }
  if (flags&LIB3DSDUMP_LIGHTS) {  
    printf("Dumping lights:\n");
    lib3ds_file_dump_lights(f);
    printf("\n");
  }
  if (flags&LIB3DSDUMP_NODES) {
    printf("Dumping node hierarchy:\n");
    lib3ds_file_dump_nodes(f);
    printf("\n");
  }
  if (output && (flags&LIB3DSDUMP_WRITE_3DS)) {
    if (!lib3ds_file_save(f, output)) {
      printf("***ERROR**** Writing %s\n", output);
    }
  }

  lib3ds_file_free(f);
  return(0);
}
예제 #15
0
파일: 3ds2rib.c 프로젝트: Neoniet/upspring
int
main(int argc, char **argv)
{
  Lib3dsFile *f=0;
  FILE *o;

  parse_args(argc, argv);
  f=lib3ds_file_load(filename);
  if (!f) {
    fprintf(stderr, "***ERROR***\nLoading file %s failed\n", filename);
    exit(1);
  }

  if (output) {
    o=fopen(output, "w+");
    if (!o) {
      fprintf(stderr, "***ERROR***\nCan't open %s for writing\n", output);
      exit(1);
    }
  }
  else {
    o=stdout;
  }

  fprintf(o, "Option \"searchpath\" \"shader\" [\".:../shaders:&\"]\n");
  if (flags&LIB3DS2RIB_ALL) {
    int i;
    for (i=f->segment_from; i<=f->segment_to; ++i) {
      lib3ds_file_eval(f,1.0f*i);
      create_rib(f,o,i);
    }
  }
  else
  if (downcuts) {
    int i;
    int delta=f->segment_to-f->segment_from;
    for (i=0; i<downcuts; ++i) {
      float frame=f->segment_from+1.0f*i*delta/(downcuts-1);
      lib3ds_file_eval(f, frame);
      create_rib(f,o,i);
    }
  }
  else {  
    lib3ds_file_eval(f,frame);
    create_rib(f,o, (int)frame);
  }

  if (o!=stdout) {
    fclose(o);
  }
  lib3ds_file_free(f);
  return(0);
}
예제 #16
0
void Scene::prepareModels()
{
    loadTexturesForModels();

    for ( int i = 0 ; i < models->size() ; i++)
    {
        if( !models->at( i ) ) return;

        models->at( i )->getFaces();
        Lib3dsVector *vertices = new Lib3dsVector[ models->at( i )->totalFaces * 3 ];
        Lib3dsVector *normals = new Lib3dsVector[ models->at( i )->totalFaces * 3 ];
        Lib3dsTexel *texCoords = new Lib3dsTexel[ models->at( i )->totalFaces * 3 ];
        Lib3dsMesh *mesh;

        unsigned int finishedFaces = 0;

        for( mesh = models->at(i)->model->meshes; mesh != NULL ; mesh = mesh->next )
        {
            lib3ds_mesh_calculate_normals( mesh, &normals[ finishedFaces * 3 ] );
            for( unsigned int currentFace = 0; currentFace < mesh->faces ; currentFace++ )
            {
                Lib3dsFace * face = &mesh->faceL[ currentFace ];
                for( unsigned int i = 0; i < 3; i++ )
                {
                    if( &mesh->texelL )
                        memcpy( &texCoords[ finishedFaces*3 + i ], mesh->texelL[ face->points[ i ] ], sizeof( Lib3dsTexel ) );
                    memcpy( &vertices[ finishedFaces * 3 + i ], mesh->pointL[ face->points[ i ] ].pos, sizeof( Lib3dsVector ) );
                }
                finishedFaces++;
            }
        }

        glGenBuffers( 1, &models->at(i)->vertexVBO );
        glBindBuffer( GL_ARRAY_BUFFER, models->at(i)->vertexVBO );
        glBufferData( GL_ARRAY_BUFFER, sizeof( Lib3dsVector ) * 3 * models->at(i)->totalFaces, vertices, GL_STATIC_DRAW );

        glGenBuffers( 1, &models->at(i)->normalVBO );
        glBindBuffer( GL_ARRAY_BUFFER, models->at(i)->normalVBO);
        glBufferData( GL_ARRAY_BUFFER, sizeof( Lib3dsVector ) * 3 * models->at(i)->totalFaces, normals, GL_STATIC_DRAW );

        glGenBuffers( 1, &models->at(i)->texCoordVBO );
        glBindBuffer( GL_ARRAY_BUFFER, models->at(i)->texCoordVBO);
        glBufferData( GL_ARRAY_BUFFER, sizeof( Lib3dsTexel ) * 3 * models->at(i)->totalFaces, texCoords, GL_STATIC_DRAW );

        delete vertices;
        delete normals;
        delete texCoords;

        lib3ds_file_free( models->at(i)->model );
        models->at(i)->model = NULL;
    }
}
예제 #17
0
/**
 * ~Model3DS
 * Destruktor.
 */
Model3DS::~Model3DS() {
	glDeleteBuffers(1, &m_VertexVBO);
	glDeleteBuffers(1, &m_NormalVBO);
	glDeleteBuffers(1, &m_TexCoordVBO);

	if(m_model != NULL) {
		lib3ds_file_free(m_model);
	}
	if (shape != NULL)
	{
		delete shape;
	}

}
예제 #18
0
int main(int argc, char **argv) {
    Lib3dsFile *f;
    parse_args(argc, argv);

    f = lib3ds_file_open(input);
    if (!f) {
        fprintf(stderr, "***ERROR***\nLoading file failed: %s\n", input);
        exit(1);
    }

    if (mtl_file) {
        FILE *mtl = fopen(mtl_file, "wt");
        if (!mtl) {
            fprintf(stderr, "***ERROR***\nCreating output file failed: %s\n", mtl_file);
            exit(1);
        }
        write_mtl(mtl, f);
        fclose(mtl);
    }

    {
        FILE *obj = fopen(obj_file, "wt");
        if (!obj) {
            fprintf(stderr, "***ERROR***\nCreating output file failed: %s\n", obj_file);
            exit(1);
        }

        if (!f->nodes)
            lib3ds_file_create_nodes_for_meshes(f);
        lib3ds_file_eval(f, 0);
        
        fprintf(obj, "# Wavefront OBJ file\n");
        fprintf(obj, "# Converted by 3ds2obj\n");
        fprintf(obj, "# http://www.lib3ds.org\n\n");
        if (mtl_file) {
            fprintf(obj, "mtllib %s\n", mtl_file);
        }

        write_nodes(obj, f, f->nodes);
        fclose(obj);
    }

    lib3ds_file_free(f);
    return 0;
}
예제 #19
0
/*!
 * Loads a .3DS file from disk into memory.
 *
 * \param filename  The filename of the .3DS file
 *
 * \return   A pointer to the Lib3dsFile structure containing the
 *           data of the .3DS file. 
 *           If the .3DS file can not be loaded NULL is returned.
 *
 * \note     To free the returned structure use lib3ds_free.
 *
 * \see lib3ds_file_save
 * \see lib3ds_file_new
 * \see lib3ds_file_free
 *
 * \ingroup file
 */
Lib3dsFile*
lib3ds_file_load(const char *filename)
{
  FILE *f;
  Lib3dsFile *file;
  Lib3dsIo *io;

  f = fopen(filename, "rb");
  if (!f) {
    return(0);
  }
  file = lib3ds_file_new();
  if (!file) {
    fclose(f);
    return(0);
  }
  
  io = lib3ds_io_new(
    f, 
    fileio_error_func,
    fileio_seek_func,
    fileio_tell_func,
    fileio_read_func,
    fileio_write_func
  );
  if (!io) {
    lib3ds_file_free(file);
    fclose(f);
    return(0);
  }

  if (!lib3ds_file_read(file, io)) {
    free(file);
    lib3ds_io_free(io);
    fclose(f);
    return(0);
  }

  lib3ds_io_free(io);
  fclose(f);
  return(file);
}
예제 #20
0
TriMesh *load_mesh(const char *fname, const char *name) {
	TriMesh *mesh = 0;
	
	Lib3dsFile *file = lib3ds_file_load(fname);
	if(file && name) {
		Scene *scene = new Scene;
		load_objects(file, scene);

		Object *obj = scene->get_object(name);
		if(obj) {
			mesh = new TriMesh;
			*mesh = obj->get_mesh();
		}
		lib3ds_file_free(file);
		return mesh;
	}

	mesh = load_mesh_ply(fname);
	return mesh;
}
예제 #21
0
int main(int argc, char **argv)
{
	Lib3dsFile *f = NULL;
	FILE *p;

	parse_args(argc, argv);
	f = lib3ds_file_new();
	
	p = fopen(input, "r");
	if (!p)
	{
		fprintf(stderr, "Cannot open \"%s\" for reading: %s", output, strerror(errno));
		exit(1);
	}
	dump_to_3ds(f, p);
	fclose(p);
	lib3ds_file_free(f);

	return 0;
}
예제 #22
0
파일: 3dsplay.c 프로젝트: kasicass/frustum
/*!
 *
 */
static void
init(void) 
{
  glClearColor(0.5, 0.5, 0.5, 1.0);
  glShadeModel(GL_SMOOTH);
  glEnable(GL_LIGHTING);
  glEnable(GL_LIGHT0);
  glDepthFunc(GL_LEQUAL);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_CULL_FACE);
  glCullFace(GL_BACK);
  //glDisable(GL_NORMALIZE);
  //glPolygonOffset(1.0, 2);


  file=lib3ds_file_load(filename);
  if (!file) {
    puts("***ERROR*** Loading 3DS file failed.");
    exit(1);
  }
  if (!file->cameras) {
    puts("***ERROR*** No Camera found.");
    lib3ds_file_free(file);
    file=0;
    exit(1);
  }
  if (!camera) {
    camera=file->cameras->name;
  }
  camera_menu_id=glutCreateMenu(camera_menu);
  {
    Lib3dsCamera *c;
    int i;
    for (c=file->cameras,i=0; c; c=c->next,++i) {
      glutAddMenuEntry(c->name, i);
    }
  }
  glutAttachMenu(0);

  lib3ds_file_eval(file,0);
}
예제 #23
0
void GLUTCALLBACK OptionMenu(int value)
{
   static GLboolean doppler=GL_TRUE;
   switch(value) {
      case 2:
         doppler=!doppler;
         srelDoppler(doppler);
#ifdef HAVE_GLUTCAVE
         GLUTCAVE_REDISPLAY();
#else
         glutPostRedisplay();
#endif
         break;
      case 3:
#ifdef HAVE_LIB3DS
         if(file)
            lib3ds_file_free(file);
#endif
         exit(0);
         break;
   }
}
예제 #24
0
		CModel3ds(vbcString filename, string texPath)
		{
			_File3ds = lib3ds_file_load(filename.c_str());
			
			if(_File3ds == 0)
			{
				printf("Some problem occured while loading model!\n");
				return;
			}

			_Materials = new CMaterials(_File3ds, texPath);

			unsigned int meshesCount = 0;
			Lib3dsMesh* mesh;
			
			// meshes counting
			for( mesh = _File3ds->meshes; mesh != NULL; mesh = mesh->next )
			{
				meshesCount++;
			}

			_Meshes.reserve(meshesCount);

			// Read all meshes from file			
			for( mesh = _File3ds->meshes; mesh != NULL; mesh = mesh->next )
			{
				CMesh3ds* mesh3ds = new CMesh3ds(mesh, _Materials);
				mesh3ds->loadGeometry();
				
				_Meshes.push_back(mesh3ds);
			}

			if( _File3ds )
			{
				lib3ds_file_free(_File3ds);
				_File3ds = 0;
			}
		}
예제 #25
0
int LD3dsExporter::doExport(LDLModel *pTopModel)
{
	int retVal = 1;
	TCFloat matrix[16];

	TCVector::initIdentityMatrix(matrix);
	matrix[5] = 0.0;
	matrix[6] = -1.0;
	matrix[9] = 1.0;
	matrix[10] = 0.0;
	m_topModel = pTopModel;
    m_file = lib3ds_file_new();
	m_names.clear();
	m_meshes.clear();
	m_meshCount = 0;
	doExport(pTopModel, NULL, matrix, 7, false, true, false);
	//if (m_includeCamera)
	//{
	//	Lib3dsCamera *pCamera = lib3ds_camera_new("Default");
	//	Lib3dsCameraNode *pCameraNode;
	//	TCVector cameraLoc(m_camera.getPosition().transformPoint(matrix));

	//	pCamera->position[0] = cameraLoc[0];
	//	pCamera->position[1] = cameraLoc[1];
	//	pCamera->position[2] = cameraLoc[2];
	//	pCamera->fov = m_fov;
	//	pCameraNode = lib3ds_node_new_camera(pCamera);
	//	lib3ds_file_append_node(m_file, (Lib3dsNode *)pCameraNode, NULL);
	//}
	if (!lib3ds_file_save(m_file, m_filename.c_str()))
	{
		retVal = 0;
	}
	lib3ds_file_free(m_file);
	return retVal;
}
예제 #26
0
파일: model.cpp 프로젝트: zanneth/ZGE
ZModel::ZModel(std::string filename) :
    _faces_count(0),
    _vertices_count(0),
    _render_mode(ZRENDER_MODE_TRIANGLES)
{
    ZRenderContext *ctx = ZRenderContext::get_current_context();
    zassert(ctx, "invalid context");

    _vertex_array = ctx->create_vertex_array();
    _vertex_vbo = ctx->create_graphics_buffer();
    _normal_vbo = ctx->create_graphics_buffer();

    ZBufferAttribute vertex_attrib = {
        .components_per_vertex = 3,
        .component_type = ZCOMPONENT_TYPE_FLOAT,
        .normalized = false,
        .stride = 0,
        .offset = 0
    };
    _vertex_vbo->add_attribute(vertex_attrib);

    ZBufferAttribute normal_attrib = {
        .components_per_vertex = 3,
        .component_type = ZCOMPONENT_TYPE_FLOAT,
        .normalized = false,
        .stride = 0,
        .offset = 0
    };
    _normal_vbo->add_attribute(normal_attrib);

    _vertex_array->add_buffer(_vertex_vbo, ZVERTEX_ATTRIB_POSITION);
    _vertex_array->add_buffer(_normal_vbo, ZVERTEX_ATTRIB_NORMAL);

    if (filename.length()) {
        load_file(filename);
    }
}

ZGeometryRef ZModel::copy() const
{
    return std::make_shared<ZModel>(*this);
}

#pragma mark - Loading from Files

void ZModel::load_file(std::string filename)
{
    Lib3dsFile *model_file = lib3ds_file_load(filename.c_str());
    if (!model_file) {
        ZException e(ZFILE_EXCEPTION_CODE);
        e.extra_info = "Unable to load file " + filename;
        throw e;
    }

    if (model_file->meshes == nullptr) {
        ZException e(ZENGINE_EXCEPTION_CODE);
        e.extra_info = "Model file " + filename + " contains no meshes.";
        throw e;
    }

    // load information about the model
    _name = model_file->name;

    size_t total_faces = 0;
    size_t total_vertices = 0;
    std::vector<std::array<float, 3>> vertices;
    std::vector<std::array<float, 3>> normals;

    // copy data for each mesh from model file
    Lib3dsMesh *mesh = model_file->meshes;
    do {
        size_t mesh_faces_count = mesh->faces;
        size_t mesh_vertices_count = mesh->points;

        float (*calculated_normals)[3] = new float[mesh_faces_count * 3][3];
        lib3ds_mesh_calculate_normals(mesh, calculated_normals);

        unsigned cur_normals_idx = 0;
        for (unsigned j = 0; j < mesh_faces_count; ++j) {
            Lib3dsFace *face = &mesh->faceL[j];
            for (unsigned k = 0; k < 3; ++k) {
                vertices.push_back(__copy_vertex_data<float, 3>(mesh->pointL[face->points[k]].pos));
                normals.push_back(__copy_vertex_data<float, 3>(calculated_normals[cur_normals_idx++]));
            }
        }

        total_faces += mesh_faces_count;
        total_vertices += mesh_vertices_count;
        delete [] calculated_normals;
    } while ((mesh = mesh->next));

    // load data into each VBO
#define VEC_ARR_DATA_SZ(vec) (vec.size() * 3 * sizeof(decltype(vec)::value_type::value_type))
    ZBufferUsage static_draw = { ZBUFFER_USAGE_FREQUENCY_STATIC, ZBUFFER_USAGE_NATURE_DRAW };
    _vertex_vbo->load_data(vertices.data(), VEC_ARR_DATA_SZ(vertices), static_draw);
    _normal_vbo->load_data(normals.data(), VEC_ARR_DATA_SZ(normals), static_draw);

    _faces_count = total_faces;
    _vertices_count = total_vertices;

    lib3ds_file_free(model_file);
}

#pragma mark - Accessors

std::string ZModel::get_name() const {
    return _name;
}
ZRenderMode ZModel::get_render_mode() const {
    return _render_mode;
}
void ZModel::set_render_mode(ZRenderMode mode) {
    _render_mode = mode;
}

#pragma mark - Drawing

void ZModel::render(ZRenderContextRef context)
{
    ZGeometry::render(context);

    context->set_depth_testing_enabled(true);
    context->draw_array(_render_mode, _vertex_array, 0, _faces_count * 3);
    context->set_depth_testing_enabled(false);
}
예제 #27
0
int
main(int argc, char **argv) {
    FILE *file;
    Lib3dsFile *f = 0;
    Lib3dsIo io;
    int result;
    int i;

    parse_args(argc, argv);

    file = fopen(filename, "rb");
    if (!file) {
        fprintf(stderr, "***ERROR***\nFile not found: %s\n", filename);
        exit(1);
    }

    f = lib3ds_file_new();

    memset(&io, 0, sizeof(io));
    io.self = file;
    io.seek_func = fileio_seek_func;
    io.tell_func = fileio_tell_func;
    io.read_func = fileio_read_func;
    io.write_func = fileio_write_func;
    io.log_func = fileio_log_func;

    result =  lib3ds_file_read(f, &io);

    fclose(file);

    if (!result) {
        fprintf(stderr, "***ERROR***\nLoading file failed: %s\n", filename);
        exit(1);
    }

    if (flags & LIB3DSDUMP_MATERIALS) {
        printf("Dumping materials:\n");
        for (i = 0; i < f->nmaterials; ++i) material_dump(f->materials[i]);
        printf("\n");
    }
    if (flags & LIB3DSDUMP_TRIMESHES) {
        printf("Dumping meshes:\n");
        for (i = 0; i < f->nmeshes; ++i) mesh_dump(f->meshes[i]);
        printf("\n");
    }
    if (flags & LIB3DSDUMP_INSTANCES) {
        Lib3dsNode *p;
        printf("Dumping instances:\n");
        for (p = f->nodes; p != 0; p = p->next) {
            dump_instances(p, "");
        }
        printf("\n");
    }
    if (flags & LIB3DSDUMP_CAMERAS) {
        printf("Dumping cameras:\n");
        for (i = 0; i < f->ncameras; ++i) camera_dump(f->cameras[i]);
        printf("\n");
    }
    if (flags & LIB3DSDUMP_LIGHTS) {
        printf("Dumping lights:\n");
        for (i = 0; i < f->nlights; ++i) light_dump(f->lights[i]);
        printf("\n");
    }
    if (flags & LIB3DSDUMP_NODES) {
        Lib3dsNode *p;
        printf("Dumping node hierarchy:\n");
        for (p = f->nodes; p != 0; p = p->next) {
            node_dump(p, 1);
        }
        printf("\n");
    }
    if (output) {
        if (!lib3ds_file_save(f, output)) {
            printf("***ERROR**** Writing %s\n", output);
        }
    }

    lib3ds_file_free(f);
    return 0;
}
예제 #28
0
    /*!
     * See \ref Loader3ds::loadFromFileToOneMesh
     */
    dcollide::Mesh* Loader3dsInternal::loadFromFileToOneMesh(const char* fileName, TextureInformation* textureInformation) {
        // AB:
        // we cannot load texture information here, because we are merging all
        // meshes into a single one.
        // -> adjusting the texels may still be possible, however if the model
        //    uses > 1 texture, we can't change that.

        mData->mProxy2Transformation.clear();
        mData->mProxy2TextureInformation.clear();
        if (!fileName) {
            throw dcollide::NullPointerException("fileName");
        }

        mFile = lib3ds_file_load(fileName);
        if (!mFile) {
            std::cout << dc_funcinfo << "unable to load " << fileName << std::endl;
            return 0;
        }

        // AB: some files don't store nodes and just want exactly one node per mesh.
        //     atm we don't support that.
        if (!mFile->nodes) {
            std::cout << dc_funcinfo << "File " << fileName << " does not contain any nodes. mesh-only files not supported currently." << std::endl;
            lib3ds_file_free(mFile);
            mFile = 0;
            return 0;
        }

        // 3ds stores several frames, we want the first
        lib3ds_file_eval(mFile, 0);

        std::list<Lib3dsNode*> nodes;
        Lib3dsNode* node = mFile->nodes;
        while (node) {
            nodes.push_back(node);
            node = node->next;
        }

        bool texelLoadError = false;
        std::vector<dcollide::Vector3> texels;
        std::vector<dcollide::Vertex*> vertices;
        std::vector<dcollide::Triangle*> triangles;
        std::vector<int> indices;
        while (!nodes.empty()) {
            Lib3dsNode* node = nodes.front();
            nodes.pop_front();

            for (Lib3dsNode* n = node->childs; n; n = n->next) {
                nodes.push_back(n);
            }

            // node->type can be object, light, camera, ...
            // -> only object nodes are relevant to us
            if (node->type != LIB3DS_OBJECT_NODE) {
                continue;
            }

            if (strcmp(node->name, "$$$DUMMY") == 0) {
                // AB: nodes with this name are only transformation nodes, i.e. they
                // don't have a mesh, only a matrix.
                continue;
            }

            unsigned int pointOffset = vertices.size();

            Lib3dsMesh* mesh = lib3ds_file_mesh_by_name(mFile, node->name);
            Lib3dsMatrix origMeshMatrix;
            lib3ds_matrix_copy(origMeshMatrix, mesh->matrix);
            lib3ds_matrix_inv(origMeshMatrix); // 3ds stores inverted mesh matrix
            dcollide::Matrix meshMatrix(&origMeshMatrix[0][0]);
            dcollide::Matrix nodeMatrix(&node->matrix[0][0]);

            Lib3dsObjectData* data = &node->data.object;
            nodeMatrix.translate(dcollide::Vector3(-data->pivot[0], -data->pivot[1], -data->pivot[2]));

            dcollide::Matrix matrix = nodeMatrix;
            matrix.multiply(&meshMatrix);

            for (unsigned int i = 0; i < mesh->points; i++) {
                Lib3dsPoint* p = &mesh->pointL[i];
                dcollide::Vector3 pos;
                matrix.transform(&pos, dcollide::Vector3(
                            p->pos[0],
                            p->pos[1],
                            p->pos[2]
                            ));
                vertices.push_back(new dcollide::Vertex(pos));
            }

            for (unsigned int i = 0; i < mesh->faces; i++) {
                Lib3dsFace* f = &mesh->faceL[i];
                indices.push_back(f->points[0] + pointOffset);
                indices.push_back(f->points[1] + pointOffset);
                indices.push_back(f->points[2] + pointOffset);
            }

            if (textureInformation) {
                TextureInformation t = loadTextureInformation(node);
                const std::vector<dcollide::Vector3>& nodeTexels = t.getTexels();
                if (mesh->texelL && nodeTexels.size() != mesh->texels) {
                    dcollide::warning() << "texturing problem in " << fileName;
                    dcollide::warning() << "invalid texel count loaded: have=" << nodeTexels.size() << " expected=" << mesh->texels;
                    dcollide::warning() << "adding dummy texels...";
                    for (unsigned int i = 0; i < mesh->texels; i++) {
                        texels.push_back(dcollide::Vector3(0.0, 0.0, 0.0));
                    }
//                    texelLoadError = true;
                } else {
                    for (unsigned int i = 0; i < nodeTexels.size(); i++) {
                        texels.push_back(nodeTexels[i]);
                    }
                }
            }
        }

        if (textureInformation) {
            if (!texelLoadError) {
                textureInformation->setTextured(true);
                textureInformation->setTextureFileName("deformable.tga");
                textureInformation->setTexels(texels);
            } else {
                textureInformation->setTextured(false);
            }
        }

        lib3ds_file_free(mFile);
        mFile = 0;

        dcollide::Mesh* mesh = new dcollide::Mesh(vertices, indices);
        return mesh;
    }
예제 #29
0
 Loader3dsInternal::~Loader3dsInternal() {
     if (mFile) {
         lib3ds_file_free(mFile);
         mFile = 0;
     }
 }
예제 #30
0
파일: 3dsplay.c 프로젝트: gdh1995/GhostFace
/*!
* Load the model from .3ds file.
*/
static void
load_model(void)
{
  file=lib3ds_file_load(filepath);
  if (!file) {
    puts("3dsplayer: Error: Loading 3DS file failed.\n");
    exit(1);
  }

  /* No nodes?  Fabricate nodes to display all the meshes. */
  if( !file->nodes )
  {
    Lib3dsMesh *mesh;
    Lib3dsNode *node;

    for(mesh = file->meshes; mesh != NULL; mesh = mesh->next)
    {
      node = lib3ds_node_new_object();
      strcpy(node->name, mesh->name);
      node->parent_id = LIB3DS_NO_PARENT;
      lib3ds_file_insert_node(file, node);
    }
  }

  lib3ds_file_eval(file, 1.0f);
  lib3ds_file_bounding_box_of_nodes(file, LIB3DS_TRUE, LIB3DS_FALSE, LIB3DS_FALSE, bmin, bmax);
  sx = bmax[0] - bmin[0];
  sy = bmax[1] - bmin[1];
  sz = bmax[2] - bmin[2];
  size = MAX(sx, sy); size = MAX(size, sz);
  cx = (bmin[0] + bmax[0])/2;
  cy = (bmin[1] + bmax[1])/2;
  cz = (bmin[2] + bmax[2])/2;


  /* No cameras in the file?  Add four */

  if( !file->cameras ) {

    /* Add some cameras that encompass the bounding box */

    Lib3dsCamera *camera = lib3ds_camera_new("Camera_X");
    camera->target[0] = cx;
    camera->target[1] = cy;
    camera->target[2] = cz;
    memcpy(camera->position, camera->target, sizeof(camera->position));
    camera->position[0] = bmax[0] + 1.5 * MAX(sy,sz);
    camera->near_range = ( camera->position[0] - bmax[0] ) * .5;
    camera->far_range = ( camera->position[0] - bmin[0] ) * 2;
    lib3ds_file_insert_camera(file, camera);

    /* Since lib3ds considers +Y to be into the screen, we'll put
    * this camera on the -Y axis, looking in the +Y direction.
    */
    camera = lib3ds_camera_new("Camera_Y");
    camera->target[0] = cx;
    camera->target[1] = cy;
    camera->target[2] = cz;
    memcpy(camera->position, camera->target, sizeof(camera->position));
    camera->position[1] = bmin[1] - 1.5 * MAX(sx,sz);
    camera->near_range = ( bmin[1] - camera->position[1] ) * .5;
    camera->far_range = ( bmax[1] - camera->position[1] ) * 2;
    lib3ds_file_insert_camera(file, camera);

    camera = lib3ds_camera_new("Camera_Z");
    camera->target[0] = cx;
    camera->target[1] = cy;
    camera->target[2] = cz;
    memcpy(camera->position, camera->target, sizeof(camera->position));
    camera->position[2] = bmax[2] + 1.5 * MAX(sx,sy);
    camera->near_range = ( camera->position[2] - bmax[2] ) * .5;
    camera->far_range = ( camera->position[2] - bmin[2] ) * 2;
    lib3ds_file_insert_camera(file, camera);

    camera = lib3ds_camera_new("Camera_ISO");
    camera->target[0] = cx;
    camera->target[1] = cy;
    camera->target[2] = cz;
    memcpy(camera->position, camera->target, sizeof(camera->position));
    camera->position[0] = bmax[0] + .75 * size;
    camera->position[1] = bmin[1] - .75 * size;
    camera->position[2] = bmax[2] + .75 * size;
    camera->near_range = ( camera->position[0] - bmax[0] ) * .5;
    camera->far_range = ( camera->position[0] - bmin[0] ) * 3;
    lib3ds_file_insert_camera(file, camera);
  }


  /* No lights in the file?  Add some. */

  if (file->lights == NULL)
  {
    Lib3dsLight *light;

    light = lib3ds_light_new("light0");
    light->spot_light = 0;
    light->see_cone = 0;
    light->color[0] = light->color[1] = light->color[2] = .6;
    light->position[0] = cx + size * .75;
    light->position[1] = cy - size * 1.;
    light->position[2] = cz + size * 1.5;
    light->position[3] = 0.;
    light->outer_range = 100;
    light->inner_range = 10;
    light->multiplier = 1;
    lib3ds_file_insert_light(file, light);

    light = lib3ds_light_new("light1");
    light->spot_light = 0;
    light->see_cone = 0;
    light->color[0] = light->color[1] = light->color[2] = .3;
    light->position[0] = cx - size;
    light->position[1] = cy - size;
    light->position[2] = cz + size * .75;
    light->position[3] = 0.;
    light->outer_range = 100;
    light->inner_range = 10;
    light->multiplier = 1;
    lib3ds_file_insert_light(file, light);

    light = lib3ds_light_new("light2");
    light->spot_light = 0;
    light->see_cone = 0;
    light->color[0] = light->color[1] = light->color[2] = .3;
    light->position[0] = cx;
    light->position[1] = cy + size;
    light->position[2] = cz + size;
    light->position[3] = 0.;
    light->outer_range = 100;
    light->inner_range = 10;
    light->multiplier = 1;
    lib3ds_file_insert_light(file, light);

  }

  if (!file->cameras) {
    fputs("3dsplayer: Error: No Camera found.\n", stderr);
    lib3ds_file_free(file);
    file=0;
    exit(1);
  }
  if (!camera) {
    camera=file->cameras->name;
  }

  lib3ds_file_eval(file,0.);
}