cylinder static method

Geometry cylinder({
  1. double radius = 1.0,
  2. double length = 1.0,
  3. bool normals = true,
  4. bool uvs = true,
})

Implementation

static Geometry cylinder({double radius = 1.0, double length = 1.0, bool normals = true, bool uvs = true }) {
  int segments = 32;
  List<double> verticesList = [];
  List<double> normalsList = [];
  List<double> uvsList = [];
  List<int> indices = [];

  // Create vertices, normals, and UVs
  for (int i = 0; i <= segments; i++) {
    double theta = i * 2 * pi / segments;
    double x = radius * cos(theta);
    double z = radius * sin(theta);

    // Top circle
    verticesList.addAll([x, length / 2, z]);
    normalsList.addAll([x / radius, 0, z / radius]);
    uvsList.addAll([i / segments, 1]);

    // Bottom circle
    verticesList.addAll([x, -length / 2, z]);
    normalsList.addAll([x / radius, 0, z / radius]);
    uvsList.addAll([i / segments, 0]);
  }

  // Create indices
  for (int i = 0; i < segments; i++) {
    int topFirst = i * 2;
    int topSecond = (i + 1) * 2;
    int bottomFirst = topFirst + 1;
    int bottomSecond = topSecond + 1;

    // Top face (counter-clockwise)
    indices.addAll([segments * 2, topSecond, topFirst]);
    // Bottom face (counter-clockwise when viewed from below)
    indices.addAll([segments * 2 + 1, bottomFirst, bottomSecond]);
    // Side faces (counter-clockwise)
    indices.addAll([topFirst, bottomFirst, topSecond]);
    indices.addAll([bottomFirst, bottomSecond, topSecond]);
  }

  // Add center vertices, normals, and UVs for top and bottom faces
  verticesList.addAll([0, length / 2, 0]); // Top center
  normalsList.addAll([0, 1, 0]);
  uvsList.addAll([0.5, 0.5]); // Center of top face

  verticesList.addAll([0, -length / 2, 0]); // Bottom center
  normalsList.addAll([0, -1, 0]);
  uvsList.addAll([0.5, 0.5]); // Center of bottom face

  // Add top and bottom face normals and UVs
  for (int i = 0; i <= segments; i++) {
    normalsList.addAll([0, 1, 0]); // Top face normal
    normalsList.addAll([0, -1, 0]); // Bottom face normal

    double u = 0.5 + 0.5 * cos(i * 2 * pi / segments);
    double v = 0.5 + 0.5 * sin(i * 2 * pi / segments);
    uvsList.addAll([u, v]); // Top face UV
    uvsList.addAll([u, v]); // Bottom face UV
  }

  Float32List vertices = Float32List.fromList(verticesList);
  Float32List? _normals = normals ? Float32List.fromList(normalsList) : null;
  Float32List? _uvs = uvs ? Float32List.fromList(uvsList) : null;

  return Geometry(vertices, indices, normals: _normals, uvs: _uvs);
}