Compare commits

...

55 Commits

Author SHA1 Message Date
Syoyo Fujita
81bd50c106 Merge branch 'release' of github.com:syoyo/tinygltf into release 2025-11-02 10:11:11 +09:00
Syoyo Fujita
6d8bba0d8a Update the usage code: https://github.com/syoyo/tinygltf/pull/524 2025-11-02 10:10:11 +09:00
Syoyo Fujita
2aa77e5d0a Merge pull request #525 from nyalldawson/performance
Minor performance fixes
2025-11-02 10:08:23 +09:00
Nyall Dawson
1fac6234d9 Fix some 'use of auto that causes a copy' warnings 2025-10-31 08:44:42 +10:00
Nyall Dawson
bcd666fbd4 Fix some variable copied when could be moved warnings 2025-10-31 08:44:26 +10:00
Syoyo Fujita
37250b3470 Merge pull request #517 from nepp95/release
Removed TINYGLTF_USE_CPP14 option since it is unused
2025-05-20 06:31:38 +09:00
Niels Eppenhof
7385235e29 Removed TINYGLTF_USE_CPP14 option since it is unused 2025-05-19 14:58:41 +02:00
Syoyo Fujita
3564b48760 Merge pull request #516 from DrQuackeroo/c24695-fix
Initialize Accessor::Sparse members to default values
2025-05-06 09:14:08 +09:00
Sammy Newhide
2ad433b68f Revert 1b517f2 by adding default constructor for Accessor 2025-05-05 17:04:52 -07:00
Sammy Newhide
1b517f2b23 Remove explicit default constructor for Accessor
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-05-05 16:43:20 -07:00
Sammy Newhide
bd7255e095 Initialize Accessor::Sparse members to default values 2025-05-05 15:20:30 -07:00
Syoyo Fujita
a5e653e46c Merge pull request #512 from ctrlaltf2/oob-fix
Add bounds check to images loaded from bufferviews
2025-01-22 22:45:07 +09:00
ctrlaltf2
d530cd410b Add bounds check to images loaded from bufferviews 2025-01-20 23:43:07 -05:00
Syoyo Fujita
1831424c71 Merge pull request #509 from NoirMorilec/fix-no-fs
Added NO_FS definition for std::ofstream usage
2024-12-30 22:11:09 +09:00
Leonid
5e008af65d Added NO_FS definition for std::ofstream usage 2024-12-30 03:12:20 +08:00
Syoyo Fujita
fbff1f45b5 Merge pull request #507 from thearchivalone/release
Documentation: Submodule hint added
2024-12-21 19:59:42 +09:00
Brad
d950e7cd9b Documentation: Submodule hint added 2024-12-20 17:49:51 -06:00
Syoyo Fujita
116d0030f9 Merge pull request #504 from nim65s/vendor 2024-10-16 23:27:42 +09:00
Syoyo Fujita
ff972dcf1b Merge pull request #503 from nim65s/release 2024-10-16 23:26:53 +09:00
Guilhem Saurel
8bec431699 CMake: fix export install dir 2024-10-16 15:53:48 +02:00
Guilhem Saurel
21485496b1 CMake: allow opt-out of installing vendored headers 2024-10-16 14:58:42 +02:00
Syoyo Fujita
fda7422022 Merge pull request #501 from msklywenn/release
Fix Animation extensions being loaded in place of Sampler extensions
2024-08-08 21:47:56 +09:00
Daniel Borges
decfabd67e Merge branch 'syoyo:release' into release 2024-08-08 10:25:11 +02:00
Syoyo Fujita
10b23b6af2 Merge pull request #496 from ptc-tgamper/bug/issue-495
Allow WriteImageDataFunction() callback to be called with empty images
2024-07-26 21:44:16 +09:00
Thomas Gamper
fe3cfbe996 fixes #495
Fix issues that block custom image loaders and writers to deal with empty images
2024-07-23 11:45:54 +02:00
Daniel Borges
3b73caa8e8 fixed ParseAnimation loading animation's extensions into sampler instead of sample's extensions. 2024-07-19 12:34:16 +02:00
Syoyo Fujita
fea6786129 Merge pull request #493 from ptc-tgamper/bug/model_clear_on_load
Properly clear the model before loading
2024-07-06 02:43:52 +09:00
Thomas Gamper
fb58f88a4e Properly clear the model before loading 2024-07-05 08:57:36 +02:00
Syoyo Fujita
143ff45b61 Update README.md 2024-07-04 03:01:46 +09:00
Syoyo Fujita
cfbec35dc7 Merge pull request #492 from danwillm/inverse-bind-matrix
Make inverseBindMatrices optional
2024-07-04 02:59:35 +09:00
danwillm
4ad8c82c9e Add test for inverse bind matrices being optional 2024-07-01 22:32:17 +01:00
danwillm
2e7ba45a6c Make inverseBindMatrices optional 2024-07-01 18:31:00 +01:00
Syoyo Fujita
cf9767668a bump minor version. 2024-06-28 21:30:43 +09:00
Syoyo Fujita
8a269aa5e9 Merge pull request #491 from ptc-tgamper/bug/image_saving
Fix images not being saved due to missing filesystem callbacks
2024-06-28 21:24:53 +09:00
Thomas Gamper
38614763e9 fixes #487
Support image as_is flag in loading and saving
2024-06-28 12:17:38 +02:00
Thomas Gamper
3245906248 fixes #473
tiny_gltf.h - explicitly pass filesystem callbacks to image related functions
tester.cc - add respective test case, fix image uri test case
2024-06-25 15:12:30 +02:00
Syoyo Fujita
847df8456a Merge pull request #489 from SeanCurtis-TRI/PR_callback_as_function
Update typedefs of C-style function pointers to std::function
2024-06-12 04:01:37 +09:00
Sean Curtis
6482c08cf7 Remove asserts 2024-06-10 14:18:31 -07:00
Sean Curtis
e08df72575 Update typedefs of C-style function pointers to std::function
This allows for the callback to maintain their own state (without recourse
to globals).

In addition, added some incidental clean up:

  - URICallback, passed by pointer, is now asserted to be non-null before
    accessing.
  - FSCallbacks are validated when they are set (in debug builds).
2024-06-06 07:45:01 -07:00
Syoyo Fujita
f03fe26579 Merge pull request #486 from pmcgvr/release
Fix stripping of slashes from paths
2024-05-24 02:49:22 +09:00
Syoyo Fujita
e54660fbf9 Merge pull request #485 from bwrsandman/patch-1
msvc 32bit: Fix C4244 warning
2024-05-21 04:11:31 +09:00
Patrick Mc Gartoll
1bdd404c04 Fix stripping of slashes from paths 2024-05-16 18:11:26 -07:00
Sandy
2191085580 msvc 32bit: Fix C4244 warning
On 32 bit msvc compilers with warnings on, there are C4244 warnings about  from 'std::streamoff' to size_t to vector::size_type
2024-05-10 08:47:23 -04:00
Syoyo Fujita
cde43ef668 Merge pull request #482 from jam3sward/fix-c4018-warnings-msvc-win32
Fix C4018 warnings in MSVC on WIN32
2024-03-27 03:43:42 +09:00
jamesvert
e3f9a7d8b3 Resolve overload ambiguity in VS2015 (version 14.0) 2024-03-26 11:32:43 +00:00
jamesvert
f57d18ad74 Fix C4018 warnings in MSVC on WIN32 2024-03-26 11:06:16 +00:00
Syoyo Fujita
ed3d1ec2f5 Merge pull request #481 from jam3sward/fix-c4267-warnings-vs-win32
Fix C4267 warnings in Visual Studio on WIN32
2024-03-26 05:23:03 +09:00
James Ward
9b4e1eae9e Fix C4267 warnings in Visual Studio on WIN32 2024-03-25 17:50:33 +00:00
Syoyo Fujita
cbc8e1bea6 Merge pull request #479 from The0Dev/fix_wopen_ronly
Added the pmode argument to _wopen to fix the access permission on MinGW
2024-03-26 02:36:27 +09:00
Syoyo Fujita
212de904ca Merge pull request #480 from ptc-tgamper/bug/msft_lod_extension_used
Bug/msft lod extension used
2024-03-26 02:35:51 +09:00
Thomas Gamper
1f5b8f8b8c tester.cc - extend MSFT_lod test 2024-03-25 17:01:08 +01:00
Thomas Gamper
b274b34972 tiny_gltf.h - register MSFT_lod with the model's used extensions 2024-03-25 17:00:41 +01:00
TheDev
22dfeab315 Added the pmode argument to _wopen to fix the access permission on MinGW 2024-03-25 18:21:20 +03:00
Syoyo Fujita
b132612307 Merge pull request #475 from jam3sward/issue-474
M_PI was not defined by <cmath>
2024-03-20 21:11:56 +09:00
James Ward
50d90c91ac M_PI was not defined by <cmath> 2024-03-19 19:06:19 +00:00
6 changed files with 580 additions and 230 deletions

