jkuhlmann / cgltf

:diamond_shape_with_a_dot_inside: Single-file glTF 2.0 loader and writer written in C99
MIT License
1.42k stars 135 forks source link

load glb crash #247

Closed Xarvie closed 5 months ago

Xarvie commented 5 months ago

untitled16.zip

Is this a bug, or did I miss something? I tried using tiny_gltf and it successfully loaded.

Xarvie commented 5 months ago

line 43: data[i] = ((unsigned char *) bv->buffer)[offset]; <- crash here.

Xarvie commented 5 months ago

#include <iostream>

#define CGLTF_IMPLEMENTATION
#include "cgltf.h"
cgltf_data *loadGltfFile(const char *path) {
    cgltf_options options;
    memset(&options, 0, sizeof(cgltf_options));
    cgltf_data *data = NULL;

    cgltf_result result = cgltf_parse_file(&options, path, &data);
    if (result != cgltf_result_success) {
        std::cout << "Could not load input file: " << path << "\n";
        return 0;
    }
    result = cgltf_load_buffers(&options, data, path);
    if (result != cgltf_result_success) {
        cgltf_free(data);
        std::cout << "Could not load buffers for: " << path << "\n";
        return 0;
    }
    result = cgltf_validate(data);
    if (result != cgltf_result_success) {
        cgltf_free(data);
        std::cout << "Invalid gltf file: " << path << "\n";
        return 0;
    }
    return data;
}

void LoadglTFTexture(const cgltf_texture &gltf_texture) {
    std::string mimeType;
    size_t imageByteLen = 0;
    const unsigned char *imageBytes = nullptr;
    const cgltf_buffer_view *bv = gltf_texture.image->buffer_view;
    if (gltf_texture.image->uri) {

    } else {
        unsigned char *data = (unsigned char *) malloc(bv->size);
        int offset = (int) bv->offset;
        int stride = (int) bv->stride ? (int) bv->stride : 1;

        for (unsigned int i = 0; i < bv->size; i++) {
            data[i] = ((unsigned char *) bv->buffer)[offset];
            offset += stride;
        }
    }
}

int main() {
    auto data = loadGltfFile("a.glb");
    for (std::size_t i = 0; i < data->textures_count; ++i) {
        cgltf_texture *tex = data->textures + i;
        LoadglTFTexture(*tex);
    }
    return 0;
}
Xarvie commented 5 months ago

sorry, resolved.

//data[i] = ((unsigned char *) bv->buffer)[offset];
data[i] = ((unsigned char *) bv->buffer->data)[offset];