Addons.cpp 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487
  1. //
  2. // Copyright (c) 2008-2020 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. #include "../Precompiled.h"
  23. #include "../AngelScript/Addons.h"
  24. #include <cstring>
  25. #include <new>
  26. #include <cstdio>
  27. // Adapted from Angelscript's scriptarray & scriptstdstring add-ons, but with garbage collection disabled
  28. namespace Urho3D
  29. {
  30. using namespace std;
  31. // Set the default memory routines
  32. // Use the angelscript engine's memory routines by default
  33. static asALLOCFUNC_t userAlloc = asAllocMem;
  34. static asFREEFUNC_t userFree = asFreeMem;
  35. // Allows the application to set which memory routines should be used by the array object
  36. void CScriptArray::SetMemoryFunctions(asALLOCFUNC_t allocFunc, asFREEFUNC_t freeFunc)
  37. {
  38. userAlloc = allocFunc;
  39. userFree = freeFunc;
  40. }
  41. static void RegisterScriptArray_Native(asIScriptEngine *engine);
  42. static void RegisterScriptArray_Generic(asIScriptEngine *engine);
  43. /// %Script array buffer.
  44. struct SArrayBuffer
  45. {
  46. asDWORD maxElements;
  47. asDWORD numElements;
  48. asBYTE data[1];
  49. };
  50. /// %Script array cache.
  51. struct SArrayCache
  52. {
  53. asIScriptFunction *cmpFunc;
  54. asIScriptFunction *eqFunc;
  55. int cmpFuncReturnCode; // To allow better error message in case of multiple matches
  56. int eqFuncReturnCode;
  57. };
  58. // We just define a number here that we assume nobody else is using for
  59. // object type user data. The add-ons have reserved the numbers 1000
  60. // through 1999 for this purpose, so we should be fine.
  61. const asPWORD ARRAY_CACHE = 1000;
  62. static void CleanupTypeInfoArrayCache(asITypeInfo *type)
  63. {
  64. auto*cache = reinterpret_cast<SArrayCache*>(type->GetUserData(ARRAY_CACHE));
  65. if (cache)
  66. {
  67. cache->~SArrayCache();
  68. userFree(cache);
  69. }
  70. }
  71. CScriptArray* CScriptArray::Create(asITypeInfo *ot, asUINT length)
  72. {
  73. asIScriptContext *ctx = asGetActiveContext();
  74. // Allocate the memory
  75. void *mem = userAlloc(sizeof(CScriptArray));
  76. if( mem == nullptr )
  77. {
  78. if( ctx )
  79. ctx->SetException("Out of memory");
  80. return nullptr;
  81. }
  82. // Initialize the object
  83. auto*a = new(mem) CScriptArray(length, ot);
  84. // It's possible the constructor raised a script exception, in which case we
  85. // need to free the memory and return null instead, else we get a memory leak.
  86. if( ctx && ctx->GetState() == asEXECUTION_EXCEPTION )
  87. {
  88. a->Release();
  89. return nullptr;
  90. }
  91. return a;
  92. }
  93. CScriptArray* CScriptArray::Create(asITypeInfo *ot, void *initList)
  94. {
  95. asIScriptContext *ctx = asGetActiveContext();
  96. // Allocate the memory
  97. void *mem = userAlloc(sizeof(CScriptArray));
  98. if( mem == nullptr )
  99. {
  100. if( ctx )
  101. ctx->SetException("Out of memory");
  102. return nullptr;
  103. }
  104. // Initialize the object
  105. auto*a = new(mem) CScriptArray(ot, initList);
  106. // It's possible the constructor raised a script exception, in which case we
  107. // need to free the memory and return null instead, else we get a memory leak.
  108. if( ctx && ctx->GetState() == asEXECUTION_EXCEPTION )
  109. {
  110. a->Release();
  111. return nullptr;
  112. }
  113. return a;
  114. }
  115. CScriptArray* CScriptArray::Create(asITypeInfo *ot, asUINT length, void *defVal)
  116. {
  117. asIScriptContext *ctx = asGetActiveContext();
  118. // Allocate the memory
  119. void *mem = userAlloc(sizeof(CScriptArray));
  120. if( mem == nullptr )
  121. {
  122. if( ctx )
  123. ctx->SetException("Out of memory");
  124. return nullptr;
  125. }
  126. // Initialize the object
  127. auto*a = new(mem) CScriptArray(length, defVal, ot);
  128. // It's possible the constructor raised a script exception, in which case we
  129. // need to free the memory and return null instead, else we get a memory leak.
  130. if( ctx && ctx->GetState() == asEXECUTION_EXCEPTION )
  131. {
  132. a->Release();
  133. return nullptr;
  134. }
  135. return a;
  136. }
  137. CScriptArray* CScriptArray::Create(asITypeInfo *ot)
  138. {
  139. return CScriptArray::Create(ot, asUINT(0));
  140. }
  141. // This optional callback is called when the template type is first used by the compiler.
  142. // It allows the application to validate if the template can be instantiated for the requested
  143. // subtype at compile time, instead of at runtime. The output argument dontGarbageCollect
  144. // allow the callback to tell the engine if the template instance type shouldn't be garbage collected,
  145. // i.e. no asOBJ_GC flag.
  146. static bool ScriptArrayTemplateCallback(asITypeInfo *ti, bool &dontGarbageCollect)
  147. {
  148. // Make sure the subtype can be instantiated with a default factory/constructor,
  149. // otherwise we won't be able to instantiate the elements.
  150. int typeId = ti->GetSubTypeId();
  151. if (typeId == asTYPEID_VOID)
  152. return false;
  153. if ((typeId & asTYPEID_MASK_OBJECT) && !(typeId & asTYPEID_OBJHANDLE))
  154. {
  155. asITypeInfo *subtype = ti->GetEngine()->GetTypeInfoById(typeId);
  156. asDWORD flags = subtype->GetFlags();
  157. if ((flags & asOBJ_VALUE) && !(flags & asOBJ_POD))
  158. {
  159. // Verify that there is a default constructor
  160. bool found = false;
  161. for (asUINT n = 0; n < subtype->GetBehaviourCount(); n++)
  162. {
  163. asEBehaviours beh;
  164. asIScriptFunction *func = subtype->GetBehaviourByIndex(n, &beh);
  165. if (beh != asBEHAVE_CONSTRUCT) continue;
  166. if (func->GetParamCount() == 0)
  167. {
  168. // Found the default constructor
  169. found = true;
  170. break;
  171. }
  172. }
  173. if (!found)
  174. {
  175. // There is no default constructor
  176. // TODO: Should format the message to give the name of the subtype for better understanding
  177. ti->GetEngine()->WriteMessage("array", 0, 0, asMSGTYPE_ERROR, "The subtype has no default constructor");
  178. return false;
  179. }
  180. }
  181. else if ((flags & asOBJ_REF))
  182. {
  183. bool found = false;
  184. // If value assignment for ref type has been disabled then the array
  185. // can be created if the type has a default factory function
  186. if (!ti->GetEngine()->GetEngineProperty(asEP_DISALLOW_VALUE_ASSIGN_FOR_REF_TYPE))
  187. {
  188. // Verify that there is a default factory
  189. for (asUINT n = 0; n < subtype->GetFactoryCount(); n++)
  190. {
  191. asIScriptFunction *func = subtype->GetFactoryByIndex(n);
  192. if (func->GetParamCount() == 0)
  193. {
  194. // Found the default factory
  195. found = true;
  196. break;
  197. }
  198. }
  199. }
  200. if (!found)
  201. {
  202. // No default factory
  203. // TODO: Should format the message to give the name of the subtype for better understanding
  204. ti->GetEngine()->WriteMessage("array", 0, 0, asMSGTYPE_ERROR, "The subtype has no default factory");
  205. return false;
  206. }
  207. }
  208. // If the object type is not garbage collected then the array also doesn't need to be
  209. if (!(flags & asOBJ_GC))
  210. dontGarbageCollect = true;
  211. }
  212. else if (!(typeId & asTYPEID_OBJHANDLE))
  213. {
  214. // Arrays with primitives cannot form circular references,
  215. // thus there is no need to garbage collect them
  216. dontGarbageCollect = true;
  217. }
  218. else
  219. {
  220. assert(typeId & asTYPEID_OBJHANDLE);
  221. // It is not necessary to set the array as garbage collected for all handle types.
  222. // If it is possible to determine that the handle cannot refer to an object type
  223. // that can potentially form a circular reference with the array then it is not
  224. // necessary to make the array garbage collected.
  225. asITypeInfo *subtype = ti->GetEngine()->GetTypeInfoById(typeId);
  226. asDWORD flags = subtype->GetFlags();
  227. if (!(flags & asOBJ_GC))
  228. {
  229. if ((flags & asOBJ_SCRIPT_OBJECT))
  230. {
  231. // Even if a script class is by itself not garbage collected, it is possible
  232. // that classes that derive from it may be, so it is not possible to know
  233. // that no circular reference can occur.
  234. if ((flags & asOBJ_NOINHERIT))
  235. {
  236. // A script class declared as final cannot be inherited from, thus
  237. // we can be certain that the object cannot be garbage collected.
  238. dontGarbageCollect = true;
  239. }
  240. }
  241. else
  242. {
  243. // For application registered classes we assume the application knows
  244. // what it is doing and don't mark the array as garbage collected unless
  245. // the type is also garbage collected.
  246. dontGarbageCollect = true;
  247. }
  248. }
  249. }
  250. // The type is ok
  251. return true;
  252. }
  253. CScriptArray &CScriptArray::operator=(const CScriptArray &other)
  254. {
  255. // Only perform the copy if the array types are the same
  256. if( &other != this &&
  257. other.GetArrayObjectType() == GetArrayObjectType() )
  258. {
  259. // Make sure the arrays are of the same size
  260. Resize(other.buffer->numElements);
  261. // Copy the value of each element
  262. CopyBuffer(buffer, other.buffer);
  263. }
  264. return *this;
  265. }
  266. CScriptArray::CScriptArray(asITypeInfo *ot, void *buf)
  267. {
  268. refCount = 1;
  269. gcFlag = false;
  270. objType = ot;
  271. objType->AddRef();
  272. buffer = nullptr;
  273. Precache();
  274. asIScriptEngine *engine = ot->GetEngine();
  275. // Determine element size
  276. if( subTypeId & asTYPEID_MASK_OBJECT )
  277. elementSize = sizeof(asPWORD);
  278. else
  279. elementSize = engine->GetSizeOfPrimitiveType(subTypeId);
  280. // Determine the initial size from the buffer
  281. asUINT length = *(asUINT*)buf;
  282. // Make sure the array size isn't too large for us to handle
  283. if( !CheckMaxSize(length) )
  284. {
  285. // Don't continue with the initialization
  286. return;
  287. }
  288. // Copy the values of the array elements from the buffer
  289. if( (ot->GetSubTypeId() & asTYPEID_MASK_OBJECT) == 0 )
  290. {
  291. CreateBuffer(&buffer, length);
  292. // Copy the values of the primitive type into the internal buffer
  293. memcpy(At(0), (((asUINT*)buf)+1), length * elementSize);
  294. }
  295. else if( ot->GetSubTypeId() & asTYPEID_OBJHANDLE )
  296. {
  297. CreateBuffer(&buffer, length);
  298. // Copy the handles into the internal buffer
  299. memcpy(At(0), (((asUINT*)buf)+1), length * elementSize);
  300. // With object handles it is safe to clear the memory in the received buffer
  301. // instead of increasing the ref count. It will save time both by avoiding the
  302. // call the increase ref, and also relieve the engine from having to release
  303. // its references too
  304. memset((((asUINT*)buf)+1), 0, length * elementSize);
  305. }
  306. else if( ot->GetSubType()->GetFlags() & asOBJ_REF )
  307. {
  308. // Only allocate the buffer, but not the objects
  309. subTypeId |= asTYPEID_OBJHANDLE;
  310. CreateBuffer(&buffer, length);
  311. subTypeId &= ~asTYPEID_OBJHANDLE;
  312. // Copy the handles into the internal buffer
  313. memcpy(buffer->data, (((asUINT*)buf)+1), length * elementSize);
  314. // For ref types we can do the same as for handles, as they are
  315. // implicitly stored as handles.
  316. memset((((asUINT*)buf)+1), 0, length * elementSize);
  317. }
  318. else
  319. {
  320. // TODO: Optimize by calling the copy constructor of the object instead of
  321. // constructing with the default constructor and then assigning the value
  322. // TODO: With C++11 ideally we should be calling the move constructor, instead
  323. // of the copy constructor as the engine will just discard the objects in the
  324. // buffer afterwards.
  325. CreateBuffer(&buffer, length);
  326. // For value types we need to call the opAssign for each individual object
  327. for( asUINT n = 0; n < length; n++ )
  328. {
  329. void *obj = At(n);
  330. auto*srcObj = (asBYTE*)buf;
  331. srcObj += 4 + n*ot->GetSubType()->GetSize();
  332. engine->AssignScriptObject(obj, srcObj, ot->GetSubType());
  333. }
  334. }
  335. // Urho3D: garbage collection disabled
  336. // Notify the GC of the successful creation
  337. /*
  338. if( objType->GetFlags() & asOBJ_GC )
  339. objType->GetEngine()->NotifyGarbageCollectorOfNewObject(this, objType);
  340. */
  341. }
  342. CScriptArray::CScriptArray(asUINT length, asITypeInfo *ot)
  343. {
  344. refCount = 1;
  345. gcFlag = false;
  346. objType = ot;
  347. objType->AddRef();
  348. buffer = nullptr;
  349. Precache();
  350. // Determine element size
  351. if( subTypeId & asTYPEID_MASK_OBJECT )
  352. elementSize = sizeof(asPWORD);
  353. else
  354. elementSize = objType->GetEngine()->GetSizeOfPrimitiveType(subTypeId);
  355. // Make sure the array size isn't too large for us to handle
  356. if( !CheckMaxSize(length) )
  357. {
  358. // Don't continue with the initialization
  359. return;
  360. }
  361. CreateBuffer(&buffer, length);
  362. // Urho3D: garbage collection disabled
  363. /*
  364. // Notify the GC of the successful creation
  365. if( objType->GetFlags() & asOBJ_GC )
  366. objType->GetEngine()->NotifyGarbageCollectorOfNewObject(this, objType);
  367. */
  368. }
  369. CScriptArray::CScriptArray(const CScriptArray &other)
  370. {
  371. refCount = 1;
  372. gcFlag = false;
  373. objType = other.objType;
  374. objType->AddRef();
  375. buffer = nullptr;
  376. Precache();
  377. elementSize = other.elementSize;
  378. // Urho3D: garbage collection disabled
  379. /*
  380. if( objType->GetFlags() & asOBJ_GC )
  381. objType->GetEngine()->NotifyGarbageCollectorOfNewObject(this, objType);
  382. */
  383. CreateBuffer(&buffer, 0);
  384. // Copy the content
  385. *this = other;
  386. }
  387. CScriptArray::CScriptArray(asUINT length, void *defVal, asITypeInfo *ot)
  388. {
  389. refCount = 1;
  390. gcFlag = false;
  391. objType = ot;
  392. objType->AddRef();
  393. buffer = nullptr;
  394. Precache();
  395. // Determine element size
  396. if( subTypeId & asTYPEID_MASK_OBJECT )
  397. elementSize = sizeof(asPWORD);
  398. else
  399. elementSize = objType->GetEngine()->GetSizeOfPrimitiveType(subTypeId);
  400. // Make sure the array size isn't too large for us to handle
  401. if( !CheckMaxSize(length) )
  402. {
  403. // Don't continue with the initialization
  404. return;
  405. }
  406. CreateBuffer(&buffer, length);
  407. // Urho3D: garbage collection disabled
  408. /*
  409. // Notify the GC of the successful creation
  410. if( objType->GetFlags() & asOBJ_GC )
  411. objType->GetEngine()->NotifyGarbageCollectorOfNewObject(this, objType);
  412. */
  413. // Initialize the elements with the default value
  414. for( asUINT n = 0; n < GetSize(); n++ )
  415. SetValue(n, defVal);
  416. }
  417. void CScriptArray::SetValue(asUINT index, void *value)
  418. {
  419. // At() will take care of the out-of-bounds checking, though
  420. // if called from the application then nothing will be done
  421. void *ptr = At(index);
  422. if( ptr == nullptr ) return;
  423. if( (subTypeId & ~asTYPEID_MASK_SEQNBR) && !(subTypeId & asTYPEID_OBJHANDLE) )
  424. objType->GetEngine()->AssignScriptObject(ptr, value, objType->GetSubType());
  425. else if( subTypeId & asTYPEID_OBJHANDLE )
  426. {
  427. void *tmp = *(void**)ptr;
  428. *(void**)ptr = *(void**)value;
  429. objType->GetEngine()->AddRefScriptObject(*(void**)value, objType->GetSubType());
  430. if( tmp )
  431. objType->GetEngine()->ReleaseScriptObject(tmp, objType->GetSubType());
  432. }
  433. else if( subTypeId == asTYPEID_BOOL ||
  434. subTypeId == asTYPEID_INT8 ||
  435. subTypeId == asTYPEID_UINT8 )
  436. *(char*)ptr = *(char*)value;
  437. else if( subTypeId == asTYPEID_INT16 ||
  438. subTypeId == asTYPEID_UINT16 )
  439. *(short*)ptr = *(short*)value;
  440. else if( subTypeId == asTYPEID_INT32 ||
  441. subTypeId == asTYPEID_UINT32 ||
  442. subTypeId == asTYPEID_FLOAT ||
  443. subTypeId > asTYPEID_DOUBLE ) // enums have a type id larger than doubles
  444. *(int*)ptr = *(int*)value;
  445. else if( subTypeId == asTYPEID_INT64 ||
  446. subTypeId == asTYPEID_UINT64 ||
  447. subTypeId == asTYPEID_DOUBLE )
  448. *(double*)ptr = *(double*)value;
  449. }
  450. CScriptArray::~CScriptArray()
  451. {
  452. if( buffer )
  453. {
  454. DeleteBuffer(buffer);
  455. buffer = nullptr;
  456. }
  457. if( objType ) objType->Release();
  458. }
  459. asUINT CScriptArray::GetSize() const
  460. {
  461. return buffer->numElements;
  462. }
  463. bool CScriptArray::IsEmpty() const
  464. {
  465. return buffer->numElements == 0;
  466. }
  467. void CScriptArray::Reserve(asUINT maxElements)
  468. {
  469. if( maxElements <= buffer->maxElements )
  470. return;
  471. if( !CheckMaxSize(maxElements) )
  472. return;
  473. // Allocate memory for the buffer
  474. auto*newBuffer = reinterpret_cast<SArrayBuffer*>(userAlloc(sizeof(SArrayBuffer)-1 + elementSize*maxElements));
  475. if( newBuffer )
  476. {
  477. newBuffer->numElements = buffer->numElements;
  478. newBuffer->maxElements = maxElements;
  479. }
  480. else
  481. {
  482. // Out of memory
  483. asIScriptContext *ctx = asGetActiveContext();
  484. if( ctx )
  485. ctx->SetException("Out of memory");
  486. return;
  487. }
  488. // TODO: memcpy assumes the objects in the array doesn't hold pointers to themselves
  489. // This should really be using the objects copy/move constructor to copy each object
  490. // to the new location. It would most likely be a hit on the performance though.
  491. memcpy(newBuffer->data, buffer->data, buffer->numElements*elementSize);
  492. // Release the old buffer
  493. userFree(buffer);
  494. buffer = newBuffer;
  495. }
  496. void CScriptArray::Resize(asUINT numElements)
  497. {
  498. if( !CheckMaxSize(numElements) )
  499. return;
  500. Resize((int)numElements - (int)buffer->numElements, (asUINT)-1);
  501. }
  502. // Internal
  503. void CScriptArray::Resize(int delta, asUINT at)
  504. {
  505. if( delta < 0 )
  506. {
  507. if( -delta > (int)buffer->numElements )
  508. delta = -(int)buffer->numElements;
  509. if( at > buffer->numElements + delta )
  510. at = buffer->numElements + delta;
  511. }
  512. else if( delta > 0 )
  513. {
  514. // Make sure the array size isn't too large for us to handle
  515. if( delta > 0 && !CheckMaxSize(buffer->numElements + delta) )
  516. return;
  517. if( at > buffer->numElements )
  518. at = buffer->numElements;
  519. }
  520. if( delta == 0 ) return;
  521. if( buffer->maxElements < buffer->numElements + delta )
  522. {
  523. // Allocate memory for the buffer
  524. auto*newBuffer = reinterpret_cast<SArrayBuffer*>(userAlloc(sizeof(SArrayBuffer)-1 + elementSize*(buffer->numElements + delta)));
  525. if( newBuffer )
  526. {
  527. newBuffer->numElements = buffer->numElements + delta;
  528. newBuffer->maxElements = newBuffer->numElements;
  529. }
  530. else
  531. {
  532. // Out of memory
  533. asIScriptContext *ctx = asGetActiveContext();
  534. if( ctx )
  535. ctx->SetException("Out of memory");
  536. return;
  537. }
  538. // TODO: memcpy assumes the objects in the array doesn't hold pointers to themselves
  539. // This should really be using the objects copy/move constructor to copy each object
  540. // to the new location. It would most likely be a hit on the performance though.
  541. memcpy(newBuffer->data, buffer->data, at*elementSize);
  542. if( at < buffer->numElements )
  543. memcpy(newBuffer->data + (at+delta)*elementSize, buffer->data + at*elementSize, (buffer->numElements-at)*elementSize);
  544. // Initialize the new elements with default values
  545. Construct(newBuffer, at, at+delta);
  546. // Release the old buffer
  547. userFree(buffer);
  548. buffer = newBuffer;
  549. }
  550. else if( delta < 0 )
  551. {
  552. Destruct(buffer, at, at-delta);
  553. // TODO: memmove assumes the objects in the array doesn't hold pointers to themselves
  554. // This should really be using the objects copy/move constructor to copy each object
  555. // to the new location. It would most likely be a hit on the performance though.
  556. memmove(buffer->data + at*elementSize, buffer->data + (at-delta)*elementSize, (buffer->numElements - (at-delta))*elementSize);
  557. buffer->numElements += delta;
  558. }
  559. else
  560. {
  561. // TODO: memmove assumes the objects in the array doesn't hold pointers to themselves
  562. // This should really be using the objects copy/move constructor to copy each object
  563. // to the new location. It would most likely be a hit on the performance though.
  564. memmove(buffer->data + (at+delta)*elementSize, buffer->data + at*elementSize, (buffer->numElements - at)*elementSize);
  565. Construct(buffer, at, at+delta);
  566. buffer->numElements += delta;
  567. }
  568. }
  569. // internal
  570. bool CScriptArray::CheckMaxSize(asUINT numElements)
  571. {
  572. // This code makes sure the size of the buffer that is allocated
  573. // for the array doesn't overflow and becomes smaller than requested
  574. asUINT maxSize = 0xFFFFFFFFul - sizeof(SArrayBuffer) + 1;
  575. if( elementSize > 0 )
  576. maxSize /= elementSize;
  577. if( numElements > maxSize )
  578. {
  579. asIScriptContext *ctx = asGetActiveContext();
  580. if( ctx )
  581. ctx->SetException("Too large array size");
  582. return false;
  583. }
  584. // OK
  585. return true;
  586. }
  587. asITypeInfo *CScriptArray::GetArrayObjectType() const
  588. {
  589. return objType;
  590. }
  591. int CScriptArray::GetArrayTypeId() const
  592. {
  593. return objType->GetTypeId();
  594. }
  595. int CScriptArray::GetElementTypeId() const
  596. {
  597. return subTypeId;
  598. }
  599. void CScriptArray::InsertAt(asUINT index, void *value)
  600. {
  601. if( index > buffer->numElements )
  602. {
  603. // If this is called from a script we raise a script exception
  604. asIScriptContext *ctx = asGetActiveContext();
  605. if( ctx )
  606. ctx->SetException("Index out of bounds");
  607. return;
  608. }
  609. // Make room for the new element
  610. Resize(1, index);
  611. // Set the value of the new element
  612. SetValue(index, value);
  613. }
  614. void CScriptArray::InsertLast(void *value)
  615. {
  616. InsertAt(buffer->numElements, value);
  617. }
  618. void CScriptArray::RemoveAt(asUINT index)
  619. {
  620. if( index >= buffer->numElements )
  621. {
  622. // If this is called from a script we raise a script exception
  623. asIScriptContext *ctx = asGetActiveContext();
  624. if( ctx )
  625. ctx->SetException("Index out of bounds");
  626. return;
  627. }
  628. // Remove the element
  629. Resize(-1, index);
  630. }
  631. void CScriptArray::RemoveLast()
  632. {
  633. RemoveAt(buffer->numElements-1);
  634. }
  635. // Return a pointer to the array element. Returns 0 if the index is out of bounds
  636. const void *CScriptArray::At(asUINT index) const
  637. {
  638. if( buffer == nullptr || index >= buffer->numElements )
  639. {
  640. // If this is called from a script we raise a script exception
  641. asIScriptContext *ctx = asGetActiveContext();
  642. if( ctx )
  643. ctx->SetException("Index out of bounds");
  644. return nullptr;
  645. }
  646. if( (subTypeId & asTYPEID_MASK_OBJECT) && !(subTypeId & asTYPEID_OBJHANDLE) )
  647. return *(void**)(buffer->data + elementSize*index);
  648. else
  649. return buffer->data + elementSize*index;
  650. }
  651. void *CScriptArray::At(asUINT index)
  652. {
  653. return const_cast<void*>(const_cast<const CScriptArray *>(this)->At(index));
  654. }
  655. // internal
  656. void CScriptArray::CreateBuffer(SArrayBuffer **buf, asUINT numElements)
  657. {
  658. *buf = reinterpret_cast<SArrayBuffer*>(userAlloc(sizeof(SArrayBuffer)-1+elementSize*numElements));
  659. if( *buf )
  660. {
  661. (*buf)->numElements = numElements;
  662. (*buf)->maxElements = numElements;
  663. Construct(*buf, 0, numElements);
  664. }
  665. else
  666. {
  667. // Oops, out of memory
  668. asIScriptContext *ctx = asGetActiveContext();
  669. if( ctx )
  670. ctx->SetException("Out of memory");
  671. }
  672. }
  673. // internal
  674. void CScriptArray::DeleteBuffer(SArrayBuffer *buf)
  675. {
  676. Destruct(buf, 0, buf->numElements);
  677. // Free the buffer
  678. userFree(buf);
  679. }
  680. // internal
  681. void CScriptArray::Construct(SArrayBuffer *buf, asUINT start, asUINT end)
  682. {
  683. if( (subTypeId & asTYPEID_MASK_OBJECT) && !(subTypeId & asTYPEID_OBJHANDLE) )
  684. {
  685. // Create an object using the default constructor/factory for each element
  686. auto**max = (void**)(buf->data + end * sizeof(void*));
  687. auto**d = (void**)(buf->data + start * sizeof(void*));
  688. asIScriptEngine *engine = objType->GetEngine();
  689. asITypeInfo *subType = objType->GetSubType();
  690. for( ; d < max; d++ )
  691. {
  692. *d = (void*)engine->CreateScriptObject(subType);
  693. if( *d == nullptr )
  694. {
  695. // Set the remaining entries to null so the destructor
  696. // won't attempt to destroy invalid objects later
  697. memset(d, 0, sizeof(void*)*(max-d));
  698. // There is no need to set an exception on the context,
  699. // as CreateScriptObject has already done that
  700. return;
  701. }
  702. }
  703. }
  704. else
  705. {
  706. // Set all elements to zero whether they are handles or primitives
  707. auto*d = (void*)(buf->data + start * elementSize);
  708. memset(d, 0, (end-start)*elementSize);
  709. }
  710. }
  711. // internal
  712. void CScriptArray::Destruct(SArrayBuffer *buf, asUINT start, asUINT end)
  713. {
  714. if( subTypeId & asTYPEID_MASK_OBJECT )
  715. {
  716. asIScriptEngine *engine = objType->GetEngine();
  717. auto**max = (void**)(buf->data + end * sizeof(void*));
  718. auto**d = (void**)(buf->data + start * sizeof(void*));
  719. for( ; d < max; d++ )
  720. {
  721. if( *d )
  722. engine->ReleaseScriptObject(*d, objType->GetSubType());
  723. }
  724. }
  725. }
  726. // internal
  727. bool CScriptArray::Less(const void *a, const void *b, bool asc, asIScriptContext *ctx, SArrayCache *cache)
  728. {
  729. if( !asc )
  730. {
  731. // Swap items
  732. const void *TEMP = a;
  733. a = b;
  734. b = TEMP;
  735. }
  736. if( !(subTypeId & ~asTYPEID_MASK_SEQNBR) )
  737. {
  738. // Simple compare of values
  739. switch( subTypeId )
  740. {
  741. #define COMPARE(T) *((T*)a) < *((T*)b)
  742. case asTYPEID_BOOL: return COMPARE(bool);
  743. case asTYPEID_INT8: return COMPARE(signed char);
  744. case asTYPEID_UINT8: return COMPARE(unsigned char);
  745. case asTYPEID_INT16: return COMPARE(signed short);
  746. case asTYPEID_UINT16: return COMPARE(unsigned short);
  747. case asTYPEID_INT32: return COMPARE(signed int);
  748. case asTYPEID_UINT32: return COMPARE(unsigned int);
  749. case asTYPEID_FLOAT: return COMPARE(float);
  750. case asTYPEID_DOUBLE: return COMPARE(double);
  751. default: return COMPARE(signed int); // All enums fall in this case
  752. #undef COMPARE
  753. }
  754. }
  755. else
  756. {
  757. int r = 0;
  758. if( subTypeId & asTYPEID_OBJHANDLE )
  759. {
  760. // Allow sort to work even if the array contains null handles
  761. if( *(void**)a == nullptr ) return true;
  762. if( *(void**)b == nullptr ) return false;
  763. }
  764. // Execute object opCmp
  765. if( cache && cache->cmpFunc )
  766. {
  767. // TODO: Add proper error handling
  768. r = ctx->Prepare(cache->cmpFunc); assert(r >= 0);
  769. if( subTypeId & asTYPEID_OBJHANDLE )
  770. {
  771. r = ctx->SetObject(*((void**)a)); assert(r >= 0);
  772. r = ctx->SetArgObject(0, *((void**)b)); assert(r >= 0);
  773. }
  774. else
  775. {
  776. r = ctx->SetObject((void*)a); assert(r >= 0);
  777. r = ctx->SetArgObject(0, (void*)b); assert(r >= 0);
  778. }
  779. r = ctx->Execute();
  780. if( r == asEXECUTION_FINISHED )
  781. {
  782. return (int)ctx->GetReturnDWord() < 0;
  783. }
  784. }
  785. }
  786. return false;
  787. }
  788. void CScriptArray::Reverse()
  789. {
  790. asUINT size = GetSize();
  791. if( size >= 2 )
  792. {
  793. asBYTE TEMP[16];
  794. for( asUINT i = 0; i < size / 2; i++ )
  795. {
  796. Copy(TEMP, GetArrayItemPointer(i));
  797. Copy(GetArrayItemPointer(i), GetArrayItemPointer(size - i - 1));
  798. Copy(GetArrayItemPointer(size - i - 1), TEMP);
  799. }
  800. }
  801. }
  802. bool CScriptArray::operator==(const CScriptArray &other) const
  803. {
  804. if( objType != other.objType )
  805. return false;
  806. if( GetSize() != other.GetSize() )
  807. return false;
  808. asIScriptContext *cmpContext = nullptr;
  809. bool isNested = false;
  810. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  811. {
  812. // Try to reuse the active context
  813. cmpContext = asGetActiveContext();
  814. if( cmpContext )
  815. {
  816. if( cmpContext->GetEngine() == objType->GetEngine() && cmpContext->PushState() >= 0 )
  817. isNested = true;
  818. else
  819. cmpContext = nullptr;
  820. }
  821. if( cmpContext == nullptr )
  822. {
  823. // TODO: Ideally this context would be retrieved from a pool, so we don't have to
  824. // create a new one every time. We could keep a context with the array object
  825. // but that would consume a lot of resources as each context is quite heavy.
  826. cmpContext = objType->GetEngine()->CreateContext();
  827. }
  828. }
  829. // Check if all elements are equal
  830. bool isEqual = true;
  831. auto*cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  832. for( asUINT n = 0; n < GetSize(); n++ )
  833. if( !Equals(At(n), other.At(n), cmpContext, cache) )
  834. {
  835. isEqual = false;
  836. break;
  837. }
  838. if( cmpContext )
  839. {
  840. if( isNested )
  841. {
  842. asEContextState state = cmpContext->GetState();
  843. cmpContext->PopState();
  844. if( state == asEXECUTION_ABORTED )
  845. cmpContext->Abort();
  846. }
  847. else
  848. cmpContext->Release();
  849. }
  850. return isEqual;
  851. }
  852. // internal
  853. bool CScriptArray::Equals(const void *a, const void *b, asIScriptContext *ctx, SArrayCache *cache) const
  854. {
  855. if( !(subTypeId & ~asTYPEID_MASK_SEQNBR) )
  856. {
  857. // Simple compare of values
  858. switch( subTypeId )
  859. {
  860. #define COMPARE(T) *((T*)a) == *((T*)b)
  861. case asTYPEID_BOOL: return COMPARE(bool);
  862. case asTYPEID_INT8: return COMPARE(signed char);
  863. case asTYPEID_UINT8: return COMPARE(unsigned char);
  864. case asTYPEID_INT16: return COMPARE(signed short);
  865. case asTYPEID_UINT16: return COMPARE(unsigned short);
  866. case asTYPEID_INT32: return COMPARE(signed int);
  867. case asTYPEID_UINT32: return COMPARE(unsigned int);
  868. case asTYPEID_FLOAT: return COMPARE(float);
  869. case asTYPEID_DOUBLE: return COMPARE(double);
  870. default: return COMPARE(signed int); // All enums fall here
  871. #undef COMPARE
  872. }
  873. }
  874. else
  875. {
  876. int r = 0;
  877. if( subTypeId & asTYPEID_OBJHANDLE )
  878. {
  879. // Allow the find to work even if the array contains null handles
  880. if( *(void**)a == *(void**)b ) return true;
  881. }
  882. // Execute object opEquals if available
  883. if( cache && cache->eqFunc )
  884. {
  885. // TODO: Add proper error handling
  886. r = ctx->Prepare(cache->eqFunc); assert(r >= 0);
  887. if( subTypeId & asTYPEID_OBJHANDLE )
  888. {
  889. r = ctx->SetObject(*((void**)a)); assert(r >= 0);
  890. r = ctx->SetArgObject(0, *((void**)b)); assert(r >= 0);
  891. }
  892. else
  893. {
  894. r = ctx->SetObject((void*)a); assert(r >= 0);
  895. r = ctx->SetArgObject(0, (void*)b); assert(r >= 0);
  896. }
  897. r = ctx->Execute();
  898. if( r == asEXECUTION_FINISHED )
  899. return ctx->GetReturnByte() != 0;
  900. return false;
  901. }
  902. // Execute object opCmp if available
  903. if( cache && cache->cmpFunc )
  904. {
  905. // TODO: Add proper error handling
  906. r = ctx->Prepare(cache->cmpFunc); assert(r >= 0);
  907. if( subTypeId & asTYPEID_OBJHANDLE )
  908. {
  909. r = ctx->SetObject(*((void**)a)); assert(r >= 0);
  910. r = ctx->SetArgObject(0, *((void**)b)); assert(r >= 0);
  911. }
  912. else
  913. {
  914. r = ctx->SetObject((void*)a); assert(r >= 0);
  915. r = ctx->SetArgObject(0, (void*)b); assert(r >= 0);
  916. }
  917. r = ctx->Execute();
  918. if( r == asEXECUTION_FINISHED )
  919. return (int)ctx->GetReturnDWord() == 0;
  920. return false;
  921. }
  922. }
  923. return false;
  924. }
  925. int CScriptArray::FindByRef(void *ref) const
  926. {
  927. return FindByRef(0, ref);
  928. }
  929. int CScriptArray::FindByRef(asUINT startAt, void *ref) const
  930. {
  931. // Find the matching element by its reference
  932. asUINT size = GetSize();
  933. if( subTypeId & asTYPEID_OBJHANDLE )
  934. {
  935. // Dereference the pointer
  936. ref = *(void**)ref;
  937. for( asUINT i = startAt; i < size; i++ )
  938. {
  939. if( *(void**)At(i) == ref )
  940. return i;
  941. }
  942. }
  943. else
  944. {
  945. // Compare the reference directly
  946. for( asUINT i = startAt; i < size; i++ )
  947. {
  948. if( At(i) == ref )
  949. return i;
  950. }
  951. }
  952. return -1;
  953. }
  954. bool CScriptArray::Swap(CScriptArray& other)
  955. {
  956. if (other.GetArrayObjectType() == GetArrayObjectType())
  957. {
  958. Urho3D::Swap(buffer, other.buffer);
  959. return true;
  960. }
  961. return false;
  962. }
  963. int CScriptArray::Find(void *value) const
  964. {
  965. return Find(0, value);
  966. }
  967. int CScriptArray::Find(asUINT startAt, void *value) const
  968. {
  969. // Check if the subtype really supports find()
  970. // TODO: Can't this be done at compile time too by the template callback
  971. SArrayCache *cache = nullptr;
  972. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  973. {
  974. cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  975. if( !cache || (cache->cmpFunc == nullptr && cache->eqFunc == nullptr) )
  976. {
  977. asIScriptContext *ctx = asGetActiveContext();
  978. asITypeInfo* subType = objType->GetEngine()->GetTypeInfoById(subTypeId);
  979. // Throw an exception
  980. if( ctx )
  981. {
  982. char tmp[512];
  983. if( cache && cache->eqFuncReturnCode == asMULTIPLE_FUNCTIONS )
  984. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  985. sprintf_s(tmp, 512, "Type '%s' has multiple matching opEquals or opCmp methods", subType->GetName());
  986. #else
  987. sprintf(tmp, "Type '%s' has multiple matching opEquals or opCmp methods", subType->GetName());
  988. #endif
  989. else
  990. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  991. sprintf_s(tmp, 512, "Type '%s' does not have a matching opEquals or opCmp method", subType->GetName());
  992. #else
  993. sprintf(tmp, "Type '%s' does not have a matching opEquals or opCmp method", subType->GetName());
  994. #endif
  995. ctx->SetException(tmp);
  996. }
  997. return -1;
  998. }
  999. }
  1000. asIScriptContext *cmpContext = nullptr;
  1001. bool isNested = false;
  1002. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  1003. {
  1004. // Try to reuse the active context
  1005. cmpContext = asGetActiveContext();
  1006. if( cmpContext )
  1007. {
  1008. if( cmpContext->GetEngine() == objType->GetEngine() && cmpContext->PushState() >= 0 )
  1009. isNested = true;
  1010. else
  1011. cmpContext = nullptr;
  1012. }
  1013. if( cmpContext == nullptr )
  1014. {
  1015. // TODO: Ideally this context would be retrieved from a pool, so we don't have to
  1016. // create a new one every time. We could keep a context with the array object
  1017. // but that would consume a lot of resources as each context is quite heavy.
  1018. cmpContext = objType->GetEngine()->CreateContext();
  1019. }
  1020. }
  1021. // Find the matching element
  1022. int ret = -1;
  1023. asUINT size = GetSize();
  1024. for( asUINT i = startAt; i < size; i++ )
  1025. {
  1026. // value passed by reference
  1027. if( Equals(At(i), value, cmpContext, cache) )
  1028. {
  1029. ret = (int)i;
  1030. break;
  1031. }
  1032. }
  1033. if( cmpContext )
  1034. {
  1035. if( isNested )
  1036. {
  1037. asEContextState state = cmpContext->GetState();
  1038. cmpContext->PopState();
  1039. if( state == asEXECUTION_ABORTED )
  1040. cmpContext->Abort();
  1041. }
  1042. else
  1043. cmpContext->Release();
  1044. }
  1045. return ret;
  1046. }
  1047. // internal
  1048. // Copy object handle or primitive value
  1049. void CScriptArray::Copy(void *dst, void *src)
  1050. {
  1051. memcpy(dst, src, elementSize);
  1052. }
  1053. // internal
  1054. // Return pointer to array item (object handle or primitive value)
  1055. void *CScriptArray::GetArrayItemPointer(int index)
  1056. {
  1057. return buffer->data + index * elementSize;
  1058. }
  1059. // internal
  1060. // Return pointer to data in buffer (object or primitive)
  1061. void *CScriptArray::GetDataPointer(void *buffer)
  1062. {
  1063. if ((subTypeId & asTYPEID_MASK_OBJECT) && !(subTypeId & asTYPEID_OBJHANDLE) )
  1064. {
  1065. // Real address of object
  1066. return reinterpret_cast<void*>(*(size_t*)buffer);
  1067. }
  1068. else
  1069. {
  1070. // Primitive is just a raw data
  1071. return buffer;
  1072. }
  1073. }
  1074. // Sort ascending
  1075. void CScriptArray::SortAsc()
  1076. {
  1077. Sort(0, GetSize(), true);
  1078. }
  1079. // Sort ascending
  1080. void CScriptArray::SortAsc(asUINT startAt, asUINT count)
  1081. {
  1082. Sort(startAt, count, true);
  1083. }
  1084. // Sort descending
  1085. void CScriptArray::SortDesc()
  1086. {
  1087. Sort(0, GetSize(), false);
  1088. }
  1089. // Sort descending
  1090. void CScriptArray::SortDesc(asUINT startAt, asUINT count)
  1091. {
  1092. Sort(startAt, count, false);
  1093. }
  1094. // internal
  1095. void CScriptArray::Sort(asUINT startAt, asUINT count, bool asc)
  1096. {
  1097. // Subtype isn't primitive and doesn't have opCmp
  1098. auto*cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  1099. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  1100. {
  1101. if( !cache || cache->cmpFunc == nullptr )
  1102. {
  1103. asIScriptContext *ctx = asGetActiveContext();
  1104. asITypeInfo* subType = objType->GetEngine()->GetTypeInfoById(subTypeId);
  1105. // Throw an exception
  1106. if( ctx )
  1107. {
  1108. char tmp[512];
  1109. if( cache && cache->cmpFuncReturnCode == asMULTIPLE_FUNCTIONS )
  1110. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  1111. sprintf_s(tmp, 512, "Type '%s' has multiple matching opCmp methods", subType->GetName());
  1112. #else
  1113. sprintf(tmp, "Type '%s' has multiple matching opCmp methods", subType->GetName());
  1114. #endif
  1115. else
  1116. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  1117. sprintf_s(tmp, 512, "Type '%s' does not have a matching opCmp method", subType->GetName());
  1118. #else
  1119. sprintf(tmp, "Type '%s' does not have a matching opCmp method", subType->GetName());
  1120. #endif
  1121. ctx->SetException(tmp);
  1122. }
  1123. return;
  1124. }
  1125. }
  1126. // No need to sort
  1127. if( count < 2 )
  1128. {
  1129. return;
  1130. }
  1131. int start = startAt;
  1132. int end = startAt + count;
  1133. // Check if we could access invalid item while sorting
  1134. if( start >= (int)buffer->numElements || end > (int)buffer->numElements )
  1135. {
  1136. asIScriptContext *ctx = asGetActiveContext();
  1137. // Throw an exception
  1138. if( ctx )
  1139. {
  1140. ctx->SetException("Index out of bounds");
  1141. }
  1142. return;
  1143. }
  1144. asBYTE tmp[16];
  1145. asIScriptContext *cmpContext = nullptr;
  1146. bool isNested = false;
  1147. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  1148. {
  1149. // Try to reuse the active context
  1150. cmpContext = asGetActiveContext();
  1151. if( cmpContext )
  1152. {
  1153. if( cmpContext->GetEngine() == objType->GetEngine() && cmpContext->PushState() >= 0 )
  1154. isNested = true;
  1155. else
  1156. cmpContext = nullptr;
  1157. }
  1158. if( cmpContext == nullptr )
  1159. {
  1160. // TODO: Ideally this context would be retrieved from a pool, so we don't have to
  1161. // create a new one every time. We could keep a context with the array object
  1162. // but that would consume a lot of resources as each context is quite heavy.
  1163. cmpContext = objType->GetEngine()->CreateContext();
  1164. }
  1165. }
  1166. // Insertion sort
  1167. for( int i = start + 1; i < end; i++ )
  1168. {
  1169. Copy(tmp, GetArrayItemPointer(i));
  1170. int j = i - 1;
  1171. while( j >= start && Less(GetDataPointer(tmp), At(j), asc, cmpContext, cache) )
  1172. {
  1173. Copy(GetArrayItemPointer(j + 1), GetArrayItemPointer(j));
  1174. j--;
  1175. }
  1176. Copy(GetArrayItemPointer(j + 1), tmp);
  1177. }
  1178. if( cmpContext )
  1179. {
  1180. if( isNested )
  1181. {
  1182. asEContextState state = cmpContext->GetState();
  1183. cmpContext->PopState();
  1184. if( state == asEXECUTION_ABORTED )
  1185. cmpContext->Abort();
  1186. }
  1187. else
  1188. cmpContext->Release();
  1189. }
  1190. }
  1191. // internal
  1192. void CScriptArray::CopyBuffer(SArrayBuffer *dst, SArrayBuffer *src)
  1193. {
  1194. asIScriptEngine *engine = objType->GetEngine();
  1195. if( subTypeId & asTYPEID_OBJHANDLE )
  1196. {
  1197. // Copy the references and increase the reference counters
  1198. if( dst->numElements > 0 && src->numElements > 0 )
  1199. {
  1200. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  1201. auto**max = (void**)(dst->data + count * sizeof(void*));
  1202. auto**d = (void**)dst->data;
  1203. auto**s = (void**)src->data;
  1204. for( ; d < max; d++, s++ )
  1205. {
  1206. void *tmp = *d;
  1207. *d = *s;
  1208. if( *d )
  1209. engine->AddRefScriptObject(*d, objType->GetSubType());
  1210. // Release the old ref after incrementing the new to avoid problem incase it is the same ref
  1211. if( tmp )
  1212. engine->ReleaseScriptObject(tmp, objType->GetSubType());
  1213. }
  1214. }
  1215. }
  1216. else
  1217. {
  1218. if( dst->numElements > 0 && src->numElements > 0 )
  1219. {
  1220. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  1221. if( subTypeId & asTYPEID_MASK_OBJECT )
  1222. {
  1223. // Call the assignment operator on all of the objects
  1224. auto**max = (void**)(dst->data + count * sizeof(void*));
  1225. auto**d = (void**)dst->data;
  1226. auto**s = (void**)src->data;
  1227. asITypeInfo *subType = objType->GetSubType();
  1228. for( ; d < max; d++, s++ )
  1229. engine->AssignScriptObject(*d, *s, subType);
  1230. }
  1231. else
  1232. {
  1233. // Primitives are copied byte for byte
  1234. memcpy(dst->data, src->data, count*elementSize);
  1235. }
  1236. }
  1237. }
  1238. }
  1239. // internal
  1240. // Precache some info
  1241. void CScriptArray::Precache()
  1242. {
  1243. subTypeId = objType->GetSubTypeId();
  1244. // Check if it is an array of objects. Only for these do we need to cache anything
  1245. // Type ids for primitives and enums only has the sequence number part
  1246. if( !(subTypeId & ~asTYPEID_MASK_SEQNBR) )
  1247. return;
  1248. // The opCmp and opEquals methods are cached because the searching for the
  1249. // methods is quite time consuming if a lot of array objects are created.
  1250. // First check if a cache already exists for this array type
  1251. auto*cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  1252. if( cache ) return;
  1253. // We need to make sure the cache is created only once, even
  1254. // if multiple threads reach the same point at the same time
  1255. asAcquireExclusiveLock();
  1256. // Now that we got the lock, we need to check again to make sure the
  1257. // cache wasn't created while we were waiting for the lock
  1258. cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  1259. if( cache )
  1260. {
  1261. asReleaseExclusiveLock();
  1262. return;
  1263. }
  1264. // Create the cache
  1265. cache = reinterpret_cast<SArrayCache*>(userAlloc(sizeof(SArrayCache)));
  1266. memset(cache, 0, sizeof(SArrayCache));
  1267. // If the sub type is a handle to const, then the methods must be const too
  1268. bool mustBeConst = (subTypeId & asTYPEID_HANDLETOCONST) ? true : false;
  1269. asITypeInfo *subType = objType->GetEngine()->GetTypeInfoById(subTypeId);
  1270. if( subType )
  1271. {
  1272. for( asUINT i = 0; i < subType->GetMethodCount(); i++ )
  1273. {
  1274. asIScriptFunction *func = subType->GetMethodByIndex(i);
  1275. if( func->GetParamCount() == 1 && (!mustBeConst || func->IsReadOnly()) )
  1276. {
  1277. asDWORD flags = 0;
  1278. int returnTypeId = func->GetReturnTypeId(&flags);
  1279. // The method must not return a reference
  1280. if( flags != asTM_NONE )
  1281. continue;
  1282. // opCmp returns an int and opEquals returns a bool
  1283. bool isCmp = false, isEq = false;
  1284. if( returnTypeId == asTYPEID_INT32 && strcmp(func->GetName(), "opCmp") == 0 )
  1285. isCmp = true;
  1286. if( returnTypeId == asTYPEID_BOOL && strcmp(func->GetName(), "opEquals") == 0 )
  1287. isEq = true;
  1288. if( !isCmp && !isEq )
  1289. continue;
  1290. // The parameter must either be a reference to the subtype or a handle to the subtype
  1291. int paramTypeId;
  1292. func->GetParam(0, &paramTypeId, &flags);
  1293. if( (paramTypeId & ~(asTYPEID_OBJHANDLE|asTYPEID_HANDLETOCONST)) != (subTypeId & ~(asTYPEID_OBJHANDLE|asTYPEID_HANDLETOCONST)) )
  1294. continue;
  1295. if( (flags & asTM_INREF) )
  1296. {
  1297. if( (paramTypeId & asTYPEID_OBJHANDLE) || (mustBeConst && !(flags & asTM_CONST)) )
  1298. continue;
  1299. }
  1300. else if( paramTypeId & asTYPEID_OBJHANDLE )
  1301. {
  1302. if( mustBeConst && !(paramTypeId & asTYPEID_HANDLETOCONST) )
  1303. continue;
  1304. }
  1305. else
  1306. continue;
  1307. if( isCmp )
  1308. {
  1309. if( cache->cmpFunc || cache->cmpFuncReturnCode )
  1310. {
  1311. cache->cmpFunc = nullptr;
  1312. cache->cmpFuncReturnCode = asMULTIPLE_FUNCTIONS;
  1313. }
  1314. else
  1315. cache->cmpFunc = func;
  1316. }
  1317. else if( isEq )
  1318. {
  1319. if( cache->eqFunc || cache->eqFuncReturnCode )
  1320. {
  1321. cache->eqFunc = nullptr;
  1322. cache->eqFuncReturnCode = asMULTIPLE_FUNCTIONS;
  1323. }
  1324. else
  1325. cache->eqFunc = func;
  1326. }
  1327. }
  1328. }
  1329. }
  1330. if( cache->eqFunc == nullptr && cache->eqFuncReturnCode == 0 )
  1331. cache->eqFuncReturnCode = asNO_FUNCTION;
  1332. if( cache->cmpFunc == nullptr && cache->cmpFuncReturnCode == 0 )
  1333. cache->cmpFuncReturnCode = asNO_FUNCTION;
  1334. // Set the user data only at the end so others that retrieve it will know it is complete
  1335. objType->SetUserData(cache, ARRAY_CACHE);
  1336. asReleaseExclusiveLock();
  1337. }
  1338. // GC behaviour
  1339. void CScriptArray::EnumReferences(asIScriptEngine *engine)
  1340. {
  1341. // If the array is holding handles, then we need to notify the GC of them
  1342. if( subTypeId & asTYPEID_MASK_OBJECT )
  1343. {
  1344. auto**d = (void**)buffer->data;
  1345. for( asUINT n = 0; n < buffer->numElements; n++ )
  1346. {
  1347. if( d[n] )
  1348. engine->GCEnumCallback(d[n]);
  1349. }
  1350. }
  1351. }
  1352. // GC behaviour
  1353. void CScriptArray::ReleaseAllHandles(asIScriptEngine *)
  1354. {
  1355. // Resizing to zero will release everything
  1356. Resize(0);
  1357. }
  1358. void CScriptArray::AddRef() const
  1359. {
  1360. // Clear the GC flag then increase the counter
  1361. gcFlag = false;
  1362. asAtomicInc(refCount);
  1363. }
  1364. void CScriptArray::Release() const
  1365. {
  1366. // Clearing the GC flag then descrease the counter
  1367. gcFlag = false;
  1368. if( asAtomicDec(refCount) == 0 )
  1369. {
  1370. // When reaching 0 no more references to this instance
  1371. // exists and the object should be destroyed
  1372. this->~CScriptArray();
  1373. userFree(const_cast<CScriptArray*>(this));
  1374. }
  1375. }
  1376. // GC behaviour
  1377. int CScriptArray::GetRefCount()
  1378. {
  1379. return refCount;
  1380. }
  1381. // GC behaviour
  1382. void CScriptArray::SetFlag()
  1383. {
  1384. gcFlag = true;
  1385. }
  1386. // GC behaviour
  1387. bool CScriptArray::GetFlag()
  1388. {
  1389. return gcFlag;
  1390. }
  1391. static void ScriptArrayClear(CScriptArray* ptr)
  1392. {
  1393. ptr->Resize(0);
  1394. }
  1395. void RegisterArray(asIScriptEngine* engine)
  1396. {
  1397. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_TEMPLATE_CALLBACK, "bool f(int&in, bool&out)", asFUNCTION(ScriptArrayTemplateCallback), asCALL_CDECL);
  1398. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int&in)", asFUNCTIONPR(CScriptArray::Create, (asITypeInfo*), CScriptArray*), asCALL_CDECL);
  1399. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int&in, uint)", asFUNCTIONPR(CScriptArray::Create, (asITypeInfo*, asUINT), CScriptArray*), asCALL_CDECL);
  1400. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int&in, uint, const T &in)", asFUNCTIONPR(CScriptArray::Create, (asITypeInfo*, asUINT, void *), CScriptArray*), asCALL_CDECL);
  1401. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_LIST_FACTORY, "Array<T>@ f(int&in type, int&in list) {repeat T}", asFUNCTIONPR(CScriptArray::Create, (asITypeInfo*, void*), CScriptArray*), asCALL_CDECL);
  1402. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_ADDREF, "void f()", asMETHOD(CScriptArray, AddRef), asCALL_THISCALL);
  1403. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_RELEASE, "void f()", asMETHOD(CScriptArray, Release), asCALL_THISCALL);
  1404. engine->RegisterObjectMethod("Array<T>", "T& opIndex(uint)", asMETHODPR(CScriptArray, At, (unsigned), void*), asCALL_THISCALL);
  1405. engine->RegisterObjectMethod("Array<T>", "const T& opIndex(uint) const", asMETHODPR(CScriptArray, At, (unsigned), void*), asCALL_THISCALL);
  1406. engine->RegisterObjectMethod("Array<T>", "Array<T>& opAssign(const Array<T>& in)", asMETHOD(CScriptArray, operator=), asCALL_THISCALL);
  1407. engine->RegisterObjectMethod("Array<T>", "void Insert(uint, const T& in)", asMETHOD(CScriptArray, InsertAt), asCALL_THISCALL);
  1408. engine->RegisterObjectMethod("Array<T>", "void Erase(uint)", asMETHOD(CScriptArray, RemoveAt), asCALL_THISCALL);
  1409. engine->RegisterObjectMethod("Array<T>", "void Push(const T& in)", asMETHOD(CScriptArray, InsertLast), asCALL_THISCALL);
  1410. engine->RegisterObjectMethod("Array<T>", "void Pop()", asMETHOD(CScriptArray, RemoveLast), asCALL_THISCALL);
  1411. engine->RegisterObjectMethod("Array<T>", "void Reserve(uint)", asMETHOD(CScriptArray, Reserve), asCALL_THISCALL);
  1412. engine->RegisterObjectMethod("Array<T>", "void Resize(uint)", asMETHODPR(CScriptArray, Resize, (asUINT), void), asCALL_THISCALL);
  1413. engine->RegisterObjectMethod("Array<T>", "void Clear()", asFUNCTION(ScriptArrayClear), asCALL_CDECL_OBJLAST);
  1414. engine->RegisterObjectMethod("Array<T>", "void Sort()", asMETHODPR(CScriptArray, SortAsc, (), void), asCALL_THISCALL);
  1415. engine->RegisterObjectMethod("Array<T>", "void Sort(uint, uint)", asMETHODPR(CScriptArray, SortAsc, (asUINT, asUINT), void), asCALL_THISCALL);
  1416. engine->RegisterObjectMethod("Array<T>", "void SortReverse()", asMETHODPR(CScriptArray, SortDesc, (), void), asCALL_THISCALL);
  1417. engine->RegisterObjectMethod("Array<T>", "void SortReverse(uint, uint)", asMETHODPR(CScriptArray, SortDesc, (asUINT, asUINT), void), asCALL_THISCALL);
  1418. engine->RegisterObjectMethod("Array<T>", "void Reverse()", asMETHOD(CScriptArray, Reverse), asCALL_THISCALL);
  1419. engine->RegisterObjectMethod("Array<T>", "int Find(const T&in) const", asMETHODPR(CScriptArray, Find, (void*) const, int), asCALL_THISCALL);
  1420. engine->RegisterObjectMethod("Array<T>", "int Find(uint, const T&in) const", asMETHODPR(CScriptArray, Find, (asUINT, void*) const, int), asCALL_THISCALL);
  1421. engine->RegisterObjectMethod("Array<T>", "int FindByRef(const T&in) const", asMETHODPR(CScriptArray, FindByRef, (void*) const, int), asCALL_THISCALL);
  1422. engine->RegisterObjectMethod("Array<T>", "int FindByRef(uint, const T&in) const", asMETHODPR(CScriptArray, FindByRef, (asUINT, void*) const, int), asCALL_THISCALL);
  1423. engine->RegisterObjectMethod("Array<T>", "bool Swap(Array<T>&inout)", asMETHOD(CScriptArray, Swap), asCALL_THISCALL);
  1424. engine->RegisterObjectMethod("Array<T>", "bool opEquals(const Array<T>&in) const", asMETHOD(CScriptArray, operator==), asCALL_THISCALL);
  1425. engine->RegisterObjectMethod("Array<T>", "uint get_length() const", asMETHOD(CScriptArray, GetSize), asCALL_THISCALL);
  1426. engine->RegisterObjectMethod("Array<T>", "void set_length(uint)", asMETHODPR(CScriptArray, Resize, (asUINT), void), asCALL_THISCALL);
  1427. engine->RegisterObjectMethod("Array<T>", "bool get_empty() const", asMETHOD(CScriptArray, IsEmpty), asCALL_THISCALL);
  1428. engine->RegisterDefaultArrayType("Array<T>");
  1429. }
  1430. CScriptDictionary *CScriptDictionary::Create(asIScriptEngine *engine)
  1431. {
  1432. // Use the custom memory routine from AngelScript to allow application to better control how much memory is used
  1433. auto*obj = (CScriptDictionary*)asAllocMem(sizeof(CScriptDictionary));
  1434. new(obj) CScriptDictionary(engine);
  1435. return obj;
  1436. }
  1437. CScriptDictionary *CScriptDictionary::Create(asBYTE *buffer)
  1438. {
  1439. // Use the custom memory routine from AngelScript to allow application to better control how much memory is used
  1440. auto*obj = (CScriptDictionary*)asAllocMem(sizeof(CScriptDictionary));
  1441. new(obj) CScriptDictionary(buffer);
  1442. return obj;
  1443. }
  1444. CScriptDictionary::CScriptDictionary(asIScriptEngine *engine)
  1445. {
  1446. // We start with one reference
  1447. refCount = 1;
  1448. gcFlag = false;
  1449. // Keep a reference to the engine for as long as we live
  1450. // We don't increment the reference counter, because the
  1451. // engine will hold a pointer to the object.
  1452. this->engine = engine;
  1453. // Urho3D: garbage collection disabled
  1454. /*
  1455. // Notify the garbage collector of this object
  1456. // TODO: The object type should be cached
  1457. engine->NotifyGarbageCollectorOfNewObject(this, engine->GetObjectTypeByName("Dictionary"));
  1458. */
  1459. }
  1460. CScriptDictionary::CScriptDictionary(asBYTE *buffer)
  1461. {
  1462. // We start with one reference
  1463. refCount = 1;
  1464. gcFlag = false;
  1465. // This constructor will always be called from a script
  1466. // so we can get the engine from the active context
  1467. asIScriptContext *ctx = asGetActiveContext();
  1468. engine = ctx->GetEngine();
  1469. // Urho3D: garbage collection disabled
  1470. /*
  1471. // Notify the garbage collector of this object
  1472. // TODO: The type id should be cached
  1473. engine->NotifyGarbageCollectorOfNewObject(this, engine->GetObjectTypeByName("Dictionary"));
  1474. */
  1475. // Initialize the dictionary from the buffer
  1476. asUINT length = *(asUINT*)buffer;
  1477. buffer += 4;
  1478. while( length-- )
  1479. {
  1480. // Align the buffer pointer on a 4 byte boundary in
  1481. // case previous value was smaller than 4 bytes
  1482. if( asPWORD(buffer) & 0x3 )
  1483. buffer += 4 - (asPWORD(buffer) & 0x3);
  1484. // Get the name value pair from the buffer and insert it in the dictionary
  1485. String name = *(String*)buffer;
  1486. buffer += sizeof(String);
  1487. // Get the type id of the value
  1488. int typeId = *(int*)buffer;
  1489. buffer += sizeof(int);
  1490. // Depending on the type id, the value will inline in the buffer or a pointer
  1491. auto*ref = (void*)buffer;
  1492. if( typeId >= asTYPEID_INT8 && typeId <= asTYPEID_DOUBLE )
  1493. {
  1494. // Convert primitive values to either int64 or double, so we can use the overloaded Set methods
  1495. asINT64 i64;
  1496. double d;
  1497. switch( typeId )
  1498. {
  1499. case asTYPEID_INT8: i64 = *(char*)ref; break;
  1500. case asTYPEID_INT16: i64 = *(short*)ref; break;
  1501. case asTYPEID_INT32: i64 = *(int*)ref; break;
  1502. case asTYPEID_INT64: i64 = *(asINT64*)ref; break;
  1503. case asTYPEID_UINT8: i64 = *(unsigned char*)ref; break;
  1504. case asTYPEID_UINT16: i64 = *(unsigned short*)ref; break;
  1505. case asTYPEID_UINT32: i64 = *(unsigned int*)ref; break;
  1506. case asTYPEID_UINT64: i64 = *(asINT64*)ref; break;
  1507. case asTYPEID_FLOAT: d = *(float*)ref; break;
  1508. case asTYPEID_DOUBLE: d = *(double*)ref; break;
  1509. }
  1510. if( typeId >= asTYPEID_FLOAT )
  1511. Set(name, d);
  1512. else
  1513. Set(name, i64);
  1514. }
  1515. else
  1516. {
  1517. if( (typeId & asTYPEID_MASK_OBJECT) &&
  1518. !(typeId & asTYPEID_OBJHANDLE) &&
  1519. (engine->GetTypeInfoById(typeId)->GetFlags() & asOBJ_REF))
  1520. {
  1521. // Dereference the pointer to get the reference to the actual object
  1522. ref = *(void**)ref;
  1523. }
  1524. Set(name, ref, typeId);
  1525. }
  1526. // Advance the buffer pointer with the size of the value
  1527. if( typeId & asTYPEID_MASK_OBJECT )
  1528. {
  1529. asITypeInfo *ot = engine->GetTypeInfoById(typeId);
  1530. if( ot->GetFlags() & asOBJ_VALUE )
  1531. buffer += ot->GetSize();
  1532. else
  1533. buffer += sizeof(void*);
  1534. }
  1535. else if( typeId == 0 )
  1536. {
  1537. // null pointer
  1538. buffer += sizeof(void*);
  1539. }
  1540. else
  1541. {
  1542. buffer += engine->GetSizeOfPrimitiveType(typeId);
  1543. }
  1544. }
  1545. }
  1546. CScriptDictionary::~CScriptDictionary()
  1547. {
  1548. // Delete all keys and values
  1549. DeleteAll();
  1550. }
  1551. void CScriptDictionary::AddRef() const
  1552. {
  1553. // We need to clear the GC flag
  1554. gcFlag = false;
  1555. asAtomicInc(refCount);
  1556. }
  1557. void CScriptDictionary::Release() const
  1558. {
  1559. // We need to clear the GC flag
  1560. gcFlag = false;
  1561. if( asAtomicDec(refCount) == 0 )
  1562. {
  1563. this->~CScriptDictionary();
  1564. asFreeMem(const_cast<CScriptDictionary*>(this));
  1565. }
  1566. }
  1567. int CScriptDictionary::GetRefCount()
  1568. {
  1569. return refCount;
  1570. }
  1571. void CScriptDictionary::SetGCFlag()
  1572. {
  1573. gcFlag = true;
  1574. }
  1575. bool CScriptDictionary::GetGCFlag()
  1576. {
  1577. return gcFlag;
  1578. }
  1579. void CScriptDictionary::EnumReferences(asIScriptEngine *engine)
  1580. {
  1581. // Call the gc enum callback for each of the objects
  1582. HashMap<String, CScriptDictValue>::Iterator it;
  1583. for( it = dict.Begin(); it != dict.End(); it++ )
  1584. {
  1585. if( it->second_.m_typeId & asTYPEID_MASK_OBJECT )
  1586. engine->GCEnumCallback(it->second_.m_valueObj);
  1587. }
  1588. }
  1589. void CScriptDictionary::ReleaseAllReferences(asIScriptEngine * /*engine*/)
  1590. {
  1591. // We're being told to release all references in
  1592. // order to break circular references for dead objects
  1593. DeleteAll();
  1594. }
  1595. CScriptDictionary &CScriptDictionary::operator =(const CScriptDictionary &other)
  1596. {
  1597. // Clear everything we had before
  1598. DeleteAll();
  1599. // Do a shallow copy of the dictionary
  1600. HashMap<String, CScriptDictValue>::ConstIterator it;
  1601. for( it = other.dict.Begin(); it != other.dict.End(); it++ )
  1602. {
  1603. if( it->second_.m_typeId & asTYPEID_OBJHANDLE )
  1604. Set(it->first_, (void*)&it->second_.m_valueObj, it->second_.m_typeId);
  1605. else if( it->second_.m_typeId & asTYPEID_MASK_OBJECT )
  1606. Set(it->first_, (void*)it->second_.m_valueObj, it->second_.m_typeId);
  1607. else
  1608. Set(it->first_, (void*)&it->second_.m_valueInt, it->second_.m_typeId);
  1609. }
  1610. return *this;
  1611. }
  1612. CScriptDictValue *CScriptDictionary::operator[](const String &key)
  1613. {
  1614. // Return the existing value if it exists, else insert an empty value
  1615. HashMap<String, CScriptDictValue>::Iterator it;
  1616. it = dict.Find(key);
  1617. if( it == dict.End() )
  1618. it = dict.Insert(MakePair(key, CScriptDictValue()));
  1619. return &it->second_;
  1620. }
  1621. const CScriptDictValue *CScriptDictionary::operator[](const String &key) const
  1622. {
  1623. // Return the existing value if it exists
  1624. HashMap<String, CScriptDictValue>::ConstIterator it;
  1625. it = dict.Find(key);
  1626. if( it != dict.End() )
  1627. return &it->second_;
  1628. // Else raise an exception
  1629. asIScriptContext *ctx = asGetActiveContext();
  1630. if( ctx )
  1631. ctx->SetException("Invalid access to non-existing value");
  1632. return nullptr;
  1633. }
  1634. void CScriptDictionary::Set(const String &key, void *value, int typeId)
  1635. {
  1636. HashMap<String, CScriptDictValue>::Iterator it;
  1637. it = dict.Find(key);
  1638. if( it == dict.End() )
  1639. it = dict.Insert(MakePair(key, CScriptDictValue()));
  1640. it->second_.Set(engine, value, typeId);
  1641. }
  1642. // This overloaded method is implemented so that all integer and
  1643. // unsigned integers types will be stored in the dictionary as int64
  1644. // through implicit conversions. This simplifies the management of the
  1645. // numeric types when the script retrieves the stored value using a
  1646. // different type.
  1647. void CScriptDictionary::Set(const String &key, const asINT64 &value)
  1648. {
  1649. Set(key, const_cast<asINT64*>(&value), asTYPEID_INT64);
  1650. }
  1651. // This overloaded method is implemented so that all floating point types
  1652. // will be stored in the dictionary as double through implicit conversions.
  1653. // This simplifies the management of the numeric types when the script
  1654. // retrieves the stored value using a different type.
  1655. void CScriptDictionary::Set(const String &key, const double &value)
  1656. {
  1657. Set(key, const_cast<double*>(&value), asTYPEID_DOUBLE);
  1658. }
  1659. // Returns true if the value was successfully retrieved
  1660. bool CScriptDictionary::Get(const String &key, void *value, int typeId) const
  1661. {
  1662. HashMap<String, CScriptDictValue>::ConstIterator it;
  1663. it = dict.Find(key);
  1664. if( it != dict.End() )
  1665. return it->second_.Get(engine, value, typeId);
  1666. // AngelScript has already initialized the value with a default value,
  1667. // so we don't have to do anything if we don't find the element, or if
  1668. // the element is incompatible with the requested type.
  1669. return false;
  1670. }
  1671. // Returns the type id of the stored value
  1672. int CScriptDictionary::GetTypeId(const String &key) const
  1673. {
  1674. HashMap<String, CScriptDictValue>::ConstIterator it;
  1675. it = dict.Find(key);
  1676. if( it != dict.End() )
  1677. return it->second_.m_typeId;
  1678. return -1;
  1679. }
  1680. bool CScriptDictionary::Get(const String &key, asINT64 &value) const
  1681. {
  1682. return Get(key, &value, asTYPEID_INT64);
  1683. }
  1684. bool CScriptDictionary::Get(const String &key, double &value) const
  1685. {
  1686. return Get(key, &value, asTYPEID_DOUBLE);
  1687. }
  1688. bool CScriptDictionary::Exists(const String &key) const
  1689. {
  1690. HashMap<String, CScriptDictValue>::ConstIterator it;
  1691. it = dict.Find(key);
  1692. if( it != dict.End() )
  1693. return true;
  1694. return false;
  1695. }
  1696. bool CScriptDictionary::IsEmpty() const
  1697. {
  1698. if( dict.Size() == 0 )
  1699. return true;
  1700. return false;
  1701. }
  1702. asUINT CScriptDictionary::GetSize() const
  1703. {
  1704. return asUINT(dict.Size());
  1705. }
  1706. void CScriptDictionary::Delete(const String &key)
  1707. {
  1708. HashMap<String, CScriptDictValue>::Iterator it;
  1709. it = dict.Find(key);
  1710. if( it != dict.End() )
  1711. {
  1712. it->second_.FreeValue(engine);
  1713. dict.Erase(it);
  1714. }
  1715. }
  1716. void CScriptDictionary::DeleteAll()
  1717. {
  1718. HashMap<String, CScriptDictValue>::Iterator it;
  1719. for( it = dict.Begin(); it != dict.End(); it++ )
  1720. it->second_.FreeValue(engine);
  1721. dict.Clear();
  1722. }
  1723. CScriptArray* CScriptDictionary::GetKeys() const
  1724. {
  1725. // TODO: optimize: The string array type should only be determined once.
  1726. // It should be recomputed when registering the dictionary class.
  1727. // Only problem is if multiple engines are used, as they may not
  1728. // share the same type id. Alternatively it can be stored in the
  1729. // user data for the dictionary type.
  1730. asITypeInfo *ot = engine->GetTypeInfoByDecl("Array<String>");
  1731. // Create the array object
  1732. CScriptArray *array = CScriptArray::Create(ot, asUINT(dict.Size()));
  1733. long current = -1;
  1734. HashMap<String, CScriptDictValue>::ConstIterator it;
  1735. for( it = dict.Begin(); it != dict.End(); it++ )
  1736. {
  1737. current++;
  1738. *(String*)array->At(current) = it->first_;
  1739. }
  1740. return array;
  1741. }
  1742. void ScriptDictionaryFactory_Generic(asIScriptGeneric *gen)
  1743. {
  1744. *(CScriptDictionary**)gen->GetAddressOfReturnLocation() = CScriptDictionary::Create(gen->GetEngine());
  1745. }
  1746. void ScriptDictionaryListFactory_Generic(asIScriptGeneric *gen)
  1747. {
  1748. auto*buffer = (asBYTE*)gen->GetArgAddress(0);
  1749. *(CScriptDictionary**)gen->GetAddressOfReturnLocation() = CScriptDictionary::Create(buffer);
  1750. }
  1751. CScriptDictValue::CScriptDictValue() // NOLINT(hicpp-member-init)
  1752. {
  1753. m_valueObj = nullptr;
  1754. m_typeId = 0;
  1755. }
  1756. CScriptDictValue::CScriptDictValue(asIScriptEngine *engine, void *value, int typeId) // NOLINT(hicpp-member-init)
  1757. {
  1758. m_valueObj = nullptr;
  1759. m_typeId = 0;
  1760. Set(engine, value, typeId);
  1761. }
  1762. CScriptDictValue::~CScriptDictValue()
  1763. {
  1764. // Must not hold an object when destroyed, as then the object will never be freed
  1765. assert( (m_typeId & asTYPEID_MASK_OBJECT) == 0 );
  1766. }
  1767. void CScriptDictValue::FreeValue(asIScriptEngine *engine)
  1768. {
  1769. // If it is a handle or a ref counted object, call release
  1770. if( m_typeId & asTYPEID_MASK_OBJECT )
  1771. {
  1772. // Let the engine release the object
  1773. engine->ReleaseScriptObject(m_valueObj, engine->GetTypeInfoById(m_typeId));
  1774. m_valueObj = nullptr;
  1775. m_typeId = 0;
  1776. }
  1777. // For primitives, there's nothing to do
  1778. }
  1779. void CScriptDictValue::Set(asIScriptEngine *engine, void *value, int typeId)
  1780. {
  1781. FreeValue(engine);
  1782. m_typeId = typeId;
  1783. if( typeId & asTYPEID_OBJHANDLE )
  1784. {
  1785. // We're receiving a reference to the handle, so we need to dereference it
  1786. m_valueObj = *(void**)value;
  1787. engine->AddRefScriptObject(m_valueObj, engine->GetTypeInfoById(typeId));
  1788. }
  1789. else if( typeId & asTYPEID_MASK_OBJECT )
  1790. {
  1791. // Create a copy of the object
  1792. m_valueObj = engine->CreateScriptObjectCopy(value, engine->GetTypeInfoById(typeId));
  1793. }
  1794. else
  1795. {
  1796. // Copy the primitive value
  1797. // We receive a pointer to the value.
  1798. int size = engine->GetSizeOfPrimitiveType(typeId);
  1799. memcpy(&m_valueInt, value, size);
  1800. }
  1801. }
  1802. // This overloaded method is implemented so that all integer and
  1803. // unsigned integers types will be stored in the dictionary as int64
  1804. // through implicit conversions. This simplifies the management of the
  1805. // numeric types when the script retrieves the stored value using a
  1806. // different type.
  1807. void CScriptDictValue::Set(asIScriptEngine *engine, const asINT64 &value)
  1808. {
  1809. Set(engine, const_cast<asINT64*>(&value), asTYPEID_INT64);
  1810. }
  1811. // This overloaded method is implemented so that all floating point types
  1812. // will be stored in the dictionary as double through implicit conversions.
  1813. // This simplifies the management of the numeric types when the script
  1814. // retrieves the stored value using a different type.
  1815. void CScriptDictValue::Set(asIScriptEngine *engine, const double &value)
  1816. {
  1817. Set(engine, const_cast<double*>(&value), asTYPEID_DOUBLE);
  1818. }
  1819. bool CScriptDictValue::Get(asIScriptEngine *engine, void *value, int typeId) const
  1820. {
  1821. // Return the value
  1822. if( typeId & asTYPEID_OBJHANDLE )
  1823. {
  1824. // A handle can be retrieved if the stored type is a handle of same or compatible type
  1825. // or if the stored type is an object that implements the interface that the handle refer to.
  1826. void* cast = nullptr;
  1827. if ((m_typeId & asTYPEID_MASK_OBJECT) &&
  1828. engine->RefCastObject(m_valueObj, engine->GetTypeInfoById(m_typeId), engine->GetTypeInfoById(typeId), &cast) >= 0)
  1829. {
  1830. *(void**)value = m_valueObj;
  1831. return true;
  1832. }
  1833. }
  1834. else if( typeId & asTYPEID_MASK_OBJECT )
  1835. {
  1836. // Verify that the copy can be made
  1837. bool isCompatible = false;
  1838. if( m_typeId == typeId )
  1839. isCompatible = true;
  1840. // Copy the object into the given reference
  1841. if( isCompatible )
  1842. {
  1843. engine->AssignScriptObject(value, m_valueObj, engine->GetTypeInfoById(typeId));
  1844. return true;
  1845. }
  1846. }
  1847. else
  1848. {
  1849. if( m_typeId == typeId )
  1850. {
  1851. int size = engine->GetSizeOfPrimitiveType(typeId);
  1852. memcpy(value, &m_valueInt, size);
  1853. return true;
  1854. }
  1855. // We know all numbers are stored as either int64 or double, since we register overloaded functions for those
  1856. if( m_typeId == asTYPEID_INT64 && typeId == asTYPEID_DOUBLE )
  1857. {
  1858. *(double*)value = double(m_valueInt);
  1859. return true;
  1860. }
  1861. else if( m_typeId == asTYPEID_DOUBLE && typeId == asTYPEID_INT64 )
  1862. {
  1863. *(asINT64*)value = asINT64(m_valueFlt);
  1864. return true;
  1865. }
  1866. }
  1867. // It was not possible to retrieve the value using the desired typeId
  1868. return false;
  1869. }
  1870. bool CScriptDictValue::Get(asIScriptEngine *engine, asINT64 &value) const
  1871. {
  1872. return Get(engine, &value, asTYPEID_INT64);
  1873. }
  1874. bool CScriptDictValue::Get(asIScriptEngine *engine, double &value) const
  1875. {
  1876. return Get(engine, &value, asTYPEID_DOUBLE);
  1877. }
  1878. int CScriptDictValue::GetTypeId() const
  1879. {
  1880. return m_typeId;
  1881. }
  1882. static void CScriptDictValue_Construct(void *mem)
  1883. {
  1884. new(mem) CScriptDictValue();
  1885. }
  1886. static void CScriptDictValue_Destruct(CScriptDictValue *obj)
  1887. {
  1888. asIScriptContext *ctx = asGetActiveContext();
  1889. if( ctx )
  1890. {
  1891. asIScriptEngine *engine = ctx->GetEngine();
  1892. obj->FreeValue(engine);
  1893. }
  1894. obj->~CScriptDictValue();
  1895. }
  1896. static CScriptDictValue &CScriptDictValue_opAssign(void *ref, int typeId, CScriptDictValue *obj)
  1897. {
  1898. asIScriptContext *ctx = asGetActiveContext();
  1899. if( ctx )
  1900. {
  1901. asIScriptEngine *engine = ctx->GetEngine();
  1902. obj->Set(engine, ref, typeId);
  1903. }
  1904. return *obj;
  1905. }
  1906. static CScriptDictValue &CScriptDictValue_opAssign(double val, CScriptDictValue *obj)
  1907. {
  1908. return CScriptDictValue_opAssign(&val, asTYPEID_DOUBLE, obj);
  1909. }
  1910. static CScriptDictValue &CScriptDictValue_opAssign(asINT64 val, CScriptDictValue *obj)
  1911. {
  1912. return CScriptDictValue_opAssign(&val, asTYPEID_INT64, obj);
  1913. }
  1914. static void CScriptDictValue_opCast(void *ref, int typeId, CScriptDictValue *obj)
  1915. {
  1916. asIScriptContext *ctx = asGetActiveContext();
  1917. if( ctx )
  1918. {
  1919. asIScriptEngine *engine = ctx->GetEngine();
  1920. obj->Get(engine, ref, typeId);
  1921. }
  1922. }
  1923. static asINT64 CScriptDictValue_opConvInt(CScriptDictValue *obj)
  1924. {
  1925. asINT64 value;
  1926. CScriptDictValue_opCast(&value, asTYPEID_INT64, obj);
  1927. return value;
  1928. }
  1929. static double CScriptDictValue_opConvDouble(CScriptDictValue *obj)
  1930. {
  1931. double value;
  1932. CScriptDictValue_opCast(&value, asTYPEID_DOUBLE, obj);
  1933. return value;
  1934. }
  1935. #ifdef AS_MAX_PORTABILITY
  1936. static void CScriptDictValue_opAssign_gen(asIScriptGeneric* gen)
  1937. {
  1938. *static_cast<CScriptDictValue**>(gen->GetAddressOfReturnLocation()) =
  1939. &CScriptDictValue_opAssign(*static_cast<void**>(gen->GetAddressOfArg(0)),
  1940. gen->GetArgTypeId(0),
  1941. static_cast<CScriptDictValue*>(gen->GetObject()));
  1942. }
  1943. static void CScriptDictValue_opCast_gen(asIScriptGeneric* gen)
  1944. {
  1945. CScriptDictValue_opCast(
  1946. *static_cast<void**>(gen->GetAddressOfArg(0)),
  1947. gen->GetArgTypeId(0),
  1948. static_cast<CScriptDictValue*>(gen->GetObject()));
  1949. }
  1950. static void ScriptDictionarySet_Generic(asIScriptGeneric *gen)
  1951. {
  1952. CScriptDictionary* dict = (CScriptDictionary*)gen->GetObject();
  1953. String* key = *(String**)gen->GetAddressOfArg(0);
  1954. void* ref = *(void**)gen->GetAddressOfArg(1);
  1955. int type_id = gen->GetArgTypeId(1);
  1956. dict->Set(*key, ref, type_id);
  1957. }
  1958. static void ScriptDictionaryGet_Generic(asIScriptGeneric *gen)
  1959. {
  1960. CScriptDictionary* dict = (CScriptDictionary*)gen->GetObject();
  1961. String* key = *(String**)gen->GetAddressOfArg(0);
  1962. void* ref = *(void**)gen->GetAddressOfArg(1);
  1963. int type_id = gen->GetArgTypeId(1);
  1964. *(bool*)gen->GetAddressOfReturnLocation() = dict->Get(*key, ref, type_id);
  1965. }
  1966. #endif
  1967. void RegisterDictionary(asIScriptEngine *engine)
  1968. {
  1969. engine->RegisterObjectBehaviour("DictionaryValue", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(CScriptDictValue_Construct), asCALL_CDECL_OBJLAST);
  1970. engine->RegisterObjectBehaviour("DictionaryValue", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(CScriptDictValue_Destruct), asCALL_CDECL_OBJLAST);
  1971. engine->RegisterObjectMethod("DictionaryValue", "DictionaryValue &opAssign(double)", asFUNCTIONPR(CScriptDictValue_opAssign, (double, CScriptDictValue*), CScriptDictValue &), asCALL_CDECL_OBJLAST);
  1972. engine->RegisterObjectMethod("DictionaryValue", "DictionaryValue &opAssign(int64)", asFUNCTIONPR(CScriptDictValue_opAssign, (asINT64, CScriptDictValue*), CScriptDictValue &), asCALL_CDECL_OBJLAST);
  1973. engine->RegisterObjectMethod("DictionaryValue", "int64 opConv()", asFUNCTIONPR(CScriptDictValue_opConvInt, (CScriptDictValue*), asINT64), asCALL_CDECL_OBJLAST);
  1974. engine->RegisterObjectMethod("DictionaryValue", "double opConv()", asFUNCTIONPR(CScriptDictValue_opConvDouble, (CScriptDictValue*), double), asCALL_CDECL_OBJLAST);
  1975. engine->RegisterObjectType("Dictionary", sizeof(CScriptDictionary), asOBJ_REF);
  1976. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_FACTORY, "Dictionary@ f()", asFUNCTION(ScriptDictionaryFactory_Generic), asCALL_GENERIC);
  1977. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_LIST_FACTORY, "Dictionary @f(int &in) {repeat {String, ?}}", asFUNCTION(ScriptDictionaryListFactory_Generic), asCALL_GENERIC);
  1978. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_ADDREF, "void f()", asMETHOD(CScriptDictionary,AddRef), asCALL_THISCALL);
  1979. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_RELEASE, "void f()", asMETHOD(CScriptDictionary,Release), asCALL_THISCALL);
  1980. engine->RegisterObjectMethod("Dictionary", "Dictionary &opAssign(const Dictionary &in)", asMETHODPR(CScriptDictionary, operator=, (const CScriptDictionary &), CScriptDictionary&), asCALL_THISCALL);
  1981. engine->RegisterObjectMethod("Dictionary", "void Set(const String &in, const int64&in)", asMETHODPR(CScriptDictionary,Set,(const String&,const asINT64&),void), asCALL_THISCALL);
  1982. engine->RegisterObjectMethod("Dictionary", "bool Get(const String &in, int64&out) const", asMETHODPR(CScriptDictionary,Get,(const String&,asINT64&) const,bool), asCALL_THISCALL);
  1983. engine->RegisterObjectMethod("Dictionary", "void Set(const String &in, const double&in)", asMETHODPR(CScriptDictionary,Set,(const String&,const double&),void), asCALL_THISCALL);
  1984. engine->RegisterObjectMethod("Dictionary", "bool Get(const String &in, double&out) const", asMETHODPR(CScriptDictionary,Get,(const String&,double&) const,bool), asCALL_THISCALL);
  1985. engine->RegisterObjectMethod("Dictionary", "bool Exists(const String &in) const", asMETHOD(CScriptDictionary,Exists), asCALL_THISCALL);
  1986. engine->RegisterObjectMethod("Dictionary", "bool get_empty() const", asMETHOD(CScriptDictionary, IsEmpty), asCALL_THISCALL);
  1987. engine->RegisterObjectMethod("Dictionary", "uint get_length() const", asMETHOD(CScriptDictionary, GetSize), asCALL_THISCALL);
  1988. engine->RegisterObjectMethod("Dictionary", "void Erase(const String &in)", asMETHOD(CScriptDictionary,Delete), asCALL_THISCALL);
  1989. engine->RegisterObjectMethod("Dictionary", "void Clear()", asMETHOD(CScriptDictionary,DeleteAll), asCALL_THISCALL);
  1990. engine->RegisterObjectMethod("Dictionary", "Array<String> @get_keys() const", asMETHOD(CScriptDictionary,GetKeys), asCALL_THISCALL);
  1991. engine->RegisterObjectMethod("Dictionary", "DictionaryValue &opIndex(const String &in)", asMETHODPR(CScriptDictionary, operator[], (const String &), CScriptDictValue*), asCALL_THISCALL);
  1992. engine->RegisterObjectMethod("Dictionary", "const DictionaryValue &opIndex(const String &in) const", asMETHODPR(CScriptDictionary, operator[], (const String &) const, const CScriptDictValue*), asCALL_THISCALL);
  1993. #ifndef AS_MAX_PORTABILITY
  1994. engine->RegisterObjectMethod("DictionaryValue", "DictionaryValue &opHndlAssign(const ?&in)", asFUNCTIONPR(CScriptDictValue_opAssign, (void *, int, CScriptDictValue*), CScriptDictValue &), asCALL_CDECL_OBJLAST);
  1995. engine->RegisterObjectMethod("DictionaryValue", "DictionaryValue &opAssign(const ?&in)", asFUNCTIONPR(CScriptDictValue_opAssign, (void *, int, CScriptDictValue*), CScriptDictValue &), asCALL_CDECL_OBJLAST);
  1996. engine->RegisterObjectMethod("DictionaryValue", "void opCast(?&out)", asFUNCTIONPR(CScriptDictValue_opCast, (void *, int, CScriptDictValue*), void), asCALL_CDECL_OBJLAST);
  1997. engine->RegisterObjectMethod("DictionaryValue", "void opConv(?&out)", asFUNCTIONPR(CScriptDictValue_opCast, (void *, int, CScriptDictValue*), void), asCALL_CDECL_OBJLAST);
  1998. engine->RegisterObjectMethod("Dictionary", "void Set(const String &in, const ?&in)", asMETHODPR(CScriptDictionary, Set, (const String&, void*, int), void), asCALL_THISCALL);
  1999. engine->RegisterObjectMethod("Dictionary", "bool Get(const String &in, ?&out) const", asMETHODPR(CScriptDictionary, Get, (const String&, void*, int) const, bool), asCALL_THISCALL);
  2000. #else
  2001. engine->RegisterObjectMethod("DictionaryValue", "DictionaryValue &opHndlAssign(const ?&in)", asFUNCTION(CScriptDictValue_opAssign_gen), asCALL_GENERIC);
  2002. engine->RegisterObjectMethod("DictionaryValue", "DictionaryValue &opAssign(const ?&in)", asFUNCTION(CScriptDictValue_opAssign_gen), asCALL_GENERIC);
  2003. engine->RegisterObjectMethod("DictionaryValue", "void opCast(?&out)", asFUNCTION(CScriptDictValue_opCast_gen), asCALL_GENERIC);
  2004. engine->RegisterObjectMethod("DictionaryValue", "void opConv(?&out)", asFUNCTION(CScriptDictValue_opCast_gen), asCALL_GENERIC);
  2005. engine->RegisterObjectMethod("Dictionary", "void Set(const String &in, const ?&in)", asFUNCTION(ScriptDictionarySet_Generic), asCALL_GENERIC);
  2006. engine->RegisterObjectMethod("Dictionary", "bool Get(const String &in, ?&out) const", asFUNCTION(ScriptDictionaryGet_Generic), asCALL_GENERIC);
  2007. #endif
  2008. }
  2009. static void ConstructString(String* ptr)
  2010. {
  2011. new(ptr) String();
  2012. }
  2013. static void ConstructStringCopy(const String& str, String* ptr)
  2014. {
  2015. new(ptr) String(str);
  2016. }
  2017. static void DestructString(String* ptr)
  2018. {
  2019. ptr->~String();
  2020. }
  2021. static char* StringCharAt(unsigned i, String& str)
  2022. {
  2023. if (i >= str.Length())
  2024. {
  2025. asIScriptContext* context = asGetActiveContext();
  2026. if (context)
  2027. context->SetException("Index out of bounds");
  2028. return nullptr;
  2029. }
  2030. return &str[i];
  2031. }
  2032. static int StringCmp(const String& lhs, const String& rhs)
  2033. {
  2034. int cmp = 0;
  2035. if (lhs < rhs)
  2036. cmp = -1;
  2037. else if (lhs > rhs)
  2038. cmp = 1;
  2039. return cmp;
  2040. }
  2041. void StringResize(unsigned newSize, String& str)
  2042. {
  2043. unsigned oldSize = str.Length();
  2044. str.Resize(newSize);
  2045. for (unsigned i = oldSize; i < newSize; ++i)
  2046. str[i] = ' ';
  2047. }
  2048. static void ConstructStringInt(int value, String* ptr)
  2049. {
  2050. new(ptr) String(value);
  2051. }
  2052. static void ConstructStringUInt(unsigned value, String* ptr)
  2053. {
  2054. new(ptr) String(value);
  2055. }
  2056. static void ConstructStringFloat(float value, String* ptr)
  2057. {
  2058. new(ptr) String(value);
  2059. }
  2060. static void ConstructStringDouble(double value, String* ptr)
  2061. {
  2062. new(ptr)String(value);
  2063. }
  2064. static void ConstructStringBool(bool value, String* ptr)
  2065. {
  2066. new(ptr) String(value);
  2067. }
  2068. static void StringSetUTF8FromLatin1(const String& src, String& str)
  2069. {
  2070. str.SetUTF8FromLatin1(src.CString());
  2071. }
  2072. void RegisterString(asIScriptEngine *engine)
  2073. {
  2074. //static const unsigned NPOS = String::NPOS; // workaround for GCC
  2075. //static StringFactory stringFactory;
  2076. //engine->RegisterGlobalProperty("const uint NPOS", (void*)&NPOS);
  2077. //engine->RegisterStringFactory("String", &stringFactory);
  2078. // TODO Обертку с контролем размера массива
  2079. //engine->RegisterObjectMethod("String", "uint8 &opIndex(uint)", asFUNCTION(StringCharAt), asCALL_CDECL_OBJLAST);
  2080. //engine->RegisterObjectMethod("String", "const uint8 &opIndex(uint) const", asFUNCTION(StringCharAt), asCALL_CDECL_OBJLAST);
  2081. // TODO у меня int8
  2082. //engine->RegisterObjectMethod("String", "void Replace(uint8, uint8, bool caseSensitive = true)", asMETHODPR(String, Replace, (char, char, bool), void), asCALL_THISCALL);
  2083. //engine->RegisterObjectMethod("String", "String Replaced(uint8, uint8, bool caseSensitive = true) const", asMETHODPR(String, Replaced, (char, char, bool) const, String), asCALL_THISCALL);
  2084. //engine->RegisterObjectMethod("String", "uint Find(uint8, uint start = 0, bool caseSensitive = true) const", asMETHODPR(String, Find, (char, unsigned, bool) const, unsigned), asCALL_THISCALL);
  2085. // NPOS починить
  2086. //engine->RegisterObjectMethod("String", "uint FindLast(const String&in, uint start = 0xffffffff, bool caseSensitive = true) const", asMETHODPR(String, FindLast, (const String&, unsigned, bool) const, unsigned), asCALL_THISCALL);
  2087. //engine->RegisterObjectMethod("String", "uint FindLast(uint8, uint start = 0xffffffff, bool caseSensitive = true) const", asMETHODPR(String, FindLast, (char, unsigned, bool) const, unsigned), asCALL_THISCALL);
  2088. // ручная привязка
  2089. //engine->RegisterObjectMethod("String", "void SetUTF8FromLatin1(const String& in)", asFUNCTION(StringSetUTF8FromLatin1), asCALL_CDECL_OBJLAST);
  2090. // TODO у меня int8
  2091. //engine->RegisterObjectMethod("String", "bool Contains(uint8, bool caseSensitive = true) const", asMETHODPR(String, Contains, (char, bool) const, bool), asCALL_THISCALL);
  2092. }
  2093. const void* StringFactory::GetStringConstant(const char* data, asUINT length)
  2094. {
  2095. assert(strlen(data) == length);
  2096. StringHash hash(data);
  2097. auto iter = map_.Find(hash);
  2098. return reinterpret_cast<const void*>(&(iter == map_.End() ? map_.Insert(MakePair(hash, String(data))) : iter)->second_);
  2099. }
  2100. int StringFactory::ReleaseStringConstant(const void* str)
  2101. {
  2102. // Cache all the strings
  2103. return str ? asSUCCESS : asERROR;
  2104. }
  2105. int StringFactory::GetRawStringData(const void* str, char* data, asUINT* length) const
  2106. {
  2107. if (!str)
  2108. return asERROR;
  2109. auto p = reinterpret_cast<const String*>(str);
  2110. if (length)
  2111. *length = p->Length();
  2112. if (data)
  2113. memcpy(data, p->CString(), p->Length());
  2114. return asSUCCESS;
  2115. }
  2116. // This function is called before ASRegisterGenerated()
  2117. void ASRegisterManualFirst_Addons(asIScriptEngine* engine)
  2118. {
  2119. engine->SetTypeInfoUserDataCleanupCallback(CleanupTypeInfoArrayCache, ARRAY_CACHE);
  2120. engine->RegisterObjectType("Array<class T>", 0, asOBJ_REF | asOBJ_TEMPLATE);
  2121. RegisterArray(engine);
  2122. engine->RegisterObjectType("DictionaryValue", sizeof(CScriptDictValue), asOBJ_VALUE | asOBJ_ASHANDLE | asOBJ_APP_CLASS_CD);
  2123. }
  2124. // This function is called after ASRegisterGenerated()
  2125. void ASRegisterManualLast_Addons(asIScriptEngine* engine)
  2126. {
  2127. //RegisterArray(engine);
  2128. RegisterDictionary(engine);
  2129. }
  2130. }