circle.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package geometry
  5. import (
  6. "github.com/g3n/engine/gls"
  7. "github.com/g3n/engine/math32"
  8. "math"
  9. )
  10. type Circle struct {
  11. Geometry
  12. Radius float64
  13. Segments int
  14. ThetaStart float64
  15. ThetaLength float64
  16. }
  17. // NewCircle creates and returns a pointer to a new Circle geometry object.
  18. // The geometry is defined by its radius, the number of segments (triangles), minimum = 3,
  19. // the start angle in radians for the first segment (thetaStart) and
  20. // the central angle in radians (thetaLength) of the circular sector.
  21. func NewCircle(radius float64, segments int, thetaStart, thetaLength float64) *Circle {
  22. circ := new(Circle)
  23. circ.Geometry.Init()
  24. circ.Radius = radius
  25. circ.Segments = segments
  26. circ.ThetaStart = thetaStart
  27. circ.ThetaLength = thetaLength
  28. if segments < 3 {
  29. segments = 3
  30. }
  31. // Create buffers
  32. positions := math32.NewArrayF32(0, 16)
  33. normals := math32.NewArrayF32(0, 16)
  34. uvs := math32.NewArrayF32(0, 16)
  35. indices := math32.NewArrayU32(0, 16)
  36. // Append circle center position
  37. center := math32.NewVector3(0, 0, 0)
  38. positions.AppendVector3(center)
  39. // Append circle center normal
  40. var normal math32.Vector3
  41. normal.Z = 1
  42. normals.AppendVector3(&normal)
  43. // Append circle center uv coord
  44. centerUV := math32.NewVector2(0.5, 0.5)
  45. uvs.AppendVector2(centerUV)
  46. for i := 0; i <= segments; i++ {
  47. segment := thetaStart + float64(i)/float64(segments)*thetaLength
  48. vx := float32(radius * math.Cos(segment))
  49. vy := float32(radius * math.Sin(segment))
  50. // Appends vertex position, normal and uv coordinates
  51. positions.Append(vx, vy, 0)
  52. normals.AppendVector3(&normal)
  53. uvs.Append((vx/float32(radius)+1)/2, (vy/float32(radius)+1)/2)
  54. }
  55. for i := 1; i <= segments; i++ {
  56. indices.Append(uint32(i), uint32(i)+1, 0)
  57. }
  58. circ.SetIndices(indices)
  59. circ.AddVBO(gls.NewVBO().AddAttrib("VertexPosition", 3).SetBuffer(positions))
  60. circ.AddVBO(gls.NewVBO().AddAttrib("VertexNormal", 3).SetBuffer(normals))
  61. circ.AddVBO(gls.NewVBO().AddAttrib("VertexTexcoord", 2).SetBuffer(uvs))
  62. //circ.BoundingSphere = math32.NewSphere(math32.NewVector3(0,0,0), float32(radius))
  63. return circ
  64. }