View File

@@ -16,6 +16,7 @@ option(TINYGLTF_BUILD_VALIDATOR_EXAMPLE "Build validator exampe" OFF)
option(TINYGLTF_BUILD_BUILDER_EXAMPLE "Build glTF builder example" OFF)
option(TINYGLTF_HEADER_ONLY "On: header-only mode. Off: create tinygltf library(No TINYGLTF_IMPLEMENTATION required in your project)" OFF)
option(TINYGLTF_INSTALL "Install tinygltf files during install step. Usually set to OFF if you include tinygltf through add_subdirectory()" ON)
option(TINYGLTF_INSTALL_VENDOR "Install vendored nlohmann/json and nothings/stb headers" ON)
if (TINYGLTF_BUILD_LOADER_EXAMPLE)
add_executable(loader_example
@@ -61,19 +62,26 @@ endif (TINYGLTF_HEADER_ONLY)
if (TINYGLTF_INSTALL)
install(TARGETS tinygltf EXPORT tinygltfTargets)
install(EXPORT tinygltfTargets NAMESPACE tinygltf:: FILE TinyGLTFTargets.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake)
install(EXPORT tinygltfTargets NAMESPACE tinygltf:: FILE TinyGLTFTargets.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/tinygltf)
configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/TinyGLTFConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/TinyGLTFConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/TinyGLTFConfig.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/TinyGLTFConfig.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/tinygltf)
# Do not install .lib even if !TINYGLTF_HEADER_ONLY
INSTALL ( FILES
json.hpp
stb_image.h
stb_image_write.h
tiny_gltf.h
${TINYGLTF_EXTRA_SOUECES}
DESTINATION
include
)
if(TINYGLTF_INSTALL_VENDOR)
INSTALL ( FILES
json.hpp
stb_image.h
stb_image_write.h
DESTINATION
include
)
endif()
endif(TINYGLTF_INSTALL)

View File

