JSScene.cpp 2.4 KB

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