createGrass method

dynamic createGrass(
  1. dynamic camera, {
  2. dynamic grassShadow = 0.5,
  3. dynamic boundaryWidth = 200,
  4. dynamic boundaryLength = 200,
  5. dynamic edgeFalloff = 20,
  6. dynamic planeSize = 30,
  7. dynamic layerFadeAngle = 0.25,
  8. dynamic showHeightGrid = false,
  9. int heightMapResolution = _kDefaultHeightMapResolution,
  10. dynamic heightGridDivisions = 20,
  11. dynamic heightGridColor = 0xff6a00,
  12. dynamic heightGridOffset = 0.002,
  13. int? seed,
  14. List<List<double>>? excludeSquares,
  15. List<List<double>>? heightPoints,
  16. List<PlantSpec> plants = const [],
  17. dynamic worldposx,
  18. dynamic worldposy,
  19. dynamic windSpeed = 0.0,
  20. SurfaceTextureSpec? surfaceTexture,
  21. Color? color,
})

Implementation

createGrass(camera, {
  grassShadow          = 0.5,
  boundaryWidth        = 200,
  boundaryLength       = 200,
  edgeFalloff          = 20,
  planeSize            = 30,
  layerFadeAngle       = 0.25,
  showHeightGrid       = false,
  int heightMapResolution = _kDefaultHeightMapResolution,
  heightGridDivisions  = 20,
  heightGridColor      = 0xff6a00,
  heightGridOffset     = 0.002,
  int? seed,
  List<List<double>>? excludeSquares,
  List<List<double>>? heightPoints,
  List<PlantSpec> plants = const [],
  worldposx,
  worldposy,
  windSpeed=0.0,
  SurfaceTextureSpec? surfaceTexture,
  THREE.Color? color,
}) async {
  // So can reuse the old excludeSquares make a copy
  List<List<double>>? useExcludeSquares;
  useExcludeSquares=[];
  if (excludeSquares==null) {

  } else {
    // Is a pain cannot just copy entire array
    for (var square in excludeSquares) {
      useExcludeSquares.add([...square]);
    }
    //useExcludeSquares =
   //     excludeSquares.map((innerList) => List.from(innerList)).toList();
   // ; //[...excludeSquares];  //deepCopy = original.map((item) => Item(item.name, item.id)).toList();;
  }
  if (worldposx!=null&&useExcludeSquares.length>0) {
      for (var i=0; i<useExcludeSquares.length; i++) {
        useExcludeSquares[i][0]=-(worldposx- (useExcludeSquares[i][0]));
        useExcludeSquares[i][1]=  worldposy-useExcludeSquares[i][1];
      //  print("exclude"+excludeSquares[i].toString());
      }
  }
  if (heightPoints==null)
    heightPoints=[];

  // When we build height data directly from mesh faces we also capture the
  // triangle connectivity, so the Delaunay re-triangulation step can be
  // skipped.  null means "no direct triangles available – please triangulate".
  List<_TerrainTriangle>? directTriangles;

  if (heightPoints.length==0&&worldposx!=null) {
    heightPoints=[];
    var localx = worldposx;
    var localz = -worldposy;
    var localy = camera.position.y+100;
    THREE.Intersection intersectiono = OPENWORLD.Space
        .localIntersectSurfaceVector(localx, localy, localz);

   // THREE.Face? face = intersectiono.face;
    //int ind=intersection?.index;
    // int ind=intersection?.

    var mesh = intersectiono.object; //OPENWORLD.Space.mesh.children[0];//ind];
    THREE.BufferGeometry? geom = mesh?.geometry;
    print("mesh veg"+mesh.toString());
    print("mesh geom"+geom.toString());
    THREE.Float32BufferAttribute positions = geom?.getAttribute(
        THREE.Attribute.position);
    THREE.Float32Array pos = positions.array;
    //var poslist = pos.toList();
    /*print('posit inter' + intersectiono!.index.toString() + " " +
        poslist.length.toString() + " " + face!.a.toString() + " " +
        face!.b.toString() + " " + face!.c.toString()); //poslist.toString());
    print("posa" + positions.getX(face!.a).toString() + "," +
        positions.getY(face!.a).toString() + "," +
        positions.getZ(face!.a).toString());
    print("posb" + positions.getX(face!.b).toString() + "," +
        positions.getY(face!.b).toString() + "," +
        positions.getZ(face!.b).toString());
    print("posc" + positions.getX(face!.c).toString() + "," +
        positions.getY(face!.c).toString() + "," +
        positions.getZ(face!.c).toString());*/
    //positionAttribute.getY(aIndex),
    //positionAttribute.getZ(aIndex)
    // print("posx"+pos[face!.a].toString());
    var worldcenterz = OPENWORLD.Space.worldIntersectSurface(
        worldposx, worldposy);
    // Collect terrain faces that overlap the vegetation boundary by iterating
    // the mesh index buffer once — O(face_count) — instead of firing one
    // raycast per integer pixel across the boundary area (~40 k raycasts for
    // a 200×200 boundary).
    final boundLeft   = worldposx - boundaryWidth  / 2;
    final boundRight  = worldposx + boundaryWidth  / 2;
    final boundTop    = worldposy - boundaryLength / 2;
    final boundBottom = worldposy + boundaryLength / 2;

    // Named records: each entry is a (a, b, c) triplet of position-buffer indices.
    final facelist = <({int a, int b, int c})>[];

    // The mesh may be indexed (has an index buffer) or non-indexed (every 3
    // consecutive position-buffer entries form a triangle directly).  Handle
    // both: build a lightweight Iterable of (a, b, c) vertex-index triples
    // without duplicating the overlap-test logic.
    final indexAttr  = geom?.getIndex();
    final vertCount  = positions.count ?? (positions.array.length ~/ 3);
    final faceCount  = indexAttr != null
        ? indexAttr.array.length ~/ 3
        : vertCount ~/ 3;

    for (var f = 0; f < faceCount; f++) {
      final int a, b, c;
      if (indexAttr != null) {
        a = indexAttr.array[f * 3    ].toInt();
        b = indexAttr.array[f * 3 + 1].toInt();
        c = indexAttr.array[f * 3 + 2].toInt();
      } else {
        // Non-indexed geometry: vertices are already unrolled in triples.
        a = f * 3;
        b = f * 3 + 1;
        c = f * 3 + 2;
      }

      // Coordinate convention: world-X = mesh-local X, world-Y = -mesh-local Z
      final ax = positions.getX(a)!.toDouble();
      final az = positions.getZ(a)!.toDouble();
      final bx = positions.getX(b)!.toDouble();
      final bz = positions.getZ(b)!.toDouble();
      final cx = positions.getX(c)!.toDouble();
      final cz = positions.getZ(c)!.toDouble();

      // Negate Z to get world-Y, then compute face AABB for the overlap test.
      final wy_a = -az, wy_b = -bz, wy_c = -cz;
      final faceMinX = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx);
      final faceMaxX = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx);
      final faceMinY = wy_a < wy_b ? (wy_a < wy_c ? wy_a : wy_c) : (wy_b < wy_c ? wy_b : wy_c);
      final faceMaxY = wy_a > wy_b ? (wy_a > wy_c ? wy_a : wy_c) : (wy_b > wy_c ? wy_b : wy_c);

      //if (!(faceMinX < boundLeft  && faceMaxX > boundRight &&
      //    faceMinY > boundTop   && faceMaxY > boundBottom)) {
      if (faceMaxX >= boundLeft  && faceMinX <= boundRight &&
          faceMaxY >= boundTop   && faceMinY <= boundBottom) {
        facelist.add((a: a, b: b, c: c));
      }
    }
    print("facelist count"+facelist.length.toString());

    // Build height-point list and terrain triangles in a single pass over
    // the collected faces.  A map from the mesh's buffer index to our local
    // heightPoints index lets us deduplicate shared vertices in O(1) and
    // reconstruct the exact face triangles without any re-triangulation.
    final bufferIndexToHeightIndex = <int, int>{};
    directTriangles = [];

    for (var face in facelist) {
      final faceIndices = [face.a, face.b, face.c];
      final localIndices = <int>[];
      var faceValid = true;

      for (final bufIdx in faceIndices) {
        if (!bufferIndexToHeightIndex.containsKey(bufIdx)) {
          // Respect the per-instance cap early so triangle indices stay valid.
          if (heightPoints.length >= _kMaxTerrainPoints) {
            faceValid = false;
            break;
          }
          final xa = positions.getX(bufIdx)!.toDouble();
          final ya = positions.getY(bufIdx)!.toDouble();
          final za = positions.getZ(bufIdx)!.toDouble();
          // Coordinate convention: world-X = xa, world-Y = -za, height = ya
          final x = xa - worldposx;
          final y = worldposy - (-za);
          final z = ya - worldcenterz;
          bufferIndexToHeightIndex[bufIdx] = heightPoints.length;
          heightPoints.add([x, y, z]);
        }
        localIndices.add(bufferIndexToHeightIndex[bufIdx]!);
      }

      if (faceValid && directTriangles.length < _kMaxTerrainTriangles) {
        directTriangles.add(
          _TerrainTriangle(localIndices[0], localIndices[1], localIndices[2]),
        );
      }
    }

    /*for (var j = -1; j < boundaryLength + 1; j++) {
      var prevz = -9999.0;
      for (var i = -1; i < boundaryWidth + 1; i++) {
        if ((i % 4 == 0 &&
            j % 4 == 0)) { //||(i - boundarywidth2 / 2).abs()<2) {
          var worldx = worldposx - boundaryWidth / 2 + i;
          //    var worldy=worldposy-boundarylength2/2+j;
          var worldy = worldposy + boundaryLength / 2 - j;
          var worldz = OPENWORLD.Space.worldIntersectSurface(worldx, worldy);
          var x = i - boundaryWidth / 2;
          var y = j - boundaryLength / 2;
          var z = worldz - worldcenterz;
          //print('posss '+x.toString()+" "+y.toString()+' '+z.toString()+' w'+worldx.toString()+" "+worldy.toString()+" "+worldz.toString());//+" "+worldcenterz.toString());
          print(
              '[' + x.toString() + ", " + y.toString() + ', ' + z.toString() +
                  ']'); //+' '+(i - boundarywidth2 / 2).abs().toString());
          if (prevz == -9999.0 || prevz != z)
            heightPoints.add([x.toDouble(), y.toDouble(), z.toDouble()]);
         // if (prevz == z)
         //   print("xy" + x.toString() + " " + y.toString());
          prevz = z;
        }
      }
    }*/
  }
  print("height points"+heightPoints.length.toString());

  _camera = camera;
  _kWindSpeed=windSpeed;
  _kGrassShadow         = grassShadow.toDouble();
  _kBoundaryWidth       = boundaryWidth.toDouble();
  _kBoundaryLength      = boundaryLength.toDouble();
  _kEdgeFalloff         = edgeFalloff.toDouble();
  _kPlaneSize           = planeSize.toDouble();
  _kShowHeightGrid      = showHeightGrid == true;
  _kHeightGridDivisions = max(1, heightGridDivisions is int
      ? heightGridDivisions
      : (heightGridDivisions as num).toInt());
  _kHeightGridColor     = heightGridColor is int
      ? heightGridColor
      : (heightGridColor as num).toInt();
  _kHeightGridOffset    = heightGridOffset.toDouble();
  final exclusionSquareData = useExcludeSquares
      .take(_kMaxExclusionSquares)
      .where((sq) => sq.length >= 3)
      .map((sq) {
        final width = sq[2].toDouble();
        final length = (sq.length >= 4 ? sq[3] : sq[2]).toDouble();
        return [sq[0].toDouble(), sq[1].toDouble(), width, length];
      })
      .toList();
  _exclusionSquareData = exclusionSquareData;
  _terrainHeights       = heightPoints
      .take(_kMaxTerrainPoints)
      .map((pt) => [pt[0].toDouble(), pt[1].toDouble(), pt[2].toDouble()])
      .toList();
  // When height data came from the mesh we already have the correct triangle
  // connectivity; skip the Delaunay re-triangulation in that case.
  _terrainTriangles     = directTriangles ?? _buildTerrainTriangles();

  final defaultPlants = plants;/* plants.isNotEmpty
      ? plants
      : const [
          PlantSpec(
            spriteAsset: 'assets/shaders/grass.png',
            count: 10000,
            width: 0.024,
            height: 0.24,
            billboard: 1,
            flipProbability: 0.5,
          ),
        ];*/
  // Build _PlantRuntime list, processing each plant's per-plant exclusion
  // squares into local coordinates immediately so the flat-array packing below
  // and the CPU scatter test in _generateField both see the correct data.
  _plants = defaultPlants.take(_kMaxPlants).map((spec) => _PlantRuntime(
    spec,
    null,
    _processPlantExcludeSquares(spec, worldposx, worldposy),
  )).toList();

  // Pack all per-plant exclusion squares into one flat array.
  // Record the start index and count for each plant so the shader can find
  // its slice without a separate array per plant.
  final plantExcludeSquaresFlat = <THREE.Vector4>[];
  final plantExcludeStarts = <int>[];
  final plantExcludeCounts = <int>[];
  for (final runtime in _plants) {
    plantExcludeStarts.add(plantExcludeSquaresFlat.length);
    final squares = runtime.excludeSquareData
        .take(_kMaxPlantExclusionSquares - plantExcludeSquaresFlat.length)
        .toList();
    plantExcludeCounts.add(squares.length);
    for (final sq in squares) {
      plantExcludeSquaresFlat.add(THREE.Vector4(sq[0], sq[1], sq[2], sq[3]));
    }
  }
  // Pad to fixed size so the uniform array length is always known at compile time.
  while (plantExcludeSquaresFlat.length < _kMaxPlantExclusionSquares) {
    plantExcludeSquaresFlat.add(THREE.Vector4(0.0, 0.0, 0.0, 0.0));
  }
  // Pad start/count lists to _kMaxPlants entries.
  while (plantExcludeStarts.length < _kMaxPlants) {
    plantExcludeStarts.add(0);
    plantExcludeCounts.add(0);
  }

      final exclusionSquareUniforms = List<THREE.Vector4>.generate(
    _kMaxExclusionSquares,
    (index) {
      if (index < exclusionSquareData.length) {
        final sq = exclusionSquareData[index];
        return THREE.Vector4(sq[0], sq[1], sq[2], sq[3]);
      }
      return THREE.Vector4(0.0, 0.0, 0.0, 0.0);
    },
  );

  final hasEdgeFadePlants = _plants.any((p) => p.spec.edgeFadeWidth > 0.0);

  // Bake the terrain under the boundary into a height map texture that the
  // vertex shader samples, instead of uploading points/triangles as uniforms.
  _bakeHeightMap(heightMapResolution);
//  final loader = THREE.TextureLoader();
  final plantSprites = <THREE.Texture?>[];
  for (final plant in _plants) {
	      var spriteTexture;
    if (plant.spec.spriteAsset.isNotEmpty) {
      if (!textures.containsKey(plant.spec.spriteAsset)) {
        spriteTexture =await  AssetPack.loadTexture(plant.spec.spriteAsset);// await loader.fromAsset(plant.spec.spriteAsset);
        textures[plant.spec.spriteAsset]=spriteTexture;
      } else
        spriteTexture=textures[plant.spec.spriteAsset];
    } else
      spriteTexture=null;
    plantSprites.add(spriteTexture);//plant.spec.spriteAsset.isNotEmpty
     //   ? await loader.fromAsset(plant.spec.spriteAsset)
      //  : null);
  /*  plantSprites.add(plant.spec.spriteAsset.isNotEmpty
        ? await loader.fromAsset(plant.spec.spriteAsset)
        : null);*/
  }
  _plants = [
    for (int i = 0; i < _plants.length; i++)
      _PlantRuntime(_plants[i].spec, plantSprites[i], _plants[i].excludeSquareData),
  ];

  final vertSrc = await rootBundle.loadString('assets/shaders/vegetation.vert.glsl');
  final fragSrc = await rootBundle.loadString('assets/shaders/vegetation.frag.glsl');

  final uniforms = <String, dynamic>{
    'spriteAlphaThreshold': {'value': _kSpriteAlphaThreshold},
    // Web loads textures the other way up, so flip the sprites there
    'spriteFlipY': {'value': kIsWeb ? 1.0 : 0.0},
    'plantCount': {'value': _plants.length.toDouble()},
    'terrainHeightMap': {'value': _heightMapTexture},
    'heightMapHalf': {'value': THREE.Vector2(
        max(_kBoundaryWidth / 2.0, 0.0001), max(_kBoundaryLength / 2.0, 0.0001))},
    'heightMapRes': {'value': max(_heightMapRes, 2).toDouble()},
    'heightMapValid': {'value': _heightMapTexture != null ? 1.0 : 0.0},
    'excludeSquareCount': {'value': exclusionSquareData.length.toDouble()},
    'excludeSquares': {'value': exclusionSquareUniforms},
    'plantExcludeSquares': {'value': plantExcludeSquaresFlat},
    'iTime': {'value': 0.0},
    'windSpeed': {'value': _kWindSpeed},
    'cameraXZ': {'value': THREE.Vector2(0.0, 0.0)},
    'boundaryHalf': {'value': THREE.Vector2(
        _kBoundaryWidth / 2.0, _kBoundaryLength / 2.0)},
    'edgeFalloff': {'value': _kEdgeFalloff},
    'meshScale': {'value': _kMeshScale},
    'planeSize': {'value': _kPlaneSize},
    'layerFadeAngle': {'value': layerFadeAngle.toDouble()},
    'grassShadow': {'value': _kGrassShadow},
    // Standard Three.js fog uniform names - WebGLRenderer auto-populates
    // these from scene.fog every frame for any material with fog=true,
    // regardless of whether it's a built-in or fully custom
    // ShaderMaterial. Initial values here are just placeholders; the
    // renderer overwrites them before the first frame that uses them.
    'fogColor': {'value': THREE.Color.fromHex32(0xcccccc)},
    'fogNear': {'value': 1.0},
    'fogFar': {'value': 100.0},
    // Multiplied against the sampled sprite color, same role as
    // InstancedBillboards' material.color tint - defaults to white (no
    // change) unless a [color] was passed to createGrass().
    'ambientColor': {'value': color ?? THREE.Color.fromHex32(0xffffff)},
  };
  for (int i = 0; i < _kMaxPlants; i++) {
    final sprite = i < _plants.length ? _plants[i].sprite : null;
    final plantPlaneSize = i < _plants.length && _plants[i].spec.planeSize > 0.0
        ? _plants[i].spec.planeSize
        : _kPlaneSize;
    final plantEdgeFadeWidth = i < _plants.length
        ? _plants[i].spec.edgeFadeWidth
        : 0.0;
    final plantExclusionOffset = i < _plants.length
        ? _plants[i].spec.exclusionOffset
        : 0.0;
    final plantUseExclusion = i < _plants.length && _usesExclusion(_plants[i].spec);
    uniforms['plantSprite$i'] = {'value': sprite};
    uniforms['plantUseSprite$i'] = {'value': sprite != null ? 1.0 : 0.0};
    uniforms['plantBillboard$i'] = {
      'value': i < _plants.length ? _plants[i].spec.billboard.toDouble() : 0.0,
    };
    uniforms['plantPlaneSize$i'] = {'value': plantPlaneSize};
    uniforms['plantEdgeFadeWidth$i'] = {'value': plantEdgeFadeWidth};
    uniforms['plantUseFootprintExclusion$i'] = {
      'value': plantUseExclusion ? 1.0 : 0.0,
    };
    uniforms['plantExclusionOffset\$i'] = {'value': plantExclusionOffset};
    uniforms['plantScrolling$i'] = {'value': (i < _plants.length && _plants[i].spec.scrolling) ? 1.0 : 0.0};
    uniforms['plantExcludeStart$i'] = {'value': (i < plantExcludeStarts.length ? plantExcludeStarts[i] : 0).toDouble()};
    uniforms['plantExcludeCount$i'] = {'value': (i < plantExcludeCounts.length ? plantExcludeCounts[i] : 0).toDouble()};
  }

  _grassMaterial = THREE.ShaderMaterial.fromMap({
    'uniforms': uniforms,
    'vertexShader':   vertSrc,
    'fragmentShader': fragSrc,
    'side': THREE.DoubleSide,
  });
  _grassMaterial.vertexColors = false;
  _grassMaterial.transparent = false;
  _grassMaterial.depthWrite = true;
  _grassMaterial.fog = true;

  _iTimeUniform      = _grassMaterial.uniforms['iTime']!;
  _windSpeedUniform  = _grassMaterial.uniforms['windSpeed']!;
  _cameraXZUniform   = _grassMaterial.uniforms['cameraXZ']!;
  _cameraXZUniform['value'] = _cameraXZVec;
  _boundaryUniform       = _grassMaterial.uniforms['boundaryHalf']!;
  _meshScaleUniform      = _grassMaterial.uniforms['meshScale']!;
  _planeSizeUniform      = _grassMaterial.uniforms['planeSize']!;
  _grassShadowUniform = _grassMaterial.uniforms['grassShadow']!;

  final mesh = _generateField(seed: seed);

  if (surfaceTexture != null) {
    final overlay = await _buildSurfaceOverlay(surfaceTexture);
    if (overlay != null) {
      mesh.add(overlay);
    }
  }

  return mesh;
}