← Back to Blog Tech

Implementing Meshopt Decompression & WebP Quantization in libGDX (gdx-gltf)

Optimizing 3D assets for mobile is a trade-off between file size, runtime memory, and image quality. gltfpack gives you big compression wins out of the box, but its output uses extensions like EXT_meshopt_compression, KHR_mesh_quantization, and EXT_texture_webp that aren't built into general-purpose frameworks.

While updating my fork gdx-gltf-KHR, I hit a series of undocumented problems parsing these optimized meshes on Android. Here's what each one was and how I fixed it.


1. The BasisU global state crash

The basisu::ktx2_transcoder and the low-level decompression paths use global state for their Huffman codebooks and lookup tables. If you initialize the transcoder through JNI before that global state is set up, the app aborts:

F libc : fatal assertion "g_transcoder_initialized" failed
Fatal signal 6 (SIGABRT) in GLThread


The fix

Call basist::basisu_transcoder_init() once at startup, before anything calls transcoder.init().

JNIEXPORT jint JNICALL Java_net_mgsx_gltf_basis_BasisTranscoder_nativeIsAvailable(JNIEnv *env, jclass clazz) {
    // CRITICAL: Unpacks the global Huffman/ETC1S decoding tables
    basist::basisu_transcoder_init();
    return 1;
}



2. Shared buffer views and the index-out-of-bounds error

When gltfpack compresses a model it merges separate sub-meshes into one shared vertex pool inside a single bufferView, to compress better.

In an uncompressed glTF each primitive has its own byte range. In an optimized file the primitive's accessor.byteOffset points into a shared block. If your reader walks streams sequentially without honoring those bounds, you get an ArrayIndexOutOfBoundsException or corrupted data:

E ModelLoader: Failed to load asset: length=480; index=480


The fix

Slice the underlying ByteBuffer to the accessor's exact footprint before filling the array, so positions, normals, and texture coordinates stay aligned:

public int[] readBufferUShort(int accessorID) {
    GLTFAccessor accessor = glModel.accessors.get(accessorID);
    AccessorBuffer accessorBuffer = getAccessorBuffer(accessor);
    
    // Create an isolated duplicate so positions aren't corrupted across threads
    ByteBuffer bytes = accessorBuffer.prepareForReading().duplicate();
    bytes.order(java.nio.ByteOrder.LITTLE_ENDIAN);
    
    int nbShortsPerVertex = GLTFTypes.accessorTypeSize(accessor);
    int[] data = new int[accessor.count * nbShortsPerVertex];
    int stride = accessorBuffer.getByteStride();
    int basePos = bytes.position();
    
    for (int i = 0; i < accessor.count; i++) {
        int vertexOffset = basePos + (i * stride);
        for (int j = 0; j < nbShortsPerVertex; j++) {
            int bytePos = vertexOffset + (j * 2);
            if (bytePos + 1 < bytes.limit()) {
                data[i * nbShortsPerVertex + j] = bytes.getShort(bytePos) & 0xFFFF;
            }
        }
    }
    return data;
}



3. Reading the 12-bit gltfpack UV grid

By default gltfpack -cc quantizes texture coordinates to a 12-bit grid ( -vt 12). That maps coordinates to unsigned integers from 0 to 4095, not the 0 to 65535 range used by 16-bit normalized shorts.

gltfpack also moves the scale and offset out of the vertex data into the material's KHR_texture_transform. If you just divide by 65535f and ignore those values, the UVs collapse toward zero and textures tile or warp.

The fix

Divide by 4095.0f, then apply the material's texture-transform scale and offset on the CPU:

else if (glAccessor.componentType == GLTFTypes.C_USHORT) {
    int numComponents = GLTFTypes.accessorTypeSize(glAccessor);
    int strideBytes = byteStride;
    int baseOffset = accBuffer.getByteOffset();
    
    // Fallback constants extracted from the mesh specification matrix
    float scaleU = 0.25f; float scaleV = 0.75f;
    float offsetU = 0.375f; float offsetV = 0.25f;

    // Dynamically query KHR_texture_transform from the primitive material
    if (primitive.material != null && glModel.materials != null) {
        // [Reflection code logic to pull transform.scale and transform.offset]
    }

    final float normFactor = 1.0f / 4095.0f; // 12-bit grid resolution factor

    for (int j = 0; j < finalVertexCount; j++) {
        int vIndex = j * vertexFloats + attribute.offset / 4;
        int srcVertexIndex = hasIndices ? indicesArray[j] : j;
        int dIndex = baseOffset + srcVertexIndex * strideBytes;
        
        float normU = (data.getShort(dIndex) & 0xFFFF) * normFactor;
        float normV = (data.getShort(dIndex + 2) & 0xFFFF) * normFactor;
        
        vertices[vIndex]     = (normU * scaleU) + offsetU;
        vertices[vIndex + 1] = (normV * scaleV) + offsetV;
    }
}



4. WebP isn't in libGDX's core image loader

Switching textures to WebP (gltfpack -tw) shrinks them a lot. But feeding WebP into libGDX with Pixmap(FileHandle) or new Pixmap(bytes) crashes in native code:

Caused by: java.io.IOException: Error loading pixmap: Image not of any known type, or corrupt
at com.badlogic.gdx.graphics.g2d.Gdx2DPixmap.(Gdx2DPixmap.java:85)


The Gdx2DPixmap C++ library (libgdx2d.so) only decodes PNG and JPEG. Android itself can decode WebP, but gdx-gltf's core is platform-agnostic and can't pull in Android SDK classes without breaking desktop builds.

The fix

Keep the core platform-agnostic and reach Android's image decoder through reflection at runtime, decoding via BitmapFactory and uploading straight to the GPU:

private Texture loadWebPTexture(int webpSource, boolean useMipMaps, ImageResolver imageResolver) {
    final byte[] webpData = imageResolver.getRawBytes(webpSource);
    try {
        // Use reflection to locate Android's native image utilities at runtime
        Class bitmapFactoryClass = Class.forName("android.graphics.BitmapFactory");
        java.lang.reflect.Method decodeMethod = bitmapFactoryClass.getMethod("decodeByteArray", byte[].class, int.class, int.class);
        
        Object bitmapObj = decodeMethod.invoke(null, webpData, 0, webpData.length);
        int width = (Integer) bitmapObj.getClass().getMethod("getWidth").invoke(bitmapObj);
        int height = (Integer) bitmapObj.getClass().getMethod("getHeight").invoke(bitmapObj);

        // Build a raw, uninitialized libGDX Texture context target
        Texture texture = new Texture(width, height, Pixmap.Format.RGBA8888);
        texture.bind();

        // Invoke android.opengl.GLUtils.texImage2D to upload the bitmap straight to VRAM
        Class glUtilsClass = Class.forName("android.opengl.GLUtils");
        java.lang.reflect.Method texImageMethod = glUtilsClass.getMethod("texImage2D", int.class, int.class, Class.forName("android.graphics.Bitmap"), int.class);
        texImageMethod.invoke(null, 3553, 0, bitmapObj, 0); // 3553 is GL_TEXTURE_2D

        // Clean up native hardware memory allocations instantly
        bitmapObj.getClass().getMethod("recycle").invoke(bitmapObj);
        return texture;
    } catch (ClassNotFoundException e) {
        Gdx.app.error("GLTF", "Not running on Android environment. Falling back.");
        return null;
    }
}



Wrapping up

The short version: read attributes through the shared buffer bounds, use the right 12-bit divisor, and route WebP through reflection. Do those and your assets stay small and still load correctly.

The code is open-source on GitHub. Take what's useful, and tell me if you find more issues.