热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用gltfsdk创建多个gltf的mesh

gltf的sdk地址这份代码的原始例子比较不好参考,创建一个三角形还比较好参考,创建多个三角形或者元素就有点懵。所以我做了个更通用的例子(

gltf 的sdk地址

这份代码的原始例子比较不好参考,创建一个三角形还比较好参考,创建多个三角形或者元素就有点懵。所以我做了个更通用的例子(即创建多个mesh)作为使用这个gltf sdk的样例。

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.#include
#include
#include
#include
#include
#include // Replace this with (and use std::filesystem rather than
// std::experimental::filesystem) if your toolchain fully supports C++17
#include #include
#include
#include #include
#include
#include using namespace std;using namespace Microsoft::glTF;namespace
{// The glTF SDK is decoupled from all file I/O by the IStreamWriter (and IStreamReader)// interface(s) and the C++ stream-based I/O library. This allows the glTF SDK to be used in// sandboxed environments, such as WebAssembly modules and UWP apps, where any file I/O code// must be platform or use-case specific.class StreamWriter : public IStreamWriter{public:StreamWriter(std::experimental::filesystem::path pathBase) : m_pathBase(std::move(pathBase)){assert(m_pathBase.has_root_path());}// Resolves the relative URIs of any external resources declared in the glTF manifeststd::shared_ptr GetOutputStream(const std::string& filename) const override{// In order to construct a valid stream:// 1. The filename argument will be encoded as UTF-8 so use filesystem::u8path to// correctly construct a path instance.// 2. Generate an absolute path by concatenating m_pathBase with the specified filename// path. The filesystem::operator/ uses the platform's preferred directory separator// if appropriate.// 3. Always open the file stream in binary mode. The glTF SDK will handle any text// encoding issues for us.auto streamPath = m_pathBase / std::experimental::filesystem::u8path(filename);auto stream = std::make_shared(streamPath, std::ios_base::binary);// Check if the stream has no errors and is ready for I/O operationsif (!stream || !(*stream)){throw std::runtime_error("Unable to create a valid output stream for uri: " + filename);}return stream;}private:std::experimental::filesystem::path m_pathBase;}; std::string AddMaterial(Document& document, Color4& color4) {// Construct a MaterialMaterial material;material.metallicRoughness.baseColorFactor = color4;material.metallicRoughness.metallicFactor = 0.2f;material.metallicRoughness.roughnessFactor = 0.4f;material.doubleSided = true;// Add it to the Document and store the generated IDauto materialId = document.materials.Append(std::move(material), AppendIdPolicy::GenerateOnEmpty).id;return materialId;}//添加顶点索引Accessorstring AddIndexAccessor(BufferBuilder& bufferBuilder, const vector &indices) {// Create a BufferView with a target of ELEMENT_ARRAY_BUFFER (as it will reference index// data) - it will be the 'current' BufferView that all the Accessors created by this// BufferBuilder will automatically referencebufferBuilder.AddBufferView(BufferViewTarget::ELEMENT_ARRAY_BUFFER);// Add an Accessor for the indices// Copy the Accessor's id - subsequent calls to AddAccessor may invalidate the returned referencereturn bufferBuilder.AddAccessor(indices, { TYPE_SCALAR, COMPONENT_UNSIGNED_SHORT }).id;}//添加顶点Accessorstring AddPositionsAccessor(BufferBuilder& bufferBuilder,const vector &positions) {// Create a BufferView with target ARRAY_BUFFER (as it will reference vertex attribute data)bufferBuilder.AddBufferView(BufferViewTarget::ARRAY_BUFFER);// Add an Accessor for the positions//std::vector positions = {// 0.0f, 0.0f, 0.0f, // Vertex 0// 1.0f, 0.0f, 0.0f, // Vertex 1// 0.0f, 1.0f, 0.0f // Vertex 2//};std::vector minValues(3U, std::numeric_limits::max());std::vector maxValues(3U, std::numeric_limits::lowest());const size_t positionCount = positions.size();// Accessor min/max properties must be set for vertex position data so calculate them herefor (size_t i = 0U, j = 0U; i (&bufferBuilder.GetResourceWriter())){bufferId = GLB_BUFFER_ID;}// Create a Buffer - it will be the 'current' Buffer that all the BufferViews// created by this BufferBuilder will automatically referencebufferBuilder.AddBuffer(bufferId);#pragma region 添加索引Accessorstd::vector indices = {0U, 1U, 2U};accessorIdIndices = AddIndexAccessor(bufferBuilder,indices);
#pragma endregion#pragma region 添加顶点Accessor// Add an Accessor for the positionsstd::vector positions = {0.0f, 0.0f, 0.0f, // Vertex 01.0f, 0.0f, 0.0f, // Vertex 10.0f, 1.0f, 0.0f // Vertex 2};accessorIdPositions = AddPositionsAccessor(bufferBuilder, positions);
#pragma endregion#pragma region 添加索引Accessorstd::vector indices2 = {0U, 1U, 2U};accessorIdIndices2 = AddIndexAccessor(bufferBuilder, indices2);
#pragma endregion#pragma region 添加顶点Accessor// Add an Accessor for the positionsstd::vector positions2 = {1.0f, 0.0f, 0.0f, // Vertex 02.0f, 0.0f, 0.0f, // Vertex 11.0f, 1.0f, 0.0f // Vertex 2};accessorIdPositions2 = AddPositionsAccessor(bufferBuilder, positions2);
#pragma endregion// Add all of the Buffers, BufferViews and Accessors that were created using BufferBuilder to// the Document. Note that after this point, no further calls should be made to BufferBuilderbufferBuilder.Output(document);// Construct a MaterialColor4 color(1.0f, 0.0f, 0.0f, 1.0f);auto materialId &#61; AddMaterial(document, color);Color4 color2(0.0f, 1.0f, 0.0f, 1.0f);auto materialId2 &#61; AddMaterial(document, color2);// Construct a MeshPrimitive. Unlike most types in glTF, MeshPrimitives are direct children// of their parent Mesh entity rather than being children of the Document. This is why they// don&#39;t have an ID member.Scene scene;AddMesh(document, materialId, accessorIdIndices, accessorIdPositions, scene);AddMesh(document, materialId2, accessorIdIndices2, accessorIdPositions2, scene);// Add it to the Document, using a utility method that also sets the Scene as the Document&#39;s defaultdocument.SetDefaultScene(std::move(scene), AppendIdPolicy::GenerateOnEmpty);}void SerializeTriangle(const std::experimental::filesystem::path& path){// Pass the absolute path, without the filename, to the stream writerauto streamWriter &#61; std::make_unique(path.parent_path());std::experimental::filesystem::path pathFile &#61; path.filename();std::experimental::filesystem::path pathFileExt &#61; pathFile.extension();auto MakePathExt &#61; [](const std::string& ext){return "." &#43; ext;};std::unique_ptr resourceWriter;// If the file has a &#39;.gltf&#39; extension then create a GLTFResourceWriterif (pathFileExt &#61;&#61; MakePathExt(GLTF_EXTENSION)){resourceWriter &#61; std::make_unique(std::move(streamWriter));}// If the file has a &#39;.glb&#39; extension then create a GLBResourceWriter. This class derives// from GLTFResourceWriter and adds support for writing manifests to a GLB container&#39;s// JSON chunk and resource data to the binary chunk.if (pathFileExt &#61;&#61; MakePathExt(GLB_EXTENSION)){resourceWriter &#61; std::make_unique(std::move(streamWriter));}if (!resourceWriter){throw std::runtime_error("Command line argument path filename extension must be .gltf or .glb");}// The Document instance represents the glTF JSON manifestDocument document;// Use the BufferBuilder helper class to simplify the process of// constructing valid glTF Buffer, BufferView and Accessor entitiesBufferBuilder bufferBuilder(std::move(resourceWriter));CreateTrianglesResources(document, bufferBuilder);//CreateTriangle2Entities(document, accessorIdIndices, accessorIdPositions);//CreateTriangle2Resources(document, bufferBuilder, accessorIdIndices, accessorIdPositions);//CreateTriangle2Entities(document, accessorIdIndices, accessorIdPositions);std::string manifest;try{// Serialize the glTF Document into a JSON manifestmanifest &#61; Serialize(document, SerializeFlags::Pretty);}catch (const GLTFException& ex){std::stringstream ss;ss <<"Microsoft::glTF::Serialize failed: ";ss <(&gltfResourceWriter)){glbResourceWriter->Flush(manifest, pathFile.u8string()); // A GLB container isn&#39;t created until the GLBResourceWriter::Flush member function is called}else{gltfResourceWriter.WriteExternal(pathFile.u8string(), manifest); // Binary resources have already been written, just need to write the manifest}}
}int main()
{const char* argv[1] &#61; {"D:\\test.gltf" };try{std::experimental::filesystem::path path &#61; argv[0U];if (path.is_relative()){auto pathCurrent &#61; std::experimental::filesystem::current_path();// Convert the relative path into an absolute path by appending the command line argument to the current pathpathCurrent /&#61; path;pathCurrent.swap(path);}if (!path.has_filename()){throw std::runtime_error("Command line argument path has no filename");}if (!path.has_extension()){throw std::runtime_error("Command line argument path has no filename extension");}SerializeTriangle(path);}catch (const std::runtime_error& ex){std::cerr <<"Error! - ";std::cerr <}

 


推荐阅读
  • Android中将独立SO库封装进JAR包并实现SO库的加载与调用
    在Android开发中,将独立的SO库封装进JAR包并实现其加载与调用是一个常见的需求。本文详细介绍了如何将SO库嵌入到JAR包中,并确保在外部应用调用该JAR包时能够正确加载和使用这些SO库。通过这种方式,开发者可以更方便地管理和分发包含原生代码的库文件,提高开发效率和代码复用性。文章还探讨了常见的问题及其解决方案,帮助开发者避免在实际应用中遇到的坑。 ... [详细]
  • MySQL初级篇——字符串、日期时间、流程控制函数的相关应用
    文章目录:1.字符串函数2.日期时间函数2.1获取日期时间2.2日期与时间戳的转换2.3获取年月日、时分秒、星期数、天数等函数2.4时间和秒钟的转换2. ... [详细]
  • 本文介绍了Spring 2.0引入的TaskExecutor接口及其多种实现,包括同步和异步执行任务的方式。文章详细解释了如何在Spring应用中配置和使用这些线程池实现,以提高应用的性能和可管理性。 ... [详细]
  • 本文介绍了如何使用Flume从Linux文件系统收集日志并存储到HDFS,然后通过MapReduce清洗数据,使用Hive进行数据分析,并最终通过Sqoop将结果导出到MySQL数据库。 ... [详细]
  • 应用链时代,详解 Avalanche 与 Cosmos 的差异 ... [详细]
  • 在软件开发过程中,经常需要将多个项目或模块进行集成和调试,尤其是当项目依赖于第三方开源库(如Cordova、CocoaPods)时。本文介绍了如何在Xcode中高效地进行多项目联合调试,分享了一些实用的技巧和最佳实践,帮助开发者解决常见的调试难题,提高开发效率。 ... [详细]
  • Java Socket 关键参数详解与优化建议
    Java Socket 的 API 虽然被广泛使用,但其关键参数的用途却鲜为人知。本文详细解析了 Java Socket 中的重要参数,如 backlog 参数,它用于控制服务器等待连接请求的队列长度。此外,还探讨了其他参数如 SO_TIMEOUT、SO_REUSEADDR 等的配置方法及其对性能的影响,并提供了优化建议,帮助开发者提升网络通信的稳定性和效率。 ... [详细]
  • 本文深入探讨了NoSQL数据库的四大主要类型:键值对存储、文档存储、列式存储和图数据库。NoSQL(Not Only SQL)是指一系列非关系型数据库系统,它们不依赖于固定模式的数据存储方式,能够灵活处理大规模、高并发的数据需求。键值对存储适用于简单的数据结构;文档存储支持复杂的数据对象;列式存储优化了大数据量的读写性能;而图数据库则擅长处理复杂的关系网络。每种类型的NoSQL数据库都有其独特的优势和应用场景,本文将详细分析它们的特点及应用实例。 ... [详细]
  • 在Android平台中,播放音频的采样率通常固定为44.1kHz,而录音的采样率则固定为8kHz。为了确保音频设备的正常工作,底层驱动必须预先设定这些固定的采样率。当上层应用提供的采样率与这些预设值不匹配时,需要通过重采样(resample)技术来调整采样率,以保证音频数据的正确处理和传输。本文将详细探讨FFMpeg在音频处理中的基础理论及重采样技术的应用。 ... [详细]
  • 本文探讨了如何利用Java代码获取当前本地操作系统中正在运行的进程列表及其详细信息。通过引入必要的包和类,开发者可以轻松地实现这一功能,为系统监控和管理提供有力支持。示例代码展示了具体实现方法,适用于需要了解系统进程状态的开发人员。 ... [详细]
  • 在Android应用开发中,实现与MySQL数据库的连接是一项重要的技术任务。本文详细介绍了Android连接MySQL数据库的操作流程和技术要点。首先,Android平台提供了SQLiteOpenHelper类作为数据库辅助工具,用于创建或打开数据库。开发者可以通过继承并扩展该类,实现对数据库的初始化和版本管理。此外,文章还探讨了使用第三方库如Retrofit或Volley进行网络请求,以及如何通过JSON格式交换数据,确保与MySQL服务器的高效通信。 ... [详细]
  • 今天我开始学习Flutter,并在Android Studio 3.5.3中创建了一个新的Flutter项目。然而,在首次尝试运行时遇到了问题,Gradle任务 `assembleDebug` 执行失败,退出状态码为1。经过初步排查,发现可能是由于依赖项配置不当或Gradle版本不兼容导致的。为了解决这个问题,我计划检查项目的 `build.gradle` 文件,确保所有依赖项和插件版本都符合要求,并尝试更新Gradle版本。此外,还将验证环境变量配置是否正确,以确保开发环境的稳定性。 ... [详细]
  • 本文介绍了如何将包含复杂对象的字典保存到文件,并从文件中读取这些字典。 ... [详细]
  • 基于Linux开源VOIP系统LinPhone[四]
    ****************************************************************************************** ... [详细]
  • 本文介绍了Java中的com.sun.codemodel.JBlock._continue()方法,并提供了多个实际代码示例,帮助开发者更好地理解和使用该方法。 ... [详细]
author-avatar
airchampion
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有