SPB Git

Repository Public License

shim.c 24.2 KB 461 lines c

1// ORIX Convert — Packages/EngineModel3D/Sources/CAssimpShim/shim.c2// Description: Implementation of the C layer over Assimp (see orix_assimp_shim.h).3// Author: Simon-Pierre Boucher — contact@spboucher.ai4#include "orix_assimp_shim.h"5#include <assimp/cimport.h>6#include <assimp/cexport.h>7#include <assimp/postprocess.h>8#include <assimp/config.h>9#include <assimp/version.h>10#include <assimp/GltfMaterial.h>11#include <stdio.h>12#include <stdlib.h>13#include <string.h>14#include <xlocale.h>1516static void set_err(char *err, size_t errlen, const char *msg) {17    if (!err || errlen == 0) return;18    snprintf(err, errlen, "%s", msg ? msg : "unknown error");19}2021// ---- Confined file access: Assimp may only open files inside the model's folder. ----2223#include <assimp/cfileio.h>24#include <limits.h>25#include <sys/stat.h>2627typedef struct { char root[PATH_MAX]; int blocked; } orix_fs;2829static size_t fs_read(struct aiFile *f, char *buffer, size_t size, size_t count) { return fread(buffer, size, count, (FILE *)f->UserData); }30static size_t fs_write(struct aiFile *f, const char *buffer, size_t size, size_t count) { (void)f; (void)buffer; (void)size; (void)count; return 0; }31static size_t fs_tell(struct aiFile *f) { off_t p = ftello((FILE *)f->UserData); return p < 0 ? 0 : (size_t)p; }32static size_t fs_size(struct aiFile *f) {33    struct stat st;34    if (fstat(fileno((FILE *)f->UserData), &st) != 0) return 0;35    return (size_t)st.st_size;36}37static aiReturn fs_seek(struct aiFile *f, size_t offset, enum aiOrigin origin) {38    int whence = origin == aiOrigin_SET ? SEEK_SET : (origin == aiOrigin_CUR ? SEEK_CUR : SEEK_END);39    return fseeko((FILE *)f->UserData, (off_t)offset, whence) == 0 ? aiReturn_SUCCESS : aiReturn_FAILURE;40}41static void fs_flush(struct aiFile *f) { (void)f; }4243static struct aiFile *fs_open(struct aiFileIO *io, const char *path, const char *mode) {44    orix_fs *fs = (orix_fs *)io->UserData;45    if (!path || !mode || strchr(mode, 'w') || strchr(mode, 'a') || strchr(mode, '+')) { fs->blocked++; return NULL; }46    char real[PATH_MAX];47    if (!realpath(path, real)) return NULL;                       // does not exist48    size_t n = strlen(fs->root);49    if (strncmp(real, fs->root, n) != 0 || (real[n] != '/' && real[n] != 0)) { fs->blocked++; return NULL; }50    struct stat st;51    if (stat(real, &st) != 0 || !S_ISREG(st.st_mode)) return NULL;52    FILE *file = fopen(real, "rb");53    if (!file) return NULL;54    struct aiFile *f = calloc(1, sizeof *f);55    f->ReadProc = fs_read; f->WriteProc = fs_write; f->TellProc = fs_tell; f->FileSizeProc = fs_size;56    f->SeekProc = fs_seek; f->FlushProc = fs_flush; f->UserData = (aiUserData)file;57    return f;58}59static void fs_close(struct aiFileIO *io, struct aiFile *f) { (void)io; if (f) { fclose((FILE *)f->UserData); free(f); } }6061const struct aiScene *orix_import(const char *path, const char *root, uint64_t max_vertices, uint64_t max_faces, int *blocked,62                                  orix_prestats *stats, int *limit_hit, char *err, size_t errlen) {63    if (limit_hit) *limit_hit = 0;64    if (blocked) *blocked = 0;65    orix_fs fs; memset(&fs, 0, sizeof fs);66    if (!root || !realpath(root, fs.root)) { set_err(err, errlen, "the folder of the model cannot be resolved"); return NULL; }67    struct aiFileIO io; io.OpenProc = fs_open; io.CloseProc = fs_close; io.UserData = (aiUserData)&fs;68    struct aiPropertyStore *props = aiCreatePropertyStore();69    aiSetImportPropertyInteger(props, AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, 1);70    aiSetImportPropertyInteger(props, AI_CONFIG_IMPORT_COLLADA_IGNORE_UNIT_SIZE, 1);71    aiSetImportPropertyInteger(props, AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, 0);72    aiSetImportPropertyInteger(props, AI_CONFIG_PP_SBP_REMOVE, 0);73    const struct aiScene *scene = aiImportFileExWithProperties(path, aiProcess_ValidateDataStructure, &io, props);74    aiReleasePropertyStore(props);75    if (blocked) *blocked = fs.blocked;76    if (!scene) { set_err(err, errlen, aiGetErrorString()); return NULL; }77    if (!scene->mRootNode) { set_err(err, errlen, "the file has no scene graph"); aiReleaseImport(scene); return NULL; }7879    orix_prestats s; memset(&s, 0, sizeof s);80    for (unsigned m = 0; m < scene->mNumMeshes; m++) {81        const struct aiMesh *mesh = scene->mMeshes[m];82        if (!mesh) continue;83        s.vertices += mesh->mNumVertices;84        s.faces += mesh->mNumFaces;85        s.bones += mesh->mNumBones;86        s.morphTargets += mesh->mNumAnimMeshes;87        unsigned uv = 0, col = 0;88        for (unsigned c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; c++) if (mesh->mTextureCoords[c]) uv++;89        for (unsigned c = 0; c < AI_MAX_NUMBER_OF_COLOR_SETS; c++) if (mesh->mColors[c]) col++;90        if (uv > s.maxUVChannels) s.maxUVChannels = uv;91        if (col > s.maxColorChannels) s.maxColorChannels = col;92        if (!mesh->mFaces) continue;93        for (unsigned f = 0; f < mesh->mNumFaces; f++) {94            unsigned n = mesh->mFaces[f].mNumIndices;95            if (n == 1) s.points++; else if (n == 2) s.lines++; else if (n == 3) s.triangles++; else if (n > 3) s.polygons++;96        }97    }98    if (stats) *stats = s;99    if (s.vertices > max_vertices || s.faces > max_faces) {100        char msg[200];101        snprintf(msg, sizeof msg, "the model has %llu vertices and %llu faces (limits: %llu and %llu)",102                 (unsigned long long)s.vertices, (unsigned long long)s.faces, (unsigned long long)max_vertices, (unsigned long long)max_faces);103        set_err(err, errlen, msg);104        if (limit_hit) *limit_hit = 1;105        aiReleaseImport(scene);106        return NULL;107    }108    const struct aiScene *processed = aiApplyPostProcessing(scene, aiProcess_Triangulate | aiProcess_SortByPType);109    if (!processed) {110        set_err(err, errlen, aiGetErrorString());111        return NULL;   // Assimp released the scene itself112    }113    return processed;114}115116void orix_release(const struct aiScene *scene) { if (scene) aiReleaseImport(scene); }117118const char *orix_str(const struct aiString *s) { return s ? s->data : ""; }119120uint32_t orix_mesh_triangles(const struct aiMesh *mesh, uint32_t *out) {121    uint32_t count = 0;122    if (!mesh || !mesh->mFaces) return 0;123    for (unsigned f = 0; f < mesh->mNumFaces; f++) {124        const struct aiFace *face = &mesh->mFaces[f];125        if (face->mNumIndices != 3 || !face->mIndices) continue;126        unsigned a = face->mIndices[0], b = face->mIndices[1], c = face->mIndices[2];127        if (a >= mesh->mNumVertices || b >= mesh->mNumVertices || c >= mesh->mNumVertices) continue;128        if (out) { out[count * 3] = a; out[count * 3 + 1] = b; out[count * 3 + 2] = c; }129        count++;130    }131    return count;132}133134uint32_t orix_mesh_nontriangles(const struct aiMesh *mesh) {135    if (!mesh) return 0;136    return mesh->mNumFaces - orix_mesh_triangles(mesh, NULL);137}138139void orix_copy_vec3(const struct aiVector3D *src, uint32_t n, float *dst) {140    for (uint32_t i = 0; i < n; i++) { dst[i * 4] = src[i].x; dst[i * 4 + 1] = src[i].y; dst[i * 4 + 2] = src[i].z; dst[i * 4 + 3] = 0; }141}142143void orix_copy_uv(const struct aiVector3D *src, uint32_t n, float *dst) {144    for (uint32_t i = 0; i < n; i++) { dst[i * 2] = src[i].x; dst[i * 2 + 1] = src[i].y; }145}146147const struct aiVector3D *orix_mesh_uv(const struct aiMesh *mesh, uint32_t channel) {148    return (mesh && channel < AI_MAX_NUMBER_OF_TEXTURECOORDS) ? mesh->mTextureCoords[channel] : NULL;149}150151const struct aiColor4D *orix_mesh_color(const struct aiMesh *mesh, uint32_t channel) {152    return (mesh && channel < AI_MAX_NUMBER_OF_COLOR_SETS) ? mesh->mColors[channel] : NULL;153}154155int orix_copy_tangents(const struct aiMesh *mesh, float *dst) {156    if (!mesh || !mesh->mTangents || !mesh->mBitangents || !mesh->mNormals) return 0;157    for (uint32_t i = 0; i < mesh->mNumVertices; i++) {158        struct aiVector3D n = mesh->mNormals[i], t = mesh->mTangents[i], b = mesh->mBitangents[i];159        float cx = n.y * t.z - n.z * t.y, cy = n.z * t.x - n.x * t.z, cz = n.x * t.y - n.y * t.x;160        float d = cx * b.x + cy * b.y + cz * b.z;161        dst[i * 4] = t.x; dst[i * 4 + 1] = t.y; dst[i * 4 + 2] = t.z; dst[i * 4 + 3] = d < 0 ? -1.0f : 1.0f;162    }163    return 1;164}165166static const struct aiMetadataEntry *meta_find(const struct aiMetadata *meta, const char *key) {167    if (!meta || !meta->mKeys || !meta->mValues) return NULL;168    for (unsigned i = 0; i < meta->mNumProperties; i++)169        if (strcmp(meta->mKeys[i].data, key) == 0) return &meta->mValues[i];170    return NULL;171}172173int orix_meta_number(const struct aiMetadata *meta, const char *key, double *out) {174    const struct aiMetadataEntry *e = meta_find(meta, key);175    if (!e || !e->mData) return 0;176    switch (e->mType) {177        case AI_BOOL: *out = *(const char *)e->mData ? 1 : 0; return 1;178        case AI_INT32: *out = *(const int32_t *)e->mData; return 1;179        case AI_UINT32: *out = *(const uint32_t *)e->mData; return 1;180        case AI_INT64: *out = (double)*(const int64_t *)e->mData; return 1;181        case AI_UINT64: *out = (double)*(const uint64_t *)e->mData; return 1;182        case AI_FLOAT: *out = *(const float *)e->mData; return 1;183        case AI_DOUBLE: *out = *(const double *)e->mData; return 1;184        default: return 0;185    }186}187188int orix_meta_string(const struct aiMetadata *meta, const char *key, char *out, size_t outlen) {189    const struct aiMetadataEntry *e = meta_find(meta, key);190    if (!e || !e->mData || e->mType != AI_AISTRING || outlen == 0) return 0;191    snprintf(out, outlen, "%s", ((const struct aiString *)e->mData)->data);192    return 1;193}194195static int tex_slot(const struct aiMaterial *mat, enum aiTextureType type, orix_texslot *slot) {196    if (slot->present) return 1;197    if (aiGetMaterialTextureCount(mat, type) == 0) return 0;198    struct aiString path; memset(&path, 0, sizeof path);199    unsigned uv = 0;200    if (aiGetMaterialTexture(mat, type, 0, &path, NULL, &uv, NULL, NULL, NULL, NULL) != aiReturn_SUCCESS) return 0;201    snprintf(slot->path, sizeof slot->path, "%s", path.data);202    slot->present = 1;203    slot->uvIndex = (int)uv;204    return 1;205}206207static int has_prefix(const struct aiMaterial *mat, const char *prefix) {208    // A feature counts as used when one of its properties is a texture/string or a non-zero number.209    size_t n = strlen(prefix);210    for (unsigned i = 0; i < mat->mNumProperties; i++) {211        const struct aiMaterialProperty *p = mat->mProperties[i];212        if (!p || strncmp(p->mKey.data, prefix, n) != 0 || !p->mData) continue;213        if (p->mType == aiPTI_Float) {214            for (unsigned k = 0; k + sizeof(float) <= p->mDataLength; k += sizeof(float)) { float v; memcpy(&v, p->mData + k, sizeof v); if (v != 0) return 1; }215        } else if (p->mType == aiPTI_Double) {216            for (unsigned k = 0; k + sizeof(double) <= p->mDataLength; k += sizeof(double)) { double v; memcpy(&v, p->mData + k, sizeof v); if (v != 0) return 1; }217        } else if (p->mType == aiPTI_Integer) {218            for (unsigned k = 0; k + sizeof(int) <= p->mDataLength; k += sizeof(int)) { int v; memcpy(&v, p->mData + k, sizeof v); if (v != 0) return 1; }219        } else {220            return 1;221        }222    }223    return 0;224}225226void orix_material_info(const struct aiMaterial *mat, orix_matinfo *out) {227    memset(out, 0, sizeof *out);228    out->metallic = out->roughness = out->opacity = out->shininess = -1;229    out->base[0] = out->base[1] = out->base[2] = out->base[3] = 1;230    out->alphaCutoff = 0.5f;231    if (!mat) return;232    struct aiString s; memset(&s, 0, sizeof s);233    if (aiGetMaterialString(mat, AI_MATKEY_NAME, &s) == aiReturn_SUCCESS) snprintf(out->name, sizeof out->name, "%s", s.data);234    struct aiColor4D c;235    if (aiGetMaterialColor(mat, AI_MATKEY_BASE_COLOR, &c) == aiReturn_SUCCESS) {236        out->base[0] = c.r; out->base[1] = c.g; out->base[2] = c.b; out->base[3] = c.a; out->hasBase = 1;237    } else if (aiGetMaterialColor(mat, AI_MATKEY_COLOR_DIFFUSE, &c) == aiReturn_SUCCESS) {238        out->base[0] = c.r; out->base[1] = c.g; out->base[2] = c.b; out->base[3] = 1; out->hasBase = 2;239    }240    if (aiGetMaterialColor(mat, AI_MATKEY_COLOR_EMISSIVE, &c) == aiReturn_SUCCESS) { out->emissive[0] = c.r; out->emissive[1] = c.g; out->emissive[2] = c.b; }241    if (aiGetMaterialColor(mat, AI_MATKEY_COLOR_SPECULAR, &c) == aiReturn_SUCCESS) { out->specular[0] = c.r; out->specular[1] = c.g; out->specular[2] = c.b; out->hasSpecular = 1; }242    float f; unsigned n = 1;243    if (aiGetMaterialFloatArray(mat, AI_MATKEY_METALLIC_FACTOR, &f, &n) == aiReturn_SUCCESS) out->metallic = f;244    n = 1; if (aiGetMaterialFloatArray(mat, AI_MATKEY_ROUGHNESS_FACTOR, &f, &n) == aiReturn_SUCCESS) out->roughness = f;245    n = 1; if (aiGetMaterialFloatArray(mat, AI_MATKEY_OPACITY, &f, &n) == aiReturn_SUCCESS) out->opacity = f;246    n = 1; if (aiGetMaterialFloatArray(mat, AI_MATKEY_SHININESS, &f, &n) == aiReturn_SUCCESS) out->shininess = f;247    n = 1; if (aiGetMaterialFloatArray(mat, AI_MATKEY_GLTF_ALPHACUTOFF, &f, &n) == aiReturn_SUCCESS) out->alphaCutoff = f;248    int two = 0; n = 1;249    if (aiGetMaterialIntegerArray(mat, AI_MATKEY_TWOSIDED, &two, &n) == aiReturn_SUCCESS) out->twoSided = two != 0;250    if (aiGetMaterialString(mat, AI_MATKEY_GLTF_ALPHAMODE, &s) == aiReturn_SUCCESS) snprintf(out->alphaMode, sizeof out->alphaMode, "%s", s.data);251252    tex_slot(mat, aiTextureType_BASE_COLOR, &out->texBaseColor) || tex_slot(mat, aiTextureType_DIFFUSE, &out->texBaseColor);253    tex_slot(mat, aiTextureType_NORMALS, &out->texNormal) || tex_slot(mat, aiTextureType_NORMAL_CAMERA, &out->texNormal);254    tex_slot(mat, aiTextureType_EMISSIVE, &out->texEmissive) || tex_slot(mat, aiTextureType_EMISSION_COLOR, &out->texEmissive);255    tex_slot(mat, aiTextureType_GLTF_METALLIC_ROUGHNESS, &out->texMetallicRoughness) || tex_slot(mat, aiTextureType_UNKNOWN, &out->texMetallicRoughness)256        || tex_slot(mat, aiTextureType_METALNESS, &out->texMetallicRoughness);257    tex_slot(mat, aiTextureType_AMBIENT_OCCLUSION, &out->texOcclusion) || tex_slot(mat, aiTextureType_LIGHTMAP, &out->texOcclusion);258    static const enum aiTextureType others[] = { aiTextureType_SPECULAR, aiTextureType_AMBIENT, aiTextureType_HEIGHT, aiTextureType_SHININESS,259        aiTextureType_OPACITY, aiTextureType_DISPLACEMENT, aiTextureType_REFLECTION, aiTextureType_SHEEN, aiTextureType_CLEARCOAT,260        aiTextureType_TRANSMISSION, aiTextureType_ANISOTROPY };261    for (size_t i = 0; i < sizeof others / sizeof others[0]; i++) out->otherTextures += aiGetMaterialTextureCount(mat, others[i]);262263    if (has_prefix(mat, "$mat.clearcoat")) out->extensions |= ORIX_EXT_CLEARCOAT;264    if (has_prefix(mat, "$mat.sheen") || has_prefix(mat, "$clr.sheen")) out->extensions |= ORIX_EXT_SHEEN;265    if (has_prefix(mat, "$mat.transmission")) out->extensions |= ORIX_EXT_TRANSMISSION;266    if (has_prefix(mat, "$mat.volume")) out->extensions |= ORIX_EXT_VOLUME;267    if (has_prefix(mat, "$mat.glossinessFactor")) out->extensions |= ORIX_EXT_SPECGLOSS;268    if (has_prefix(mat, "$mat.anisotropy")) out->extensions |= ORIX_EXT_ANISOTROPY;269    if (has_prefix(mat, "$mat.emissiveIntensity")) out->extensions |= ORIX_EXT_EMISSIVE_STRENGTH;270    if (has_prefix(mat, "$mat.specularFactor")) out->extensions |= ORIX_EXT_SPECULAR;271}272273int orix_texture_info(const struct aiScene *scene, uint32_t index, const void **data, size_t *len,274                      char *hint, size_t hintlen, char *name, size_t namelen, int *compressed, uint32_t *width, uint32_t *height) {275    if (!scene || index >= scene->mNumTextures || !scene->mTextures || !scene->mTextures[index]) return 0;276    const struct aiTexture *t = scene->mTextures[index];277    *data = t->pcData;278    *compressed = t->mHeight == 0;279    *len = t->mHeight == 0 ? (size_t)t->mWidth : (size_t)t->mWidth * (size_t)t->mHeight * 4;280    *width = t->mWidth; *height = t->mHeight;281    if (hint && hintlen) { size_t n = sizeof t->achFormatHint; if (n >= hintlen) n = hintlen - 1; memcpy(hint, t->achFormatHint, n); hint[n] = 0; }282    if (name && namelen) snprintf(name, namelen, "%s", t->mFilename.data);283    return t->pcData != NULL;284}285286// ---- Export ----287288static void set_aistring(struct aiString *s, const char *text) {289    size_t n = text ? strlen(text) : 0;290    if (n >= AI_MAXLEN) n = AI_MAXLEN - 1;291    s->length = (ai_uint32)n;292    if (n) memcpy(s->data, text, n);293    s->data[n] = 0;294}295296static void add_prop(struct aiMaterial *mat, const char *key, unsigned semantic, enum aiPropertyTypeInfo type, const void *data, unsigned length) {297    struct aiMaterialProperty *p = calloc(1, sizeof *p);298    set_aistring(&p->mKey, key);299    p->mSemantic = semantic; p->mIndex = 0; p->mType = type; p->mDataLength = length;300    p->mData = malloc(length);301    memcpy(p->mData, data, length);302    mat->mProperties[mat->mNumProperties++] = p;303}304305static void add_string_prop(struct aiMaterial *mat, const char *key, unsigned semantic, const char *text) {306    // Material strings are stored as a 32-bit length followed by the zero-terminated characters.307    size_t n = strlen(text);308    if (n >= AI_MAXLEN) n = AI_MAXLEN - 1;309    unsigned length = (unsigned)(4 + n + 1);310    char *buf = calloc(1, length);311    ai_uint32 l = (ai_uint32)n;312    memcpy(buf, &l, 4); memcpy(buf + 4, text, n);313    add_prop(mat, key, semantic, aiPTI_String, buf, length);314    free(buf);315}316317static void free_scene(struct aiScene *scene, struct aiNode **nodes, uint32_t nodeCount) {318    for (unsigned m = 0; m < scene->mNumMeshes; m++) {319        struct aiMesh *mesh = scene->mMeshes[m];320        if (!mesh) continue;321        free(mesh->mVertices); free(mesh->mNormals); free(mesh->mTextureCoords[0]); free(mesh->mColors[0]);322        if (mesh->mFaces) { if (mesh->mNumFaces) free(mesh->mFaces[0].mIndices); free(mesh->mFaces); }323        free(mesh);324    }325    free(scene->mMeshes);326    for (unsigned m = 0; m < scene->mNumMaterials; m++) {327        struct aiMaterial *mat = scene->mMaterials[m];328        if (!mat) continue;329        for (unsigned p = 0; p < mat->mNumProperties; p++) { free(mat->mProperties[p]->mData); free(mat->mProperties[p]); }330        free(mat->mProperties); free(mat);331    }332    free(scene->mMaterials);333    if (nodes) {334        for (uint32_t i = 0; i < nodeCount; i++) if (nodes[i]) { free(nodes[i]->mChildren); free(nodes[i]->mMeshes); free(nodes[i]); }335        free(nodes);336    }337    free(scene);338}339340int orix_export(const orix_xnode *xnodes, uint32_t nodeCount, const orix_xmesh *xmeshes, uint32_t meshCount,341                const orix_xmaterial *xmats, uint32_t materialCount,342                const char *format_id, const char *path, char *err, size_t errlen) {343    if (nodeCount == 0 || meshCount == 0 || materialCount == 0) { set_err(err, errlen, "nothing to export"); return 1; }344    struct aiScene *scene = calloc(1, sizeof *scene);345    struct aiNode **nodes = calloc(nodeCount, sizeof *nodes);346    scene->mFlags = AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;347348    scene->mNumMaterials = materialCount;349    scene->mMaterials = calloc(materialCount, sizeof *scene->mMaterials);350    for (uint32_t i = 0; i < materialCount; i++) {351        const orix_xmaterial *x = &xmats[i];352        struct aiMaterial *mat = calloc(1, sizeof *mat);353        mat->mNumAllocated = 16; mat->mNumProperties = 0;354        mat->mProperties = calloc(mat->mNumAllocated, sizeof *mat->mProperties);355        add_string_prop(mat, "?mat.name", 0, x->name ? x->name : "material");356        add_prop(mat, "$clr.diffuse", 0, aiPTI_Float, x->base, 3 * sizeof(float));357        add_prop(mat, "$clr.base", 0, aiPTI_Float, x->base, 4 * sizeof(float));358        add_prop(mat, "$mat.opacity", 0, aiPTI_Float, &x->base[3], sizeof(float));359        add_prop(mat, "$mat.metallicFactor", 0, aiPTI_Float, &x->metallic, sizeof(float));360        add_prop(mat, "$mat.roughnessFactor", 0, aiPTI_Float, &x->roughness, sizeof(float));361        add_prop(mat, "$clr.emissive", 0, aiPTI_Float, x->emissive, 3 * sizeof(float));362        int two = x->twoSided ? 1 : 0;363        add_prop(mat, "$mat.twosided", 0, aiPTI_Integer, &two, sizeof two);364        if (x->baseColorTexture) add_string_prop(mat, "$tex.file", aiTextureType_DIFFUSE, x->baseColorTexture);365        if (x->normalTexture) add_string_prop(mat, "$tex.file", aiTextureType_NORMALS, x->normalTexture);366        if (x->emissiveTexture) add_string_prop(mat, "$tex.file", aiTextureType_EMISSIVE, x->emissiveTexture);367        scene->mMaterials[i] = mat;368    }369370    scene->mNumMeshes = meshCount;371    scene->mMeshes = calloc(meshCount, sizeof *scene->mMeshes);372    for (uint32_t i = 0; i < meshCount; i++) {373        const orix_xmesh *x = &xmeshes[i];374        struct aiMesh *mesh = calloc(1, sizeof *mesh);375        scene->mMeshes[i] = mesh;376        set_aistring(&mesh->mName, x->name ? x->name : "mesh");377        mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;378        mesh->mMaterialIndex = x->material < materialCount ? x->material : 0;379        mesh->mNumVertices = x->vertexCount;380        mesh->mVertices = malloc(sizeof(struct aiVector3D) * (size_t)x->vertexCount);381        memcpy(mesh->mVertices, x->positions, sizeof(float) * 3 * (size_t)x->vertexCount);382        if (x->normals) {383            mesh->mNormals = malloc(sizeof(struct aiVector3D) * (size_t)x->vertexCount);384            memcpy(mesh->mNormals, x->normals, sizeof(float) * 3 * (size_t)x->vertexCount);385        }386        if (x->uvs) {387            mesh->mTextureCoords[0] = malloc(sizeof(struct aiVector3D) * (size_t)x->vertexCount);388            for (uint32_t v = 0; v < x->vertexCount; v++) {389                mesh->mTextureCoords[0][v].x = x->uvs[v * 2]; mesh->mTextureCoords[0][v].y = x->uvs[v * 2 + 1]; mesh->mTextureCoords[0][v].z = 0;390            }391            mesh->mNumUVComponents[0] = 2;392        }393        if (x->colors) {394            mesh->mColors[0] = malloc(sizeof(struct aiColor4D) * (size_t)x->vertexCount);395            memcpy(mesh->mColors[0], x->colors, sizeof(float) * 4 * (size_t)x->vertexCount);396        }397        uint32_t faces = x->indexCount / 3;398        mesh->mNumFaces = faces;399        mesh->mFaces = calloc(faces ? faces : 1, sizeof(struct aiFace));400        unsigned int *all = malloc(sizeof(unsigned int) * (size_t)(faces ? faces * 3 : 1));401        for (uint32_t f = 0; f < faces; f++) {402            all[f * 3] = x->indices[f * 3]; all[f * 3 + 1] = x->indices[f * 3 + 1]; all[f * 3 + 2] = x->indices[f * 3 + 2];403            mesh->mFaces[f].mNumIndices = 3;404            mesh->mFaces[f].mIndices = all + (size_t)f * 3;405        }406        if (faces == 0) free(all);407    }408409    uint32_t *childCounts = calloc(nodeCount, sizeof *childCounts);410    for (uint32_t i = 0; i < nodeCount; i++) {411        const orix_xnode *x = &xnodes[i];412        struct aiNode *node = calloc(1, sizeof *node);413        nodes[i] = node;414        set_aistring(&node->mName, x->name ? x->name : "node");415        const float *t = x->transform;416        struct aiMatrix4x4 m = { t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8], t[9], t[10], t[11], t[12], t[13], t[14], t[15] };417        node->mTransformation = m;418        node->mNumMeshes = x->meshCount;419        if (x->meshCount) {420            node->mMeshes = malloc(sizeof(unsigned int) * x->meshCount);421            for (uint32_t k = 0; k < x->meshCount; k++) node->mMeshes[k] = x->meshes[k] < meshCount ? x->meshes[k] : 0;422        }423        if (i > 0) { int32_t p = x->parent; if (p < 0 || (uint32_t)p >= i) p = 0; childCounts[p]++; }424    }425    for (uint32_t i = 0; i < nodeCount; i++) if (childCounts[i]) nodes[i]->mChildren = calloc(childCounts[i], sizeof(struct aiNode *));426    for (uint32_t i = 1; i < nodeCount; i++) {427        int32_t p = xnodes[i].parent;428        if (p < 0 || (uint32_t)p >= i) p = 0;429        nodes[i]->mParent = nodes[p];430        nodes[p]->mChildren[nodes[p]->mNumChildren++] = nodes[i];431    }432    free(childCounts);433    scene->mRootNode = nodes[0];434435    aiReturn result = aiExportScene(scene, format_id, path, 0);436    if (result != aiReturn_SUCCESS) set_err(err, errlen, aiGetErrorString());437    free_scene(scene, nodes, nodeCount);438    return result == aiReturn_SUCCESS ? 0 : 1;439}440441int orix_can_import(const char *extension) { return aiIsExtensionSupported(extension) ? 1 : 0; }442443int orix_can_export(const char *format_id) {444    size_t n = aiGetExportFormatCount();445    for (size_t i = 0; i < n; i++) {446        const struct aiExportFormatDesc *d = aiGetExportFormatDescription(i);447        int match = d && strcmp(d->id, format_id) == 0;448        if (d) aiReleaseExportFormatDescription(d);449        if (match) return 1;450    }451    return 0;452}453454const char *orix_assimp_version(void) {455    static char v[32];456    snprintf(v, sizeof v, "%u.%u.%u", aiGetVersionMajor(), aiGetVersionMinor(), aiGetVersionPatch());457    return v;458}459460double orix_strtod(const char *text, char **end) { return strtod_l(text, end, NULL); }461
Files main
Menu

Theme