fromGltf static method

FlutterSceneResolvedImport? fromGltf(
  1. GltfAsset gltf, {
  2. int? jointPaletteCapacity,
})

Returns null when the GLB needs no resource, extension or skin adaptation.

jointPaletteCapacity is the largest skin the renderer animates. The renderer owns that bound, so the caller supplies it; null leaves every skin as authored.

Implementation

static FlutterSceneResolvedImport? fromGltf(
  GltfAsset gltf, {
  int? jointPaletteCapacity,
}) {
  final hasExternalResource =
      gltf.buffers.any((buffer) => _isExternalUri(buffer.uri)) ||
      gltf.images.any((image) => _isExternalUri(image.uri));
  final hasVrmExtension = gltf.extensionsRequired.any(
    _flvttermOwnedExtensions.contains,
  );
  final hasCompression =
      gltf.extensionsUsed.any(_compressionExtensions.contains) ||
      gltf.extensionsRequired.any(_compressionExtensions.contains) ||
      gltf.buffers.any((b) => b.extensions.containsKey(_meshoptExtension)) ||
      gltf.bufferViews.any(
        (b) => b.extensions.containsKey(_meshoptExtension),
      ) ||
      gltf.meshes.any(
        (mesh) => mesh.primitives.any(
          (primitive) => primitive.extensions.containsKey(_dracoExtension),
        ),
      );
  final needsSkinReduction =
      jointPaletteCapacity != null &&
      gltfNeedsSkinReduction(gltf, jointPaletteCapacity);
  if (!hasExternalResource &&
      !hasVrmExtension &&
      !hasCompression &&
      !needsSkinReduction) {
    return null;
  }

  final decoded = jsonDecode(jsonEncode(gltf.json));
  if (decoded is! Map<String, Object?>) {
    throw StateError('Parsed glTF JSON root is not an object.');
  }

  // Core and this adapter consume these VRM extensions. Keep their data in
  // the model, but do not ask the glTF-only renderer to implement them too.
  // Unknown required extensions remain required and fail renderer validation.
  if (hasVrmExtension) {
    decoded['extensionsRequired'] = gltf.extensionsRequired
        .where((name) => !_flvttermOwnedExtensions.contains(name))
        .toList();
  }

  final resources = <String, Uint8List>{};
  final reservedUris = {for (final image in gltf.images) ?image.uri};

  for (final buffer in gltf.buffers) {
    final data = buffer.data;
    if (data == null) {
      throw StateError(
        'glTF buffer ${buffer.index} was not resolved for Flutter Scene.',
      );
    }
    final buffers = decoded['buffers'];
    if (buffers is! List ||
        buffer.index >= buffers.length ||
        buffers[buffer.index] is! Map) {
      throw StateError('Parsed glTF buffer metadata is unavailable.');
    }
    final syntheticUri = _uniqueBufferUri(reservedUris);
    (buffers[buffer.index] as Map)['uri'] = syntheticUri;
    reservedUris.add(syntheticUri);
    resources[syntheticUri] = data;
  }

  for (final image in gltf.images) {
    final uri = image.uri;
    if (!_isExternalUri(uri)) continue;
    final data = image.data;
    if (data == null) {
      throw StateError(
        'glTF image ${image.index} URI $uri was not resolved for Flutter '
        'Scene.',
      );
    }
    final existing = resources[uri];
    if (existing != null && !listEquals(existing, data)) {
      throw StateError(
        'glTF URI $uri resolved to conflicting byte payloads.',
      );
    }
    resources[uri!] = data;
  }

  if (hasCompression) {
    // Core supports ordinary fallback geometry, not compressed streams. Check
    // that fallback before removing optional decoder hints. Required codecs
    // retain core's unsupported-extension diagnostic even in permissive mode.
    final validation = GltfAsset.tryParse(
      bytes: Uint8List.fromList(utf8.encode(jsonEncode(decoded))),
      validation: VrmValidationMode.permissive,
      uriResolver: (uri) => resources[uri],
    ).validation;
    final requiredCompression = gltf.extensionsRequired.any(
      _compressionExtensions.contains,
    );
    if (requiredCompression ||
        validation.errors.any(
          (diagnostic) =>
              diagnostic.code != 'gltf.unsupportedRequiredExtension',
        )) {
      throw VrmInvalidAssetException(
        'Flutter Scene requires core-validated uncompressed fallback geometry.',
        validation,
      );
    }
    for (final key in ['buffers', 'bufferViews']) {
      for (final item in _jsonObjects(decoded[key])) {
        _jsonObject(item['extensions'])?.remove(_meshoptExtension);
      }
    }
    for (final mesh in _jsonObjects(decoded['meshes'])) {
      for (final primitive in _jsonObjects(mesh['primitives'])) {
        _jsonObject(primitive['extensions'])?.remove(_dracoExtension);
      }
    }
    decoded['extensionsUsed'] = gltf.extensionsUsed
        .where((name) => !_compressionExtensions.contains(name))
        .toList();
  }

  final skinReduction = needsSkinReduction
      ? reduceOversizedSkins(
          gltf,
          decoded,
          resources,
          reservedUris,
          jointPaletteCapacity: jointPaletteCapacity,
        )
      : null;

  return FlutterSceneResolvedImport._(
    Uint8List.fromList(utf8.encode(jsonEncode(decoded))),
    resources,
    skinReduction,
  );
}