createModel static method

Future<Group> createModel(
  1. String path, {
  2. Map<String, String>? texturereplace,
  3. bool basic = false,
  4. bool castshadow = false,
  5. bool merge = false,
  6. bool turnfix = true,
  7. String rename(
    1. String groupName,
    2. int groupIndex
    )?,
  8. Set<String> hidegroups = const {},
})

Loads a static model. Mesh names are the MS3D group names (so BaseObject.setVisible(obj, false, groupname: 'bubbles') works); each mesh also keeps the original name in extra'groupname'.

rename can rename groups, e.g. to add openworld's "surface" tag to walkable terrain groups. merge combines groups that end up with the same name and material into one mesh (fewer draw calls for terrains). turnfix adds the 180° turn that openworld's objTurn expects (set it false for something placed directly in world coordinates, like a terrain).

Implementation

static Future<THREE.Group> createModel(
  String path, {
  Map<String, String>? texturereplace,
  bool basic = false,
  bool castshadow = false,
  bool merge = false,
  bool turnfix = true,
  String Function(String groupName, int groupIndex)? rename,
  Set<String> hidegroups = const {},
}) async {
  final m = await loadMs3d(path);
  final mats = await _materials(path, m, texturereplace: texturereplace, basic: basic);
  final fallback = THREE.MeshStandardMaterial();
  final root = THREE.Group();
  final holder = THREE.Group();
  if (turnfix) holder.rotation.y = math.pi; // see header: cancels objTurn's extra 180°
  root.add(holder);

  final entries = <(String, String, int, List<int>)>[]; // name, original, material, tris
  final index = <String, int>{};
  for (var gi = 0; gi < m.groups.length; gi++) {
    final g = m.groups[gi];
    final name = rename != null ? rename(g.name, gi) : g.name;
    final tris = [for (final t in g.triangleIndices) t];
    final key = '$name\u0000${g.materialIndex}';
    final i = merge ? index[key] : null;
    if (i == null) {
      index[key] = entries.length;
      entries.add((name, g.name, g.materialIndex, tris));
    } else {
      entries[i].$4.addAll(tris);
    }
  }
  for (final (name, original, mi, tris) in entries) {
    final (geo, _) = _geometry(m, tris);
    final mesh = THREE.Mesh(geo, mi >= 0 ? mats[mi] : fallback);
    mesh.name = name;
    mesh.extra['groupname'] = original;
    mesh.castShadow = castshadow;
    mesh.visible = !hidegroups.contains(original);
    holder.add(mesh);
  }
  root.extra['path'] = path;
  root.extra['ms3d'] = m;
  root.castShadow = castshadow;
  return root;
}