Addons.cpp 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549
  1. //
  2. // Copyright (c) 2008-2017 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 <stdio.h>
  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. SArrayCache *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 == 0 )
  77. {
  78. if( ctx )
  79. ctx->SetException("Out of memory");
  80. return 0;
  81. }
  82. // Initialize the object
  83. CScriptArray *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 0;
  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 == 0 )
  99. {
  100. if( ctx )
  101. ctx->SetException("Out of memory");
  102. return 0;
  103. }
  104. // Initialize the object
  105. CScriptArray *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 0;
  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 == 0 )
  121. {
  122. if( ctx )
  123. ctx->SetException("Out of memory");
  124. return 0;
  125. }
  126. // Initialize the object
  127. CScriptArray *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 0;
  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 = 0;
  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. asBYTE *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 = 0;
  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 = 0;
  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 = 0;
  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 == 0 ) 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 = 0;
  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. SArrayBuffer *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. SArrayBuffer *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 == 0 || 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 0;
  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. void **max = (void**)(buf->data + end * sizeof(void*));
  687. void **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 == 0 )
  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. void *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. void **max = (void**)(buf->data + end * sizeof(void*));
  718. void **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 == 0 ) return true;
  762. if( *(void**)b == 0 ) 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 = 0;
  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 = 0;
  820. }
  821. if( cmpContext == 0 )
  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. SArrayCache *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. int CScriptArray::Find(void *value) const
  955. {
  956. return Find(0, value);
  957. }
  958. int CScriptArray::Find(asUINT startAt, void *value) const
  959. {
  960. // Check if the subtype really supports find()
  961. // TODO: Can't this be done at compile time too by the template callback
  962. SArrayCache *cache = 0;
  963. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  964. {
  965. cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  966. if( !cache || (cache->cmpFunc == 0 && cache->eqFunc == 0) )
  967. {
  968. asIScriptContext *ctx = asGetActiveContext();
  969. asITypeInfo* subType = objType->GetEngine()->GetTypeInfoById(subTypeId);
  970. // Throw an exception
  971. if( ctx )
  972. {
  973. char tmp[512];
  974. if( cache && cache->eqFuncReturnCode == asMULTIPLE_FUNCTIONS )
  975. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  976. sprintf_s(tmp, 512, "Type '%s' has multiple matching opEquals or opCmp methods", subType->GetName());
  977. #else
  978. sprintf(tmp, "Type '%s' has multiple matching opEquals or opCmp methods", subType->GetName());
  979. #endif
  980. else
  981. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  982. sprintf_s(tmp, 512, "Type '%s' does not have a matching opEquals or opCmp method", subType->GetName());
  983. #else
  984. sprintf(tmp, "Type '%s' does not have a matching opEquals or opCmp method", subType->GetName());
  985. #endif
  986. ctx->SetException(tmp);
  987. }
  988. return -1;
  989. }
  990. }
  991. asIScriptContext *cmpContext = 0;
  992. bool isNested = false;
  993. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  994. {
  995. // Try to reuse the active context
  996. cmpContext = asGetActiveContext();
  997. if( cmpContext )
  998. {
  999. if( cmpContext->GetEngine() == objType->GetEngine() && cmpContext->PushState() >= 0 )
  1000. isNested = true;
  1001. else
  1002. cmpContext = 0;
  1003. }
  1004. if( cmpContext == 0 )
  1005. {
  1006. // TODO: Ideally this context would be retrieved from a pool, so we don't have to
  1007. // create a new one every time. We could keep a context with the array object
  1008. // but that would consume a lot of resources as each context is quite heavy.
  1009. cmpContext = objType->GetEngine()->CreateContext();
  1010. }
  1011. }
  1012. // Find the matching element
  1013. int ret = -1;
  1014. asUINT size = GetSize();
  1015. for( asUINT i = startAt; i < size; i++ )
  1016. {
  1017. // value passed by reference
  1018. if( Equals(At(i), value, cmpContext, cache) )
  1019. {
  1020. ret = (int)i;
  1021. break;
  1022. }
  1023. }
  1024. if( cmpContext )
  1025. {
  1026. if( isNested )
  1027. {
  1028. asEContextState state = cmpContext->GetState();
  1029. cmpContext->PopState();
  1030. if( state == asEXECUTION_ABORTED )
  1031. cmpContext->Abort();
  1032. }
  1033. else
  1034. cmpContext->Release();
  1035. }
  1036. return ret;
  1037. }
  1038. // internal
  1039. // Copy object handle or primitive value
  1040. void CScriptArray::Copy(void *dst, void *src)
  1041. {
  1042. memcpy(dst, src, elementSize);
  1043. }
  1044. // internal
  1045. // Return pointer to array item (object handle or primitive value)
  1046. void *CScriptArray::GetArrayItemPointer(int index)
  1047. {
  1048. return buffer->data + index * elementSize;
  1049. }
  1050. // internal
  1051. // Return pointer to data in buffer (object or primitive)
  1052. void *CScriptArray::GetDataPointer(void *buffer)
  1053. {
  1054. if ((subTypeId & asTYPEID_MASK_OBJECT) && !(subTypeId & asTYPEID_OBJHANDLE) )
  1055. {
  1056. // Real address of object
  1057. return reinterpret_cast<void*>(*(size_t*)buffer);
  1058. }
  1059. else
  1060. {
  1061. // Primitive is just a raw data
  1062. return buffer;
  1063. }
  1064. }
  1065. // Sort ascending
  1066. void CScriptArray::SortAsc()
  1067. {
  1068. Sort(0, GetSize(), true);
  1069. }
  1070. // Sort ascending
  1071. void CScriptArray::SortAsc(asUINT startAt, asUINT count)
  1072. {
  1073. Sort(startAt, count, true);
  1074. }
  1075. // Sort descending
  1076. void CScriptArray::SortDesc()
  1077. {
  1078. Sort(0, GetSize(), false);
  1079. }
  1080. // Sort descending
  1081. void CScriptArray::SortDesc(asUINT startAt, asUINT count)
  1082. {
  1083. Sort(startAt, count, false);
  1084. }
  1085. // internal
  1086. void CScriptArray::Sort(asUINT startAt, asUINT count, bool asc)
  1087. {
  1088. // Subtype isn't primitive and doesn't have opCmp
  1089. SArrayCache *cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  1090. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  1091. {
  1092. if( !cache || cache->cmpFunc == 0 )
  1093. {
  1094. asIScriptContext *ctx = asGetActiveContext();
  1095. asITypeInfo* subType = objType->GetEngine()->GetTypeInfoById(subTypeId);
  1096. // Throw an exception
  1097. if( ctx )
  1098. {
  1099. char tmp[512];
  1100. if( cache && cache->cmpFuncReturnCode == asMULTIPLE_FUNCTIONS )
  1101. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  1102. sprintf_s(tmp, 512, "Type '%s' has multiple matching opCmp methods", subType->GetName());
  1103. #else
  1104. sprintf(tmp, "Type '%s' has multiple matching opCmp methods", subType->GetName());
  1105. #endif
  1106. else
  1107. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  1108. sprintf_s(tmp, 512, "Type '%s' does not have a matching opCmp method", subType->GetName());
  1109. #else
  1110. sprintf(tmp, "Type '%s' does not have a matching opCmp method", subType->GetName());
  1111. #endif
  1112. ctx->SetException(tmp);
  1113. }
  1114. return;
  1115. }
  1116. }
  1117. // No need to sort
  1118. if( count < 2 )
  1119. {
  1120. return;
  1121. }
  1122. int start = startAt;
  1123. int end = startAt + count;
  1124. // Check if we could access invalid item while sorting
  1125. if( start >= (int)buffer->numElements || end > (int)buffer->numElements )
  1126. {
  1127. asIScriptContext *ctx = asGetActiveContext();
  1128. // Throw an exception
  1129. if( ctx )
  1130. {
  1131. ctx->SetException("Index out of bounds");
  1132. }
  1133. return;
  1134. }
  1135. asBYTE tmp[16];
  1136. asIScriptContext *cmpContext = 0;
  1137. bool isNested = false;
  1138. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  1139. {
  1140. // Try to reuse the active context
  1141. cmpContext = asGetActiveContext();
  1142. if( cmpContext )
  1143. {
  1144. if( cmpContext->GetEngine() == objType->GetEngine() && cmpContext->PushState() >= 0 )
  1145. isNested = true;
  1146. else
  1147. cmpContext = 0;
  1148. }
  1149. if( cmpContext == 0 )
  1150. {
  1151. // TODO: Ideally this context would be retrieved from a pool, so we don't have to
  1152. // create a new one every time. We could keep a context with the array object
  1153. // but that would consume a lot of resources as each context is quite heavy.
  1154. cmpContext = objType->GetEngine()->CreateContext();
  1155. }
  1156. }
  1157. // Insertion sort
  1158. for( int i = start + 1; i < end; i++ )
  1159. {
  1160. Copy(tmp, GetArrayItemPointer(i));
  1161. int j = i - 1;
  1162. while( j >= start && Less(GetDataPointer(tmp), At(j), asc, cmpContext, cache) )
  1163. {
  1164. Copy(GetArrayItemPointer(j + 1), GetArrayItemPointer(j));
  1165. j--;
  1166. }
  1167. Copy(GetArrayItemPointer(j + 1), tmp);
  1168. }
  1169. if( cmpContext )
  1170. {
  1171. if( isNested )
  1172. {
  1173. asEContextState state = cmpContext->GetState();
  1174. cmpContext->PopState();
  1175. if( state == asEXECUTION_ABORTED )
  1176. cmpContext->Abort();
  1177. }
  1178. else
  1179. cmpContext->Release();
  1180. }
  1181. }
  1182. // internal
  1183. void CScriptArray::CopyBuffer(SArrayBuffer *dst, SArrayBuffer *src)
  1184. {
  1185. asIScriptEngine *engine = objType->GetEngine();
  1186. if( subTypeId & asTYPEID_OBJHANDLE )
  1187. {
  1188. // Copy the references and increase the reference counters
  1189. if( dst->numElements > 0 && src->numElements > 0 )
  1190. {
  1191. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  1192. void **max = (void**)(dst->data + count * sizeof(void*));
  1193. void **d = (void**)dst->data;
  1194. void **s = (void**)src->data;
  1195. for( ; d < max; d++, s++ )
  1196. {
  1197. void *tmp = *d;
  1198. *d = *s;
  1199. if( *d )
  1200. engine->AddRefScriptObject(*d, objType->GetSubType());
  1201. // Release the old ref after incrementing the new to avoid problem incase it is the same ref
  1202. if( tmp )
  1203. engine->ReleaseScriptObject(tmp, objType->GetSubType());
  1204. }
  1205. }
  1206. }
  1207. else
  1208. {
  1209. if( dst->numElements > 0 && src->numElements > 0 )
  1210. {
  1211. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  1212. if( subTypeId & asTYPEID_MASK_OBJECT )
  1213. {
  1214. // Call the assignment operator on all of the objects
  1215. void **max = (void**)(dst->data + count * sizeof(void*));
  1216. void **d = (void**)dst->data;
  1217. void **s = (void**)src->data;
  1218. asITypeInfo *subType = objType->GetSubType();
  1219. for( ; d < max; d++, s++ )
  1220. engine->AssignScriptObject(*d, *s, subType);
  1221. }
  1222. else
  1223. {
  1224. // Primitives are copied byte for byte
  1225. memcpy(dst->data, src->data, count*elementSize);
  1226. }
  1227. }
  1228. }
  1229. }
  1230. // internal
  1231. // Precache some info
  1232. void CScriptArray::Precache()
  1233. {
  1234. subTypeId = objType->GetSubTypeId();
  1235. // Check if it is an array of objects. Only for these do we need to cache anything
  1236. // Type ids for primitives and enums only has the sequence number part
  1237. if( !(subTypeId & ~asTYPEID_MASK_SEQNBR) )
  1238. return;
  1239. // The opCmp and opEquals methods are cached because the searching for the
  1240. // methods is quite time consuming if a lot of array objects are created.
  1241. // First check if a cache already exists for this array type
  1242. SArrayCache *cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  1243. if( cache ) return;
  1244. // We need to make sure the cache is created only once, even
  1245. // if multiple threads reach the same point at the same time
  1246. asAcquireExclusiveLock();
  1247. // Now that we got the lock, we need to check again to make sure the
  1248. // cache wasn't created while we were waiting for the lock
  1249. cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  1250. if( cache )
  1251. {
  1252. asReleaseExclusiveLock();
  1253. return;
  1254. }
  1255. // Create the cache
  1256. cache = reinterpret_cast<SArrayCache*>(userAlloc(sizeof(SArrayCache)));
  1257. memset(cache, 0, sizeof(SArrayCache));
  1258. // If the sub type is a handle to const, then the methods must be const too
  1259. bool mustBeConst = (subTypeId & asTYPEID_HANDLETOCONST) ? true : false;
  1260. asITypeInfo *subType = objType->GetEngine()->GetTypeInfoById(subTypeId);
  1261. if( subType )
  1262. {
  1263. for( asUINT i = 0; i < subType->GetMethodCount(); i++ )
  1264. {
  1265. asIScriptFunction *func = subType->GetMethodByIndex(i);
  1266. if( func->GetParamCount() == 1 && (!mustBeConst || func->IsReadOnly()) )
  1267. {
  1268. asDWORD flags = 0;
  1269. int returnTypeId = func->GetReturnTypeId(&flags);
  1270. // The method must not return a reference
  1271. if( flags != asTM_NONE )
  1272. continue;
  1273. // opCmp returns an int and opEquals returns a bool
  1274. bool isCmp = false, isEq = false;
  1275. if( returnTypeId == asTYPEID_INT32 && strcmp(func->GetName(), "opCmp") == 0 )
  1276. isCmp = true;
  1277. if( returnTypeId == asTYPEID_BOOL && strcmp(func->GetName(), "opEquals") == 0 )
  1278. isEq = true;
  1279. if( !isCmp && !isEq )
  1280. continue;
  1281. // The parameter must either be a reference to the subtype or a handle to the subtype
  1282. int paramTypeId;
  1283. func->GetParam(0, &paramTypeId, &flags);
  1284. if( (paramTypeId & ~(asTYPEID_OBJHANDLE|asTYPEID_HANDLETOCONST)) != (subTypeId & ~(asTYPEID_OBJHANDLE|asTYPEID_HANDLETOCONST)) )
  1285. continue;
  1286. if( (flags & asTM_INREF) )
  1287. {
  1288. if( (paramTypeId & asTYPEID_OBJHANDLE) || (mustBeConst && !(flags & asTM_CONST)) )
  1289. continue;
  1290. }
  1291. else if( paramTypeId & asTYPEID_OBJHANDLE )
  1292. {
  1293. if( mustBeConst && !(paramTypeId & asTYPEID_HANDLETOCONST) )
  1294. continue;
  1295. }
  1296. else
  1297. continue;
  1298. if( isCmp )
  1299. {
  1300. if( cache->cmpFunc || cache->cmpFuncReturnCode )
  1301. {
  1302. cache->cmpFunc = 0;
  1303. cache->cmpFuncReturnCode = asMULTIPLE_FUNCTIONS;
  1304. }
  1305. else
  1306. cache->cmpFunc = func;
  1307. }
  1308. else if( isEq )
  1309. {
  1310. if( cache->eqFunc || cache->eqFuncReturnCode )
  1311. {
  1312. cache->eqFunc = 0;
  1313. cache->eqFuncReturnCode = asMULTIPLE_FUNCTIONS;
  1314. }
  1315. else
  1316. cache->eqFunc = func;
  1317. }
  1318. }
  1319. }
  1320. }
  1321. if( cache->eqFunc == 0 && cache->eqFuncReturnCode == 0 )
  1322. cache->eqFuncReturnCode = asNO_FUNCTION;
  1323. if( cache->cmpFunc == 0 && cache->cmpFuncReturnCode == 0 )
  1324. cache->cmpFuncReturnCode = asNO_FUNCTION;
  1325. // Set the user data only at the end so others that retrieve it will know it is complete
  1326. objType->SetUserData(cache, ARRAY_CACHE);
  1327. asReleaseExclusiveLock();
  1328. }
  1329. // GC behaviour
  1330. void CScriptArray::EnumReferences(asIScriptEngine *engine)
  1331. {
  1332. // If the array is holding handles, then we need to notify the GC of them
  1333. if( subTypeId & asTYPEID_MASK_OBJECT )
  1334. {
  1335. void **d = (void**)buffer->data;
  1336. for( asUINT n = 0; n < buffer->numElements; n++ )
  1337. {
  1338. if( d[n] )
  1339. engine->GCEnumCallback(d[n]);
  1340. }
  1341. }
  1342. }
  1343. // GC behaviour
  1344. void CScriptArray::ReleaseAllHandles(asIScriptEngine *)
  1345. {
  1346. // Resizing to zero will release everything
  1347. Resize(0);
  1348. }
  1349. void CScriptArray::AddRef() const
  1350. {
  1351. // Clear the GC flag then increase the counter
  1352. gcFlag = false;
  1353. asAtomicInc(refCount);
  1354. }
  1355. void CScriptArray::Release() const
  1356. {
  1357. // Clearing the GC flag then descrease the counter
  1358. gcFlag = false;
  1359. if( asAtomicDec(refCount) == 0 )
  1360. {
  1361. // When reaching 0 no more references to this instance
  1362. // exists and the object should be destroyed
  1363. this->~CScriptArray();
  1364. userFree(const_cast<CScriptArray*>(this));
  1365. }
  1366. }
  1367. // GC behaviour
  1368. int CScriptArray::GetRefCount()
  1369. {
  1370. return refCount;
  1371. }
  1372. // GC behaviour
  1373. void CScriptArray::SetFlag()
  1374. {
  1375. gcFlag = true;
  1376. }
  1377. // GC behaviour
  1378. bool CScriptArray::GetFlag()
  1379. {
  1380. return gcFlag;
  1381. }
  1382. static void ScriptArrayClear(CScriptArray* ptr)
  1383. {
  1384. ptr->Resize(0);
  1385. }
  1386. void RegisterArray(asIScriptEngine* engine)
  1387. {
  1388. engine->SetTypeInfoUserDataCleanupCallback(CleanupTypeInfoArrayCache, ARRAY_CACHE);
  1389. engine->RegisterObjectType("Array<class T>", 0, asOBJ_REF | asOBJ_TEMPLATE);
  1390. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_TEMPLATE_CALLBACK, "bool f(int&in, bool&out)", asFUNCTION(ScriptArrayTemplateCallback), asCALL_CDECL);
  1391. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int&in)", asFUNCTIONPR(CScriptArray::Create, (asITypeInfo*), CScriptArray*), asCALL_CDECL);
  1392. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int&in, uint)", asFUNCTIONPR(CScriptArray::Create, (asITypeInfo*, asUINT), CScriptArray*), asCALL_CDECL);
  1393. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int&in, uint, const T &in)", asFUNCTIONPR(CScriptArray::Create, (asITypeInfo*, asUINT, void *), CScriptArray*), asCALL_CDECL);
  1394. 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);
  1395. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_ADDREF, "void f()", asMETHOD(CScriptArray, AddRef), asCALL_THISCALL);
  1396. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_RELEASE, "void f()", asMETHOD(CScriptArray, Release), asCALL_THISCALL);
  1397. engine->RegisterObjectMethod("Array<T>", "T& opIndex(uint)", asMETHODPR(CScriptArray, At, (unsigned), void*), asCALL_THISCALL);
  1398. engine->RegisterObjectMethod("Array<T>", "const T& opIndex(uint) const", asMETHODPR(CScriptArray, At, (unsigned), void*), asCALL_THISCALL);
  1399. engine->RegisterObjectMethod("Array<T>", "Array<T>& opAssign(const Array<T>& in)", asMETHOD(CScriptArray, operator=), asCALL_THISCALL);
  1400. engine->RegisterObjectMethod("Array<T>", "void Insert(uint, const T& in)", asMETHOD(CScriptArray, InsertAt), asCALL_THISCALL);
  1401. engine->RegisterObjectMethod("Array<T>", "void Erase(uint)", asMETHOD(CScriptArray, RemoveAt), asCALL_THISCALL);
  1402. engine->RegisterObjectMethod("Array<T>", "void Push(const T& in)", asMETHOD(CScriptArray, InsertLast), asCALL_THISCALL);
  1403. engine->RegisterObjectMethod("Array<T>", "void Pop()", asMETHOD(CScriptArray, RemoveLast), asCALL_THISCALL);
  1404. engine->RegisterObjectMethod("Array<T>", "void Reserve(uint)", asMETHOD(CScriptArray, Reserve), asCALL_THISCALL);
  1405. engine->RegisterObjectMethod("Array<T>", "void Resize(uint)", asMETHODPR(CScriptArray, Resize, (asUINT), void), asCALL_THISCALL);
  1406. engine->RegisterObjectMethod("Array<T>", "void Clear()", asFUNCTION(ScriptArrayClear), asCALL_CDECL_OBJLAST);
  1407. engine->RegisterObjectMethod("Array<T>", "void Sort()", asMETHODPR(CScriptArray, SortAsc, (), void), asCALL_THISCALL);
  1408. engine->RegisterObjectMethod("Array<T>", "void Sort(uint, uint)", asMETHODPR(CScriptArray, SortAsc, (asUINT, asUINT), void), asCALL_THISCALL);
  1409. engine->RegisterObjectMethod("Array<T>", "void SortReverse()", asMETHODPR(CScriptArray, SortDesc, (), void), asCALL_THISCALL);
  1410. engine->RegisterObjectMethod("Array<T>", "void SortReverse(uint, uint)", asMETHODPR(CScriptArray, SortDesc, (asUINT, asUINT), void), asCALL_THISCALL);
  1411. engine->RegisterObjectMethod("Array<T>", "void Reverse()", asMETHOD(CScriptArray, Reverse), asCALL_THISCALL);
  1412. engine->RegisterObjectMethod("Array<T>", "int Find(const T&in) const", asMETHODPR(CScriptArray, Find, (void*) const, int), asCALL_THISCALL);
  1413. engine->RegisterObjectMethod("Array<T>", "int Find(uint, const T&in) const", asMETHODPR(CScriptArray, Find, (asUINT, void*) const, int), asCALL_THISCALL);
  1414. engine->RegisterObjectMethod("Array<T>", "int FindByRef(const T&in) const", asMETHODPR(CScriptArray, FindByRef, (void*) const, int), asCALL_THISCALL);
  1415. engine->RegisterObjectMethod("Array<T>", "int FindByRef(uint, const T&in) const", asMETHODPR(CScriptArray, FindByRef, (asUINT, void*) const, int), asCALL_THISCALL);
  1416. engine->RegisterObjectMethod("Array<T>", "bool opEquals(const Array<T>&in) const", asMETHOD(CScriptArray, operator==), asCALL_THISCALL);
  1417. engine->RegisterObjectMethod("Array<T>", "uint get_length() const", asMETHOD(CScriptArray, GetSize), asCALL_THISCALL);
  1418. engine->RegisterObjectMethod("Array<T>", "void set_length(uint)", asMETHODPR(CScriptArray, Resize, (asUINT), void), asCALL_THISCALL);
  1419. engine->RegisterObjectMethod("Array<T>", "bool get_empty() const", asMETHOD(CScriptArray, IsEmpty), asCALL_THISCALL);
  1420. engine->RegisterDefaultArrayType("Array<T>");
  1421. }
  1422. CScriptDictionary *CScriptDictionary::Create(asIScriptEngine *engine)
  1423. {
  1424. // Use the custom memory routine from AngelScript to allow application to better control how much memory is used
  1425. CScriptDictionary *obj = (CScriptDictionary*)asAllocMem(sizeof(CScriptDictionary));
  1426. new(obj) CScriptDictionary(engine);
  1427. return obj;
  1428. }
  1429. CScriptDictionary *CScriptDictionary::Create(asBYTE *buffer)
  1430. {
  1431. // Use the custom memory routine from AngelScript to allow application to better control how much memory is used
  1432. CScriptDictionary *obj = (CScriptDictionary*)asAllocMem(sizeof(CScriptDictionary));
  1433. new(obj) CScriptDictionary(buffer);
  1434. return obj;
  1435. }
  1436. CScriptDictionary::CScriptDictionary(asIScriptEngine *engine)
  1437. {
  1438. // We start with one reference
  1439. refCount = 1;
  1440. gcFlag = false;
  1441. // Keep a reference to the engine for as long as we live
  1442. // We don't increment the reference counter, because the
  1443. // engine will hold a pointer to the object.
  1444. this->engine = engine;
  1445. // Urho3D: garbage collection disabled
  1446. /*
  1447. // Notify the garbage collector of this object
  1448. // TODO: The object type should be cached
  1449. engine->NotifyGarbageCollectorOfNewObject(this, engine->GetObjectTypeByName("Dictionary"));
  1450. */
  1451. }
  1452. CScriptDictionary::CScriptDictionary(asBYTE *buffer)
  1453. {
  1454. // We start with one reference
  1455. refCount = 1;
  1456. gcFlag = false;
  1457. // This constructor will always be called from a script
  1458. // so we can get the engine from the active context
  1459. asIScriptContext *ctx = asGetActiveContext();
  1460. engine = ctx->GetEngine();
  1461. // Urho3D: garbage collection disabled
  1462. /*
  1463. // Notify the garbage collector of this object
  1464. // TODO: The type id should be cached
  1465. engine->NotifyGarbageCollectorOfNewObject(this, engine->GetObjectTypeByName("Dictionary"));
  1466. */
  1467. // Initialize the dictionary from the buffer
  1468. asUINT length = *(asUINT*)buffer;
  1469. buffer += 4;
  1470. while( length-- )
  1471. {
  1472. // Align the buffer pointer on a 4 byte boundary in
  1473. // case previous value was smaller than 4 bytes
  1474. if( asPWORD(buffer) & 0x3 )
  1475. buffer += 4 - (asPWORD(buffer) & 0x3);
  1476. // Get the name value pair from the buffer and insert it in the dictionary
  1477. String name = *(String*)buffer;
  1478. buffer += sizeof(String);
  1479. // Get the type id of the value
  1480. int typeId = *(int*)buffer;
  1481. buffer += sizeof(int);
  1482. // Depending on the type id, the value will inline in the buffer or a pointer
  1483. void *ref = (void*)buffer;
  1484. if( typeId >= asTYPEID_INT8 && typeId <= asTYPEID_DOUBLE )
  1485. {
  1486. // Convert primitive values to either int64 or double, so we can use the overloaded Set methods
  1487. asINT64 i64;
  1488. double d;
  1489. switch( typeId )
  1490. {
  1491. case asTYPEID_INT8: i64 = *(char*)ref; break;
  1492. case asTYPEID_INT16: i64 = *(short*)ref; break;
  1493. case asTYPEID_INT32: i64 = *(int*)ref; break;
  1494. case asTYPEID_INT64: i64 = *(asINT64*)ref; break;
  1495. case asTYPEID_UINT8: i64 = *(unsigned char*)ref; break;
  1496. case asTYPEID_UINT16: i64 = *(unsigned short*)ref; break;
  1497. case asTYPEID_UINT32: i64 = *(unsigned int*)ref; break;
  1498. case asTYPEID_UINT64: i64 = *(asINT64*)ref; break;
  1499. case asTYPEID_FLOAT: d = *(float*)ref; break;
  1500. case asTYPEID_DOUBLE: d = *(double*)ref; break;
  1501. }
  1502. if( typeId >= asTYPEID_FLOAT )
  1503. Set(name, d);
  1504. else
  1505. Set(name, i64);
  1506. }
  1507. else
  1508. {
  1509. if( (typeId & asTYPEID_MASK_OBJECT) &&
  1510. !(typeId & asTYPEID_OBJHANDLE) &&
  1511. (engine->GetTypeInfoById(typeId)->GetFlags() & asOBJ_REF))
  1512. {
  1513. // Dereference the pointer to get the reference to the actual object
  1514. ref = *(void**)ref;
  1515. }
  1516. Set(name, ref, typeId);
  1517. }
  1518. // Advance the buffer pointer with the size of the value
  1519. if( typeId & asTYPEID_MASK_OBJECT )
  1520. {
  1521. asITypeInfo *ot = engine->GetTypeInfoById(typeId);
  1522. if( ot->GetFlags() & asOBJ_VALUE )
  1523. buffer += ot->GetSize();
  1524. else
  1525. buffer += sizeof(void*);
  1526. }
  1527. else if( typeId == 0 )
  1528. {
  1529. // null pointer
  1530. buffer += sizeof(void*);
  1531. }
  1532. else
  1533. {
  1534. buffer += engine->GetSizeOfPrimitiveType(typeId);
  1535. }
  1536. }
  1537. }
  1538. CScriptDictionary::~CScriptDictionary()
  1539. {
  1540. // Delete all keys and values
  1541. DeleteAll();
  1542. }
  1543. void CScriptDictionary::AddRef() const
  1544. {
  1545. // We need to clear the GC flag
  1546. gcFlag = false;
  1547. asAtomicInc(refCount);
  1548. }
  1549. void CScriptDictionary::Release() const
  1550. {
  1551. // We need to clear the GC flag
  1552. gcFlag = false;
  1553. if( asAtomicDec(refCount) == 0 )
  1554. {
  1555. this->~CScriptDictionary();
  1556. asFreeMem(const_cast<CScriptDictionary*>(this));
  1557. }
  1558. }
  1559. int CScriptDictionary::GetRefCount()
  1560. {
  1561. return refCount;
  1562. }
  1563. void CScriptDictionary::SetGCFlag()
  1564. {
  1565. gcFlag = true;
  1566. }
  1567. bool CScriptDictionary::GetGCFlag()
  1568. {
  1569. return gcFlag;
  1570. }
  1571. void CScriptDictionary::EnumReferences(asIScriptEngine *engine)
  1572. {
  1573. // Call the gc enum callback for each of the objects
  1574. HashMap<String, CScriptDictValue>::Iterator it;
  1575. for( it = dict.Begin(); it != dict.End(); it++ )
  1576. {
  1577. if( it->second_.m_typeId & asTYPEID_MASK_OBJECT )
  1578. engine->GCEnumCallback(it->second_.m_valueObj);
  1579. }
  1580. }
  1581. void CScriptDictionary::ReleaseAllReferences(asIScriptEngine * /*engine*/)
  1582. {
  1583. // We're being told to release all references in
  1584. // order to break circular references for dead objects
  1585. DeleteAll();
  1586. }
  1587. CScriptDictionary &CScriptDictionary::operator =(const CScriptDictionary &other)
  1588. {
  1589. // Clear everything we had before
  1590. DeleteAll();
  1591. // Do a shallow copy of the dictionary
  1592. HashMap<String, CScriptDictValue>::ConstIterator it;
  1593. for( it = other.dict.Begin(); it != other.dict.End(); it++ )
  1594. {
  1595. if( it->second_.m_typeId & asTYPEID_OBJHANDLE )
  1596. Set(it->first_, (void*)&it->second_.m_valueObj, it->second_.m_typeId);
  1597. else if( it->second_.m_typeId & asTYPEID_MASK_OBJECT )
  1598. Set(it->first_, (void*)it->second_.m_valueObj, it->second_.m_typeId);
  1599. else
  1600. Set(it->first_, (void*)&it->second_.m_valueInt, it->second_.m_typeId);
  1601. }
  1602. return *this;
  1603. }
  1604. CScriptDictValue *CScriptDictionary::operator[](const String &key)
  1605. {
  1606. // Return the existing value if it exists, else insert an empty value
  1607. HashMap<String, CScriptDictValue>::Iterator it;
  1608. it = dict.Find(key);
  1609. if( it == dict.End() )
  1610. it = dict.Insert(MakePair(key, CScriptDictValue()));
  1611. return &it->second_;
  1612. }
  1613. const CScriptDictValue *CScriptDictionary::operator[](const String &key) const
  1614. {
  1615. // Return the existing value if it exists
  1616. HashMap<String, CScriptDictValue>::ConstIterator it;
  1617. it = dict.Find(key);
  1618. if( it != dict.End() )
  1619. return &it->second_;
  1620. // Else raise an exception
  1621. asIScriptContext *ctx = asGetActiveContext();
  1622. if( ctx )
  1623. ctx->SetException("Invalid access to non-existing value");
  1624. return 0;
  1625. }
  1626. void CScriptDictionary::Set(const String &key, void *value, int typeId)
  1627. {
  1628. HashMap<String, CScriptDictValue>::Iterator it;
  1629. it = dict.Find(key);
  1630. if( it == dict.End() )
  1631. it = dict.Insert(MakePair(key, CScriptDictValue()));
  1632. it->second_.Set(engine, value, typeId);
  1633. }
  1634. // This overloaded method is implemented so that all integer and
  1635. // unsigned integers types will be stored in the dictionary as int64
  1636. // through implicit conversions. This simplifies the management of the
  1637. // numeric types when the script retrieves the stored value using a
  1638. // different type.
  1639. void CScriptDictionary::Set(const String &key, const asINT64 &value)
  1640. {
  1641. Set(key, const_cast<asINT64*>(&value), asTYPEID_INT64);
  1642. }
  1643. // This overloaded method is implemented so that all floating point types
  1644. // will be stored in the dictionary as double through implicit conversions.
  1645. // This simplifies the management of the numeric types when the script
  1646. // retrieves the stored value using a different type.
  1647. void CScriptDictionary::Set(const String &key, const double &value)
  1648. {
  1649. Set(key, const_cast<double*>(&value), asTYPEID_DOUBLE);
  1650. }
  1651. // Returns true if the value was successfully retrieved
  1652. bool CScriptDictionary::Get(const String &key, void *value, int typeId) const
  1653. {
  1654. HashMap<String, CScriptDictValue>::ConstIterator it;
  1655. it = dict.Find(key);
  1656. if( it != dict.End() )
  1657. return it->second_.Get(engine, value, typeId);
  1658. // AngelScript has already initialized the value with a default value,
  1659. // so we don't have to do anything if we don't find the element, or if
  1660. // the element is incompatible with the requested type.
  1661. return false;
  1662. }
  1663. // Returns the type id of the stored value
  1664. int CScriptDictionary::GetTypeId(const String &key) const
  1665. {
  1666. HashMap<String, CScriptDictValue>::ConstIterator it;
  1667. it = dict.Find(key);
  1668. if( it != dict.End() )
  1669. return it->second_.m_typeId;
  1670. return -1;
  1671. }
  1672. bool CScriptDictionary::Get(const String &key, asINT64 &value) const
  1673. {
  1674. return Get(key, &value, asTYPEID_INT64);
  1675. }
  1676. bool CScriptDictionary::Get(const String &key, double &value) const
  1677. {
  1678. return Get(key, &value, asTYPEID_DOUBLE);
  1679. }
  1680. bool CScriptDictionary::Exists(const String &key) const
  1681. {
  1682. HashMap<String, CScriptDictValue>::ConstIterator it;
  1683. it = dict.Find(key);
  1684. if( it != dict.End() )
  1685. return true;
  1686. return false;
  1687. }
  1688. bool CScriptDictionary::IsEmpty() const
  1689. {
  1690. if( dict.Size() == 0 )
  1691. return true;
  1692. return false;
  1693. }
  1694. asUINT CScriptDictionary::GetSize() const
  1695. {
  1696. return asUINT(dict.Size());
  1697. }
  1698. void CScriptDictionary::Delete(const String &key)
  1699. {
  1700. HashMap<String, CScriptDictValue>::Iterator it;
  1701. it = dict.Find(key);
  1702. if( it != dict.End() )
  1703. {
  1704. it->second_.FreeValue(engine);
  1705. dict.Erase(it);
  1706. }
  1707. }
  1708. void CScriptDictionary::DeleteAll()
  1709. {
  1710. HashMap<String, CScriptDictValue>::Iterator it;
  1711. for( it = dict.Begin(); it != dict.End(); it++ )
  1712. it->second_.FreeValue(engine);
  1713. dict.Clear();
  1714. }
  1715. CScriptArray* CScriptDictionary::GetKeys() const
  1716. {
  1717. // TODO: optimize: The string array type should only be determined once.
  1718. // It should be recomputed when registering the dictionary class.
  1719. // Only problem is if multiple engines are used, as they may not
  1720. // share the same type id. Alternatively it can be stored in the
  1721. // user data for the dictionary type.
  1722. asITypeInfo *ot = engine->GetTypeInfoByDecl("Array<String>");
  1723. // Create the array object
  1724. CScriptArray *array = CScriptArray::Create(ot, asUINT(dict.Size()));
  1725. long current = -1;
  1726. HashMap<String, CScriptDictValue>::ConstIterator it;
  1727. for( it = dict.Begin(); it != dict.End(); it++ )
  1728. {
  1729. current++;
  1730. *(String*)array->At(current) = it->first_;
  1731. }
  1732. return array;
  1733. }
  1734. void ScriptDictionaryFactory_Generic(asIScriptGeneric *gen)
  1735. {
  1736. *(CScriptDictionary**)gen->GetAddressOfReturnLocation() = CScriptDictionary::Create(gen->GetEngine());
  1737. }
  1738. void ScriptDictionaryListFactory_Generic(asIScriptGeneric *gen)
  1739. {
  1740. asBYTE *buffer = (asBYTE*)gen->GetArgAddress(0);
  1741. *(CScriptDictionary**)gen->GetAddressOfReturnLocation() = CScriptDictionary::Create(buffer);
  1742. }
  1743. CScriptDictValue::CScriptDictValue()
  1744. {
  1745. m_valueObj = 0;
  1746. m_typeId = 0;
  1747. }
  1748. CScriptDictValue::CScriptDictValue(asIScriptEngine *engine, void *value, int typeId)
  1749. {
  1750. m_valueObj = 0;
  1751. m_typeId = 0;
  1752. Set(engine, value, typeId);
  1753. }
  1754. CScriptDictValue::~CScriptDictValue()
  1755. {
  1756. // Must not hold an object when destroyed, as then the object will never be freed
  1757. assert( (m_typeId & asTYPEID_MASK_OBJECT) == 0 );
  1758. }
  1759. void CScriptDictValue::FreeValue(asIScriptEngine *engine)
  1760. {
  1761. // If it is a handle or a ref counted object, call release
  1762. if( m_typeId & asTYPEID_MASK_OBJECT )
  1763. {
  1764. // Let the engine release the object
  1765. engine->ReleaseScriptObject(m_valueObj, engine->GetTypeInfoById(m_typeId));
  1766. m_valueObj = 0;
  1767. m_typeId = 0;
  1768. }
  1769. // For primitives, there's nothing to do
  1770. }
  1771. void CScriptDictValue::Set(asIScriptEngine *engine, void *value, int typeId)
  1772. {
  1773. FreeValue(engine);
  1774. m_typeId = typeId;
  1775. if( typeId & asTYPEID_OBJHANDLE )
  1776. {
  1777. // We're receiving a reference to the handle, so we need to dereference it
  1778. m_valueObj = *(void**)value;
  1779. engine->AddRefScriptObject(m_valueObj, engine->GetTypeInfoById(typeId));
  1780. }
  1781. else if( typeId & asTYPEID_MASK_OBJECT )
  1782. {
  1783. // Create a copy of the object
  1784. m_valueObj = engine->CreateScriptObjectCopy(value, engine->GetTypeInfoById(typeId));
  1785. }
  1786. else
  1787. {
  1788. // Copy the primitive value
  1789. // We receive a pointer to the value.
  1790. int size = engine->GetSizeOfPrimitiveType(typeId);
  1791. memcpy(&m_valueInt, value, size);
  1792. }
  1793. }
  1794. // This overloaded method is implemented so that all integer and
  1795. // unsigned integers types will be stored in the dictionary as int64
  1796. // through implicit conversions. This simplifies the management of the
  1797. // numeric types when the script retrieves the stored value using a
  1798. // different type.
  1799. void CScriptDictValue::Set(asIScriptEngine *engine, const asINT64 &value)
  1800. {
  1801. Set(engine, const_cast<asINT64*>(&value), asTYPEID_INT64);
  1802. }
  1803. // This overloaded method is implemented so that all floating point types
  1804. // will be stored in the dictionary as double through implicit conversions.
  1805. // This simplifies the management of the numeric types when the script
  1806. // retrieves the stored value using a different type.
  1807. void CScriptDictValue::Set(asIScriptEngine *engine, const double &value)
  1808. {
  1809. Set(engine, const_cast<double*>(&value), asTYPEID_DOUBLE);
  1810. }
  1811. bool CScriptDictValue::Get(asIScriptEngine *engine, void *value, int typeId) const
  1812. {
  1813. // Return the value
  1814. if( typeId & asTYPEID_OBJHANDLE )
  1815. {
  1816. // A handle can be retrieved if the stored type is a handle of same or compatible type
  1817. // or if the stored type is an object that implements the interface that the handle refer to.
  1818. void* cast = 0x0;
  1819. if ((m_typeId & asTYPEID_MASK_OBJECT) &&
  1820. engine->RefCastObject(m_valueObj, engine->GetTypeInfoById(m_typeId), engine->GetTypeInfoById(typeId), &cast) >= 0)
  1821. {
  1822. *(void**)value = m_valueObj;
  1823. return true;
  1824. }
  1825. }
  1826. else if( typeId & asTYPEID_MASK_OBJECT )
  1827. {
  1828. // Verify that the copy can be made
  1829. bool isCompatible = false;
  1830. if( m_typeId == typeId )
  1831. isCompatible = true;
  1832. // Copy the object into the given reference
  1833. if( isCompatible )
  1834. {
  1835. engine->AssignScriptObject(value, m_valueObj, engine->GetTypeInfoById(typeId));
  1836. return true;
  1837. }
  1838. }
  1839. else
  1840. {
  1841. if( m_typeId == typeId )
  1842. {
  1843. int size = engine->GetSizeOfPrimitiveType(typeId);
  1844. memcpy(value, &m_valueInt, size);
  1845. return true;
  1846. }
  1847. // We know all numbers are stored as either int64 or double, since we register overloaded functions for those
  1848. if( m_typeId == asTYPEID_INT64 && typeId == asTYPEID_DOUBLE )
  1849. {
  1850. *(double*)value = double(m_valueInt);
  1851. return true;
  1852. }
  1853. else if( m_typeId == asTYPEID_DOUBLE && typeId == asTYPEID_INT64 )
  1854. {
  1855. *(asINT64*)value = asINT64(m_valueFlt);
  1856. return true;
  1857. }
  1858. }
  1859. // It was not possible to retrieve the value using the desired typeId
  1860. return false;
  1861. }
  1862. bool CScriptDictValue::Get(asIScriptEngine *engine, asINT64 &value) const
  1863. {
  1864. return Get(engine, &value, asTYPEID_INT64);
  1865. }
  1866. bool CScriptDictValue::Get(asIScriptEngine *engine, double &value) const
  1867. {
  1868. return Get(engine, &value, asTYPEID_DOUBLE);
  1869. }
  1870. int CScriptDictValue::GetTypeId() const
  1871. {
  1872. return m_typeId;
  1873. }
  1874. static void CScriptDictValue_Construct(void *mem)
  1875. {
  1876. new(mem) CScriptDictValue();
  1877. }
  1878. static void CScriptDictValue_Destruct(CScriptDictValue *obj)
  1879. {
  1880. asIScriptContext *ctx = asGetActiveContext();
  1881. if( ctx )
  1882. {
  1883. asIScriptEngine *engine = ctx->GetEngine();
  1884. obj->FreeValue(engine);
  1885. }
  1886. obj->~CScriptDictValue();
  1887. }
  1888. static CScriptDictValue &CScriptDictValue_opAssign(void *ref, int typeId, CScriptDictValue *obj)
  1889. {
  1890. asIScriptContext *ctx = asGetActiveContext();
  1891. if( ctx )
  1892. {
  1893. asIScriptEngine *engine = ctx->GetEngine();
  1894. obj->Set(engine, ref, typeId);
  1895. }
  1896. return *obj;
  1897. }
  1898. static CScriptDictValue &CScriptDictValue_opAssign(double val, CScriptDictValue *obj)
  1899. {
  1900. return CScriptDictValue_opAssign(&val, asTYPEID_DOUBLE, obj);
  1901. }
  1902. static CScriptDictValue &CScriptDictValue_opAssign(asINT64 val, CScriptDictValue *obj)
  1903. {
  1904. return CScriptDictValue_opAssign(&val, asTYPEID_INT64, obj);
  1905. }
  1906. static void CScriptDictValue_opCast(void *ref, int typeId, CScriptDictValue *obj)
  1907. {
  1908. asIScriptContext *ctx = asGetActiveContext();
  1909. if( ctx )
  1910. {
  1911. asIScriptEngine *engine = ctx->GetEngine();
  1912. obj->Get(engine, ref, typeId);
  1913. }
  1914. }
  1915. static asINT64 CScriptDictValue_opConvInt(CScriptDictValue *obj)
  1916. {
  1917. asINT64 value;
  1918. CScriptDictValue_opCast(&value, asTYPEID_INT64, obj);
  1919. return value;
  1920. }
  1921. static double CScriptDictValue_opConvDouble(CScriptDictValue *obj)
  1922. {
  1923. double value;
  1924. CScriptDictValue_opCast(&value, asTYPEID_DOUBLE, obj);
  1925. return value;
  1926. }
  1927. void RegisterDictionary(asIScriptEngine *engine)
  1928. {
  1929. engine->RegisterObjectType("DictionaryValue", sizeof(CScriptDictValue), asOBJ_VALUE | asOBJ_ASHANDLE | asOBJ_APP_CLASS_CD);
  1930. engine->RegisterObjectBehaviour("DictionaryValue", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(CScriptDictValue_Construct), asCALL_CDECL_OBJLAST);
  1931. engine->RegisterObjectBehaviour("DictionaryValue", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(CScriptDictValue_Destruct), asCALL_CDECL_OBJLAST);
  1932. engine->RegisterObjectMethod("DictionaryValue", "DictionaryValue &opHndlAssign(const ?&in)", asFUNCTIONPR(CScriptDictValue_opAssign, (void *, int, CScriptDictValue*), CScriptDictValue &), asCALL_CDECL_OBJLAST);
  1933. engine->RegisterObjectMethod("DictionaryValue", "DictionaryValue &opAssign(const ?&in)", asFUNCTIONPR(CScriptDictValue_opAssign, (void *, int, CScriptDictValue*), CScriptDictValue &), asCALL_CDECL_OBJLAST);
  1934. engine->RegisterObjectMethod("DictionaryValue", "DictionaryValue &opAssign(double)", asFUNCTIONPR(CScriptDictValue_opAssign, (double, CScriptDictValue*), CScriptDictValue &), asCALL_CDECL_OBJLAST);
  1935. engine->RegisterObjectMethod("DictionaryValue", "DictionaryValue &opAssign(int64)", asFUNCTIONPR(CScriptDictValue_opAssign, (asINT64, CScriptDictValue*), CScriptDictValue &), asCALL_CDECL_OBJLAST);
  1936. engine->RegisterObjectMethod("DictionaryValue", "void opCast(?&out)", asFUNCTIONPR(CScriptDictValue_opCast, (void *, int, CScriptDictValue*), void), asCALL_CDECL_OBJLAST);
  1937. engine->RegisterObjectMethod("DictionaryValue", "void opConv(?&out)", asFUNCTIONPR(CScriptDictValue_opCast, (void *, int, CScriptDictValue*), void), asCALL_CDECL_OBJLAST);
  1938. engine->RegisterObjectMethod("DictionaryValue", "int64 opConv()", asFUNCTIONPR(CScriptDictValue_opConvInt, (CScriptDictValue*), asINT64), asCALL_CDECL_OBJLAST);
  1939. engine->RegisterObjectMethod("DictionaryValue", "double opConv()", asFUNCTIONPR(CScriptDictValue_opConvDouble, (CScriptDictValue*), double), asCALL_CDECL_OBJLAST);
  1940. engine->RegisterObjectType("Dictionary", sizeof(CScriptDictionary), asOBJ_REF);
  1941. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_FACTORY, "Dictionary@ f()", asFUNCTION(ScriptDictionaryFactory_Generic), asCALL_GENERIC);
  1942. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_LIST_FACTORY, "Dictionary @f(int &in) {repeat {String, ?}}", asFUNCTION(ScriptDictionaryListFactory_Generic), asCALL_GENERIC);
  1943. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_ADDREF, "void f()", asMETHOD(CScriptDictionary,AddRef), asCALL_THISCALL);
  1944. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_RELEASE, "void f()", asMETHOD(CScriptDictionary,Release), asCALL_THISCALL);
  1945. engine->RegisterObjectMethod("Dictionary", "Dictionary &opAssign(const Dictionary &in)", asMETHODPR(CScriptDictionary, operator=, (const CScriptDictionary &), CScriptDictionary&), asCALL_THISCALL);
  1946. engine->RegisterObjectMethod("Dictionary", "void Set(const String &in, const ?&in)", asMETHODPR(CScriptDictionary,Set,(const String&,void*,int),void), asCALL_THISCALL);
  1947. engine->RegisterObjectMethod("Dictionary", "bool Get(const String &in, ?&out) const", asMETHODPR(CScriptDictionary,Get,(const String&,void*,int) const,bool), asCALL_THISCALL);
  1948. engine->RegisterObjectMethod("Dictionary", "void Set(const String &in, const int64&in)", asMETHODPR(CScriptDictionary,Set,(const String&,const asINT64&),void), asCALL_THISCALL);
  1949. engine->RegisterObjectMethod("Dictionary", "bool Get(const String &in, int64&out) const", asMETHODPR(CScriptDictionary,Get,(const String&,asINT64&) const,bool), asCALL_THISCALL);
  1950. engine->RegisterObjectMethod("Dictionary", "void Set(const String &in, const double&in)", asMETHODPR(CScriptDictionary,Set,(const String&,const double&),void), asCALL_THISCALL);
  1951. engine->RegisterObjectMethod("Dictionary", "bool Get(const String &in, double&out) const", asMETHODPR(CScriptDictionary,Get,(const String&,double&) const,bool), asCALL_THISCALL);
  1952. engine->RegisterObjectMethod("Dictionary", "bool Exists(const String &in) const", asMETHOD(CScriptDictionary,Exists), asCALL_THISCALL);
  1953. engine->RegisterObjectMethod("Dictionary", "bool get_empty() const", asMETHOD(CScriptDictionary, IsEmpty), asCALL_THISCALL);
  1954. engine->RegisterObjectMethod("Dictionary", "uint get_length() const", asMETHOD(CScriptDictionary, GetSize), asCALL_THISCALL);
  1955. engine->RegisterObjectMethod("Dictionary", "void Erase(const String &in)", asMETHOD(CScriptDictionary,Delete), asCALL_THISCALL);
  1956. engine->RegisterObjectMethod("Dictionary", "void Clear()", asMETHOD(CScriptDictionary,DeleteAll), asCALL_THISCALL);
  1957. engine->RegisterObjectMethod("Dictionary", "Array<String> @get_keys() const", asMETHOD(CScriptDictionary,GetKeys), asCALL_THISCALL);
  1958. engine->RegisterObjectMethod("Dictionary", "DictionaryValue &opIndex(const String &in)", asMETHODPR(CScriptDictionary, operator[], (const String &), CScriptDictValue*), asCALL_THISCALL);
  1959. engine->RegisterObjectMethod("Dictionary", "const DictionaryValue &opIndex(const String &in) const", asMETHODPR(CScriptDictionary, operator[], (const String &) const, const CScriptDictValue*), asCALL_THISCALL);
  1960. }
  1961. static String StringFactory(asUINT length, const char* s)
  1962. {
  1963. return String(s, length);
  1964. }
  1965. static void ConstructString(String* ptr)
  1966. {
  1967. new(ptr) String();
  1968. }
  1969. static void ConstructStringCopy(const String& str, String* ptr)
  1970. {
  1971. new(ptr) String(str);
  1972. }
  1973. static void DestructString(String* ptr)
  1974. {
  1975. ptr->~String();
  1976. }
  1977. static char* StringCharAt(unsigned i, String& str)
  1978. {
  1979. if (i >= str.Length())
  1980. {
  1981. asIScriptContext* context = asGetActiveContext();
  1982. if (context)
  1983. context->SetException("Index out of bounds");
  1984. return 0;
  1985. }
  1986. return &str[i];
  1987. }
  1988. static int StringCmp(const String& lhs, const String& rhs)
  1989. {
  1990. int cmp = 0;
  1991. if (lhs < rhs)
  1992. cmp = -1;
  1993. else if (lhs > rhs)
  1994. cmp = 1;
  1995. return cmp;
  1996. }
  1997. void StringResize(unsigned newSize, String& str)
  1998. {
  1999. unsigned oldSize = str.Length();
  2000. str.Resize(newSize);
  2001. for (unsigned i = oldSize; i < newSize; ++i)
  2002. str[i] = ' ';
  2003. }
  2004. static void ConstructStringInt(int value, String* ptr)
  2005. {
  2006. new(ptr) String(value);
  2007. }
  2008. static void ConstructStringUInt(unsigned value, String* ptr)
  2009. {
  2010. new(ptr) String(value);
  2011. }
  2012. static void ConstructStringFloat(float value, String* ptr)
  2013. {
  2014. new(ptr) String(value);
  2015. }
  2016. static void ConstructStringDouble(double value, String* ptr)
  2017. {
  2018. new(ptr)String(value);
  2019. }
  2020. static void ConstructStringBool(bool value, String* ptr)
  2021. {
  2022. new(ptr) String(value);
  2023. }
  2024. static String& StringAssignInt(int value, String& str)
  2025. {
  2026. str = String(value);
  2027. return str;
  2028. }
  2029. static String& StringAddAssignInt(int value, String& str)
  2030. {
  2031. str += String(value);
  2032. return str;
  2033. }
  2034. static String StringAddInt(int value, const String& str)
  2035. {
  2036. return str + String(value);
  2037. }
  2038. static String StringAddIntReverse(int value, const String& str)
  2039. {
  2040. return String(value) + str;
  2041. }
  2042. static String& StringAssignUInt(unsigned value, String& str)
  2043. {
  2044. str = String(value);
  2045. return str;
  2046. }
  2047. static String& StringAddAssignUInt(unsigned value, String& str)
  2048. {
  2049. str += String(value);
  2050. return str;
  2051. }
  2052. static String StringAddUInt(unsigned value, const String& str)
  2053. {
  2054. return str + String(value);
  2055. }
  2056. static String StringAddUIntReverse(unsigned value, const String& str)
  2057. {
  2058. return String(value) + str;
  2059. }
  2060. static String& StringAssignFloat(float value, String& str)
  2061. {
  2062. str = String(value);
  2063. return str;
  2064. }
  2065. static String& StringAddAssignFloat(float value, String& str)
  2066. {
  2067. str += String(value);
  2068. return str;
  2069. }
  2070. static String StringAddFloat(float value, const String& str)
  2071. {
  2072. return str + String(value);
  2073. }
  2074. static String StringAddFloatReverse(float value, const String& str)
  2075. {
  2076. return String(value) + str;
  2077. }
  2078. static String& StringAssignDouble(double value, String& str)
  2079. {
  2080. str = String(value);
  2081. return str;
  2082. }
  2083. static String& StringAddAssignDouble(double value, String& str)
  2084. {
  2085. str += String(value);
  2086. return str;
  2087. }
  2088. static String StringAddDouble(double value, const String& str)
  2089. {
  2090. return str + String(value);
  2091. }
  2092. static String StringAddDoubleReverse(double value, const String& str)
  2093. {
  2094. return String(value) + str;
  2095. }
  2096. static String& StringAssignBool(bool value, String& str)
  2097. {
  2098. str = String(value);
  2099. return str;
  2100. }
  2101. static String& StringAddAssignBool(bool value, String& str)
  2102. {
  2103. str += String(value);
  2104. return str;
  2105. }
  2106. static String StringAddBool(bool value, const String& str)
  2107. {
  2108. return str + String(value);
  2109. }
  2110. static String StringAddBoolReverse(bool value, const String& str)
  2111. {
  2112. return String(value) + str;
  2113. }
  2114. static void StringSetUTF8FromLatin1(const String& src, String& str)
  2115. {
  2116. str.SetUTF8FromLatin1(src.CString());
  2117. }
  2118. static const unsigned NPOS = String::NPOS; // workaround for GCC
  2119. void RegisterString(asIScriptEngine *engine)
  2120. {
  2121. engine->RegisterGlobalProperty("const uint NPOS", (void*)&NPOS);
  2122. engine->RegisterObjectType("String", sizeof(String), asOBJ_VALUE | asOBJ_APP_CLASS_CDAK);
  2123. engine->RegisterStringFactory("String", asFUNCTION(StringFactory), asCALL_CDECL);
  2124. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ConstructString), asCALL_CDECL_OBJLAST);
  2125. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(const String&in)", asFUNCTION(ConstructStringCopy), asCALL_CDECL_OBJLAST);
  2126. engine->RegisterObjectBehaviour("String", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(DestructString), asCALL_CDECL_OBJLAST);
  2127. engine->RegisterObjectMethod("String", "String& opAssign(const String&in)", asMETHODPR(String, operator =, (const String&), String&), asCALL_THISCALL);
  2128. engine->RegisterObjectMethod("String", "String& opAddAssign(const String&in)", asMETHODPR(String, operator +=, (const String&), String&), asCALL_THISCALL);
  2129. engine->RegisterObjectMethod("String", "bool opEquals(const String&in) const", asMETHODPR(String, operator ==, (const String&) const, bool), asCALL_THISCALL);
  2130. engine->RegisterObjectMethod("String", "int opCmp(const String&in) const", asFUNCTION(StringCmp), asCALL_CDECL_OBJFIRST);
  2131. engine->RegisterObjectMethod("String", "String opAdd(const String&in) const", asMETHODPR(String, operator +, (const String&) const, String), asCALL_THISCALL);
  2132. engine->RegisterObjectMethod("String", "uint8 &opIndex(uint)", asFUNCTION(StringCharAt), asCALL_CDECL_OBJLAST);
  2133. engine->RegisterObjectMethod("String", "const uint8 &opIndex(uint) const", asFUNCTION(StringCharAt), asCALL_CDECL_OBJLAST);
  2134. engine->RegisterObjectMethod("String", "void Replace(uint8, uint8, bool caseSensitive = true)", asMETHODPR(String, Replace, (char, char, bool), void), asCALL_THISCALL);
  2135. engine->RegisterObjectMethod("String", "void Replace(const String&in, const String&in, bool caseSensitive = true)", asMETHODPR(String, Replace, (const String&, const String&, bool), void), asCALL_THISCALL);
  2136. engine->RegisterObjectMethod("String", "String Replaced(uint8, uint8, bool caseSensitive = true) const", asMETHODPR(String, Replaced, (char, char, bool) const, String), asCALL_THISCALL);
  2137. engine->RegisterObjectMethod("String", "String Replaced(const String&in, const String&in, bool caseSensitive = true) const", asMETHODPR(String, Replaced, (const String&, const String&, bool) const, String), asCALL_THISCALL);
  2138. engine->RegisterObjectMethod("String", "void Resize(uint)", asFUNCTION(StringResize), asCALL_CDECL_OBJLAST);
  2139. engine->RegisterObjectMethod("String", "uint Find(const String&in, uint start = 0, bool caseSensitive = true) const", asMETHODPR(String, Find, (const String&, unsigned, bool) const, unsigned), asCALL_THISCALL);
  2140. engine->RegisterObjectMethod("String", "uint Find(uint8, uint start = 0, bool caseSensitive = true) const", asMETHODPR(String, Find, (char, unsigned, bool) const, unsigned), asCALL_THISCALL);
  2141. 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);
  2142. engine->RegisterObjectMethod("String", "uint FindLast(uint8, uint start = 0xffffffff, bool caseSensitive = true) const", asMETHODPR(String, FindLast, (char, unsigned, bool) const, unsigned), asCALL_THISCALL);
  2143. engine->RegisterObjectMethod("String", "bool StartsWith(const String&in, bool caseSensitive = true) const", asMETHOD(String, StartsWith), asCALL_THISCALL);
  2144. engine->RegisterObjectMethod("String", "bool EndsWith(const String&in, bool caseSensitive = true) const", asMETHOD(String, EndsWith), asCALL_THISCALL);
  2145. engine->RegisterObjectMethod("String", "String Substring(uint) const", asMETHODPR(String, Substring, (unsigned) const, String), asCALL_THISCALL);
  2146. engine->RegisterObjectMethod("String", "String Substring(uint, uint) const", asMETHODPR(String, Substring, (unsigned, unsigned) const, String), asCALL_THISCALL);
  2147. engine->RegisterObjectMethod("String", "String ToUpper() const", asMETHOD(String, ToUpper), asCALL_THISCALL);
  2148. engine->RegisterObjectMethod("String", "String ToLower() const", asMETHOD(String, ToLower), asCALL_THISCALL);
  2149. engine->RegisterObjectMethod("String", "String Trimmed() const", asMETHOD(String, Trimmed), asCALL_THISCALL);
  2150. engine->RegisterObjectMethod("String", "void SetUTF8FromLatin1(const String& in)", asFUNCTION(StringSetUTF8FromLatin1), asCALL_CDECL_OBJLAST);
  2151. engine->RegisterObjectMethod("String", "uint get_utf8Length() const", asMETHOD(String, LengthUTF8), asCALL_THISCALL);
  2152. engine->RegisterObjectMethod("String", "uint ByteOffsetUTF8(uint) const", asMETHOD(String, ByteOffsetUTF8), asCALL_THISCALL);
  2153. engine->RegisterObjectMethod("String", "uint NextUTF8Char(uint&) const", asMETHOD(String, NextUTF8Char), asCALL_THISCALL);
  2154. engine->RegisterObjectMethod("String", "uint AtUTF8(uint) const", asMETHOD(String, AtUTF8), asCALL_THISCALL);
  2155. engine->RegisterObjectMethod("String", "void ReplaceUTF8(uint, uint)", asMETHOD(String, ReplaceUTF8), asCALL_THISCALL);
  2156. engine->RegisterObjectMethod("String", "void AppendUTF8(uint)", asMETHOD(String, AppendUTF8), asCALL_THISCALL);
  2157. engine->RegisterObjectMethod("String", "String SubstringUTF8(uint) const", asMETHODPR(String, SubstringUTF8, (unsigned) const, String), asCALL_THISCALL);
  2158. engine->RegisterObjectMethod("String", "String SubstringUTF8(uint, uint) const", asMETHODPR(String, SubstringUTF8, (unsigned, unsigned) const, String), asCALL_THISCALL);
  2159. engine->RegisterObjectMethod("String", "uint get_length() const", asMETHOD(String, Length), asCALL_THISCALL);
  2160. engine->RegisterObjectMethod("String", "bool get_empty() const", asMETHOD(String, Empty), asCALL_THISCALL);
  2161. engine->RegisterObjectMethod("String", "int Compare(const String&in, bool caseSensitive = true) const", asMETHODPR(String, Compare, (const String&, bool) const, int), asCALL_THISCALL);
  2162. engine->RegisterObjectMethod("String", "bool Contains(const String&in, bool caseSensitive = true) const", asMETHODPR(String, Contains, (const String&, bool) const, bool), asCALL_THISCALL);
  2163. engine->RegisterObjectMethod("String", "bool Contains(uint8, bool caseSensitive = true) const", asMETHODPR(String, Contains, (char, bool) const, bool), asCALL_THISCALL);
  2164. engine->RegisterObjectMethod("String", "void Clear()", asMETHOD(String, Clear), asCALL_THISCALL);
  2165. // Register automatic conversion functions for convenience
  2166. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(int)", asFUNCTION(ConstructStringInt), asCALL_CDECL_OBJLAST);
  2167. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(uint)", asFUNCTION(ConstructStringUInt), asCALL_CDECL_OBJLAST);
  2168. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(float)", asFUNCTION(ConstructStringFloat), asCALL_CDECL_OBJLAST);
  2169. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(double)", asFUNCTION(ConstructStringDouble), asCALL_CDECL_OBJLAST);
  2170. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(bool)", asFUNCTION(ConstructStringBool), asCALL_CDECL_OBJLAST);
  2171. engine->RegisterObjectMethod("String", "String& opAssign(int)", asFUNCTION(StringAssignInt), asCALL_CDECL_OBJLAST);
  2172. engine->RegisterObjectMethod("String", "String& opAddAssign(int)", asFUNCTION(StringAddAssignInt), asCALL_CDECL_OBJLAST);
  2173. engine->RegisterObjectMethod("String", "String opAdd(int) const", asFUNCTION(StringAddInt), asCALL_CDECL_OBJLAST);
  2174. engine->RegisterObjectMethod("String", "String opAdd_r(int) const", asFUNCTION(StringAddIntReverse), asCALL_CDECL_OBJLAST);
  2175. engine->RegisterObjectMethod("String", "String& opAssign(uint)", asFUNCTION(StringAssignUInt), asCALL_CDECL_OBJLAST);
  2176. engine->RegisterObjectMethod("String", "String& opAddAssign(uint)", asFUNCTION(StringAddAssignUInt), asCALL_CDECL_OBJLAST);
  2177. engine->RegisterObjectMethod("String", "String opAdd(uint) const", asFUNCTION(StringAddUInt), asCALL_CDECL_OBJLAST);
  2178. engine->RegisterObjectMethod("String", "String opAdd_r(uint) const", asFUNCTION(StringAddUIntReverse), asCALL_CDECL_OBJLAST);
  2179. engine->RegisterObjectMethod("String", "String& opAssign(float)", asFUNCTION(StringAssignFloat), asCALL_CDECL_OBJLAST);
  2180. engine->RegisterObjectMethod("String", "String& opAddAssign(float)", asFUNCTION(StringAddAssignFloat), asCALL_CDECL_OBJLAST);
  2181. engine->RegisterObjectMethod("String", "String opAdd(float) const", asFUNCTION(StringAddFloat), asCALL_CDECL_OBJLAST);
  2182. engine->RegisterObjectMethod("String", "String opAdd_r(float) const", asFUNCTION(StringAddFloatReverse), asCALL_CDECL_OBJLAST);
  2183. engine->RegisterObjectMethod("String", "String& opAssign(double)", asFUNCTION(StringAssignDouble), asCALL_CDECL_OBJLAST);
  2184. engine->RegisterObjectMethod("String", "String& opAddAssign(double)", asFUNCTION(StringAddAssignDouble), asCALL_CDECL_OBJLAST);
  2185. engine->RegisterObjectMethod("String", "String opAdd(double) const", asFUNCTION(StringAddDouble), asCALL_CDECL_OBJLAST);
  2186. engine->RegisterObjectMethod("String", "String opAdd_r(double) const", asFUNCTION(StringAddDoubleReverse), asCALL_CDECL_OBJLAST);
  2187. engine->RegisterObjectMethod("String", "String& opAssign(bool)", asFUNCTION(StringAssignBool), asCALL_CDECL_OBJLAST);
  2188. engine->RegisterObjectMethod("String", "String& opAddAssign(bool)", asFUNCTION(StringAddAssignBool), asCALL_CDECL_OBJLAST);
  2189. engine->RegisterObjectMethod("String", "String opAdd(bool) const", asFUNCTION(StringAddBool), asCALL_CDECL_OBJLAST);
  2190. engine->RegisterObjectMethod("String", "String opAdd_r(bool) const", asFUNCTION(StringAddBoolReverse), asCALL_CDECL_OBJLAST);
  2191. }
  2192. }