camera.lua 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. -- Copyright (c) 2012-2025 Daniele Bartolini et al.
  2. -- SPDX-License-Identifier: MIT
  3. require "core/lua/class"
  4. FPSCamera = class(FPSCamera)
  5. function FPSCamera:init(world, unit)
  6. self._world = world
  7. self._unit = unit
  8. self._scene_graph = World.scene_graph(world)
  9. self._movement_speed = 20
  10. self._rotation_speed = 0.14
  11. end
  12. function FPSCamera:unit()
  13. return self._unit;
  14. end
  15. function FPSCamera:camera()
  16. return World.camera_instance(self._world, self._unit)
  17. end
  18. function FPSCamera:world_pose()
  19. local camera_transform = SceneGraph.instance(self._scene_graph, self._unit)
  20. return SceneGraph.world_pose(self._scene_graph, camera_transform)
  21. end
  22. function FPSCamera:rotate(dt, dx, dy)
  23. local camear_transform = SceneGraph.instance(self._scene_graph, self._unit)
  24. local camera_local_pose = SceneGraph.local_pose(self._scene_graph, camear_transform)
  25. local camera_right_vector = Matrix4x4.x(camera_local_pose)
  26. local camera_position = Matrix4x4.translation(camera_local_pose)
  27. local camera_rotation = Matrix4x4.rotation(camera_local_pose)
  28. local view_dir = Matrix4x4.y(camera_local_pose)
  29. -- Rotate.
  30. if dx ~= 0 or dy ~= 0 then
  31. local rotation_speed = self._rotation_speed * dt
  32. local rotation_around_world_up = Quaternion(Vector3(0, 0, 1), -dx * rotation_speed)
  33. local rotation_around_camera_right = Quaternion(camera_right_vector, -dy * rotation_speed)
  34. local rotation = Quaternion.multiply(rotation_around_world_up, rotation_around_camera_right)
  35. local old_rotation = Matrix4x4.from_quaternion(camera_rotation)
  36. local delta_rotation = Matrix4x4.from_quaternion(rotation)
  37. local new_rotation = Matrix4x4.multiply(old_rotation, delta_rotation)
  38. Matrix4x4.set_translation(new_rotation, camera_position)
  39. -- Fixme
  40. SceneGraph.set_local_pose(self._scene_graph, camear_transform, new_rotation)
  41. end
  42. end
  43. function FPSCamera:move(dt, dx, dy)
  44. local camera_transform = SceneGraph.instance(self._scene_graph, self._unit)
  45. local camera_local_pose = SceneGraph.local_pose(self._scene_graph, camera_transform)
  46. local camera_right_vector = Matrix4x4.x(camera_local_pose)
  47. local camera_position = Matrix4x4.translation(camera_local_pose)
  48. local view_dir = Matrix4x4.y(camera_local_pose)
  49. -- Translate.
  50. local translation_speed = self._movement_speed * dt
  51. camera_position = camera_position + view_dir * translation_speed * dy
  52. camera_position = camera_position + camera_right_vector * translation_speed * dx
  53. SceneGraph.set_local_position(self._scene_graph, camera_transform, camera_position)
  54. end