JSScene.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  2. // Please see LICENSE.md in repository root for license information
  3. // https://github.com/AtomicGameEngine/AtomicGameEngine
  4. #include <Atomic/Resource/ResourceCache.h>
  5. #include <Atomic/IO/File.h>
  6. #include <Atomic/Scene/Node.h>
  7. #include <Atomic/Scene/Scene.h>
  8. #include "JSScene.h"
  9. #include "JSComponent.h"
  10. #include "JSVM.h"
  11. namespace Atomic
  12. {
  13. static int Node_CreateJSComponent(duk_context* ctx)
  14. {
  15. duk_push_this(ctx);
  16. Node* node = js_to_class_instance<Node>(ctx, -1, 0);
  17. JSComponent* jsc = node->CreateComponent<JSComponent>();
  18. jsc->SetClassName(duk_to_string(ctx, 0));
  19. js_push_class_object_instance(ctx, jsc, "JSComponent");
  20. return 1;
  21. }
  22. static int Node_GetChildrenWithComponent(duk_context* ctx)
  23. {
  24. StringHash type = duk_to_string(ctx, 0);
  25. bool recursive = false;
  26. if (duk_get_top(ctx) == 2)
  27. if (duk_get_boolean(ctx, 1))
  28. recursive = true;
  29. duk_push_this(ctx);
  30. Node* node = js_to_class_instance<Node>(ctx, -1, 0);
  31. PODVector<Node*> dest;
  32. node->GetChildrenWithComponent(dest, type, recursive);
  33. duk_push_array(ctx);
  34. for (unsigned i = 0; i < dest.Size(); i++)
  35. {
  36. js_push_class_object_instance(ctx, dest[i], "Node");
  37. duk_put_prop_index(ctx, -2, i);
  38. }
  39. return 1;
  40. }
  41. static int Scene_LoadXML(duk_context* ctx)
  42. {
  43. JSVM* vm = JSVM::GetJSVM(ctx);
  44. String filename = duk_to_string(ctx, 0);
  45. ResourceCache* cache = vm->GetSubsystem<ResourceCache>();
  46. SharedPtr<File> file = cache->GetFile(filename);
  47. if (!file->IsOpen())
  48. {
  49. duk_push_false(ctx);
  50. return 1;
  51. }
  52. duk_push_this(ctx);
  53. Scene* scene = js_to_class_instance<Scene>(ctx, -1, 0);
  54. bool success = scene->LoadXML(*file);
  55. if (success)
  56. duk_push_true(ctx);
  57. else
  58. duk_push_false(ctx);
  59. return 1;
  60. }
  61. void jsapi_init_scene(JSVM* vm)
  62. {
  63. duk_context* ctx = vm->GetJSContext();
  64. js_class_get_prototype(ctx, "Node");
  65. duk_push_c_function(ctx, Node_GetChildrenWithComponent, DUK_VARARGS);
  66. duk_put_prop_string(ctx, -2, "getChildrenWithComponent");
  67. duk_push_c_function(ctx, Node_CreateJSComponent, 1);
  68. duk_put_prop_string(ctx, -2, "createJSComponent");
  69. duk_pop(ctx);
  70. js_class_get_prototype(ctx, "Scene");
  71. duk_push_c_function(ctx, Scene_LoadXML, 1);
  72. duk_put_prop_string(ctx, -2, "loadXML");
  73. duk_pop(ctx);
  74. }
  75. }