directional.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. // NewDirectional creates and returns a pointer of a new directional light
  22. // the specified color and intensity.
  23. func NewDirectional(color *math32.Color, intensity float32) *Directional {
  24. ld := new(Directional)
  25. ld.Node.Init()
  26. ld.color = *color
  27. ld.intensity = intensity
  28. ld.uni.Init("DirLight")
  29. ld.SetColor(color)
  30. return ld
  31. }
  32. // SetColor sets the color of this light
  33. func (ld *Directional) SetColor(color *math32.Color) {
  34. ld.color = *color
  35. ld.udata.color = ld.color
  36. ld.udata.color.MultiplyScalar(ld.intensity)
  37. }
  38. // Color returns the current color of this light
  39. func (ld *Directional) Color() math32.Color {
  40. return ld.color
  41. }
  42. // SetIntensity sets the intensity of this light
  43. func (ld *Directional) SetIntensity(intensity float32) {
  44. ld.intensity = intensity
  45. ld.udata.color = ld.color
  46. ld.udata.color.MultiplyScalar(ld.intensity)
  47. }
  48. // Intensity returns the current intensity of this light
  49. func (ld *Directional) Intensity() float32 {
  50. return ld.intensity
  51. }
  52. // RenderSetup is called by the engine before rendering the scene
  53. func (ld *Directional) RenderSetup(gs *gls.GLS, rinfo *core.RenderInfo, idx int) {
  54. // Calculates light position in camera coordinates and updates uniform
  55. var pos math32.Vector3
  56. ld.WorldPosition(&pos)
  57. pos4 := math32.Vector4{pos.X, pos.Y, pos.Z, 0.0}
  58. pos4.ApplyMatrix4(&rinfo.ViewMatrix)
  59. //ld.uni.SetVector3(dirPosition, &math32.Vector3{pos4.X, pos4.Y, pos4.Z})
  60. ld.udata.position.X = pos4.X
  61. ld.udata.position.Y = pos4.Y
  62. ld.udata.position.Z = pos4.Z
  63. // Transfer uniform data
  64. const vec3count = 2
  65. location := ld.uni.LocationIdx(gs, vec3count*int32(idx))
  66. gs.Uniform3fvUP(location, vec3count, unsafe.Pointer(&ld.udata))
  67. }