@@ -9,7 +9,7 @@ If you are looking for old, C++03 version, please use `devel-picojson` branch (b
## Status
Currently TinyGLTF is stable and maintenance mode. No drastic changes and feature additions planned.
- v2.9.0 Various fixes and improvements. Filesystem callback API change.
- v2.8.0 Add URICallbacks for custom URI handling in Buffer and Image. PR#397
- v2.7.0 Change WriteImageDataFunction user callback function signature. PR#393
- v2.6.0 Support serializing sparse accessor(Thanks to @fynv).
@@ -159,9 +159,10 @@ Model model;
TinyGLTF loader;
std::string err;
std::string warn;
std::string filename = "input.gltf";
bool ret = loader.LoadASCIIFromFile(&model, &err, &warn, argv[1]);
//bool ret = loader.LoadBinaryFromFile(&model, &err, &warn, argv[1]); // for binary glTF(.glb)
bool ret = loader.LoadASCIIFromFile(&model, &err, &warn, filename);
//bool ret = loader.LoadBinaryFromFile(&model, &err, &warn, filename); // for binary glTF(.glb)
if (!warn.empty()) {
printf("Warn: %s\n", warn.c_str());
@@ -172,8 +173,7 @@ if (!err.empty()) {
}
if (!ret) {
printf("Failed to parse glTF\n");
return -1;
printf("Failed to parse glTF: %s\n", filename.c_str());
}
```
@@ -194,7 +194,6 @@ if (!ret) {
* `TINYGLTF_NO_INCLUDE_STB_IMAGE `: Disable including `stb_image.h` from within `tiny_gltf.h` because it has been already included before or you want to include it using custom path before including `tiny_gltf.h`.
* `TINYGLTF_NO_INCLUDE_STB_IMAGE_WRITE `: Disable including `stb_image_write.h` from within `tiny_gltf.h` because it has been already included before or you want to include it using custom path before including `tiny_gltf.h`.
* `TINYGLTF_USE_RAPIDJSON` : Use RapidJSON as a JSON parser/serializer. RapidJSON files are not included in TinyGLTF repo. Please set an include path to RapidJSON if you enable this feature.
* `TINYGLTF_USE_CPP14` : Use C++14 feature(requires C++14 compiler). This may give better performance than C++11.
## CMake options
@@ -211,6 +210,11 @@ set(TINYGLTF_INSTALL OFF CACHE INTERNAL "" FORCE)
add_subdirectory(/path/to/tinygltf)
```
NOTE: Using tinygltf as a submodule doesn't automatically add the headers to your include path (as standard for many libraries). To get this functionality, add the following to the CMakeLists.txt file from above:
```
target_include_directories(${PROJECT_NAME} PRIVATE "/path/to/tinygltf")
```
### Saving gltTF 2.0 model

View File

@@ -788,8 +788,10 @@ static void QuatToAngleAxis(const std::vector<double> quaternion,
return;
}
constexpr double pi = 3.14159265358979323846;
double denom = sqrt(1-qw*qw);
outAngleDegrees = angleRadians * 180.0 / M_PI;
outAngleDegrees = angleRadians * 180.0 / pi;
axis[0] = qx / denom;
axis[1] = qy / denom;
axis[2] = qz / denom;

BIN
tests/issue-492.glb Normal file

Binary file not shown.

View File

@@ -474,7 +474,7 @@ TEST_CASE("image-uri-spaces", "[issue-236]") {
}
REQUIRE(true == ret);
REQUIRE(err.empty());
REQUIRE(!warn.empty()); // relative image path won't exist in tests/
REQUIRE(warn.empty());
REQUIRE(saved.images.size() == model.images.size());
// The image uri in CubeImageUriMultipleSpaces.gltf is not encoded and
@@ -662,10 +662,11 @@ TEST_CASE("serialize-image-callback", "[issue-394]") {
auto writer = [](const std::string *basepath, const std::string *filename,
const tinygltf::Image *image, bool embedImages,
const tinygltf::URICallbacks *uri_cb, std::string *out_uri,
void *user_pointer) -> bool {
const tinygltf::FsCallbacks* fs, const tinygltf::URICallbacks *uri_cb,
std::string *out_uri, void *user_pointer) -> bool {
(void)basepath;
(void)image;
(void)fs;
(void)uri_cb;
REQUIRE(*filename == "foo");
REQUIRE(embedImages == true);
@@ -699,12 +700,13 @@ TEST_CASE("serialize-image-failure", "[issue-394]") {
auto writer = [](const std::string *basepath, const std::string *filename,
const tinygltf::Image *image, bool embedImages,
const tinygltf::URICallbacks *uri_cb, std::string *out_uri,
void *user_pointer) -> bool {
const tinygltf::FsCallbacks* fs, const tinygltf::URICallbacks *uri_cb,
std::string *out_uri, void *user_pointer) -> bool {
(void)basepath;
(void)filename;
(void)image;
(void)embedImages;
(void)fs;
(void)uri_cb;
(void)out_uri;
(void)user_pointer;
@@ -978,19 +980,20 @@ TEST_CASE("serialize-lods", "[lods]") {
{
tinygltf::Model m;
m.nodes.resize(3);
m.nodes.resize(4);
// Add Node 1 and Node 2 as lods to Node 0
m.nodes[0].lods.push_back(1);
m.nodes[0].lods.push_back(2);
// Add Material 1 and Material 2 as lods to Material 0
m.materials.resize(3);
m.materials.resize(4);
m.materials[0].lods.push_back(1);
m.materials[0].lods.push_back(2);
tinygltf::Scene scene;
// Scene uses Node 0 as root node
// Scene uses Node 0 and 3 as root node
scene.nodes.push_back(0);
scene.nodes.push_back(3);
// Add scene to the model
m.scenes.push_back(scene);
@@ -1006,28 +1009,241 @@ TEST_CASE("serialize-lods", "[lods]") {
// Parse the serialized model
bool ok = ctx.LoadASCIIFromString(&m, nullptr, nullptr, os.str().c_str(), os.str().size(), "");
REQUIRE(true == ok);
// Make sure the model's used extensions hold MSFT_lod
CHECK(m.extensionsUsed.size() == 1);
CHECK(m.extensionsUsed[0].compare("MSFT_lod") == 0);
// MSFT_lod is not a required extension
CHECK(m.extensionsRequired.size() == 0);
// Make sure all three materials are there
REQUIRE(3 == m.materials.size());
// Make sure all four materials are there
REQUIRE(4 == m.materials.size());
// Make sure the first material has both lod materials
REQUIRE(2 == m.materials[0].lods.size());
// Make sure the order is still the same after serialization and deserialization
CHECK(1 == m.materials[0].lods[0]);
CHECK(2 == m.materials[0].lods[1]);
// Make sure the material with lods exposes the MSFT_lod extension
CHECK(m.materials[0].extensions.size() == 1);
CHECK(m.materials[0].extensions.count("MSFT_lod") == 1);
// Make sure the last material has no lod materials
CHECK(0 == m.materials[3].lods.size());
// Make sure the material without lods does not exposes the MSFT_lod extension
CHECK(m.materials[3].extensions.size() == 0);
CHECK(m.materials[3].extensions.count("MSFT_lod") == 0);
// Make sure the single scene is there
REQUIRE(1 == m.scenes.size());
// Make sure all three nodes are there
REQUIRE(3 == m.nodes.size());
// Make sure the single root node of the scene is there
REQUIRE(1 == m.scenes[0].nodes.size());
// Make sure all four nodes are there
REQUIRE(4 == m.nodes.size());
// Make sure the two root nodes of the scene are there
REQUIRE(2 == m.scenes[0].nodes.size());
REQUIRE(0 == m.scenes[0].nodes[0]);
// Retrieve the scene root node
const tinygltf::Node& node = m.nodes[m.scenes[0].nodes[0]];
// Make sure the single root node has both lod nodes
REQUIRE(2 == node.lods.size());
REQUIRE(3 == m.scenes[0].nodes[1]);
// Retrieve the node with lods
const tinygltf::Node& nodeWithLods = m.nodes[m.scenes[0].nodes[0]];
// Make sure the node has both lod nodes
REQUIRE(2 == nodeWithLods.lods.size());
// Make sure the order is still the same after serialization and deserialization
CHECK(1 == node.lods[0]);
CHECK(2 == node.lods[1]);
CHECK(1 == nodeWithLods.lods[0]);
CHECK(2 == nodeWithLods.lods[1]);
// Make sure the node with lods exposes the MSFT_lod extension
CHECK(nodeWithLods.extensions.size() == 1);
CHECK(nodeWithLods.extensions.count("MSFT_lod") == 1);
// Retrieve the node without lods
const tinygltf::Node& nodeWithoutLods = m.nodes[m.scenes[0].nodes[1]];
// Make sure the node has no lod nodes
CHECK(0 == nodeWithoutLods.lods.size());
// Make sure the node without lods does not exposes the MSFT_lod extension
CHECK(nodeWithoutLods.extensions.size() == 0);
CHECK(nodeWithoutLods.extensions.count("MSFT_lod") == 0);
}
}
TEST_CASE("write-image-issue", "[issue-473]") {
std::string err;
std::string warn;
tinygltf::Model model;
tinygltf::TinyGLTF ctx;
bool ok = ctx.LoadASCIIFromFile(&model, &err, &warn, "../models/Cube/Cube.gltf");
REQUIRE(ok);
REQUIRE(err.empty());
REQUIRE(warn.empty());
REQUIRE(model.images.size() == 2);
REQUIRE(model.images[0].uri == "Cube_BaseColor.png");
REQUIRE(model.images[1].uri == "Cube_MetallicRoughness.png");
REQUIRE_FALSE(model.images[0].image.empty());
REQUIRE_FALSE(model.images[1].image.empty());
ok = ctx.WriteGltfSceneToFile(&model, "Cube.gltf");
REQUIRE(ok);
for (const auto& image : model.images) {
std::fstream file(image.uri);
CHECK(file.good());
}
}
TEST_CASE("images-as-is", "[issue-487]") {
std::string err;
std::string warn;
tinygltf::Model model;
tinygltf::TinyGLTF ctx;
ctx.SetImagesAsIs(true);
bool ok = ctx.LoadASCIIFromFile(&model, &err, &warn, "../models/Cube/Cube.gltf");
REQUIRE(ok);
REQUIRE(err.empty());
REQUIRE(warn.empty());
for (const auto& image : model.images) {
CHECK(image.as_is == true);
CHECK_FALSE(image.uri.empty());
CHECK_FALSE(image.image.empty());
#ifndef TINYGLTF_NO_STB_IMAGE
// Make sure we can decode the images
int w = -1, h = -1, component = -1;
unsigned char *data = stbi_load_from_memory(image.image.data(), static_cast<int>(image.image.size()), &w, &h, &component, 0);
CHECK(data != nullptr);
CHECK(w == 512);
CHECK(h == 512);
CHECK(component >= 3);
stbi_image_free(data);
#endif
}
// Write glTF model to disk, and images as separate files
{
ok = ctx.WriteGltfSceneToFile(&model, "Cube_with_image_files.gltf");
REQUIRE(ok);
// All the images should have been written to disk with their original data
for (const auto& image : model.images) {
// Make sure the image files exist
std::fstream file(image.uri);
CHECK(file.good());
#ifndef TINYGLTF_NO_STB_IMAGE
// Make sure we can load the images
int w = -1, h = -1, component = -1;
unsigned char *data = stbi_load(image.uri.c_str(), &w, &h, &component, 0);
CHECK(data != nullptr);
CHECK(w == 512);
CHECK(h == 512);
CHECK(component >= 3);
stbi_image_free(data);
#endif
}
}
// Write glTF model to disk, and embed images as data URIs
{
ok = ctx.WriteGltfSceneToFile(&model, "Cube_with_embedded_images.gltf", true, false);
REQUIRE(ok);
// Load above model again, and check if the images are loaded properly
tinygltf::Model embeddedImages;
ctx.SetImagesAsIs(false);
bool ok = ctx.LoadASCIIFromFile(&embeddedImages, &err, &warn, "Cube_with_embedded_images.gltf");
REQUIRE(ok);
REQUIRE(err.empty());
REQUIRE(warn.empty());
for (const auto& image : embeddedImages.images) {
CHECK(image.as_is == false);
CHECK_FALSE(image.mimeType.empty());
CHECK_FALSE(image.image.empty());
CHECK(image.width == 512);
CHECK(image.height == 512);
CHECK(image.component >= 3);
}
}
// Write glTF model to disk, as GLB
{
ok = ctx.WriteGltfSceneToFile(&model, "Cube.glb", true, true, true, true);
REQUIRE(ok);
// Load above model again, and check if the images are loaded properly
tinygltf::Model glbModel;
ctx.SetImagesAsIs(false);
bool ok = ctx.LoadBinaryFromFile(&glbModel, &err, &warn, "Cube.glb");
REQUIRE(ok);
REQUIRE(err.empty());
REQUIRE(warn.empty());
for (const auto& image : glbModel.images) {
CHECK(image.as_is == false);
CHECK_FALSE(image.mimeType.empty());
CHECK_FALSE(image.image.empty());
CHECK(image.width == 512);
CHECK(image.height == 512);
CHECK(image.component >= 3);
}
}
}
TEST_CASE("inverse-bind-matrices-optional", "[issue-492]") {
tinygltf::Model model;
tinygltf::TinyGLTF ctx;
std::string err;
std::string warn;
bool ret = ctx.LoadBinaryFromFile(&model, &err, &warn, "issue-492.glb");
if (!warn.empty()) {
std::cout << "WARN:" << warn << std::endl;
}
if (!err.empty()) {
std::cerr << "ERR:" << err << std::endl;
}
REQUIRE(true == ret);
REQUIRE(err.empty());
}
bool LoadImageData(tinygltf::Image * /* image */, const int /* image_idx */, std::string * /* err */,
std::string * /* warn */, int /* req_width */, int /* req_height */,
const unsigned char * /* bytes */, int /* size */, void * /*user_data */) {
return true;
}
bool WriteImageData(const std::string * /* basepath */, const std::string * /* filename */,
const tinygltf::Image *image, bool /* embedImages */,
const tinygltf::FsCallbacks * /* fs_cb */, const tinygltf::URICallbacks * /* uri_cb */,
std::string * /* out_uri */, void * user_pointer) {
REQUIRE(user_pointer != nullptr);
auto counter = static_cast<int*>(user_pointer);
*counter = *counter + 1;
return true;
}
TEST_CASE("empty-images-not-written", "[issue-495]") {
std::string err;
std::string warn;
tinygltf::Model model;
tinygltf::TinyGLTF ctx;
ctx.SetImageLoader(LoadImageData, nullptr);
bool ok = ctx.LoadASCIIFromFile(&model, &err, &warn, "../models/Cube/Cube.gltf");
REQUIRE(ok);
REQUIRE(err.empty());
REQUIRE(warn.empty());
CHECK(model.images.size() == 2);
for (const auto& image : model.images) {
// No data loaded or decoded
CHECK(image.image.empty());
// The URI is kept
CHECK_FALSE(image.uri.empty());
// The URI should not be a data URI
CHECK(image.uri.find("data:") != 0);
}
// Now write the loaded model
int counter = 0;
ctx.SetImageWriter(WriteImageData, &counter);
ok = ctx.WriteGltfSceneToFile(&model, "issue-495-external.gltf");
CHECK(ok);
// WriteImageData should be invoked for both images
CHECK(counter == 2);
}

View File

@@ -25,7 +25,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Version: - v2.8.10
// Version: - v2.9.*
// See https://github.com/syoyo/tinygltf/releases for release history.
//
// Tiny glTF loader is using following third party libraries:
@@ -43,17 +43,13 @@
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <limits>
#include <map>
#include <string>
#include <utility>
#include <vector>
// Auto-detect C++14 standard version
#if !defined(TINYGLTF_USE_CPP14) && defined(__cplusplus) && \
(__cplusplus >= 201402L)
#define TINYGLTF_USE_CPP14
#endif
#ifdef __ANDROID__
#ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS
#include <android/asset_manager.h>
@@ -337,12 +333,11 @@ class Value {
T &Get();
// Lookup value from an array
const Value &Get(int idx) const {
const Value &Get(size_t idx) const {
static Value null_value;
assert(IsArray());
assert(idx >= 0);
return (static_cast<size_t>(idx) < array_value_.size())
? array_value_[static_cast<size_t>(idx)]
return (idx < array_value_.size())
? array_value_[idx]
: null_value;
}
@@ -648,9 +643,7 @@ struct Image {
// When this flag is true, data is stored to `image` in as-is format(e.g. jpeg
// compressed for "image/jpeg" mime) This feature is good if you use custom
// image loader function. (e.g. delayed decoding of images for faster glTF
// parsing) Default parser for Image does not provide as-is loading feature at
// the moment. (You can manipulate this by providing your own LoadImageData
// function)
// parsing).
bool as_is{false};
Image() = default;
@@ -835,20 +828,20 @@ struct Accessor {
maxValues; // optional. integer value is promoted to double
struct Sparse {
int count;
bool isSparse;
int count{0};
bool isSparse{false};
struct {
size_t byteOffset;
int bufferView;
int componentType; // a TINYGLTF_COMPONENT_TYPE_ value
size_t byteOffset{0};
int bufferView{-1};
int componentType{-1}; // a TINYGLTF_COMPONENT_TYPE_ value
Value extras;
ExtensionMap extensions;
std::string extras_json_string;
std::string extensions_json_string;
} indices;
struct {
int bufferView;
size_t byteOffset;
int bufferView{-1};
size_t byteOffset{0};
Value extras;
ExtensionMap extensions;
std::string extras_json_string;
@@ -899,11 +892,7 @@ struct Accessor {
// unreachable return 0;
}
Accessor()
{
sparse.isSparse = false;
}
Accessor() = default;
DEFAULT_METHODS(Accessor)
bool operator==(const tinygltf::Accessor &) const;
};
@@ -1264,17 +1253,18 @@ enum SectionCheck {
/// image URIs differently, for example. See
/// https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#uris
///
typedef bool (*URIEncodeFunction)(const std::string &in_uri,
const std::string &object_type,
std::string *out_uri, void *user_data);
using URIEncodeFunction = std::function<bool(
const std::string & /* in_uri */, const std::string & /* object_type */,
std::string * /* out_uri */, void * /* user_data */)>;
///
/// URIDecodeFunction type. Signature for custom URI decoding of external
/// resources such as .bin and image files. Used by tinygltf when computing
/// filenames to write resources.
///
typedef bool (*URIDecodeFunction)(const std::string &in_uri,
std::string *out_uri, void *user_data);
using URIDecodeFunction =
std::function<bool(const std::string & /* in_uri */,
std::string * /* out_uri */, void * /* user_data */)>;
// Declaration of default uri decode function
bool URIDecode(const std::string &in_uri, std::string *out_uri,
@@ -1291,69 +1281,36 @@ struct URICallbacks {
};
///
/// LoadImageDataFunction type. Signature for custom image loading callbacks.
/// FileExistsFunction type. Signature for custom filesystem callbacks.
///
typedef bool (*LoadImageDataFunction)(Image *, const int, std::string *,
std::string *, int, int,
const unsigned char *, int,
void *user_pointer);
///
/// WriteImageDataFunction type. Signature for custom image writing callbacks.
/// The out_uri parameter becomes the URI written to the gltf and may reference
/// a file or contain a data URI.
///
typedef bool (*WriteImageDataFunction)(const std::string *basepath,
const std::string *filename,
const Image *image, bool embedImages,
const URICallbacks *uri_cb,
std::string *out_uri,
void *user_pointer);
#ifndef TINYGLTF_NO_STB_IMAGE
// Declaration of default image loader callback
bool LoadImageData(Image *image, const int image_idx, std::string *err,
std::string *warn, int req_width, int req_height,
const unsigned char *bytes, int size, void *);
#endif
#ifndef TINYGLTF_NO_STB_IMAGE_WRITE
// Declaration of default image writer callback
bool WriteImageData(const std::string *basepath, const std::string *filename,
const Image *image, bool embedImages,
const URICallbacks *uri_cb, std::string *out_uri, void *);
#endif
///
/// FilExistsFunction type. Signature for custom filesystem callbacks.
///
typedef bool (*FileExistsFunction)(const std::string &abs_filename, void *);
using FileExistsFunction = std::function<bool(
const std::string & /* abs_filename */, void * /* user_data */)>;
///
/// ExpandFilePathFunction type. Signature for custom filesystem callbacks.
///
typedef std::string (*ExpandFilePathFunction)(const std::string &, void *);
using ExpandFilePathFunction =
std::function<std::string(const std::string &, void *)>;
///
/// ReadWholeFileFunction type. Signature for custom filesystem callbacks.
///
typedef bool (*ReadWholeFileFunction)(std::vector<unsigned char> *,
std::string *, const std::string &,
void *);
using ReadWholeFileFunction = std::function<bool(
std::vector<unsigned char> *, std::string *, const std::string &, void *)>;
///
/// WriteWholeFileFunction type. Signature for custom filesystem callbacks.
///
typedef bool (*WriteWholeFileFunction)(std::string *, const std::string &,
const std::vector<unsigned char> &,
void *);
using WriteWholeFileFunction =
std::function<bool(std::string *, const std::string &,
const std::vector<unsigned char> &, void *)>;
///
/// GetFileSizeFunction type. Signature for custom filesystem callbacks.
///
typedef bool (*GetFileSizeFunction)(size_t *filesize_out, std::string *err,
const std::string &abs_filename,
void *userdata);
using GetFileSizeFunction =
std::function<bool(size_t *filesize_out, std::string *err,
const std::string &abs_filename, void *userdata)>;
///
/// A structure containing all required filesystem callbacks and a pointer to
@@ -1394,6 +1351,40 @@ bool GetFileSizeInBytes(size_t *filesize_out, std::string *err,
const std::string &filepath, void *);
#endif
///
/// LoadImageDataFunction type. Signature for custom image loading callbacks.
///
using LoadImageDataFunction = std::function<bool(
Image * /* image */, const int /* image_idx */, std::string * /* err */,
std::string * /* warn */, int /* req_width */, int /* req_height */,
const unsigned char * /* bytes */, int /* size */, void * /*user_data */)>;
///
/// WriteImageDataFunction type. Signature for custom image writing callbacks.
/// The out_uri parameter becomes the URI written to the gltf and may reference
/// a file or contain a data URI.
///
using WriteImageDataFunction = std::function<bool(
const std::string * /* basepath */, const std::string * /* filename */,
const Image *image, bool /* embedImages */,
const FsCallbacks * /* fs_cb */, const URICallbacks * /* uri_cb */,
std::string * /* out_uri */, void * /* user_pointer */)>;
#ifndef TINYGLTF_NO_STB_IMAGE
// Declaration of default image loader callback
bool LoadImageData(Image *image, const int image_idx, std::string *err,
std::string *warn, int req_width, int req_height,
const unsigned char *bytes, int size, void *);
#endif
#ifndef TINYGLTF_NO_STB_IMAGE_WRITE
// Declaration of default image writer callback
bool WriteImageData(const std::string *basepath, const std::string *filename,
const Image *image, bool embedImages,
const FsCallbacks* fs_cb, const URICallbacks *uri_cb,
std::string *out_uri, void *);
#endif
///
/// glTF Parser/Serializer context.
///
@@ -1476,7 +1467,8 @@ class TinyGLTF {
void SetParseStrictness(ParseStrictness strictness);
///
/// Set callback to use for loading image data
/// Set callback to use for loading image data. Passing the nullptr is akin to
/// calling RemoveImageLoader().
///
void SetImageLoader(LoadImageDataFunction LoadImageData, void *user_data);
@@ -1491,14 +1483,18 @@ class TinyGLTF {
void SetImageWriter(WriteImageDataFunction WriteImageData, void *user_data);
///
/// Set callbacks to use for URI encoding and decoding and their user data
/// Set callbacks to use for URI encoding and decoding and their user data.
/// Returns false if there is an error with the callbacks. If err is not
/// nullptr, explanation will be written there.
///
void SetURICallbacks(URICallbacks callbacks);
bool SetURICallbacks(URICallbacks callbacks, std::string* err = nullptr);
///
/// Set callbacks to use for filesystem (fs) access and their user data
/// Set callbacks to use for filesystem (fs) access and their user data.
/// Returns false if there is an error with the callbacks. If err is not
/// nullptr, explanation will be written there.
///
void SetFsCallbacks(FsCallbacks callbacks);
bool SetFsCallbacks(FsCallbacks callbacks, std::string* err = nullptr);
///
/// Set serializing default values(default = false).
@@ -1536,6 +1532,17 @@ class TinyGLTF {
preserve_image_channels_ = onoff;
}
bool GetPreserveImageChannels() const { return preserve_image_channels_; }
///
/// Specifiy whether image data is decoded/decompressed during load, or left as is
///
void SetImagesAsIs(bool onoff) {
images_as_is_ = onoff;
}
bool GetImagesAsIs() const { return images_as_is_; }
///
/// Set maximum allowed external file size in bytes.
/// Default: 2GB
@@ -1547,8 +1554,6 @@ class TinyGLTF {
size_t GetMaxExternalFileSize() const { return max_external_file_size_; }
bool GetPreserveImageChannels() const { return preserve_image_channels_; }
private:
///
/// Loads glTF asset from string(memory).
@@ -1573,6 +1578,8 @@ class TinyGLTF {
bool preserve_image_channels_ = false; /// Default false(expand channels to
/// RGBA) for backward compatibility.
bool images_as_is_ = false; /// Default false (decode/decompress images)
size_t max_external_file_size_{
size_t((std::numeric_limits<int32_t>::max)())}; // Default 2GB
@@ -1898,6 +1905,9 @@ struct LoadImageDataOption {
// channels) default `false`(channels are expanded to RGBA for backward
// compatibility).
bool preserve_channels{false};
// true: do not decode/decompress image data.
// default `false`: decode/decompress image data.
bool as_is{false};
};
// Equals function for Value, for recursivity
@@ -1927,7 +1937,7 @@ static bool Equals(const tinygltf::Value &one, const tinygltf::Value &other) {
}
case ARRAY_TYPE: {
if (one.Size() != other.Size()) return false;
for (int i = 0; i < int(one.Size()); ++i)
for (size_t i = 0; i < one.Size(); ++i)
if (!Equals(one.Get(i), other.Get(i))) return false;
return true;
}
@@ -2246,7 +2256,7 @@ static std::string GetFilePathExtension(const std::string &FileName) {
static std::string GetBaseDir(const std::string &filepath) {
if (filepath.find_last_of("/\\") != std::string::npos)
return filepath.substr(0, filepath.find_last_of("/\\"));
return filepath.substr(0, filepath.find_last_of("/\\") + 1);
return "";
}
@@ -2572,7 +2582,11 @@ void TinyGLTF::SetParseStrictness(ParseStrictness strictness) {
}
void TinyGLTF::SetImageLoader(LoadImageDataFunction func, void *user_data) {
LoadImageData = func;
if (func == nullptr) {
RemoveImageLoader();
return;
}
LoadImageData = std::move(func);
load_image_user_data_ = user_data;
user_image_loader_ = true;
}
@@ -2602,48 +2616,65 @@ bool LoadImageData(Image *image, const int image_idx, std::string *err,
int w = 0, h = 0, comp = 0, req_comp = 0;
unsigned char *data = nullptr;
// Try to decode image header
if (!stbi_info_from_memory(bytes, size, &w, &h, &comp)) {
// On failure, if we load images as is, we just warn.
std::string* msgOut = option.as_is ? warn : err;
if (msgOut) {
(*msgOut) +=
"Unknown image format. STB cannot decode image header for image[" +
std::to_string(image_idx) + "] name = \"" + image->name + "\".\n";
}
if (!option.as_is) {
// If we decode images, error out.
return false;
} else {
// If we load images as is, we copy the image data,
// set all image properties to invalid, and report success.
image->width = image->height = image->component = -1;
image->bits = image->pixel_type = -1;
image->image.resize(static_cast<size_t>(size));
std::copy(bytes, bytes + size, image->image.begin());
return true;
}
}
int bits = 8;
int pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
if (stbi_is_16_bit_from_memory(bytes, size)) {
bits = 16;
pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT;
}
// preserve_channels true: Use channels stored in the image file.
// false: force 32-bit textures for common Vulkan compatibility. It appears
// that some GPU drivers do not support 24-bit images for Vulkan
req_comp = option.preserve_channels ? 0 : 4;
int bits = 8;
int pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
req_comp = (option.preserve_channels || option.as_is) ? 0 : 4;
// It is possible that the image we want to load is a 16bit per channel image
// We are going to attempt to load it as 16bit per channel, and if it worked,
// set the image data accordingly. We are casting the returned pointer into
// unsigned char, because we are representing "bytes". But we are updating
// the Image metadata to signal that this image uses 2 bytes (16bits) per
// channel:
if (stbi_is_16_bit_from_memory(bytes, size)) {
data = reinterpret_cast<unsigned char *>(
stbi_load_16_from_memory(bytes, size, &w, &h, &comp, req_comp));
if (data) {
bits = 16;
pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT;
unsigned char* data = nullptr;
// Perform image decoding if requested
if (!option.as_is) {
// If the image is marked as 16 bit per channel, attempt to decode it as such first.
// If that fails, we are going to attempt to load it as 8 bit per channel image.
if (bits == 16) {
data = reinterpret_cast<unsigned char *>(stbi_load_16_from_memory(bytes, size, &w, &h, &comp, req_comp));
}
}
// at this point, if data is still NULL, it means that the image wasn't
// 16bit per channel, we are going to load it as a normal 8bit per channel
// image as we used to do:
// if image cannot be decoded, ignore parsing and keep it by its path
// don't break in this case
// FIXME we should only enter this function if the image is embedded. If
// image->uri references
// an image file, it should be left as it is. Image loading should not be
// mandatory (to support other formats)
if (!data) data = stbi_load_from_memory(bytes, size, &w, &h, &comp, req_comp);
if (!data) {
// NOTE: you can use `warn` instead of `err`
if (err) {
(*err) +=
"Unknown image format. STB cannot decode image data for image[" +
std::to_string(image_idx) + "] name = \"" + image->name + "\".\n";
// Load as 8 bit per channel data
if (!data) {
data = stbi_load_from_memory(bytes, size, &w, &h, &comp, req_comp);
if (!data) {
if (err) {
(*err) +=
"Unknown image format. STB cannot decode image data for image[" +
std::to_string(image_idx) + "] name = \"" + image->name + "\".\n";
}
return false;
}
// If we were succesful, mark as 8 bit
bits = 8;
pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
}
return false;
}
if ((w < 1) || (h < 1)) {
@@ -2689,16 +2720,26 @@ bool LoadImageData(Image *image, const int image_idx, std::string *err,
image->component = comp;
image->bits = bits;
image->pixel_type = pixel_type;
image->image.resize(static_cast<size_t>(w * h * comp) * size_t(bits / 8));
std::copy(data, data + w * h * comp * (bits / 8), image->image.begin());
stbi_image_free(data);
image->as_is = option.as_is;
if (option.as_is) {
// Store the original image data
image->image.resize(static_cast<size_t>(size));
std::copy(bytes, bytes + size, image->image.begin());
}
else {
// Store the decoded image data
image->image.resize(static_cast<size_t>(w * h * comp) * size_t(bits / 8));
std::copy(data, data + w * h * comp * (bits / 8), image->image.begin());
}
stbi_image_free(data);
return true;
}
#endif
void TinyGLTF::SetImageWriter(WriteImageDataFunction func, void *user_data) {
WriteImageData = func;
WriteImageData = std::move(func);
write_image_user_data_ = user_data;
}
@@ -2714,36 +2755,51 @@ static void WriteToMemory_stbi(void *context, void *data, int size) {
bool WriteImageData(const std::string *basepath, const std::string *filename,
const Image *image, bool embedImages,
const URICallbacks *uri_cb, std::string *out_uri,
void *fsPtr) {
const FsCallbacks* fs_cb, const URICallbacks *uri_cb,
std::string *out_uri, void *) {
// Early out on empty images, report the original uri if the image was not written.
if (image->image.empty()) {
*out_uri = *filename;
return true;
}
const std::string ext = GetFilePathExtension(*filename);
// Write image to temporary buffer
std::string header;
std::vector<unsigned char> data;
if (ext == "png") {
if ((image->bits != 8) ||
(image->pixel_type != TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE)) {
// Unsupported pixel format
return false;
}
// If the image data is already encoded, take it as is
if (image->as_is) {
data = image->image;
}
if (!stbi_write_png_to_func(WriteToMemory_stbi, &data, image->width,
image->height, image->component,
&image->image[0], 0)) {
return false;
if (ext == "png") {
if (!image->as_is) {
if ((image->bits != 8) ||
(image->pixel_type != TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE)) {
// Unsupported pixel format
return false;
}
if (!stbi_write_png_to_func(WriteToMemory_stbi, &data, image->width,
image->height, image->component,
&image->image[0], 0)) {
return false;
}
}
header = "data:image/png;base64,";
} else if (ext == "jpg") {
if (!stbi_write_jpg_to_func(WriteToMemory_stbi, &data, image->width,
if (!image->as_is &&
!stbi_write_jpg_to_func(WriteToMemory_stbi, &data, image->width,
image->height, image->component,
&image->image[0], 100)) {
return false;
}
header = "data:image/jpeg;base64,";
} else if (ext == "bmp") {
if (!stbi_write_bmp_to_func(WriteToMemory_stbi, &data, image->width,
if (!image->as_is &&
!stbi_write_bmp_to_func(WriteToMemory_stbi, &data, image->width,
image->height, image->component,
&image->image[0])) {
return false;
@@ -2764,12 +2820,11 @@ bool WriteImageData(const std::string *basepath, const std::string *filename,
}
} else {
// Write image to disc
FsCallbacks *fs = reinterpret_cast<FsCallbacks *>(fsPtr);
if ((fs != nullptr) && (fs->WriteWholeFile != nullptr)) {
if ((fs_cb != nullptr) && (fs_cb->WriteWholeFile != nullptr)) {
const std::string imagefilepath = JoinPath(*basepath, *filename);
std::string writeError;
if (!fs->WriteWholeFile(&writeError, imagefilepath, data,
fs->user_data)) {
if (!fs_cb->WriteWholeFile(&writeError, imagefilepath, data,
fs_cb->user_data)) {
// Could not write image file to disc; Throw error ?
return false;
}
@@ -2789,14 +2844,36 @@ bool WriteImageData(const std::string *basepath, const std::string *filename,
}
#endif
void TinyGLTF::SetURICallbacks(URICallbacks callbacks) {
assert(callbacks.decode);
if (callbacks.decode) {
uri_cb = callbacks;
bool TinyGLTF::SetURICallbacks(URICallbacks callbacks, std::string* err) {
if (callbacks.decode == nullptr) {
if (err != nullptr) {
*err = "URI Callback require a non-null decode function.";
}
return false;
}
if (callbacks.decode) {
uri_cb = std::move(callbacks);
}
return true;
}
void TinyGLTF::SetFsCallbacks(FsCallbacks callbacks) { fs = callbacks; }
bool TinyGLTF::SetFsCallbacks(FsCallbacks callbacks, std::string *err) {
// If callbacks are defined at all, they must all be defined.
if (callbacks.FileExists == nullptr || callbacks.ExpandFilePath == nullptr ||
callbacks.ReadWholeFile == nullptr ||
callbacks.WriteWholeFile == nullptr ||
callbacks.GetFileSizeInBytes == nullptr) {
if (err != nullptr) {
*err =
"FS Callbacks must be completely defined. At least one callback is "
"null.";
}
return false;
}
fs = std::move(callbacks);
return true;
}
#ifdef _WIN32
static inline std::wstring UTF8ToWchar(const std::string &str) {
@@ -3020,18 +3097,18 @@ bool GetFileSizeInBytes(size_t *filesize_out, std::string *err,
}
f.seekg(0, f.end);
size_t sz = static_cast<size_t>(f.tellg());
const auto sz = f.tellg();
// std::cout << "sz = " << sz << "\n";
f.seekg(0, f.beg);
if (int64_t(sz) < 0) {
if (sz < 0) {
if (err) {
(*err) += "Invalid file size : " + filepath +
" (does the path point to a directory?)";
}
return false;
} else if (sz == 0) {
} else if (sz == std::streamoff(0)) {
if (err) {
(*err) += "File is empty : " + filepath + "\n";
}
@@ -3043,7 +3120,7 @@ bool GetFileSizeInBytes(size_t *filesize_out, std::string *err,
return false;
}
(*filesize_out) = sz;
(*filesize_out) = static_cast<size_t>(sz);
return true;
#endif
}
@@ -3068,7 +3145,7 @@ bool ReadWholeFile(std::vector<unsigned char> *out, std::string *err,
}
return false;
}
out->resize(size);
out->resize(static_cast<size_t>(size));
AAsset_read(asset, reinterpret_cast<char *>(&out->at(0)), size);
AAsset_close(asset);
return true;
@@ -3115,18 +3192,18 @@ bool ReadWholeFile(std::vector<unsigned char> *out, std::string *err,
}
f.seekg(0, f.end);
size_t sz = static_cast<size_t>(f.tellg());
const auto sz = f.tellg();
// std::cout << "sz = " << sz << "\n";
f.seekg(0, f.beg);
if (int64_t(sz) < 0) {
if (sz < 0) {
if (err) {
(*err) += "Invalid file size : " + filepath +
" (does the path point to a directory?)";
}
return false;
} else if (sz == 0) {
} else if (sz == std::streamoff(0)) {
if (err) {
(*err) += "File is empty : " + filepath + "\n";
}
@@ -3151,7 +3228,7 @@ bool WriteWholeFile(std::string *err, const std::string &filepath,
#ifdef _WIN32
#if defined(__GLIBCXX__) // mingw
int file_descriptor = _wopen(UTF8ToWchar(filepath).c_str(),
_O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
_O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY, _S_IWRITE);
__gnu_cxx::stdio_filebuf<char> wfile_buf(
file_descriptor, std::ios_base::out | std::ios_base::binary);
std::ostream f(&wfile_buf);
@@ -3200,8 +3277,9 @@ static std::string MimeToExt(const std::string &mimeType) {
static bool UpdateImageObject(const Image &image, std::string &baseDir,
int index, bool embedImages,
const FsCallbacks *fs_cb,
const URICallbacks *uri_cb,
WriteImageDataFunction *WriteImageData,
const WriteImageDataFunction& WriteImageData,
void *user_data, std::string *out_uri) {
std::string filename;
std::string ext;
@@ -3227,13 +3305,14 @@ static bool UpdateImageObject(const Image &image, std::string &baseDir,
filename = std::to_string(index) + "." + ext;
}
// If callback is set and image data exists, modify image data object. If
// image data does not exist, this is not considered a failure and the
// original uri should be maintained.
// If callback is set, modify image data object.
// Note that the callback is also invoked for images without data.
// The default callback implementation simply returns true for
// empty images and sets the out URI to filename.
bool imageWritten = false;
if (*WriteImageData != nullptr && !filename.empty() && !image.image.empty()) {
imageWritten = (*WriteImageData)(&baseDir, &filename, &image, embedImages,
uri_cb, out_uri, user_data);
if (WriteImageData != nullptr && !filename.empty()) {
imageWritten = WriteImageData(&baseDir, &filename, &image, embedImages,
fs_cb, uri_cb, out_uri, user_data);
if (!imageWritten) {
return false;
}
@@ -4215,7 +4294,7 @@ static bool ParseImage(Image *image, const int image_idx, std::string *err,
bool store_original_json_for_extras_and_extensions,
const std::string &basedir, const size_t max_file_size,
FsCallbacks *fs, const URICallbacks *uri_cb,
LoadImageDataFunction *LoadImageData = nullptr,
const LoadImageDataFunction& LoadImageData = nullptr,
void *load_image_user_data = nullptr) {
// A glTF image must either reference a bufferView or an image uri
@@ -4273,7 +4352,7 @@ static bool ParseImage(Image *image, const int image_idx, std::string *err,
// Just only save some information here. Loading actual image data from
// bufferView is done after this `ParseImage` function.
image->bufferView = bufferView;
image->mimeType = mime_type;
image->mimeType = std::move( mime_type );
image->width = width;
image->height = height;
@@ -4305,7 +4384,7 @@ static bool ParseImage(Image *image, const int image_idx, std::string *err,
}
} else {
// Assume external file
// Keep texture path (for textures that cannot be decoded)
// Unconditionally keep the external URI of the image
image->uri = uri;
#ifdef TINYGLTF_NO_EXTERNAL_IMAGE
return true;
@@ -4346,14 +4425,15 @@ static bool ParseImage(Image *image, const int image_idx, std::string *err,
#endif
}
if (*LoadImageData == nullptr) {
if (LoadImageData == nullptr) {
if (err) {
(*err) += "No LoadImageData callback specified.\n";
}
return false;
}
return (*LoadImageData)(image, image_idx, err, warn, 0, 0, &img.at(0),
static_cast<int>(img.size()), load_image_user_data);
return LoadImageData(image, image_idx, err, warn, 0, 0, &img.at(0),
static_cast<int>(img.size()), load_image_user_data);
}
static bool ParseTexture(Texture *texture, std::string *err,
@@ -5171,7 +5251,7 @@ static bool ParseNode(Node *node, std::string *err, const detail::json &o,
if (node->extensions.count("MSFT_lod") != 0) {
auto const &msft_lod_ext = node->extensions["MSFT_lod"];
if (msft_lod_ext.Has("ids")) {
auto idsArr = msft_lod_ext.Get("ids");
const auto &idsArr = msft_lod_ext.Get("ids");
for (size_t i = 0; i < idsArr.ArrayLen(); ++i) {
node->lods.emplace_back(idsArr.Get(i).GetNumberAsInt());
}
@@ -5200,7 +5280,7 @@ static bool ParseScene(Scene *scene, std::string *err, const detail::json &o,
if (scene->extensions.count("KHR_audio") != 0) {
auto const &audio_ext = scene->extensions["KHR_audio"];
if (audio_ext.Has("emitters")) {
auto emittersArr = audio_ext.Get("emitters");
const auto &emittersArr = audio_ext.Get("emitters");
for (size_t i = 0; i < emittersArr.ArrayLen(); ++i) {
scene->audioEmitters.emplace_back(emittersArr.Get(i).GetNumberAsInt());
}
@@ -5236,7 +5316,7 @@ static bool ParsePbrMetallicRoughness(
}
return false;
}
pbr->baseColorFactor = baseColorFactor;
pbr->baseColorFactor = std::move( baseColorFactor );
}
{
@@ -5388,7 +5468,7 @@ static bool ParseMaterial(Material *material, std::string *err, std::string *war
if (material->extensions.count("MSFT_lod") != 0) {
auto const &msft_lod_ext = material->extensions["MSFT_lod"];
if (msft_lod_ext.Has("ids")) {
auto idsArr = msft_lod_ext.Get("ids");
const auto &idsArr = msft_lod_ext.Get("ids");
for (size_t i = 0; i < idsArr.ArrayLen(); ++i) {
material->lods.emplace_back(idsArr.Get(i).GetNumberAsInt());
}
@@ -5515,7 +5595,7 @@ static bool ParseAnimation(Animation *animation, std::string *err,
}
sampler.input = inputIndex;
sampler.output = outputIndex;
ParseExtrasAndExtensions(&sampler, err, o,
ParseExtrasAndExtensions(&sampler, err, s,
store_original_json_for_extras_and_extensions);
animation->samplers.emplace_back(std::move(sampler));
@@ -5578,7 +5658,7 @@ static bool ParseSkin(Skin *skin, std::string *err, const detail::json &o,
skin->skeleton = skeleton;
int invBind = -1;
ParseIntegerProperty(&invBind, err, o, "inverseBindMatrices", true, "Skin");
ParseIntegerProperty(&invBind, err, o, "inverseBindMatrices", false, "Skin");
skin->inverseBindMatrices = invBind;
ParseExtrasAndExtensions(skin, err, o,
@@ -6026,16 +6106,8 @@ bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn,
}
}
model->buffers.clear();
model->bufferViews.clear();
model->accessors.clear();
model->meshes.clear();
model->cameras.clear();
model->nodes.clear();
model->extensionsUsed.clear();
model->extensionsRequired.clear();
model->extensions.clear();
model->defaultScene = -1;
// Reset the model
(*model) = Model();
// 1. Parse Asset
{
@@ -6326,6 +6398,7 @@ bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn,
load_image_user_data = load_image_user_data_;
} else {
load_image_option.preserve_channels = preserve_image_channels_;
load_image_option.as_is = images_as_is_;
load_image_user_data = reinterpret_cast<void *>(&load_image_option);
}
@@ -6342,7 +6415,7 @@ bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn,
if (!ParseImage(&image, idx, err, warn, o,
store_original_json_for_extras_and_extensions_, base_dir,
max_external_file_size_, &fs, &uri_cb,
&this->LoadImageData, load_image_user_data)) {
this->LoadImageData, load_image_user_data)) {
return false;
}
@@ -6370,8 +6443,17 @@ bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn,
return false;
}
const Buffer &buffer = model->buffers[size_t(bufferView.buffer)];
if (bufferView.byteOffset >= buffer.data.size()) {
if (err) {
std::stringstream ss;
ss << "image[" << idx << "] bufferView \"" << image.bufferView
<< "\" indexed out of bounds of its buffer." << std::endl;
(*err) += ss.str();
}
return false;
}
if (*LoadImageData == nullptr) {
if (LoadImageData == nullptr) {
if (err) {
(*err) += "No LoadImageData callback specified.\n";
}
@@ -6751,7 +6833,7 @@ bool TinyGLTF::LoadBinaryFromMemory(Model *model, std::string *err,
// 'SHOULD' in glTF spec means 'RECOMMENDED',
// So there is a situation that Chunk1(BIN) is composed of zero-sized BIN data
// (chunksize(0) + binformat(BIN) = 8bytes).
//
//
if ((header_and_json_size + 8ull) > uint64_t(length)) {
if (err) {
(*err) =
@@ -7070,10 +7152,10 @@ static bool ValueToJson(const Value &value, detail::json *ret) {
obj = detail::json(value.Get<std::string>());
break;
case ARRAY_TYPE: {
for (unsigned int i = 0; i < value.ArrayLen(); ++i) {
Value elementValue = value.Get(int(i));
for (size_t i = 0; i < value.ArrayLen(); ++i) {
Value elementValue = value.Get(i);
detail::json elementJson;
if (ValueToJson(value.Get(int(i)), &elementJson))
if (ValueToJson(value.Get(i), &elementJson))
obj.push_back(elementJson);
}
break;
@@ -7124,10 +7206,11 @@ static void SerializeGltfBufferData(const std::vector<unsigned char> &data,
static bool SerializeGltfBufferData(const std::vector<unsigned char> &data,
const std::string &binFilename) {
#ifndef TINYGLTF_NO_FS
#ifdef _WIN32
#if defined(__GLIBCXX__) // mingw
int file_descriptor = _wopen(UTF8ToWchar(binFilename).c_str(),
_O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
_O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY, _S_IWRITE);
__gnu_cxx::stdio_filebuf<char> wfile_buf(
file_descriptor, std::ios_base::out | std::ios_base::binary);
std::ostream output(&wfile_buf);
@@ -7152,6 +7235,9 @@ static bool SerializeGltfBufferData(const std::vector<unsigned char> &data,
// write empty file.
}
return true;
#else
return false;
#endif
}
#if 0 // FIXME(syoyo): not used. will be removed in the future release.
@@ -8334,6 +8420,32 @@ static void SerializeGltfModel(const Model *model, detail::json &o) {
}
}
// MSFT_lod
// Look if there is a node that employs MSFT_lod
auto msft_lod_nodes_it = std::find_if(
model->nodes.begin(), model->nodes.end(),
[](const Node& node) { return !node.lods.empty(); });
// Look if there is a material that employs MSFT_lod
auto msft_lod_materials_it = std::find_if(
model->materials.begin(), model->materials.end(),
[](const Material& material) {return !material.lods.empty(); });
// If either a node or a material employ MSFT_lod, then we need
// to add MSFT_lod to the list of used extensions.
if (msft_lod_nodes_it != model->nodes.end() || msft_lod_materials_it != model->materials.end()) {
// First check if MSFT_lod is already registered as used extension
auto has_msft_lod = std::find_if(
extensionsUsed.begin(), extensionsUsed.end(),
[](const std::string &s) { return (s.compare("MSFT_lod") == 0); });
// If MSFT_lod is not registered yet, add it
if (has_msft_lod == extensionsUsed.end()) {
extensionsUsed.push_back("MSFT_lod");
}
}
// Extensions used
if (extensionsUsed.size()) {
SerializeStringArrayProperty("extensionsUsed", extensionsUsed, o);
@@ -8347,12 +8459,13 @@ static bool WriteGltfStream(std::ostream &stream, const std::string &content) {
static bool WriteGltfFile(const std::string &output,
const std::string &content) {
#ifndef TINYGLTF_NO_FS
#ifdef _WIN32
#if defined(_MSC_VER)
std::ofstream gltfFile(UTF8ToWchar(output).c_str());
#elif defined(__GLIBCXX__)
int file_descriptor = _wopen(UTF8ToWchar(output).c_str(),
_O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
_O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY, _S_IWRITE);
__gnu_cxx::stdio_filebuf<char> wfile_buf(
file_descriptor, std::ios_base::out | std::ios_base::binary);
std::ostream gltfFile(&wfile_buf);
@@ -8366,6 +8479,9 @@ static bool WriteGltfFile(const std::string &output,
if (!gltfFile.is_open()) return false;
#endif
return WriteGltfStream(gltfFile, content);
#else
return false;
#endif
}
static bool WriteBinaryGltfStream(std::ostream &stream,
@@ -8432,12 +8548,13 @@ static bool WriteBinaryGltfStream(std::ostream &stream,
static bool WriteBinaryGltfFile(const std::string &output,
const std::string &content,
const std::vector<unsigned char> &binBuffer) {
#ifndef TINYGLTF_NO_FS
#ifdef _WIN32
#if defined(_MSC_VER)
std::ofstream gltfFile(UTF8ToWchar(output).c_str(), std::ios::binary);
#elif defined(__GLIBCXX__)
int file_descriptor = _wopen(UTF8ToWchar(output).c_str(),
_O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
_O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY, _S_IWRITE);
__gnu_cxx::stdio_filebuf<char> wfile_buf(
file_descriptor, std::ios_base::out | std::ios_base::binary);
std::ostream gltfFile(&wfile_buf);
@@ -8448,6 +8565,9 @@ static bool WriteBinaryGltfFile(const std::string &output,
std::ofstream gltfFile(output.c_str(), std::ios::binary);
#endif
return WriteBinaryGltfStream(gltfFile, content, binBuffer);
#else
return false;
#endif
}
bool TinyGLTF::WriteGltfSceneToStream(const Model *model, std::ostream &stream,
@@ -8488,7 +8608,7 @@ bool TinyGLTF::WriteGltfSceneToStream(const Model *model, std::ostream &stream,
// we
std::string uri;
if (!UpdateImageObject(model->images[i], dummystring, int(i), true,
&uri_cb, &this->WriteImageData,
&fs, &uri_cb, this->WriteImageData,
this->write_image_user_data_, &uri)) {
return false;
}
@@ -8596,7 +8716,7 @@ bool TinyGLTF::WriteGltfSceneToFile(const Model *model,
std::string uri;
if (!UpdateImageObject(model->images[i], baseDir, int(i), embedImages,
&uri_cb, &this->WriteImageData,
&fs, &uri_cb, this->WriteImageData,
this->write_image_user_data_, &uri)) {
return false;
}