JSComponent.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. class JSComponentFactory : public ObjectFactory
  42. {
  43. public:
  44. /// Construct.
  45. JSComponentFactory(Context* context) :
  46. ObjectFactory(context)
  47. {
  48. type_ = JSComponent::GetTypeStatic();
  49. baseType_ = JSComponent::GetBaseTypeStatic();
  50. typeName_ = JSComponent::GetTypeNameStatic();
  51. }
  52. /// Create an object of the specific type.
  53. SharedPtr<Object> CreateObject()
  54. {
  55. SharedPtr<Object> ptr;
  56. Variant& v = context_->GetVar("__JSComponent_ComponentFile");
  57. // __JSComponent_ComponentFile will only be set when coming from XML
  58. // in player builds, not in editor
  59. if (v.GetType() == VAR_STRING)
  60. {
  61. String componentRef = v.GetString();
  62. // clear it, in case we end up recursively creating components
  63. context_->GetVars()["__JSComponent_ComponentFile"] = Variant::EMPTY;
  64. Vector<String> split = componentRef.Split(';');
  65. if (split.Size() == 2)
  66. {
  67. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  68. JSComponentFile* componentFile = cache->GetResource<JSComponentFile>(split[1]);
  69. if (componentFile)
  70. {
  71. ptr = componentFile->CreateJSComponent();
  72. }
  73. }
  74. }
  75. if (ptr.Null())
  76. {
  77. ptr = new JSComponent(context_);
  78. }
  79. return ptr;
  80. }
  81. };
  82. JSComponent::JSComponent(Context* context) :
  83. Component(context),
  84. updateEventMask_(USE_UPDATE | USE_POSTUPDATE | USE_FIXEDUPDATE | USE_FIXEDPOSTUPDATE),
  85. currentEventMask_(0),
  86. started_(false),
  87. destroyed_(false),
  88. scriptClassInstance_(false),
  89. delayedStartCalled_(false),
  90. loading_(false)
  91. {
  92. vm_ = JSVM::GetJSVM(NULL);
  93. }
  94. JSComponent::~JSComponent()
  95. {
  96. }
  97. void JSComponent::RegisterObject(Context* context)
  98. {
  99. context->RegisterFactory(new JSComponentFactory(context), LOGIC_CATEGORY);
  100. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  101. ATTRIBUTE("FieldValues", VariantMap, fieldValues_, Variant::emptyVariantMap, AM_FILE);
  102. MIXED_ACCESSOR_ATTRIBUTE("ComponentFile", GetScriptAttr, SetScriptAttr, ResourceRef, ResourceRef(JSComponentFile::GetTypeStatic()), AM_DEFAULT);
  103. }
  104. void JSComponent::OnSetEnabled()
  105. {
  106. UpdateEventSubscription();
  107. }
  108. void JSComponent::SetUpdateEventMask(unsigned char mask)
  109. {
  110. if (updateEventMask_ != mask)
  111. {
  112. updateEventMask_ = mask;
  113. UpdateEventSubscription();
  114. }
  115. }
  116. void JSComponent::UpdateReferences(bool remove)
  117. {
  118. duk_context* ctx = vm_->GetJSContext();
  119. int top = duk_get_top(ctx);
  120. duk_push_global_stash(ctx);
  121. duk_get_prop_index(ctx, -1, JS_GLOBALSTASH_INDEX_NODE_REGISTRY);
  122. // can't use instance as key, as this coerces to [Object] for
  123. // string property, pointer will be string representation of
  124. // address, so, unique key
  125. if (node_)
  126. {
  127. duk_push_pointer(ctx, (void*) node_);
  128. if (remove)
  129. duk_push_undefined(ctx);
  130. else
  131. js_push_class_object_instance(ctx, node_);
  132. duk_put_prop(ctx, -3);
  133. }
  134. duk_push_pointer(ctx, (void*) this);
  135. if (remove)
  136. duk_push_undefined(ctx);
  137. else
  138. js_push_class_object_instance(ctx, this);
  139. duk_put_prop(ctx, -3);
  140. duk_pop_2(ctx);
  141. assert(duk_get_top(ctx) == top);
  142. }
  143. void JSComponent::ApplyAttributes()
  144. {
  145. if (!started_)
  146. InitInstance();
  147. }
  148. void JSComponent::InitInstance(bool hasArgs, int argIdx)
  149. {
  150. if (context_->GetEditorContext() || componentFile_.Null())
  151. return;
  152. duk_context* ctx = vm_->GetJSContext();
  153. duk_idx_t top = duk_get_top(ctx);
  154. // store, so pop doesn't clear
  155. UpdateReferences();
  156. // apply fields
  157. const HashMap<String, VariantType>& fields = componentFile_->GetFields();
  158. if (fields.Size())
  159. {
  160. // push self
  161. js_push_class_object_instance(ctx, this, "JSComponent");
  162. HashMap<String, VariantType>::ConstIterator itr = fields.Begin();
  163. while (itr != fields.End())
  164. {
  165. if (fieldValues_.Contains(itr->first_))
  166. {
  167. Variant& v = fieldValues_[itr->first_];
  168. if (v.GetType() == itr->second_)
  169. {
  170. js_push_variant(ctx, v);
  171. duk_put_prop_string(ctx, -2, itr->first_.CString());
  172. }
  173. }
  174. else
  175. {
  176. Variant v;
  177. componentFile_->GetDefaultFieldValue(itr->first_, v);
  178. js_push_variant(ctx, v);
  179. duk_put_prop_string(ctx, -2, itr->first_.CString());
  180. }
  181. itr++;
  182. }
  183. // pop self
  184. duk_pop(ctx);
  185. }
  186. // apply args if any
  187. if (hasArgs)
  188. {
  189. // push self
  190. js_push_class_object_instance(ctx, this, "JSComponent");
  191. duk_enum(ctx, argIdx, DUK_ENUM_OWN_PROPERTIES_ONLY);
  192. while (duk_next(ctx, -1, 1)) {
  193. duk_put_prop(ctx, -4);
  194. }
  195. // pop self and enum object
  196. duk_pop_2(ctx);
  197. }
  198. if (!componentFile_->GetScriptClass())
  199. {
  200. componentFile_->PushModule();
  201. duk_get_prop_string(ctx, -1, "component");
  202. if (!duk_is_function(ctx, -1))
  203. {
  204. duk_set_top(ctx, top);
  205. return;
  206. }
  207. // call with self
  208. js_push_class_object_instance(ctx, this, "JSComponent");
  209. if (duk_pcall(ctx, 1) != 0)
  210. {
  211. vm_->SendJSErrorEvent();
  212. duk_set_top(ctx, top);
  213. return;
  214. }
  215. }
  216. duk_set_top(ctx, top);
  217. if (!started_)
  218. {
  219. started_ = true;
  220. Start();
  221. }
  222. }
  223. void JSComponent::CallScriptMethod(const String& name, bool passValue, float value)
  224. {
  225. void* heapptr = JSGetHeapPtr();
  226. if (!heapptr)
  227. return;
  228. duk_context* ctx = vm_->GetJSContext();
  229. duk_idx_t top = duk_get_top(ctx);
  230. duk_push_heapptr(ctx, heapptr);
  231. duk_get_prop_string(ctx, -1, name.CString());
  232. if (!duk_is_function(ctx, -1))
  233. {
  234. duk_set_top(ctx, top);
  235. return;
  236. }
  237. // push this
  238. if (scriptClassInstance_)
  239. duk_push_heapptr(ctx, heapptr);
  240. if (passValue)
  241. duk_push_number(ctx, value);
  242. int status = scriptClassInstance_ ? duk_pcall_method(ctx, passValue ? 1 : 0) : duk_pcall(ctx, passValue ? 1 : 0);
  243. if (status != 0)
  244. {
  245. vm_->SendJSErrorEvent();
  246. duk_set_top(ctx, top);
  247. return;
  248. }
  249. duk_set_top(ctx, top);
  250. }
  251. void JSComponent::Start()
  252. {
  253. static String name = "start";
  254. CallScriptMethod(name);
  255. }
  256. void JSComponent::DelayedStart()
  257. {
  258. static String name = "delayedStart";
  259. CallScriptMethod(name);
  260. }
  261. void JSComponent::Update(float timeStep)
  262. {
  263. static String name = "update";
  264. CallScriptMethod(name, true, timeStep);
  265. }
  266. void JSComponent::PostUpdate(float timeStep)
  267. {
  268. static String name = "postUpdate";
  269. CallScriptMethod(name, true, timeStep);
  270. }
  271. void JSComponent::FixedUpdate(float timeStep)
  272. {
  273. static String name = "fixedUpdate";
  274. CallScriptMethod(name, true, timeStep);
  275. }
  276. void JSComponent::FixedPostUpdate(float timeStep)
  277. {
  278. static String name = "fixedPostUpdate";
  279. CallScriptMethod(name, true, timeStep);
  280. }
  281. void JSComponent::OnNodeSet(Node* node)
  282. {
  283. if (node)
  284. {
  285. // We have been attached to a node. Set initial update event subscription state
  286. UpdateEventSubscription();
  287. }
  288. else
  289. {
  290. // We are being detached from a node: execute user-defined stop function and prepare for destruction
  291. UpdateReferences(true);
  292. Stop();
  293. }
  294. }
  295. void JSComponent::UpdateEventSubscription()
  296. {
  297. // If scene node is not assigned yet, no need to update subscription
  298. if (!node_)
  299. return;
  300. Scene* scene = GetScene();
  301. if (!scene)
  302. {
  303. LOGWARNING("Node is detached from scene, can not subscribe to update events");
  304. return;
  305. }
  306. bool enabled = IsEnabledEffective();
  307. bool needUpdate = enabled && ((updateEventMask_ & USE_UPDATE) || !delayedStartCalled_);
  308. if (needUpdate && !(currentEventMask_ & USE_UPDATE))
  309. {
  310. SubscribeToEvent(scene, E_SCENEUPDATE, HANDLER(JSComponent, HandleSceneUpdate));
  311. currentEventMask_ |= USE_UPDATE;
  312. }
  313. else if (!needUpdate && (currentEventMask_ & USE_UPDATE))
  314. {
  315. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  316. currentEventMask_ &= ~USE_UPDATE;
  317. }
  318. bool needPostUpdate = enabled && (updateEventMask_ & USE_POSTUPDATE);
  319. if (needPostUpdate && !(currentEventMask_ & USE_POSTUPDATE))
  320. {
  321. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(JSComponent, HandleScenePostUpdate));
  322. currentEventMask_ |= USE_POSTUPDATE;
  323. }
  324. else if (!needUpdate && (currentEventMask_ & USE_POSTUPDATE))
  325. {
  326. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  327. currentEventMask_ &= ~USE_POSTUPDATE;
  328. }
  329. #ifdef ATOMIC_PHYSICS
  330. PhysicsWorld* world = scene->GetComponent<PhysicsWorld>();
  331. if (!world)
  332. return;
  333. bool needFixedUpdate = enabled && (updateEventMask_ & USE_FIXEDUPDATE);
  334. if (needFixedUpdate && !(currentEventMask_ & USE_FIXEDUPDATE))
  335. {
  336. SubscribeToEvent(world, E_PHYSICSPRESTEP, HANDLER(JSComponent, HandlePhysicsPreStep));
  337. currentEventMask_ |= USE_FIXEDUPDATE;
  338. }
  339. else if (!needFixedUpdate && (currentEventMask_ & USE_FIXEDUPDATE))
  340. {
  341. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  342. currentEventMask_ &= ~USE_FIXEDUPDATE;
  343. }
  344. bool needFixedPostUpdate = enabled && (updateEventMask_ & USE_FIXEDPOSTUPDATE);
  345. if (needFixedPostUpdate && !(currentEventMask_ & USE_FIXEDPOSTUPDATE))
  346. {
  347. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, HANDLER(JSComponent, HandlePhysicsPostStep));
  348. currentEventMask_ |= USE_FIXEDPOSTUPDATE;
  349. }
  350. else if (!needFixedPostUpdate && (currentEventMask_ & USE_FIXEDPOSTUPDATE))
  351. {
  352. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  353. currentEventMask_ &= ~USE_FIXEDPOSTUPDATE;
  354. }
  355. #endif
  356. }
  357. void JSComponent::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  358. {
  359. using namespace SceneUpdate;
  360. assert(!destroyed_);
  361. // Execute user-defined delayed start function before first update
  362. if (!delayedStartCalled_)
  363. {
  364. DelayedStart();
  365. delayedStartCalled_ = true;
  366. // If did not need actual update events, unsubscribe now
  367. if (!(updateEventMask_ & USE_UPDATE))
  368. {
  369. UnsubscribeFromEvent(GetScene(), E_SCENEUPDATE);
  370. currentEventMask_ &= ~USE_UPDATE;
  371. return;
  372. }
  373. }
  374. // Then execute user-defined update function
  375. Update(eventData[P_TIMESTEP].GetFloat());
  376. }
  377. void JSComponent::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  378. {
  379. using namespace ScenePostUpdate;
  380. // Execute user-defined post-update function
  381. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  382. }
  383. #ifdef ATOMIC_PHYSICS
  384. void JSComponent::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  385. {
  386. using namespace PhysicsPreStep;
  387. // Execute user-defined fixed update function
  388. FixedUpdate(eventData[P_TIMESTEP].GetFloat());
  389. }
  390. void JSComponent::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  391. {
  392. using namespace PhysicsPostStep;
  393. // Execute user-defined fixed post-update function
  394. FixedPostUpdate(eventData[P_TIMESTEP].GetFloat());
  395. }
  396. #endif
  397. bool JSComponent::Load(Deserializer& source, bool setInstanceDefault)
  398. {
  399. loading_ = true;
  400. bool success = Component::Load(source, setInstanceDefault);
  401. loading_ = false;
  402. return success;
  403. }
  404. bool JSComponent::LoadXML(const XMLElement& source, bool setInstanceDefault)
  405. {
  406. loading_ = true;
  407. bool success = Component::LoadXML(source, setInstanceDefault);
  408. loading_ = false;
  409. return success;
  410. }
  411. void JSComponent::SetComponentFile(JSComponentFile* cfile, bool loading)
  412. {
  413. componentFile_ = cfile;
  414. }
  415. ResourceRef JSComponent::GetScriptAttr() const
  416. {
  417. return GetResourceRef(componentFile_, JSComponentFile::GetTypeStatic());
  418. }
  419. void JSComponent::SetScriptAttr(const ResourceRef& value)
  420. {
  421. ResourceCache* cache = GetSubsystem<ResourceCache>();
  422. SetComponentFile(cache->GetResource<JSComponentFile>(value.name_), loading_);
  423. }
  424. }