SurfaceGrid.build constructor

SurfaceGrid.build(
  1. List<Object3D> objects,
  2. Layers raycasterLayers
)

Implementation

SurfaceGrid.build(List<THREE.Object3D> objects, THREE.Layers raycasterLayers) {
  final sw = Stopwatch()..start();

  // ---- Pass 1: collect hittable triangles and their x/z bounds ----------
  final triMesh = <int>[];
  final triStart = <int>[];
  final triMat = <int>[];
  final bounds = <double>[]; // minX, maxX, minZ, maxZ per triangle
  double sumExtent = 0;

  for (final obj in objects) {
    if (obj is! THREE.Mesh) continue;
    if (!obj.layers.test(raycasterLayers)) continue;
    final material = obj.material;
    final geometry = obj.geometry;
    if (material == null || geometry == null) continue;
    final position = geometry.attributes['position'];
    if (position == null) continue;

    final matrix = obj.matrixWorld.clone();
    // A mirrored transform (negative determinant) flips which side
    // of a triangle faces the ray, same as it does in Mesh.raycast.
    final detSign = matrix.determinant() < 0 ? -1.0 : 1.0;
    final inverse = obj.matrixWorld.clone()..invert();
    final localDown = THREE.Vector3(0, -1, 0).transformDirection(inverse);

    final meshIndex = _meshes.length;
    _meshes.add(obj);
    _matrices.add(matrix);
    _localDown.add(localDown);

    final index = geometry.index;
    final int vertexCount = index != null ? index.count : position.count as int;
    final drawStart = geometry.drawRange['start'] ?? 0;
    final drawCount = geometry.drawRange['count'] ?? vertexCount;
    // drawRange count defaults to the max int, so avoid overflow.
    final drawEnd = drawCount >= vertexCount ? vertexCount : math.min(vertexCount, drawStart + drawCount);

    void addRange(int start, int end, THREE.Material m, int matIndex) {
      final side = m.side;
      for (int j = start; j + 2 < end; j += 3) {
        final ia = index != null ? index.getX(j)!.toInt() : j;
        final ib = index != null ? index.getX(j + 1)!.toInt() : j + 1;
        final ic = index != null ? index.getX(j + 2)!.toInt() : j + 2;
        _a.fromBuffer(position, ia).applyMatrix4(matrix);
        _b.fromBuffer(position, ib).applyMatrix4(matrix);
        _c.fromBuffer(position, ic).applyMatrix4(matrix);

        // y component of the world-space face normal (b-a) x (c-a).
        final ny = (_b.z - _a.z) * (_c.x - _a.x) - (_b.x - _a.x) * (_c.z - _a.z);
        if (ny == 0) continue; // vertical or degenerate: a vertical ray can't hit it
        final facing = ny * detSign; // > 0: front face points up
        if (side == THREE.FrontSide && facing <= 0) continue;
        if (side == THREE.BackSide && facing >= 0) continue;

        final minX = math.min(_a.x, math.min(_b.x, _c.x));
        final maxX = math.max(_a.x, math.max(_b.x, _c.x));
        final minZ = math.min(_a.z, math.min(_b.z, _c.z));
        final maxZ = math.max(_a.z, math.max(_b.z, _c.z));
        bounds..add(minX)..add(maxX)..add(minZ)..add(maxZ);
        sumExtent += math.max(maxX - minX, maxZ - minZ);
        triMesh.add(meshIndex);
        triStart.add(j);
        triMat.add(matIndex);
      }
    }

    if (material is THREE.GroupMaterial) {
      for (final group in geometry.groups) {
        final int mi = group['materialIndex'] ?? 0;
        if (mi < 0 || mi >= material.children.length) continue;
        final int gStart = group['start'] ?? 0;
        final int gCount = group['count'] ?? 0;
        final start = math.max(gStart, drawStart);
        final end = math.min(drawEnd, gStart + gCount);
        addRange(start, end, material.children[mi], mi);
      }
    } else {
      final start = math.max(0, drawStart);
      final end = drawEnd;
      addRange(start, end, material, -1);
    }
  }

  triangleCount = triMesh.length;
  _triMesh = Int32List.fromList(triMesh);
  _triStart = Int32List.fromList(triStart);
  _triMatIndex = Int32List.fromList(triMat);

  if (triangleCount == 0) {
    _cellStart = Int32List(1);
    _cellTris = Int32List(0);
    return;
  }

  // ---- Choose the grid ----------------------------------------------
  double minX = double.infinity, maxX = -double.infinity;
  double minZ = double.infinity, maxZ = -double.infinity;
  for (int t = 0; t < triangleCount; t++) {
    minX = math.min(minX, bounds[t * 4]);
    maxX = math.max(maxX, bounds[t * 4 + 1]);
    minZ = math.min(minZ, bounds[t * 4 + 2]);
    maxZ = math.max(maxZ, bounds[t * 4 + 3]);
  }
  // Cells about twice the size of an average triangle keep each cell to
  // a handful of triangles without each triangle spanning many cells.
  double cell = math.max(sumExtent / triangleCount * 2.0, 1e-4);
  int nx, nz;
  while (true) {
    nx = math.max(1, ((maxX - minX) / cell).floor() + 1);
    nz = math.max(1, ((maxZ - minZ) / cell).floor() + 1);
    if (nx * nz <= _maxCells) break;
    cell *= 1.5;
  }
  _minX = minX;
  _minZ = minZ;
  _cellSize = cell;
  _nx = nx;
  _nz = nz;

  // ---- Pass 2: count triangles per cell --------------------------------
  final counts = Int32List(nx * nz + 1);
  for (int t = 0; t < triangleCount; t++) {
    final x0 = _cellX(bounds[t * 4]), x1 = _cellX(bounds[t * 4 + 1]);
    final z0 = _cellZ(bounds[t * 4 + 2]), z1 = _cellZ(bounds[t * 4 + 3]);
    for (int cz = z0; cz <= z1; cz++) {
      for (int cx = x0; cx <= x1; cx++) {
        counts[cz * nx + cx + 1]++;
      }
    }
  }
  for (int k = 1; k < counts.length; k++) {
    counts[k] += counts[k - 1];
  }
  _cellStart = counts;

  // ---- Pass 3: fill ----------------------------------------------------
  _cellTris = Int32List(counts[nx * nz]);
  final fill = Int32List.fromList(counts.sublist(0, nx * nz));
  for (int t = 0; t < triangleCount; t++) {
    final x0 = _cellX(bounds[t * 4]), x1 = _cellX(bounds[t * 4 + 1]);
    final z0 = _cellZ(bounds[t * 4 + 2]), z1 = _cellZ(bounds[t * 4 + 3]);
    for (int cz = z0; cz <= z1; cz++) {
      for (int cx = x0; cx <= x1; cx++) {
        _cellTris[fill[cz * nx + cx]++] = t;
      }
    }
  }

  sw.stop();
  print('SurfaceGrid: $triangleCount triangles, ${nx}x$nz cells of '
      '${cell.toStringAsFixed(3)}, ${_cellTris.length} entries, '
      'built in ${sw.elapsedMilliseconds}ms');
}