model.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 REGL = require('regl');
  7. import { Mat4, Quat, Vec3 } from 'mol-math/linear-algebra'
  8. import { defaults } from 'mol-util';
  9. const tmpMat4 = Mat4()
  10. type ModelProps = {
  11. rotation?: Quat,
  12. position?: Vec3,
  13. scale?: Vec3
  14. }
  15. function createModel(regl: REGL.Regl, props: ModelProps = {}) {
  16. const transform = Mat4.identity()
  17. const rotation = defaults(props.rotation, Quat.identity())
  18. const position = defaults(props.position, Vec3.zero())
  19. const scale = defaults(props.scale, Vec3.create(1, 1, 1))
  20. const draw = regl({
  21. context: { transform, rotation, position, scale },
  22. uniforms: {
  23. model(ctx: REGL.DefaultContext, props: any = {}) {
  24. const model = Mat4.identity()
  25. if ('rotation' in props) Quat.copy(rotation, props.rotation)
  26. if ('position' in props) Vec3.copy(position, props.position)
  27. if ('scale' in props) Vec3.copy(scale, props.scale)
  28. Mat4.translate(model, model, position)
  29. Mat4.mul(model, model, Mat4.fromQuat(tmpMat4, rotation))
  30. Mat4.scale(model, model, scale)
  31. if ('transform' in props) Mat4.mul(model, props.transform, model)
  32. Mat4.copy(transform, model)
  33. return model
  34. }
  35. }
  36. })
  37. return Object.assign(draw, {
  38. get transform() { return transform },
  39. get position() { return position },
  40. get rotation() { return rotation },
  41. get scale() { return scale },
  42. })
  43. }
  44. export default createModel