star.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { Vec3 } from 'mol-math/linear-algebra'
  7. import { Primitive, PrimitiveBuilder } from './primitive';
  8. export const DefaultStarProps = {
  9. pointCount: 5,
  10. outerRadius: 1,
  11. innerRadius: 0.5,
  12. thickness: 0.3
  13. }
  14. export type StarProps = Partial<typeof DefaultStarProps>
  15. const op = Vec3.zero(), on = Vec3.zero()
  16. const a = Vec3.zero(), b = Vec3.zero(), c = Vec3.zero()
  17. export function Star(props?: StarProps): Primitive {
  18. const { outerRadius, innerRadius, thickness, pointCount } = { ...DefaultStarProps, ...props }
  19. const triangleCount = pointCount * 2 * 2
  20. const builder = PrimitiveBuilder(triangleCount)
  21. const innerPoints = new Float32Array(pointCount * 2)
  22. const outerPoints = new Float32Array(pointCount * 2)
  23. for (let i = 0; i < pointCount; ++i) {
  24. const io = i * 2, ii = i * 2 + 1
  25. const co = (io + 1) / pointCount * Math.PI, ci = (ii + 1) / pointCount * Math.PI
  26. outerPoints[io] = Math.cos(co) * outerRadius
  27. outerPoints[ii] = Math.sin(co) * outerRadius
  28. innerPoints[io] = Math.cos(ci) * innerRadius
  29. innerPoints[ii] = Math.sin(ci) * innerRadius
  30. }
  31. Vec3.set(op, 0, 0, thickness / 2)
  32. Vec3.set(on, 0, 0, -thickness / 2)
  33. for (let i = 0; i < pointCount; ++i) {
  34. const ni = (i + 1) % pointCount
  35. Vec3.set(a, outerPoints[i * 2], outerPoints[i * 2 + 1], 0)
  36. Vec3.set(b, innerPoints[i * 2], innerPoints[i * 2 + 1], 0)
  37. Vec3.set(c, outerPoints[ni * 2], outerPoints[ni * 2 + 1], 0)
  38. builder.add(op, a, b)
  39. builder.add(b, a, on)
  40. builder.add(op, b, c)
  41. builder.add(c, b, on)
  42. }
  43. return builder.getPrimitive()
  44. }