createTree static method

dynamic createTree(
  1. dynamic leafpaths, {
  2. dynamic spreadytapertop = 1.0,
  3. dynamic spreadx = 1.0,
  4. dynamic spready = 1.0,
  5. dynamic spreadz = 1.0,
  6. dynamic leafspritespertree = 64,
  7. dynamic leafspritescale = 1.5,
  8. dynamic treehollowness = 1.0,
  9. dynamic useplanes = true,
  10. dynamic treepath,
  11. dynamic randomroll = 0.1,
  12. dynamic windspeed = 0.0,
})

Implementation

static  createTree(leafpaths,{spreadytapertop=1.0,spreadx=1.0, spready=1.0,  spreadz=1.0,leafspritespertree=64, leafspritescale=1.5,treehollowness=1.0,useplanes=true,treepath,randomroll=0.1,windspeed=0.0}) async {
  var trunkSource;
  if (treepath!=null) {
    final gltf = await THREE.GLTFLoader().fromAsset(treepath);
    final treeScene = gltf!.scene;

    trunkSource = treeScene.getObjectByName('trunk');
    // final foliageSource = treeScene.getObjectByName('foliage');

    if (trunkSource is! THREE.Mesh) { //|| foliageSource is! THREE.Mesh) {
      throw StateError('tree.glb is missing trunk or foliage nodes.');
    }
  } else
    trunkSource=null;


  final trunkMaterial = THREE.MeshBasicMaterial.fromMap({
    'color': 0x000000,
  });

  var leaftextures=[];
  for (var leafpathi in leafpaths) {
    var leafpath;
    var leafscale;
    if (leafpathi is List) {
      leafpath = leafpathi[0];
      leafscale = leafpathi[1];
    } else {
      leafpath=leafpathi;
      leafscale=leafspritescale;
    }

    final leafTexture;
    if (!textures.containsKey(leafpath)) {
      leafTexture = await  AssetPack.loadTexture(leafpath);//await THREE.TextureLoader().fromAsset(
        //  leafpath);
      textures[leafpath]=leafTexture;
    } else
      leafTexture=textures[leafpath];
    if (leafTexture == null) {
      throw StateError('assets/leafclump.png did not load.');
    }
    leafTexture.colorSpace = THREE.SRGBColorSpace;
    final leafWidth = leafTexture.image.width?.toDouble();// ?? 327.0;
    final leafHeight = leafTexture.image.height?.toDouble();// ?? 213.0;
    final leafAspect = leafWidth / leafHeight;

    var foliageMaterial = THREE.SpriteMaterial.fromMap({
      'map': leafTexture,
      'color': 0xffffff,
      'alphaTest': 0.5,
    });

    foliageMaterial?.sizeAttenuation = true;
    foliageMaterial?.map?.wrapT = THREE.RepeatWrapping;
    foliageMaterial?.map?.repeat.y = -1.0;
    final THREE.Material foliagePlaneMaterial;
    if (windspeed > 0.0) {
      // Wind ShaderMaterial — used when windspeed > 0.
      // u_windTime is ticked each frame by Tree.updateWind(delta).
      // V is flipped to match the repeat.y=-1 set on the shared texture.
      // sRGB gamma is applied manually since ShaderMaterial bypasses the
      // renderer's automatic output-encoding step.
      final mat = THREE.ShaderMaterial.fromMap({
        'uniforms': {
          'map':         {'value': leafTexture},
          'u_windTime':  {'value': 0.0},
          'u_windSpeed': {'value': windspeed},
        },
        'vertexShader': '''
          uniform float u_windTime;
          uniform float u_windSpeed;
          varying vec2 vUv;

          void main() {
            vUv = uv;

            // Per-instance phase from world-space XZ so each leaf plane
            // sways slightly out of sync with its neighbours.
            float phase = instanceMatrix[3][0] + instanceMatrix[3][2];

            // Scale sway by normalised local Y — top moves more than bottom.
            float normalizedY = clamp(position.y + 0.5, 0.0, 1.0);
            float power = (u_windSpeed / 5.0) * 0.5;
            float sway  = sin(u_windTime + phase) * power * normalizedY;

            float c = cos(sway);
            float s = sin(sway);
            vec3 pos = position;
            pos.xy = vec2(c * pos.x - s * pos.y,
                          s * pos.x + c * pos.y);

            gl_Position = projectionMatrix
                        * modelViewMatrix
                        * instanceMatrix
                        * vec4(pos, 1.0);
          }
        ''',
        'fragmentShader': '''
          uniform sampler2D map;
          varying vec2 vUv;
          void main() {
            vec2 uv = vec2(vUv.x, 1.0 - vUv.y);
            vec4 c  = texture2D(map, uv);
            if (c.a < 0.5) discard;
            gl_FragColor = vec4(pow(c.rgb, vec3(1.0 / 2.2)), c.a);
          }
        ''',
        'side': THREE.DoubleSide,
        'transparent': false,
      });
      windMaterials.add(mat);
      foliagePlaneMaterial = mat;
    } else {
      // No wind — plain MeshBasicMaterial, not registered in windMaterials.
      foliagePlaneMaterial = THREE.MeshBasicMaterial.fromMap({
        'map': leafTexture,
        'color': 0xffffff,
        'alphaTest': 0.5,
        'transparent': false,
        'side': THREE.DoubleSide,
      });
    }

    leaftextures.add([foliageMaterial, foliagePlaneMaterial, leafAspect, leafscale]);
  }
 /* final leafTexture2;
  if (leafpath2!=null) {
    leafTexture2 = await THREE.TextureLoader().fromAsset(
  'assets/leafclump2.png');
  if (leafTexture2 == null) {
  throw StateError('assets/leafclump.png did not load.');
  }
  }
  leafTexture2.colorSpace = THREE.SRGBColorSpace;*/
 //   const leafSpriteScale = 1.5;
 // const leafSpritesPerTree = 8 * 8;
 // const usePlanes = true;
 // const treeHollowness = 0.3; //0.1;  // 0.0 is totally hollow and 1.0 means not hollow at all - in a sense the width of the non hollow part

  // foliagePlaneMaterial2=null;

  //foliagePlaneMaterial?.map?.wrapT = THREE.RepeatWrapping;
  // foliagePlaneMaterial?.map?.repeat.y = -1.0;
  final rng = math.Random(7);

  var x = 0.0;
  var z =0.0;

  final rotationY = rng.nextDouble() * math.pi * 2;
  final scale = 0.85 + rng.nextDouble() * 0.45;

  final tree = _buildTreeInstance(
    trunkSource: trunkSource,
    //foliageSource: foliageSource,
    trunkMaterial: trunkMaterial,
    //  foliageMaterial: foliageMaterial!,
   // foliagePlaneMaterial: foliagePlaneMaterial!,
  //  foliagePlaneMaterial2: foliagePlaneMaterial2!,
    //leafAspect: leafAspect,
    leaftextures:leaftextures,
   /// leafSpriteScale: leafspritescale,//leafSpriteScale,
    leafSpritesPerTree: leafspritespertree,
    usePlanes: useplanes,
    treeHollowness: treehollowness,//treeHollowness,
    x: x,
    y: 0,
    z: z,
    rotationY: rotationY,
    scale: scale,
    spreadX: spreadx,
  //  spreadYTop: spreadytop ?? spready,
   // spreadYBottom: spreadybottom ?? spready,
    spreadY:spready,
    spreadYTaperTop:spreadytapertop,
    spreadZ: spreadz,
	  randomRoll: randomroll,
  );
  return tree;

}