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