JSComponent.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/IO/Log.h>
  24. #include <Atomic/IO/FileSystem.h>
  25. #include <Atomic/Core/Context.h>
  26. #include <Atomic/Resource/ResourceCache.h>
  27. #ifdef ATOMIC_PHYSICS
  28. #include <Atomic/Physics/PhysicsEvents.h>
  29. #include <Atomic/Physics/PhysicsWorld.h>
  30. #endif
  31. #include <Atomic/Scene/Scene.h>
  32. #include <Atomic/Scene/SceneEvents.h>
  33. #include "JSVM.h"
  34. #include "JSComponentFile.h"
  35. #include "JSComponent.h"
  36. namespace Atomic
  37. {
  38. extern const char* LOGIC_CATEGORY;
  39. class JSComponentFactory : public ObjectFactory
  40. {
  41. ATOMIC_REFCOUNTED(JSComponentFactory)
  42. public:
  43. /// Construct.
  44. JSComponentFactory(Context* context) :
  45. ObjectFactory(context)
  46. {
  47. typeInfo_ = JSComponent::GetTypeInfoStatic();
  48. }
  49. /// Create an object of the specific type.
  50. SharedPtr<Object> CreateObject(const XMLElement& source = XMLElement::EMPTY)
  51. {
  52. // if in editor, just create the JSComponent
  53. if (context_->GetEditorContext())
  54. {
  55. return SharedPtr<Object>(new JSComponent(context_));
  56. }
  57. // At runtime, a XML JSComponent may refer to a "scriptClass"
  58. // component which is new'd in JS and creates the component itself
  59. // we peek ahead here to see if we have a JSComponentFile and if it is a script class
  60. String componentRef;
  61. if (source != XMLElement::EMPTY)
  62. {
  63. XMLElement attrElem = source.GetChild("attribute");
  64. while (attrElem)
  65. {
  66. if (attrElem.GetAttribute("name") == "ComponentFile")
  67. {
  68. componentRef = attrElem.GetAttribute("value");
  69. break;
  70. }
  71. attrElem = attrElem.GetNext("attribute");
  72. }
  73. }
  74. SharedPtr<Object> ptr;
  75. if (componentRef.Length())
  76. {
  77. Vector<String> split = componentRef.Split(';');
  78. if (split.Size() == 2)
  79. {
  80. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  81. JSComponentFile* componentFile = cache->GetResource<JSComponentFile>(split[1]);
  82. if (componentFile)
  83. ptr = componentFile->CreateJSComponent();
  84. else
  85. {
  86. ATOMIC_LOGERRORF("Unable to load component file %s", split[1].CString());
  87. }
  88. }
  89. }
  90. if (ptr.Null())
  91. {
  92. ptr = new JSComponent(context_);
  93. }
  94. return ptr;
  95. }
  96. };
  97. JSComponent::JSComponent(Context* context) :
  98. ScriptComponent(context),
  99. updateEventMask_(USE_UPDATE | USE_POSTUPDATE | USE_FIXEDUPDATE | USE_FIXEDPOSTUPDATE),
  100. currentEventMask_(0),
  101. instanceInitialized_(false),
  102. started_(false),
  103. destroyed_(false),
  104. scriptClassInstance_(false),
  105. delayedStartCalled_(false),
  106. loading_(false)
  107. {
  108. vm_ = JSVM::GetJSVM(NULL);
  109. }
  110. JSComponent::~JSComponent()
  111. {
  112. }
  113. void JSComponent::RegisterObject(Context* context)
  114. {
  115. context->RegisterFactory( new JSComponentFactory(context), LOGIC_CATEGORY);
  116. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("ComponentFile", GetComponentFileAttr, SetComponentFileAttr, ResourceRef, ResourceRef(JSComponentFile::GetTypeStatic()), AM_DEFAULT);
  117. ATOMIC_COPY_BASE_ATTRIBUTES(ScriptComponent);
  118. }
  119. void JSComponent::OnSetEnabled()
  120. {
  121. UpdateEventSubscription();
  122. }
  123. void JSComponent::SetUpdateEventMask(unsigned char mask)
  124. {
  125. if (updateEventMask_ != mask)
  126. {
  127. updateEventMask_ = mask;
  128. UpdateEventSubscription();
  129. }
  130. }
  131. void JSComponent::UpdateReferences(bool remove)
  132. {
  133. if (context_->GetEditorContext())
  134. return;
  135. duk_context* ctx = vm_->GetJSContext();
  136. int top = duk_get_top(ctx);
  137. duk_push_global_stash(ctx);
  138. duk_get_prop_index(ctx, -1, JS_GLOBALSTASH_INDEX_NODE_REGISTRY);
  139. // can't use instance as key, as this coerces to [Object] for
  140. // string property, pointer will be string representation of
  141. // address, so, unique key
  142. if (node_)
  143. {
  144. duk_push_pointer(ctx, (void*) node_);
  145. if (remove)
  146. duk_push_undefined(ctx);
  147. else
  148. js_push_class_object_instance(ctx, node_);
  149. duk_put_prop(ctx, -3);
  150. }
  151. duk_push_pointer(ctx, (void*) this);
  152. if (remove)
  153. duk_push_undefined(ctx);
  154. else
  155. js_push_class_object_instance(ctx, this);
  156. duk_put_prop(ctx, -3);
  157. duk_pop_2(ctx);
  158. assert(duk_get_top(ctx) == top);
  159. }
  160. void JSComponent::ApplyAttributes()
  161. {
  162. }
  163. void JSComponent::InitInstance(bool hasArgs, int argIdx)
  164. {
  165. if (context_->GetEditorContext() || componentFile_.Null())
  166. return;
  167. duk_context* ctx = vm_->GetJSContext();
  168. duk_idx_t top = duk_get_top(ctx);
  169. // store, so pop doesn't clear
  170. UpdateReferences();
  171. // apply fields
  172. const FieldMap& fields = componentFile_->GetFields();
  173. if (fields.Size())
  174. {
  175. // push self
  176. js_push_class_object_instance(ctx, this, "JSComponent");
  177. FieldMap::ConstIterator itr = fields.Begin();
  178. while (itr != fields.End())
  179. {
  180. if (fieldValues_.Contains(itr->first_))
  181. {
  182. Variant& v = fieldValues_[itr->first_];
  183. if (v.GetType() == itr->second_)
  184. {
  185. js_push_variant(ctx, v);
  186. duk_put_prop_string(ctx, -2, itr->first_.CString());
  187. }
  188. }
  189. else
  190. {
  191. Variant v;
  192. componentFile_->GetDefaultFieldValue(itr->first_, v);
  193. js_push_variant(ctx, v);
  194. duk_put_prop_string(ctx, -2, itr->first_.CString());
  195. }
  196. itr++;
  197. }
  198. // pop self
  199. duk_pop(ctx);
  200. }
  201. // apply args if any
  202. if (hasArgs)
  203. {
  204. // push self
  205. js_push_class_object_instance(ctx, this, "JSComponent");
  206. duk_enum(ctx, argIdx, DUK_ENUM_OWN_PROPERTIES_ONLY);
  207. while (duk_next(ctx, -1, 1)) {
  208. duk_put_prop(ctx, -4);
  209. }
  210. // pop self and enum object
  211. duk_pop_2(ctx);
  212. }
  213. if (!componentFile_->GetScriptClass())
  214. {
  215. componentFile_->PushModule();
  216. if (!duk_is_object(ctx, -1))
  217. {
  218. duk_set_top(ctx, top);
  219. return;
  220. }
  221. // Check for "default" constructor which is used by TypeScript and ES2015
  222. duk_get_prop_string(ctx, -1, "default");
  223. if (!duk_is_function(ctx, -1))
  224. {
  225. duk_pop(ctx);
  226. // If "default" doesn't exist, look for component
  227. duk_get_prop_string(ctx, -1, "component");
  228. if (!duk_is_function(ctx, -1))
  229. {
  230. duk_set_top(ctx, top);
  231. return;
  232. }
  233. }
  234. // call with self
  235. js_push_class_object_instance(ctx, this, "JSComponent");
  236. if (duk_pcall(ctx, 1) != 0)
  237. {
  238. vm_->SendJSErrorEvent();
  239. duk_set_top(ctx, top);
  240. return;
  241. }
  242. }
  243. duk_set_top(ctx, top);
  244. instanceInitialized_ = true;
  245. }
  246. void JSComponent::CallScriptMethod(const String& name, bool passValue, float value)
  247. {
  248. if (destroyed_ || !node_ || !node_->GetScene())
  249. return;
  250. void* heapptr = JSGetHeapPtr();
  251. if (!heapptr)
  252. return;
  253. duk_context* ctx = vm_->GetJSContext();
  254. duk_idx_t top = duk_get_top(ctx);
  255. duk_push_heapptr(ctx, heapptr);
  256. duk_get_prop_string(ctx, -1, name.CString());
  257. if (!duk_is_function(ctx, -1))
  258. {
  259. duk_set_top(ctx, top);
  260. return;
  261. }
  262. // push this
  263. if (scriptClassInstance_)
  264. duk_push_heapptr(ctx, heapptr);
  265. if (passValue)
  266. duk_push_number(ctx, value);
  267. int status = scriptClassInstance_ ? duk_pcall_method(ctx, passValue ? 1 : 0) : duk_pcall(ctx, passValue ? 1 : 0);
  268. if (status != 0)
  269. {
  270. vm_->SendJSErrorEvent();
  271. duk_set_top(ctx, top);
  272. return;
  273. }
  274. duk_set_top(ctx, top);
  275. }
  276. void JSComponent::Start()
  277. {
  278. static String name = "start";
  279. CallScriptMethod(name);
  280. }
  281. void JSComponent::DelayedStart()
  282. {
  283. static String name = "delayedStart";
  284. CallScriptMethod(name);
  285. }
  286. void JSComponent::Update(float timeStep)
  287. {
  288. if (!instanceInitialized_)
  289. InitInstance();
  290. if (!started_)
  291. {
  292. started_ = true;
  293. Start();
  294. }
  295. static String name = "update";
  296. CallScriptMethod(name, true, timeStep);
  297. }
  298. void JSComponent::PostUpdate(float timeStep)
  299. {
  300. static String name = "postUpdate";
  301. CallScriptMethod(name, true, timeStep);
  302. }
  303. void JSComponent::FixedUpdate(float timeStep)
  304. {
  305. static String name = "fixedUpdate";
  306. CallScriptMethod(name, true, timeStep);
  307. }
  308. void JSComponent::FixedPostUpdate(float timeStep)
  309. {
  310. static String name = "fixedPostUpdate";
  311. CallScriptMethod(name, true, timeStep);
  312. }
  313. void JSComponent::OnNodeSet(Node* node)
  314. {
  315. if (node)
  316. {
  317. UpdateReferences();
  318. }
  319. else
  320. {
  321. // We are being detached from a node: execute user-defined stop function and prepare for destruction
  322. UpdateReferences(true);
  323. Stop();
  324. }
  325. }
  326. void JSComponent::OnSceneSet(Scene* scene)
  327. {
  328. if (scene)
  329. UpdateEventSubscription();
  330. else
  331. {
  332. UnsubscribeFromEvent(E_SCENEUPDATE);
  333. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  334. #ifdef ATOMIC_PHYSICS
  335. UnsubscribeFromEvent(E_PHYSICSPRESTEP);
  336. UnsubscribeFromEvent(E_PHYSICSPOSTSTEP);
  337. #endif
  338. currentEventMask_ = 0;
  339. }
  340. }
  341. void JSComponent::UpdateEventSubscription()
  342. {
  343. Scene* scene = GetScene();
  344. if (!scene)
  345. return;
  346. bool enabled = IsEnabledEffective();
  347. bool needUpdate = enabled && ((updateEventMask_ & USE_UPDATE) || !delayedStartCalled_);
  348. if (needUpdate && !(currentEventMask_ & USE_UPDATE))
  349. {
  350. SubscribeToEvent(scene, E_SCENEUPDATE, ATOMIC_HANDLER(JSComponent, HandleSceneUpdate));
  351. currentEventMask_ |= USE_UPDATE;
  352. }
  353. else if (!needUpdate && (currentEventMask_ & USE_UPDATE))
  354. {
  355. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  356. currentEventMask_ &= ~USE_UPDATE;
  357. }
  358. bool needPostUpdate = enabled && (updateEventMask_ & USE_POSTUPDATE);
  359. if (needPostUpdate && !(currentEventMask_ & USE_POSTUPDATE))
  360. {
  361. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, ATOMIC_HANDLER(JSComponent, HandleScenePostUpdate));
  362. currentEventMask_ |= USE_POSTUPDATE;
  363. }
  364. else if (!needPostUpdate && (currentEventMask_ & USE_POSTUPDATE))
  365. {
  366. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  367. currentEventMask_ &= ~USE_POSTUPDATE;
  368. }
  369. #ifdef ATOMIC_PHYSICS
  370. PhysicsWorld* world = scene->GetComponent<PhysicsWorld>();
  371. if (!world)
  372. return;
  373. bool needFixedUpdate = enabled && (updateEventMask_ & USE_FIXEDUPDATE);
  374. if (needFixedUpdate && !(currentEventMask_ & USE_FIXEDUPDATE))
  375. {
  376. SubscribeToEvent(world, E_PHYSICSPRESTEP, ATOMIC_HANDLER(JSComponent, HandlePhysicsPreStep));
  377. currentEventMask_ |= USE_FIXEDUPDATE;
  378. }
  379. else if (!needFixedUpdate && (currentEventMask_ & USE_FIXEDUPDATE))
  380. {
  381. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  382. currentEventMask_ &= ~USE_FIXEDUPDATE;
  383. }
  384. bool needFixedPostUpdate = enabled && (updateEventMask_ & USE_FIXEDPOSTUPDATE);
  385. if (needFixedPostUpdate && !(currentEventMask_ & USE_FIXEDPOSTUPDATE))
  386. {
  387. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, ATOMIC_HANDLER(JSComponent, HandlePhysicsPostStep));
  388. currentEventMask_ |= USE_FIXEDPOSTUPDATE;
  389. }
  390. else if (!needFixedPostUpdate && (currentEventMask_ & USE_FIXEDPOSTUPDATE))
  391. {
  392. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  393. currentEventMask_ &= ~USE_FIXEDPOSTUPDATE;
  394. }
  395. #endif
  396. }
  397. void JSComponent::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  398. {
  399. using namespace SceneUpdate;
  400. assert(!destroyed_);
  401. // Execute user-defined delayed start function before first update
  402. if (!delayedStartCalled_)
  403. {
  404. DelayedStart();
  405. delayedStartCalled_ = true;
  406. // If did not need actual update events, unsubscribe now
  407. if (!(updateEventMask_ & USE_UPDATE))
  408. {
  409. UnsubscribeFromEvent(GetScene(), E_SCENEUPDATE);
  410. currentEventMask_ &= ~USE_UPDATE;
  411. return;
  412. }
  413. }
  414. // Then execute user-defined update function
  415. Update(eventData[P_TIMESTEP].GetFloat());
  416. }
  417. void JSComponent::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  418. {
  419. using namespace ScenePostUpdate;
  420. // Execute user-defined post-update function
  421. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  422. }
  423. #ifdef ATOMIC_PHYSICS
  424. void JSComponent::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  425. {
  426. using namespace PhysicsPreStep;
  427. // Execute user-defined fixed update function
  428. FixedUpdate(eventData[P_TIMESTEP].GetFloat());
  429. }
  430. void JSComponent::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  431. {
  432. using namespace PhysicsPostStep;
  433. // Execute user-defined fixed post-update function
  434. FixedPostUpdate(eventData[P_TIMESTEP].GetFloat());
  435. }
  436. #endif
  437. bool JSComponent::Load(Deserializer& source, bool setInstanceDefault)
  438. {
  439. loading_ = true;
  440. bool success = Component::Load(source, setInstanceDefault);
  441. loading_ = false;
  442. return success;
  443. }
  444. bool JSComponent::LoadXML(const XMLElement& source, bool setInstanceDefault)
  445. {
  446. loading_ = true;
  447. bool success = Component::LoadXML(source, setInstanceDefault);
  448. loading_ = false;
  449. return success;
  450. }
  451. bool JSComponent::MatchScriptName(const String& path)
  452. {
  453. if (componentFile_.Null())
  454. return false;
  455. String _path = path;
  456. _path.Replace(".js", "", false);
  457. const String& name = componentFile_->GetName();
  458. if (_path == name)
  459. return true;
  460. String pathName, fileName, ext;
  461. SplitPath(name, pathName, fileName, ext);
  462. if (fileName == _path)
  463. return true;
  464. return false;
  465. }
  466. ResourceRef JSComponent::GetComponentFileAttr() const
  467. {
  468. return GetResourceRef(componentFile_, JSComponentFile::GetTypeStatic());
  469. }
  470. void JSComponent::SetComponentFileAttr(const ResourceRef& value)
  471. {
  472. ResourceCache* cache = GetSubsystem<ResourceCache>();
  473. SetComponentFile(cache->GetResource<JSComponentFile>(value.name_));
  474. }
  475. }