directional.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 light
  5. import (
  6. "unsafe"
  7. "github.com/g3n/engine/core"
  8. "github.com/g3n/engine/gls"
  9. "github.com/g3n/engine/math32"
  10. )
  11. type Directional struct {
  12. core.Node // Embedded node
  13. color math32.Color // Light color
  14. intensity float32 // Light intensity
  15. uni gls.Uniform2 // Uniform location cache
  16. udata struct { // Combined uniform data in 2 vec3:
  17. color math32.Color // Light color
  18. position math32.Vector3 // Light position
  19. }
  20. }
  21. // Number of glsl shader vec3 elements used by uniform data
  22. const udataVec3 = 2
  23. // NewDirectional creates and returns a pointer of a new directional light
  24. // the specified color and intensity.
  25. func NewDirectional(color *math32.Color, intensity float32) *Directional {
  26. ld := new(Directional)
  27. ld.Node.Init()
  28. ld.color = *color
  29. ld.intensity = intensity
  30. ld.uni.Init("DirLight")
  31. ld.SetColor(color)
  32. return ld
  33. }
  34. // SetColor sets the color of this light
  35. func (ld *Directional) SetColor(color *math32.Color) {
  36. ld.color = *color
  37. ld.udata.color = ld.color
  38. ld.udata.color.MultiplyScalar(ld.intensity)
  39. }
  40. // Color returns the current color of this light
  41. func (ld *Directional) Color() math32.Color {
  42. return ld.color
  43. }
  44. // SetIntensity sets the intensity of this light
  45. func (ld *Directional) SetIntensity(intensity float32) {
  46. ld.intensity = intensity
  47. ld.udata.color = ld.color
  48. ld.udata.color.MultiplyScalar(ld.intensity)
  49. }
  50. // Intensity returns the current intensity of this light
  51. func (ld *Directional) Intensity() float32 {
  52. return ld.intensity
  53. }
  54. // RenderSetup is called by the engine before rendering the scene
  55. func (ld *Directional) RenderSetup(gs *gls.GLS, rinfo *core.RenderInfo, idx int) {
  56. // Calculates light position in camera coordinates and updates uniform
  57. var pos math32.Vector3
  58. ld.WorldPosition(&pos)
  59. pos4 := math32.Vector4{pos.X, pos.Y, pos.Z, 0.0}
  60. pos4.ApplyMatrix4(&rinfo.ViewMatrix)
  61. //ld.uni.SetVector3(dirPosition, &math32.Vector3{pos4.X, pos4.Y, pos4.Z})
  62. ld.udata.position.X = pos4.X
  63. ld.udata.position.Y = pos4.Y
  64. ld.udata.position.Z = pos4.Z
  65. // Transfer uniform data
  66. location := ld.uni.LocationIdx(gs, int32(idx))
  67. gs.Uniform3fvUP(location, udataVec3, unsafe.Pointer(&ld.udata))
  68. }