JSComponent.cpp 15 KB

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