gltf-pipeline

repository·main·Indexed 24 days ago

https://github.com/cesiumgs/gltf-pipeline

Content pipeline tools for optimizing glTF assets, available as both a command-line tool and a Node.js library. It supports converting between glTF and glb formats, applying Draco mesh compression, managing embedded versus separate textures and buffers, and retrieving asset statistics. Version 4.3.1.

Tokens
8.6K
Snippets
10
Records
24
Agent score
84%

What's inside gltf-pipeline

  1. Handle absolute paths in glTF with `allowAbsolute`

    main

    When using processGltf without a resourceDirectory, if the glTF object contains absolute paths, the library will emit a warning. To suppress this warning and explicitly allow absolute paths, include allowAbsolute: true in your options object.

    const options = {
      allowAbsolute: true,
      /*... */
    };
    const results = await processGltf(gltf, options);
  2. Use glTF Pipeline as a command-line tool

    main

    You can perform various glTF optimizations and conversions directly from the terminal using the gltf-pipeline command.

    Common CLI Tasks:

    • Convert glTF to glb: Use -i for input, -o for output, and -b to specify binary output.
    • Convert glb to glTF: Use -i for input, -o for output, and -j to specify JSON output.
    • Apply Draco compression: Use -d to compress meshes using Draco.
    • Save separate textures: Use -t to write out textures as separate files.
    # Convert glTF to glb
    gltf-pipeline -i model.gltf -o model.glb
    gltf-pipeline -i model.gltf -b
    
    # Convert glb to glTF
    gltf-pipeline -i model.glb -o model.gltf
    gltf-pipeline -i model.glb -j
    
    # Convert glTF to Draco glTF
    gltf-pipeline -i model.gltf -o modelDraco.gltf -d
    
    # Save separate textures
    gltf-pipeline -i model.gltf -t
  3. Build and Test the project

    main

    If you are contributing to the project, use the following commands to run tests, linting, and coverage.

    Testing and Linting

    • Run tests: npm run test
    • Run ESLint: npm run eslint
    • Run ESLint watch mode: npm run eslint-watch
    • Run test coverage: npm run coverage (results are in coverage/lcov-report/index.html)

    Documentation and Building

    • Generate JSDoc: npm run jsdoc (outputs to doc/ folder)
    • Build for CesiumJS: npm run build-cesium (outputs to dist/cesium/ for use in the CesiumJS repository)
    npm run test
    npm run eslint
    npm run eslint-watch
    npm run coverage
    npm run jsdoc
    npm run build-cesium
  4. Configure Draco quantization settings

    main

    Draco compression uses quantization to reduce the precision of vertex attributes, which helps in achieving smaller file sizes. You can control the bit depth for different attributes within the dracoOptions object.

    Note: Setting a bit value to 0 for any attribute disables quantization for that specific attribute.

    Available Attribute Keys:

    • quantizePositionBits (Positions)
    • quantizeNormalBits (Normals)
    • quantizeTexcoordBits (Texture Coordinates)
    • quantizeColorBits (Color)
    • quantizeGenericBits (Skinning/Joints/Custom attributes)

    Quantization Modes:

    • Per-primitive (Default): Quantization is applied to each primitive separately.
    • Unified Quantization: By setting unifiedQuantization: true, quantization is applied to positions using the unified bounding box of all primitives. This can help maintain relative precision across the entire model.
    • Explicit Volume: By providing a quantizationVolume (an AxisAlignedBoundingBox), you can define a specific volume for quantization.
  5. Use glTF Pipeline CLI

    main

    The gltf-pipeline CLI allows you to process glTF and glb files via the command line. You can convert between formats (glTF to glb and vice versa), compress meshes using Draco, and separate textures or buffers from the main file.

    Basic Usage: node gltf-pipeline.js -i <inputPath> [-o <outputPath>]

    If no output path is provided, the tool generates a file named <inputName>-processed.<extension> in the same directory as the input.

    Common Tasks:

    • Convert glTF to glb: Use the -b flag.
    • Convert glb to glTF: Use the -j flag.
    • Compress meshes with Draco: Use the -d or --draco.compressMeshes flag.
    • Separate textures: Use the -t or --separateTextures flag to write out separate textures instead of embedding them.
  6. Save separate textures using the library

    main

    To extract textures and buffers into separate files using the library, set separateTextures: true in the processGltf options. The resulting object will contain a separateResources property which is a map of relative paths to the resource buffers.

    const gltfPipeline = require("gltf-pipeline");
    const fsExtra = require("fs-extra");
    const processGltf = gltfPipeline.processGltf;
    const gltf = fsExtra.readJsonSync("model.gltf");
    const options = {
      separateTextures: true,
    };
    processGltf(gltf, options).then(function (results) {
      fsExtra.writeJsonSync("model-separate.gltf", results.gltf);
      // Save separate resources
      const separateResources = results.separateResources;
      for (const relativePath in separateResources) {
        if (separateResources.hasOwnProperty(relativePath)) {
          const resource = separateResources[relativePath];
          fsExtra.writeFileSync(relativePath, resource);
        }
      
    });
  7. Convert glTF to Draco glTF using the library

    main

    To apply Draco mesh compression programmatically, use the processGltf method and provide dracoOptions in the options object.

    const gltfPipeline = require("gltf-pipeline");
    const fsExtra = require("fs-extra");
    const processGltf = gltfPipeline.processGltf;
    const gltf = fsExtra.readJsonSync("model.gltf");
    const options = {
      dracoOptions: {
        compressionLevel: 10,
      },
    };
    processGltf(gltf, options).then(function (results) {
      fsExtra.writeJsonSync("model-draco.gltf", results.gltf);
    });
  8. Use glTF Pipeline as a Node.js library

    main

    You can import gltf-pipeline as a module to integrate its functionality into your Node.js applications. The library provides specific functions for different conversion tasks.

    Available API Methods:

    • gltfToGlb(gltf, options): Converts a glTF JSON object to a glb buffer.
    • glbToGltf(glb): Converts a glb buffer to a glTF JSON object.
    • processGltf(gltf, options): A general-purpose method for applying various transformations like Draco compression or separating textures.
    const gltfPipeline = require("gltf-pipeline");
    const fsExtra = require("fs-extra");
    
    // Example: Convert glTF to glb
    const gltfToGlb = gltfPipeline.gltfToGlb;
    const gltf = fsExtra.readJsonSync("./input/model.gltf");
    const options = { resourceDirectory: "./input/" };
    gltfToGlb(gltf, options).then(function (results) {
      fsExtra.writeFileSync("model.glb", results.glb);
    });
  9. Configure processGltf options

    main

    When calling processGltf(gltf, options), you can provide an options object to control the pipeline behavior. Below are the available configuration keys:

    KeyTypeDefaultDescription
    resourceDirectorystringundefinedPath for reading separate resources.
    namestringundefinedName of the glTF asset, used for writing separate resources.
    separatebooleanfalseIf true, writes separate buffers, shaders, and textures instead of embedding them.
    separateTexturesbooleanfalseIf true, writes out separate textures only.
    statsbooleanfalseIf true, prints statistics to the console for input and output glTF files.
    dracoOptionsobjectundefinedOptions passed to the compressDracoMeshes stage. If undefined, Draco compression is skipped.
    customStagesStage[][]An array of custom Stage functions to run in the pipeline.
    loggerLoggerconsole.logA callback function for handling logged messages.
    baseColorTextureNamesstring[]undefinedNames of uniforms that indicate base color textures.
    baseColorFactorNamesstring[]undefinedNames of uniforms that indicate base color factors.
    keepUnusedElementsbooleanfalseIf true, prevents the removal of unused 'node', 'mesh', and 'material' elements.
    keepLegacyExtensionsbooleanfalseIf false, materials with KHR_techniques_webgl, KHR_blend, or KHR_materials_common will be converted to PBR.
  10. Reference: glTF Pipeline CLI Flags

    main

    The following flags are available for the gltf-pipeline command-line tool.

    | Flag                           | Description                                                                                                                                                                                                                                                            |
    | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | `--help`, `-h`                 | Display help                                                                                                                                                                                                                                                           |
    | `--input`, `-i`                | Path to the glTF or glb file.                                                                                                                                                                                                                                                         |
    | `--output`, `-o`               | Output path of the glTF or glb file.                                                                                                                                                                                                                                                 |
    | `--binary`, `-b`               | Convert the input glTF to glb.                                                                                                                                                                                                                                                        |
    | `--allowAbsolute`, `-a`        | Allow glTF files to refer to file URLs outside of their source path                                                                                                                                                                                                                 |
    | `--json`, `-j`                 | Convert the input glb to glTF.                                                                                                                                                                                                                                                         |
    | `--separate`, `-s`             | Write separate buffers, shaders, and textures instead of embedding them in the glTF.                                                                                                                                                                                                  |
    | `--separateTextures`, `-t`     | Write out separate textures only.                                                                                                                                                                                                                                                      |
    | `--stats`                      | Print statistics to console for output glTF file.                                                                                                                                                                                                                                      |
    | `--keepUnusedElements`         | Keep unused materials, nodes and meshes.                                                                                                                                                                                                                                              |
    | `--keepLegacyExtensions`       | When false, materials with `KHR_techniques_webgl`, `KHR_blend`, or `KHR_materials_common` will be converted to PBR.                                                                                                                                                                 |
    | `--draco.compressMeshes`, `-d` | Compress the meshes using Draco. Adds the `KHR_draco_mesh_compression` extension.                                                                                                                                                                                                     |
    | `--draco.compressionLevel`     | Draco compression level [0-10], most is 10, least is 0. A value of 0 will apply sequential encoding and preserve face order.                                                                                                                                                           | 
    | `--draco.quantizePositionBits` | Quantization bits for position attribute when using Draco compression.                                                                                                                                                                                                                 |
    | `--draco.quantizeNormalBits`   | Quantization bits for normal attribute when using Draco compression.                                                                                                                                                                                                                 |
    | `--draco.quantizeTexcoordBits` | Quantization bits for texture coordinate attribute when using Draco compression.                                                                                                                                                                                                     |
    | `--draco.quantizeColorBits`    | Quantization bits for color attribute when using Draco compression.                                                                                                                                                                                                                 |
    | `--draco.quantizeGenericBits`  | Quantization bits for skinning attribute (joint indices and joint weights) and custom attributes when using Draco compression.                                                                                                                                                           | 
    | `--draco.unifiedQuantization`  | Quantize positions of all primitives using the same quantization grid. If not set, quantization is applied separately.                                                                                                                                                           | 
    | `--draco.uncompressedFallback` | Adds uncompressed fallback versions of the compressed meshes.                                                                                                                                                                                                                                        |
    | `--baseColorTextureNames`      | Names of uniforms that should be considered to refer to base color textures <br /> when updating from the `KHR_techniques_webgl` extension to PBR materials. | 
    | `--baseColorFactorNames`       | Names of uniforms that should be considered to refer to base color factors <br /> when updating from the `KHR_techniques_webgl` extension to PBR materials. |
  11. Use gltf-pipeline as a library

    main
    The gltf-pipeline module exports several functions for processing glTF and GLB files. You can use these functions to convert formats, process assets, or extract statistics programmatically within your own Node.js applications.