Skip to content

Instantly share code, notes, and snippets.

@thomcc
Created February 21, 2019 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomcc/98427be1f288a5088ae8388517277960 to your computer and use it in GitHub Desktop.
Save thomcc/98427be1f288a5088ae8388517277960 to your computer and use it in GitHub Desktop.
#[derive(Debug, Clone, Default)]
pub struct Shape {
pub vertices: Vec<V3>,
pub tris: Vec<[u16; 3]>,
}
impl Shape {
// ...
pub fn new_sphere(radius: f32, bands: (usize, usize)) -> Self {
use std::{f32, u16};
assert_le!(bands.0 * bands.1 * 4, u16::MAX as usize);
let mut vertices = Vec::with_capacity(bands.0 * bands.1 * 4);
let mut tris = Vec::with_capacity(bands.0 * bands.1 * 2);
let lat_step = f32::consts::PI / (bands.0 as f32);
let lng_step = f32::consts::PI * 2.0 / (bands.1 as f32);
for i in 0..bands.0 {
let lat_angle = (i as f32) * lat_step;
let (lat_sin, y1) = lat_angle.sin_cos();
let (lat_sin2, y2) = (lat_angle + lat_step).sin_cos();
for j in 0..bands.1 {
let lng_angle = (j as f32) * lng_step;
let (lng_sin, lng_cos) = lng_angle.sin_cos();
let (lng_sin2, lng_cos2) = (lng_angle + lng_step).sin_cos();
let x1 = lat_sin * lng_cos;
let x2 = lat_sin * lng_cos2;
let x3 = lat_sin2 * lng_cos;
let x4 = lat_sin2 * lng_cos2;
let z1 = lat_sin * lng_sin;
let z2 = lat_sin * lng_sin2;
let z3 = lat_sin2 * lng_sin;
let z4 = lat_sin2 * lng_sin2;
// texcoords
// let u1 = 1.0 - (j as f32) / (bands.1 as f32);
// let u2 = 1.0 - (j as f32 + 1.0) / (bands.1 as f32);
// let v1 = 1.0 - (i as f32) / (bands.0 as f32);
// let v2 = 1.0 - (i as f32 + 1.0) / (bands.0 as f32);
let k = vertices.len() as u16;
vertices.extend(&[
// normals are same without * radius
vec3(x1, y1, z1) * radius,
vec3(x2, y1, z2) * radius,
vec3(x3, y2, z3) * radius,
vec3(x4, y2, z4) * radius,
]);
tris.extend(&[
[k + 0, k + 1, k + 2],
[k + 2, k + 1, k + 3],
]);
}
}
Shape { vertices, tris }
}
// ....
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment