3D模型读取库:Assimp

Assimp(Open Asset Import Library)是一个支持读取多种模型资源的开源库,当前最新的版本是3.0版,支持读取以下类型的3D模型:

https://github.com/assimp/assimp

https://github.com/assimp/assimp-net

Open Asset Import Library is a library to load various 3d file formats into a shared, in-memory format. It supports more than40 file formats for import and a growing selection of file formats for export.

APIs are provided for C and C++. There are various bindings to other languages (C#, Java, Python, Delphi, D). Assimp also runs on Android and iOS.

Additionally, assimp features various mesh post processing tools: normals and tangent space generation, triangulation, vertex cache locality optimization, removal of degenerate primitives and duplicate vertices, sorting by primitive type, merging of redundant materials and many more.

This is the development trunk containing the latest features and bugfixes. For productive use though, we recommend one of the stable releases available fromassimp.sf.net or from *nix package repositories.The current build status is:

Linux Linux Build StatusWindowsWindows Build StatusCoverityCoverity Scan Build Status

open3mod is a powerful 3D model viewer based on Assimp's import and export abilities.

Supported file formats

A full list is here.Importers:

  • 3DS
  • BLEND (Blender)
  • DAE/Collada
  • FBX
  • IFC-STEP
  • ASE
  • DXF
  • HMP
  • MD2
  • MD3
  • MD5
  • MDC
  • MDL
  • NFF
  • PLY
  • STL
  • X
  • OBJ
  • OpenGEX
  • SMD
  • LWO
  • LXO
  • LWS
  • TER
  • AC3D
  • MS3D
  • COB
  • Q3BSP
  • XGL
  • CSM
  • BVH
  • B3D
  • NDO
  • Ogre Binary
  • Ogre XML
  • Q3D
  • ASSBIN (Assimp custom format)

Additionally, some formats are supported by dependency on non-free code or external SDKs (not built by default):

Exporters:

Building

Take a look into the INSTALL file. Our build system is CMake, if you used CMake before there is a good chance you know what to do.

Repository structure

Open Asset Import Library is implemented in C++. The directory structure is:

/code       Source code
/contrib    Third-party libraries
/doc        Documentation (doxysource and pre-compiled docs)
/include    Public header C and C++ header files
/scripts    Scripts used to generate the loading code for some formats
/port       Ports to other languages and scripts to maintain those.
/test       Unit- and regression tests, test suite of models
/tools      Tools (old assimp viewer, command line `assimp`)
/samples    A small number of samples to illustrate possible 
                    use cases for Assimp
/workspaces Build enviroments for vc,xcode,... (deprecated,
        CMake has superseeded all legacy build options!)

Where to get help

For more information, visit our website. Or check out the ./doc- folder, which contains the official documentation in HTML format.(CHMs for Windows are included in some release packages and should be located right here in the root folder).

If the docs don't solve your problem, ask on StackOverflow. If you think you found a bug, please open an issue on Github.

For development discussions, there is also a (very low-volume) mailing list, assimp-discussions (subscribe here)


此外还支持对导入的模型做一些常用的处理,如把四边形转换为三角形、计算切线和副法线、将大模型分割为小模型等。

Assimp的主页:http://assimp.sourceforge.net/index.html

 

读取模型文件的一个例子:

复制代码
#include <assimp/Importer.hpp>      // 导入器在该头文件中定义
#include <assimp/scene.h>           // 读取到的模型数据都放在scene中
#include <assimp/postprocess.h>     // 该头文件中包含后处理的标志位定义

bool Import( const std::string& pFile) 
{   
    // 定义一个导入器 
    Assimp::Importer importer;   
    
    // 使用导入器导入选定的模型文件 
    const aiScene* scene = importer.ReadFile( pFile,
        aiProcess_CalcTangentSpace|            //后处理标志,自动计算切线和副法线
        aiProcess_Triangulate|                //后处理标志,自动将四边形面转换为三角面
        aiProcess_JoinIdenticalVertices|    //后处理标志,自动合并相同的顶点
        aiProcess_SortByPType);                //后处理标志,将不同图元放置到不同的模型中去,图片类型可能是点、直线、三角形等
                                            //更多后处理标志可以参考Assimp的文档  
    if( !scene)   
    {
        //导入错误,获取错误信息并进行相应的处理
        //DoTheErrorLogging( importer.GetErrorString());     
        return false;  
    }   
    // 根据需要获取scene中的模型数据,各种数据的获取方式可以参考Assimp的文档
    //DoTheSceneProcessing( scene);   
 
    return true; 
}

Assimp.Net是Assimp的一个封装,使用P/Invoke与Assimp库进行交互,Api可以分为两类:

(1) 一组低级函数,表达Assimp的C-API,它是使用AssimpMethods的静态类,这是一个P/Invoke层,需要你从unmanageable memory中整理模型数据,这些在Assimp.Unmanaged命名空间中。“Unmanaged”结构使用“Ai”作为前缀,其中的IntPtrs指向unmageged data。

(2)一组高级函数,dotNet API用来加载模型,在manageable memory中整理数据,并访问数据。这种数据结构在命名方式和组织上非常类似于Assimp数据结构,而且更便于DotNet开发人员使用。

高级层就像Assimp的C++ API,低级层就是允许用户做任何想做的事情(如把unmanaged data直接加载到他们自创的数据结构中)。

输入模型

在Assimp.net中使用的主要类是Assimp Importer,每个import实例都可以单独考虑,所有的配置与日志流只绑定与特定的实例,这个过程把一个import作为一个原子调用,Configs/Logging streams是在模型improted之前,removed之后设置的,当模型加载到managed memory,后,unmanaged Assimp 数据结构就会释放。总之,用户不需要操心这些细节。

示例代码:

[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. using System;  
  2. using System.IO;  
  3. using System.Reflection;  
  4. using Assimp;  
  5. using Assimp.Configs;  
  6.   
  7. namespace Example {  
  8.     class Program {  
  9.         static void Main(string[] args) {  
  10.             //Filepath to our model  
  11.             String fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Seymour.dae");  
  12.   
  13.             //Create a new importer  
  14.             AssimpImporter importer = new AssimpImporter();  
  15.   
  16.             //This is how we add a configuration (each config is its own class)  
  17.             NormalSmoothingAngleConfig config = new NormalSmoothingAngleConfig(66.0f);  
  18.             importer.SetConfig(config);  
  19.   
  20.             //This is how we add a logging callback   
  21.             LogStream logstream = new LogStream(delegate(String msg, String userData) {  
  22.                 Console.WriteLine(msg);  
  23.             });  
  24.             importer.AttachLogStream(logstream);  
  25.   
  26.             //Import the model - this is considered a single atomic call. All configs are set, all logstreams attached. The model  
  27.             //is imported, loaded into managed memory. Then the unmanaged memory is released, and everything is reset.  
  28.             Scene model = importer.ImportFile(fileName, PostProcessPreset.TargetRealTimeMaximumQuality);  
  29.   
  30.             //Load the model data into your own structures  
  31.   
  32.             //End of example  
  33.             importer.Dispose();  
  34.         }  
  35.     }  
  36. }  
下载地址:https://code.google.com/p/assimp-net/downloads/detail?name=AssimpNet-3.2.zip

Dynamic-Link Library Search Order

http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586%28v=vs.85%29.aspx#standard_search_order_for_desktop_applications

Assimp Namespace中的类

Animation

有多个节点的关键帧的一个动画,对于每个受到动画影响的节点,都会给定一系列分开的数据。

AnimationBehaviour

定义一个animation channel 表现定义时间范围之外的行为,这对应于动画节点的状态前和状态后。

AsssimpException

AssimpNet一般的exception

AssimpImporter

Assimp importer会使用Assimp加载模型到托管内存中

BlendeMode

定义alpha blending标志,像素的最终颜色怎么计算,基于下面的公式:

sourceColor*sourceBlend+destColor*destBlend

destColor是帧缓存之前的颜色,sourceColor是透明计算之前的材料颜色。此项对应于AI_MATKEY_BLEND_FUNC属性

Bone

表示 一块骨头的网格,一块骨头有一个名字,以便在帧结构中找到,动画也可以用它寻址。另外它对顶点还有很多影响。

Camera

描述在scene中的一个右手系相机。重要的是相机本身也是scenegraph中一部分,意味着任何一个值如方向向量不是绝对的,它们都相对于由节点定义的坐标系。

Color3D

表示一个RGB颜色

Color4D

表示一个Red-Green-Blue-Alpha(RGBA)颜色,值范围在0到1.

CompileFlags

枚举本地的Assimp DLL怎么编译

CompressedTexture

表示一个压缩嵌入式纹理。

ConsoleLogStream

把消息写到控制台的日志流

DefaultLogStream

枚举预定义的日志流的目的地

ExcludeComponent

枚举使用后处理RemoveComponent中得到的可以从输入中排除的网格数据或一个scene中一部分

ExportDataBlob

描述输出scene数据中的一个blob,Blob可以nested-每个blob可能引用另一个blob,而这个blob可能又引用另一个,……。这用来允许exporter对于一个给定的scene写多于一个输出。

ExportFormatDescription

描述Assimp可以输出的文件格式

Face

网格中的一个face,引用多个顶点。如是引用3个,那就是三角形。如果多于3个,就是多边形。如果在输入中使用SortByPrimitiveType标志,那么系统那么每个mesh will be homogenous where primitive type is concerned。

FileIOMode

定义打开一个文件时使用的I/O模式。

FileIOSystem

在硬盘上搜索文件的IOSystem的一个简单实现。在使用Assimp给出的文件路径前,可以先传给它若干搜索目录用于尝试定位文件。通过这种方式可以加载一个文件分散在很多目录模型。

IOStream

定义一个流用于文件的输入输出。这个类用于负责Assimp使用的数据的读写。

IOSystem

定义一个IO handler,它可以注册到Assimp处理IO的 importer中。这包括在输入期间搜索、打开文件和在输出时创建、写文件。

Light

描述一个scene中的光源,Assimp支持多个光源,包括Spot、point和directional光源。

LightSourceType

枚举所有支持的光源

LoggingCallback

Assimp的日志流回调代理

LogStream

表示一个日志流,它接收所有的日场信息,并把这些信息输出到其他处

Material

包含了描述怎么渲染一个mesh的所有信息。如纹理、颜色和渲染状态。在内部所有信息都存储为键-值对属性。

MaterialProperty

一个键-值对表示某些材料属性

Matrix3x3

描述一个3x3矩阵

Matrix4x4

表示一个4x4矩阵,第4列表一些变化(这是一个齐次坐标)

MemoryHelper

辅助表态类,包含的函数用于辅助处理非托管内存到托管内存的转换

Mesh

一个mesh表示只有一material的几何

MeshAnimationAttachment

一个mesh attachment保存一个特殊frame的每个顶点的animations。

MeshAnimationChannel

为一个mesh或一组mesh描述基于顶点的animations。

MeshKey

Bind的一个anim mesh到时间中一个特殊的点

Node

在输入模型结构中的一个节点

NodeAnimationChannel

描述一个node的animation

Origin

对于Assimp的虚拟文件系统API,寻找起点。

Plane

表示一个三维欧拉坐标系中的平面

PostProcessPreset

表态类,包含后处理选项中的预设属性

PostProcessSteps

后处理标志选项,指定一些步骤用于后处理

PrimitiveType

枚举几何基本类型

PropertyType

定义材料属性类型

Quaternion

一个表示旋转的4D向量

QuaterniionKey

指定给定时间内的旋转的时间-值对

Ray

定义一个3D光线,有原点和方向

RetureCode

枚举Assimp函数的返回代码

Scene

表示一个完整的输入模型或scene

SceneFlags

定义输入scene数据结构的状态

ShadingMode

定义库支持的所有shading models

Texel

表示一个texel ,格式:ARGB8888

Texture

表示一个嵌入的纹理。

TextureFlags

对于一些特殊的纹理定义了一些混合的标志,这对应于AI_MAT_KEY_TEXFLAGS属性。

TextureMapping

定义纹理的坐标怎么生成。

TextureOperation

定义一个特殊类型的第N个纹理怎么和之前所有层组合。

TextureSlot

描述一个material中的一个特殊纹理slot的所有值。

TextureType

定义纹理的目的。

TextureWrapMode

定义UV坐标如果超出[0..1]范围怎么处理

UncompressedTexture

表示一个未压缩的嵌入纹理

UVTransform

定义一个UV channel怎么变化

UVTransformFlags

定义UV坐标应当怎么变换

Vector2D

表示一个2维的向量

Vector3D

表示一个3维的向量

VectorKey

时间-值对,在一个给定的时间指定一个3D向量

VertexWeight

Represents a single influence of a bone on a vertex

Assimp.Config命名空间中的类

ACEvaluteSubdivisionConfig

配置AC loader是否估计subdivision surface。默认Assimp使用Catmull-Clark算法进行subdivsion。默认值是true

ACSeparateBackfaceCullConfig

配置AC loader从separate meshes中收集有“Backface cull”标记的surfaces。默认值是true

AnimationAccuracyConfig

为FindInvalidData步骤进行配置,specify the floating point accuracy for animation values.

ASEReconstructNormalsConfig

配置ASE loader一直从装载的文件中重建法向量,有些ASE文件中法向量是不正确的。默认值是true

BooleanPropertyConfig

描述一个布尔的配置属性

DeboneAllOrNoneConfig

Configuration that requires all bones to qualify for deboning before any are removed

DeboneThresholdConfig

配置Debone的阈值用于定义什么样的bones要被移除。

FavorSpeedConfig

配置Assimp的建议速度用于输入模型,开启这个选项不一定能加快装载,它只是告诉loader和post-process使用更快的代码。默认值是false

FloatPropertyConfig

定义一个float的配置属性

GlobalKeyFrameImportConfig

Sets the vertex animation keyframe to be imported

IFCSkipCurveShapesConfig

指定IFC loader是否跳过“Curve2D”类型的重新表示。

IFCUseCustomTriangulationConfig

指定IFC loader是否使用它自己的三角形算法和三角化wall和floor mesh。

IntergerPorpertyConfig

描述一个整数的配置属性

IRRAnimationFrameRateConfig

Defines the output frame rate of the IRR loader.

KeepSceneHierarchyConfig

为PreTransformVertices步骤进行配置,以保持scene结构。

LWOIMportOneLayerConfig

配置LWO loader从模型中只加载一层。

LWSAnimationEndConfig

Define the ending of the time range for which the LWS loader evaluates animations and comoputes AiNodeAnim's. The default value if the one taken from the file

LWSAnimationStartConfig

Defines the beginning of the time range for which the LWS loader evaluates animations and computes AiNodeAnim's. The default value is the one taken from the file.

MaterialExcludeListConfig

为RemoveRedunantMaterials步骤配置以确定保存什么材料。

MaxBoneCountConfig

为SplitByBoneCount步骤配置每个mesh的最大bone数,当mesh中的bones数大于此值时就会被split。

MD2KeyFrameImportConfig

Sets the vertex animation keyframe to be imported

MD3HandleMultiPartConfig

配置M3D loader检测和处理多个部分的Quake player 模型。

MD3KeyFrameImportConfig

Sets the vertex animation keyframe to be imported

MD3ShaderSourceConfig

指定Quake3 shader文件用于特殊的MD3文件。

MD3SkinNameConfig

告诉MD3 loader加载哪个skin files

MD5NoAnimationAutoLoadConfig

配置MD5 loader在加载MD5MESH文件时不要自动加载MD5ANIM文件

MDLColorMapConfig

配置设置colormap(paletter)用于装饰嵌入纹理

MDLKeyFrameImportConfig

Sets the vertex animation keyframe to be imported.

MeasureTimeConfig

配置开启时间测量,如果开启,加载过程的每一部分都会计算和记入日志

MeshTriangleLimitConfig

为SplitLargeMeshes步骤中配置一个mesh可以包含的最多triangle,

MeshVertexLimtConfig

为SplitLargeMesh步骤中配置一个mesh中vertices最大数,

MultithreadingConfig

配置Assimp的多线程策略,-1表示让Assimp自己判断,0表示不使用多线程,其他大于0表示使用的线程数

NodeExcludeListConfig

为OptimizeGraph步骤配置用于保存匹配给定列表中名子的nodes

NormalizeVertexComponetsConfig

为PreTransformVertices步骤配置标准化所有vertex部分到-1...1之间。

NormalSmoothingAngleConfig

Configuration to set the maximum angle between two face normals at a vertex when they are smoothed during the step to calculate smooth normals. This is frequently called the "crease angle". The maximum and default value is 175 degrees.

OgreMaterialFileConfig

Ogre importer会试着加载这个MaterialFile,

OgreTextureTypeFromFilenameConfig

Ogre importer 会试着从文件名称中检测纹理的用法

PropertyConfig

基本的属性设置

RemoveComponetConfig

为RemoveComponet步骤配置数据结构中的哪一部分应该移除。

RemoveDegeneratePrimitivesConfig

Configuration for the FindDegenerates step to remove degenerted primitives from the import immediately. The default value is false, where degenerated triangles are converted to lines, and degenerated lines to points.

SMDKeyFrameImportConfig

Sets the vertex animation keyframe to be imported. Assimp does not support vertex keyframes (only bone animation is supported). the library reads only one keyframe with vertex animations. By default this is the first frame. This config sets the global override for the SMD format.

SortByPrimitiveTypeConfig

为SortByPrimitiveType步骤中配置指定在此步骤中哪类基本类型应当移除。

StringPropertyConfig

描述一个string的配置属性

TangentSmoothingAngleConfig

Configuration to set the maximum angle that may be between two vertex tangents/bitangents when they are smoothed during the step to calculate the tangent basis. The default value is 45 degrees.

TangentTextureChannelIndexConfig

Configures which texture channel is used for tangent space computations. The channel must exist or an error will be raised.

TerragenComputeTexCoordsConfig

Configures the terragen import plugin to compute UV's for terrains, if they are not given. Furthermore, a default texture is assigned. The default value is false.

UV coordinates for terrains are so simple to compute that you'll usually want to compute them on your own, if you need them. This option is intended for model viewers which want to offer an easy way to apply textures to terrains.

TransformUVConfig

Configuration for the TransformUVCoords step that specifies which UV transformations are to be evaluated. The default value is for all combinations (scaling, rotation, translation).

UnrealHandleFlagsConfig

Configures the UNREAL 3D loader to separate faces with different surface flags (e.g. two-sided vs single-sided). The default value is true.

UnrealKeyFrameImportConfig

Sets the vertex animation keyframe to be imported. Assimp does not support vertex keyframes (only bone animation is supported). the library reads only one keyframe with vertex animations. By default this is the first frame. This config sets the global override for the Unreal format.

VertexBoneWeightLimitConfig

Configuration for the LimitBoneWeights step that specifies the maximum number of bone weights per vertex. The default value is VertexBoneWeightLimitConfigDefaultValue.

VertexCacheSizeConfig

Configuration for the ImproveCahceLocality step that specifies the size of the post-transform vertex cache. The size is given in number of vertices and the default value is VertexCacheSizeConfigDefaultValue.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值