JSComponent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  23. // Please see LICENSE.md in repository root for license information
  24. // https://github.com/AtomicGameEngine/AtomicGameEngine
  25. #include <Atomic/IO/Log.h>
  26. #include <Atomic/IO/FileSystem.h>
  27. #include <Atomic/Core/Context.h>
  28. #include <Atomic/Resource/ResourceCache.h>
  29. #ifdef ATOMIC_PHYSICS
  30. #include <Atomic/Physics/PhysicsEvents.h>
  31. #include <Atomic/Physics/PhysicsWorld.h>
  32. #endif
  33. #include <Atomic/Scene/Scene.h>
  34. #include <Atomic/Scene/SceneEvents.h>
  35. #include "JSVM.h"
  36. #include "JSComponentFile.h"
  37. #include "JSComponent.h"
  38. namespace Atomic
  39. {
  40. extern const char* LOGIC_CATEGORY;
  41. JSComponent::JSComponent(Context* context) :
  42. Component(context),
  43. updateEventMask_(USE_UPDATE | USE_POSTUPDATE | USE_FIXEDUPDATE | USE_FIXEDPOSTUPDATE),
  44. currentEventMask_(0),
  45. started_(false),
  46. delayedStartCalled_(false),
  47. loading_(false)
  48. {
  49. vm_ = JSVM::GetJSVM(NULL);
  50. }
  51. JSComponent::~JSComponent()
  52. {
  53. }
  54. void JSComponent::RegisterObject(Context* context)
  55. {
  56. context->RegisterFactory<JSComponent>(LOGIC_CATEGORY);
  57. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  58. MIXED_ACCESSOR_ATTRIBUTE("ComponentFile", GetScriptAttr, SetScriptAttr, ResourceRef, ResourceRef(JSComponentFile::GetTypeStatic()), AM_DEFAULT);
  59. }
  60. void JSComponent::OnSetEnabled()
  61. {
  62. UpdateEventSubscription();
  63. }
  64. void JSComponent::SetUpdateEventMask(unsigned char mask)
  65. {
  66. if (updateEventMask_ != mask)
  67. {
  68. updateEventMask_ = mask;
  69. UpdateEventSubscription();
  70. }
  71. }
  72. void JSComponent::UpdateReferences(bool remove)
  73. {
  74. duk_context* ctx = vm_->GetJSContext();
  75. int top = duk_get_top(ctx);
  76. duk_push_global_stash(ctx);
  77. duk_get_prop_index(ctx, -1, JS_GLOBALSTASH_INDEX_NODE_REGISTRY);
  78. // can't use instance as key, as this coerces to [Object] for
  79. // string property, pointer will be string representation of
  80. // address, so, unique key
  81. duk_push_pointer(ctx, (void*) node_);
  82. if (remove)
  83. duk_push_undefined(ctx);
  84. else
  85. js_push_class_object_instance(ctx, node_);
  86. duk_put_prop(ctx, -3);
  87. duk_push_pointer(ctx, (void*) this);
  88. if (remove)
  89. duk_push_undefined(ctx);
  90. else
  91. js_push_class_object_instance(ctx, this);
  92. duk_put_prop(ctx, -3);
  93. duk_pop_2(ctx);
  94. assert(duk_get_top(ctx) == top);
  95. }
  96. void JSComponent::ApplyAttributes()
  97. {
  98. }
  99. void JSComponent::InitModule()
  100. {
  101. if (context_->GetEditorContext() || componentFile_.Null())
  102. return;
  103. duk_context* ctx = vm_->GetJSContext();
  104. const String& path = componentFile_->GetName();
  105. String pathName, fileName, ext;
  106. SplitPath(path, pathName, fileName, ext);
  107. pathName += "/" + fileName;
  108. duk_idx_t top = duk_get_top(ctx);
  109. duk_get_global_string(ctx, "require");
  110. duk_push_string(ctx, pathName.CString());
  111. if (duk_pcall(ctx, 1) != 0)
  112. {
  113. vm_->SendJSErrorEvent();
  114. return;
  115. }
  116. if (!duk_is_object(ctx, -1))
  117. {
  118. duk_set_top(ctx, top);
  119. return;
  120. }
  121. duk_get_prop_string(ctx, -1, "component");
  122. if (!duk_is_function(ctx, -1))
  123. {
  124. duk_set_top(ctx, top);
  125. return;
  126. }
  127. // call with self
  128. js_push_class_object_instance(ctx, this, "JSComponent");
  129. if (duk_pcall(ctx, 1) != 0)
  130. {
  131. vm_->SendJSErrorEvent();
  132. duk_set_top(ctx, top);
  133. return;
  134. }
  135. UpdateReferences();
  136. duk_set_top(ctx, top);
  137. }
  138. void JSComponent::CallScriptMethod(const String& name, bool passValue, float value)
  139. {
  140. void* heapptr = JSGetHeapPtr();
  141. if (!heapptr)
  142. return;
  143. duk_context* ctx = vm_->GetJSContext();
  144. duk_idx_t top = duk_get_top(ctx);
  145. duk_push_heapptr(ctx, heapptr);
  146. duk_get_prop_string(ctx, -1, name.CString());
  147. if (!duk_is_function(ctx, -1))
  148. {
  149. duk_set_top(ctx, top);
  150. return;
  151. }
  152. if (passValue)
  153. duk_push_number(ctx, value);
  154. if (duk_pcall(ctx, passValue ? 1 : 0) != 0)
  155. {
  156. vm_->SendJSErrorEvent();
  157. duk_set_top(ctx, top);
  158. return;
  159. }
  160. duk_set_top(ctx, top);
  161. }
  162. void JSComponent::Start()
  163. {
  164. static String name = "start";
  165. CallScriptMethod(name);
  166. }
  167. void JSComponent::DelayedStart()
  168. {
  169. static String name = "delayedStart";
  170. CallScriptMethod(name);
  171. }
  172. void JSComponent::Update(float timeStep)
  173. {
  174. static String name = "update";
  175. CallScriptMethod(name, true, timeStep);
  176. }
  177. void JSComponent::PostUpdate(float timeStep)
  178. {
  179. static String name = "postUpdate";
  180. CallScriptMethod(name, true, timeStep);
  181. }
  182. void JSComponent::FixedUpdate(float timeStep)
  183. {
  184. static String name = "fixedUpdate";
  185. CallScriptMethod(name, true, timeStep);
  186. }
  187. void JSComponent::FixedPostUpdate(float timeStep)
  188. {
  189. static String name = "fixedPostUpdate";
  190. CallScriptMethod(name, true, timeStep);
  191. }
  192. void JSComponent::OnNodeSet(Node* node)
  193. {
  194. if (node)
  195. {
  196. // We have been attached to a node. Set initial update event subscription state
  197. UpdateEventSubscription();
  198. }
  199. else
  200. {
  201. // We are being detached from a node: execute user-defined stop function and prepare for destruction
  202. UpdateReferences(true);
  203. Stop();
  204. }
  205. }
  206. void JSComponent::UpdateEventSubscription()
  207. {
  208. // If scene node is not assigned yet, no need to update subscription
  209. if (!node_)
  210. return;
  211. Scene* scene = GetScene();
  212. if (!scene)
  213. {
  214. LOGWARNING("Node is detached from scene, can not subscribe to update events");
  215. return;
  216. }
  217. bool enabled = IsEnabledEffective();
  218. bool needUpdate = enabled && ((updateEventMask_ & USE_UPDATE) || !delayedStartCalled_);
  219. if (needUpdate && !(currentEventMask_ & USE_UPDATE))
  220. {
  221. SubscribeToEvent(scene, E_SCENEUPDATE, HANDLER(JSComponent, HandleSceneUpdate));
  222. currentEventMask_ |= USE_UPDATE;
  223. }
  224. else if (!needUpdate && (currentEventMask_ & USE_UPDATE))
  225. {
  226. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  227. currentEventMask_ &= ~USE_UPDATE;
  228. }
  229. bool needPostUpdate = enabled && (updateEventMask_ & USE_POSTUPDATE);
  230. if (needPostUpdate && !(currentEventMask_ & USE_POSTUPDATE))
  231. {
  232. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(JSComponent, HandleScenePostUpdate));
  233. currentEventMask_ |= USE_POSTUPDATE;
  234. }
  235. else if (!needUpdate && (currentEventMask_ & USE_POSTUPDATE))
  236. {
  237. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  238. currentEventMask_ &= ~USE_POSTUPDATE;
  239. }
  240. #ifdef ATOMIC_PHYSICS
  241. PhysicsWorld* world = scene->GetComponent<PhysicsWorld>();
  242. if (!world)
  243. return;
  244. bool needFixedUpdate = enabled && (updateEventMask_ & USE_FIXEDUPDATE);
  245. if (needFixedUpdate && !(currentEventMask_ & USE_FIXEDUPDATE))
  246. {
  247. SubscribeToEvent(world, E_PHYSICSPRESTEP, HANDLER(JSComponent, HandlePhysicsPreStep));
  248. currentEventMask_ |= USE_FIXEDUPDATE;
  249. }
  250. else if (!needFixedUpdate && (currentEventMask_ & USE_FIXEDUPDATE))
  251. {
  252. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  253. currentEventMask_ &= ~USE_FIXEDUPDATE;
  254. }
  255. bool needFixedPostUpdate = enabled && (updateEventMask_ & USE_FIXEDPOSTUPDATE);
  256. if (needFixedPostUpdate && !(currentEventMask_ & USE_FIXEDPOSTUPDATE))
  257. {
  258. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, HANDLER(JSComponent, HandlePhysicsPostStep));
  259. currentEventMask_ |= USE_FIXEDPOSTUPDATE;
  260. }
  261. else if (!needFixedPostUpdate && (currentEventMask_ & USE_FIXEDPOSTUPDATE))
  262. {
  263. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  264. currentEventMask_ &= ~USE_FIXEDPOSTUPDATE;
  265. }
  266. #endif
  267. }
  268. void JSComponent::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  269. {
  270. using namespace SceneUpdate;
  271. if (!started_)
  272. {
  273. started_ = true;
  274. InitModule();
  275. Start();
  276. }
  277. // Execute user-defined delayed start function before first update
  278. if (!delayedStartCalled_)
  279. {
  280. DelayedStart();
  281. delayedStartCalled_ = true;
  282. // If did not need actual update events, unsubscribe now
  283. if (!(updateEventMask_ & USE_UPDATE))
  284. {
  285. UnsubscribeFromEvent(GetScene(), E_SCENEUPDATE);
  286. currentEventMask_ &= ~USE_UPDATE;
  287. return;
  288. }
  289. }
  290. // Then execute user-defined update function
  291. Update(eventData[P_TIMESTEP].GetFloat());
  292. }
  293. void JSComponent::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  294. {
  295. using namespace ScenePostUpdate;
  296. // Execute user-defined post-update function
  297. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  298. }
  299. #ifdef ATOMIC_PHYSICS
  300. void JSComponent::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  301. {
  302. using namespace PhysicsPreStep;
  303. // Execute user-defined fixed update function
  304. FixedUpdate(eventData[P_TIMESTEP].GetFloat());
  305. }
  306. void JSComponent::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  307. {
  308. using namespace PhysicsPostStep;
  309. // Execute user-defined fixed post-update function
  310. FixedPostUpdate(eventData[P_TIMESTEP].GetFloat());
  311. }
  312. #endif
  313. bool JSComponent::Load(Deserializer& source, bool setInstanceDefault)
  314. {
  315. loading_ = true;
  316. bool success = Component::Load(source, setInstanceDefault);
  317. loading_ = false;
  318. return success;
  319. }
  320. bool JSComponent::LoadXML(const XMLElement& source, bool setInstanceDefault)
  321. {
  322. loading_ = true;
  323. bool success = Component::LoadXML(source, setInstanceDefault);
  324. loading_ = false;
  325. return success;
  326. }
  327. void JSComponent::SetComponentFile(JSComponentFile* cfile, bool loading)
  328. {
  329. componentFile_ = cfile;
  330. }
  331. ResourceRef JSComponent::GetScriptAttr() const
  332. {
  333. return GetResourceRef(componentFile_, JSComponentFile::GetTypeStatic());
  334. }
  335. void JSComponent::SetScriptAttr(const ResourceRef& value)
  336. {
  337. ResourceCache* cache = GetSubsystem<ResourceCache>();
  338. SetComponentFile(cache->GetResource<JSComponentFile>(value.name_), loading_);
  339. }
  340. }