lua_raycast.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "lua_stack.h"
  6. #include "lua_environment.h"
  7. #include "raycast.h"
  8. #include "memory.h"
  9. #include "array.h"
  10. namespace crown
  11. {
  12. static int raycast_cast(lua_State* L)
  13. {
  14. LuaStack stack(L);
  15. Raycast* raycast = stack.get_raycast(1);
  16. Vector3 from = stack.get_vector3(2);
  17. Vector3 dir = stack.get_vector3(3);
  18. float length = stack.get_float(4);
  19. Array<RaycastHit> hits(default_allocator());
  20. raycast->cast(from, dir, length, hits);
  21. switch(raycast->mode())
  22. {
  23. case CollisionMode::CLOSEST:
  24. {
  25. bool hit = array::size(hits) > 0 ? true : false;
  26. stack.push_bool(hit);
  27. break;
  28. }
  29. case CollisionMode::ANY:
  30. {
  31. bool hit = array::size(hits) > 0 ? true : false;
  32. stack.push_bool(hit);
  33. if (hit)
  34. {
  35. stack.push_vector3(hits[0].position);
  36. stack.push_float(hits[0].distance);
  37. stack.push_vector3(hits[0].normal);
  38. stack.push_actor(hits[0].actor);
  39. return 5;
  40. }
  41. break;
  42. }
  43. case CollisionMode::ALL:
  44. {
  45. stack.push_table();
  46. for (uint32_t i = 0; i < array::size(hits); i++)
  47. {
  48. stack.push_key_begin(i+1);
  49. stack.push_table();
  50. stack.push_key_begin("position"); stack.push_vector3(hits[i].position); stack.push_key_end();
  51. stack.push_key_begin("distance"); stack.push_float(hits[i].distance); stack.push_key_end();
  52. stack.push_key_begin("normal"); stack.push_vector3(hits[i].normal); stack.push_key_end();
  53. stack.push_key_begin("actor"); stack.push_actor(hits[i].actor); stack.push_key_end();
  54. stack.push_key_end();
  55. }
  56. break;
  57. }
  58. }
  59. return 1;
  60. }
  61. void load_raycast(LuaEnvironment& env)
  62. {
  63. env.load_module_function("Raycast", "cast", raycast_cast);
  64. }
  65. } // namespace crown