obj2gltf

repository·main·Indexed 23 days ago

https://github.com/cesiumgs/obj2gltf

A tool and Node.js library for converting OBJ model assets into glTF 2.0 format, supporting both JSON (.gltf) and binary (.glb) outputs. It features support for multiple shading models including Metallic roughness PBR, Specular glossiness PBR (via KHR_materials_pbrSpecularGlossiness), and Unlit materials (via KHR_materials_unlit). The tool provides a comprehensive CLI for managing texture overrides, axis control, and material mapping from MTL files.

Tokens
11.5K
Snippets
8
Records
24
Agent score
83%

What's inside obj2gltf

  1. Understand supported material shading models

    main

    Since glTF 2.0 uses physically-based materials (PBR) and OBJ/MTL traditionally uses Blinn-Phong, obj2gltf supports three shading models:

    1. Metallic roughness PBR: The default conversion if no flags are provided. Traditional Blinn-Phong materials are mapped to this model.
    2. Specular glossiness PBR: Uses the KHR_materials_pbrSpecularGlossiness extension.
    3. Unlit materials: Uses the KHR_materials_unlit extension. This should be used if lighting information is already baked into the model.

    If you know the material type in advance, specify it using the metallicRoughness, specularGlossiness, or unlit flags to ensure correct mapping.

  2. Run tests and check coverage

    main
    To verify the Node.js module, run the test suite using npm run test. To generate and view code coverage reports using nyc, run npm run coverage. Detailed coverage reports can be found by opening coverage/lcov-report/index.html after the command completes. Note that coverage applies to the Node.js module and does not cover the command-line interface.
    npm run test
    npm run coverage
  3. Use obj2gltf as a command-line tool

    main

    You can convert OBJ files to glTF or glb using the obj2gltf CLI. The tool requires an input path and an output path. It supports various flags to control material types, texture handling, and coordinate systems.

    Basic Usage

    node obj2gltf.js -i ./path/to/input.obj -o ./path/to/output.gltf

    Key Features

    • Format Selection: Use -b or --binary to save as .glb. If no output is specified, it defaults to the input filename with the appropriate extension.
    • Material Modes: You can specify if the .mtl file already contains PBR values using --metallicRoughness or --specularGlossiness. Note that these two modes are mutually exclusive.
    • Texture Overrides: You can override textures defined in the .mtl file by providing paths to specific textures (e.g., --baseColorTexture, --normalTexture).
    • Axis Control: Specify the up-axis for both input and output using --inputUpAxis and --outputUpAxis (choices: X, Y, Z).
  4. Use obj2gltf as a library

    main

    You can import obj2gltf into your Node.js project to perform conversions programmatically. The function returns a Promise that resolves to the glTF data.

    // Converting an obj model to gltf
    const obj2gltf = require("obj2gltf");
    const fs = require("fs");
    obj2gltf("model.obj").then(function (gltf) {
      const data = Buffer.from(JSON.stringify(gltf));
      fs.writeFileSync("model.gltf", data);
    });
  5. Configure logging in loadObj

    main
    The options object passed to loadObj can include a logger function. This function is used to output warnings or errors, such as when a material file is outside the allowed directory or when a material file cannot be read.
  6. Configure overriding textures in loadMtl

    main

    When calling loadMtl, you can pass an overridingTextures object within the options parameter to replace textures found in the .mtl file. This is useful for forcing specific maps onto a model during conversion.

    Supported override keys:

    • baseColorTexture (replaces map_Kd / diffuse)
    • normalTexture (replaces map_Bump / normal)
    • emissiveTexture (replaces map_Ke / emissive)
    • alphaTexture (replaces map_d / alpha)
    • metallicRoughnessOcclusionTexture (used for both specular/glossiness and metallic/roughness overrides)
    • specularGlossinessTexture (used for specular/glossiness overrides)
    • occlusionTexture (used for ambient/occlusion overrides)
  7. Configure triangle winding order sanitization

    main
    The loadObj function accepts a triangleWindingOrderSanitization flag in the options object. When enabled, the parser will check and correct the winding order of triangles based on their face normals to ensure consistent geometry orientation.
  8. Configure glTF output options for createGltf

    main

    When calling createGltf, the options object controls several critical aspects of the resulting glTF asset:

    OptionTypeDescription
    specularGlossinessbooleanIf true, adds KHR_materials_pbrSpecularGlossiness to extensionsUsed and extensionsRequired.
    unlitbooleanIf true, adds KHR_materials_unlit to extensionsUsed and extensionsRequired.
    separatebooleanIf true, the function may use separate buffers for different attribute types (positions, normals, etc.) if the combined buffer size exceeds the maximum allowed byte length.
  9. Configure secure material loading

    main
    The loadObj function supports a secure flag in the options object. When secure: true, the parser will attempt to prevent loading material files (.mtl) that reside outside of the OBJ file's directory. If a material is outside the directory, it will attempt to look for a version of that file within the OBJ's own directory instead.
  10. Configure obj2gltf options

    main

    The obj2gltf function accepts an optional options object to control the conversion process. Below are the available configuration keys:

    Output Format & Files

    • binary (Boolean): If true, converts to binary glTF (glb). Default: false.
    • separate (Boolean): If true, writes out separate buffer files and textures instead of embedding them. Default: false.
    • separateTextures (Boolean): If true, writes out separate textures only. Default: false.
    • outputDirectory (String): The directory used for writing separate resources if options.writer is not provided.
    • writer (Function): A callback function (file, data) => Promise used to write separate resources. file is the relative path, and data is the Buffer.

    Material & PBR Settings

    • metallicRoughness (Boolean): If true, assumes .mtl values are already PBR metallic-roughness values (Metallic in Ks/map_Ks, Roughness in Ns/map_Ns). Default: false.
    • specularGlossiness (Boolean): If true, assumes .mtl values are already PBR specular-glossiness values. Uses KHR_materials_pbrSpecularGlossiness extension. Default: false.
    • unlit (Boolean): If true, saves with KHR_materials_unlit extension. Default: false.
    • packOcclusion (Boolean): Packs the occlusion texture into the red channel of the metallic-roughness texture. Default: false.
    • doubleSidedMaterial (Boolean): Allows materials to be double sided. Default: false.
    • checkTransparency (Boolean): Performs an exhaustive check for texture transparency by inspecting the alpha channel of each pixel. Default: false.

    Texture Overrides

    Use overridingTextures to provide paths to textures that should replace those defined in the .mtl file. This is useful for models without .mtl files.

    • overridingTextures.metallicRoughnessOcclusionTexture (String): Path to a combined texture (Occlusion: Red, Roughness: Green, Metallic: Blue). Setting this automatically enables metallicRoughness and packOcclusion modes.
    • overridingTextures.specularGlossinessTexture (String): Path to a specular-glossiness texture (Specular: RGB, Glossiness: Alpha). Setting this automatically enables specularGlossiness mode.
    • overridingTextures.occlusionTexture (String): Path to the occlusion texture. (Ignored if metallicRoughnessOcclusionTexture is set).
    • overridingTextures.normalTexture (String): Path to the normal texture.
    • overridingTextures.baseColorTexture (String): Path to the baseColor/diffuse texture.
    • overridingTextures.emissiveTexture (String): Path to the emissive texture.
    • overridingTextures.alphaTexture (String): Path to the alpha texture.

    Coordinate System & Sanitization

    • inputUpAxis (String): The up axis of the source OBJ. Choices: 'X', 'Y', 'Z'. Default: 'Y'.
    • outputUpAxis (String): The up axis of the converted glTF. Choices: 'X', 'Y', 'Z'. Default: 'Y'.
    • triangleWindingOrderSanitization (Boolean): Applies triangle winding order sanitization. Default: false.

    Security & Logging

    • secure (Boolean): Prevents the converter from reading textures or .mtl files located outside the input OBJ directory. Default: false.
    • logger (Function): A callback function for handling logged messages. Defaults to console.log.