JSComponent.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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. duk_get_prop_string(ctx, -1, "component");
  223. if (!duk_is_function(ctx, -1))
  224. {
  225. duk_set_top(ctx, top);
  226. return;
  227. }
  228. // call with self
  229. js_push_class_object_instance(ctx, this, "JSComponent");
  230. if (duk_pcall(ctx, 1) != 0)
  231. {
  232. vm_->SendJSErrorEvent();
  233. duk_set_top(ctx, top);
  234. return;
  235. }
  236. }
  237. duk_set_top(ctx, top);
  238. instanceInitialized_ = true;
  239. }
  240. void JSComponent::CallScriptMethod(const String& name, bool passValue, float value)
  241. {
  242. if (destroyed_ || !node_ || !node_->GetScene())
  243. return;
  244. void* heapptr = JSGetHeapPtr();
  245. if (!heapptr)
  246. return;
  247. duk_context* ctx = vm_->GetJSContext();
  248. duk_idx_t top = duk_get_top(ctx);
  249. duk_push_heapptr(ctx, heapptr);
  250. duk_get_prop_string(ctx, -1, name.CString());
  251. if (!duk_is_function(ctx, -1))
  252. {
  253. duk_set_top(ctx, top);
  254. return;
  255. }
  256. // push this
  257. if (scriptClassInstance_)
  258. duk_push_heapptr(ctx, heapptr);
  259. if (passValue)
  260. duk_push_number(ctx, value);
  261. int status = scriptClassInstance_ ? duk_pcall_method(ctx, passValue ? 1 : 0) : duk_pcall(ctx, passValue ? 1 : 0);
  262. if (status != 0)
  263. {
  264. vm_->SendJSErrorEvent();
  265. duk_set_top(ctx, top);
  266. return;
  267. }
  268. duk_set_top(ctx, top);
  269. }
  270. void JSComponent::Start()
  271. {
  272. static String name = "start";
  273. CallScriptMethod(name);
  274. }
  275. void JSComponent::DelayedStart()
  276. {
  277. static String name = "delayedStart";
  278. CallScriptMethod(name);
  279. }
  280. void JSComponent::Update(float timeStep)
  281. {
  282. if (!instanceInitialized_)
  283. InitInstance();
  284. if (!started_)
  285. {
  286. started_ = true;
  287. Start();
  288. }
  289. static String name = "update";
  290. CallScriptMethod(name, true, timeStep);
  291. }
  292. void JSComponent::PostUpdate(float timeStep)
  293. {
  294. static String name = "postUpdate";
  295. CallScriptMethod(name, true, timeStep);
  296. }
  297. void JSComponent::FixedUpdate(float timeStep)
  298. {
  299. static String name = "fixedUpdate";
  300. CallScriptMethod(name, true, timeStep);
  301. }
  302. void JSComponent::FixedPostUpdate(float timeStep)
  303. {
  304. static String name = "fixedPostUpdate";
  305. CallScriptMethod(name, true, timeStep);
  306. }
  307. void JSComponent::OnNodeSet(Node* node)
  308. {
  309. if (node)
  310. {
  311. UpdateReferences();
  312. }
  313. else
  314. {
  315. // We are being detached from a node: execute user-defined stop function and prepare for destruction
  316. UpdateReferences(true);
  317. Stop();
  318. }
  319. }
  320. void JSComponent::OnSceneSet(Scene* scene)
  321. {
  322. if (scene)
  323. UpdateEventSubscription();
  324. else
  325. {
  326. UnsubscribeFromEvent(E_SCENEUPDATE);
  327. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  328. #ifdef ATOMIC_PHYSICS
  329. UnsubscribeFromEvent(E_PHYSICSPRESTEP);
  330. UnsubscribeFromEvent(E_PHYSICSPOSTSTEP);
  331. #endif
  332. currentEventMask_ = 0;
  333. }
  334. }
  335. void JSComponent::UpdateEventSubscription()
  336. {
  337. Scene* scene = GetScene();
  338. if (!scene)
  339. return;
  340. bool enabled = IsEnabledEffective();
  341. bool needUpdate = enabled && ((updateEventMask_ & USE_UPDATE) || !delayedStartCalled_);
  342. if (needUpdate && !(currentEventMask_ & USE_UPDATE))
  343. {
  344. SubscribeToEvent(scene, E_SCENEUPDATE, HANDLER(JSComponent, HandleSceneUpdate));
  345. currentEventMask_ |= USE_UPDATE;
  346. }
  347. else if (!needUpdate && (currentEventMask_ & USE_UPDATE))
  348. {
  349. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  350. currentEventMask_ &= ~USE_UPDATE;
  351. }
  352. bool needPostUpdate = enabled && (updateEventMask_ & USE_POSTUPDATE);
  353. if (needPostUpdate && !(currentEventMask_ & USE_POSTUPDATE))
  354. {
  355. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(JSComponent, HandleScenePostUpdate));
  356. currentEventMask_ |= USE_POSTUPDATE;
  357. }
  358. else if (!needUpdate && (currentEventMask_ & USE_POSTUPDATE))
  359. {
  360. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  361. currentEventMask_ &= ~USE_POSTUPDATE;
  362. }
  363. #ifdef ATOMIC_PHYSICS
  364. PhysicsWorld* world = scene->GetComponent<PhysicsWorld>();
  365. if (!world)
  366. return;
  367. bool needFixedUpdate = enabled && (updateEventMask_ & USE_FIXEDUPDATE);
  368. if (needFixedUpdate && !(currentEventMask_ & USE_FIXEDUPDATE))
  369. {
  370. SubscribeToEvent(world, E_PHYSICSPRESTEP, HANDLER(JSComponent, HandlePhysicsPreStep));
  371. currentEventMask_ |= USE_FIXEDUPDATE;
  372. }
  373. else if (!needFixedUpdate && (currentEventMask_ & USE_FIXEDUPDATE))
  374. {
  375. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  376. currentEventMask_ &= ~USE_FIXEDUPDATE;
  377. }
  378. bool needFixedPostUpdate = enabled && (updateEventMask_ & USE_FIXEDPOSTUPDATE);
  379. if (needFixedPostUpdate && !(currentEventMask_ & USE_FIXEDPOSTUPDATE))
  380. {
  381. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, HANDLER(JSComponent, HandlePhysicsPostStep));
  382. currentEventMask_ |= USE_FIXEDPOSTUPDATE;
  383. }
  384. else if (!needFixedPostUpdate && (currentEventMask_ & USE_FIXEDPOSTUPDATE))
  385. {
  386. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  387. currentEventMask_ &= ~USE_FIXEDPOSTUPDATE;
  388. }
  389. #endif
  390. }
  391. void JSComponent::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  392. {
  393. using namespace SceneUpdate;
  394. assert(!destroyed_);
  395. // Execute user-defined delayed start function before first update
  396. if (!delayedStartCalled_)
  397. {
  398. DelayedStart();
  399. delayedStartCalled_ = true;
  400. // If did not need actual update events, unsubscribe now
  401. if (!(updateEventMask_ & USE_UPDATE))
  402. {
  403. UnsubscribeFromEvent(GetScene(), E_SCENEUPDATE);
  404. currentEventMask_ &= ~USE_UPDATE;
  405. return;
  406. }
  407. }
  408. // Then execute user-defined update function
  409. Update(eventData[P_TIMESTEP].GetFloat());
  410. }
  411. void JSComponent::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  412. {
  413. using namespace ScenePostUpdate;
  414. // Execute user-defined post-update function
  415. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  416. }
  417. #ifdef ATOMIC_PHYSICS
  418. void JSComponent::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  419. {
  420. using namespace PhysicsPreStep;
  421. // Execute user-defined fixed update function
  422. FixedUpdate(eventData[P_TIMESTEP].GetFloat());
  423. }
  424. void JSComponent::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  425. {
  426. using namespace PhysicsPostStep;
  427. // Execute user-defined fixed post-update function
  428. FixedPostUpdate(eventData[P_TIMESTEP].GetFloat());
  429. }
  430. #endif
  431. bool JSComponent::Load(Deserializer& source, bool setInstanceDefault)
  432. {
  433. loading_ = true;
  434. bool success = Component::Load(source, setInstanceDefault);
  435. loading_ = false;
  436. return success;
  437. }
  438. bool JSComponent::LoadXML(const XMLElement& source, bool setInstanceDefault)
  439. {
  440. loading_ = true;
  441. bool success = Component::LoadXML(source, setInstanceDefault);
  442. loading_ = false;
  443. return success;
  444. }
  445. bool JSComponent::MatchScriptName(const String& path)
  446. {
  447. if (componentFile_.Null())
  448. return false;
  449. String _path = path;
  450. _path.Replace(".js", "", false);
  451. const String& name = componentFile_->GetName();
  452. if (_path == name)
  453. return true;
  454. String pathName, fileName, ext;
  455. SplitPath(name, pathName, fileName, ext);
  456. if (fileName == _path)
  457. return true;
  458. return false;
  459. }
  460. ResourceRef JSComponent::GetComponentFileAttr() const
  461. {
  462. return GetResourceRef(componentFile_, JSComponentFile::GetTypeStatic());
  463. }
  464. void JSComponent::SetComponentFileAttr(const ResourceRef& value)
  465. {
  466. ResourceCache* cache = GetSubsystem<ResourceCache>();
  467. SetComponentFile(cache->GetResource<JSComponentFile>(value.name_));
  468. }
  469. }