LightController.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * LightController.js
  3. *
  4. * @author realor
  5. */
  6. import { Controller } from './Controller.js'
  7. import * as THREE from '../lib/three.module.js'
  8. class LightController extends Controller {
  9. constructor(object, name) {
  10. super(object, name)
  11. this.input = 0
  12. this.minValue = 0
  13. this.maxValue = 1
  14. this.intensity = 1
  15. this.distance = 3
  16. this.offsetX = 0
  17. this.offsetY = 0
  18. this.offsetZ = 0
  19. this._onNodeChanged = this.onNodeChanged.bind(this)
  20. this._light = null
  21. }
  22. onStart() {
  23. this.createLight()
  24. this.update(true)
  25. this.application.addEventListener('scene', this._onNodeChanged)
  26. }
  27. onStop() {
  28. this.destroyLight()
  29. this.application.removeEventListener('scene', this._onNodeChanged)
  30. }
  31. onNodeChanged(event) {
  32. if (event.type === 'nodeChanged' && this.hasChanged(event)) {
  33. this.update(false)
  34. }
  35. }
  36. update(force) {
  37. let value = this.input
  38. let distance = this.distance
  39. let minValue = this.minValue
  40. let maxValue = this.maxValue
  41. let offsetX = this.offsetX
  42. let offsetY = this.offsetY
  43. let offsetZ = this.offsetZ
  44. let factor
  45. if (value <= minValue) {
  46. factor = 0
  47. } else if (value >= maxValue) {
  48. factor = 1
  49. } // interpolate factor
  50. else {
  51. factor = (value - minValue) / (maxValue - minValue) // [0..1]
  52. }
  53. let intensity = factor * this.intensity
  54. if (
  55. force ||
  56. this._light.intensity !== intensity ||
  57. this._light.distance !== distance ||
  58. this._light.position.x !== offsetX ||
  59. this._light.position.y !== offsetY ||
  60. this._light.position.z !== offsetZ
  61. ) {
  62. this._light.intensity = intensity
  63. this._light.distance = distance
  64. this._light.position.set(offsetX, offsetY, offsetZ)
  65. this._light.updateMatrix()
  66. this.application.notifyObjectsChanged(this.object, this)
  67. }
  68. }
  69. createLight() {
  70. this._light = new THREE.PointLight(0xffffff)
  71. const light = this._light
  72. light.name = 'light'
  73. light.userData.export = { export: false }
  74. this.application.addObject(light, this.object)
  75. }
  76. destroyLight() {
  77. this.application.removeObject(this._light, this.object)
  78. this._light = null
  79. }
  80. }
  81. Controller.addClass(LightController)
  82. export { LightController }