array.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. /*************************************************************************/
  2. /* array.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "array.h"
  31. #include "container_type_validate.h"
  32. #include "core/object/class_db.h"
  33. #include "core/object/script_language.h"
  34. #include "core/templates/hashfuncs.h"
  35. #include "core/templates/vector.h"
  36. #include "core/variant/callable.h"
  37. #include "core/variant/variant.h"
  38. class ArrayPrivate {
  39. public:
  40. SafeRefCount refcount;
  41. Vector<Variant> array;
  42. ContainerTypeValidate typed;
  43. };
  44. void Array::_ref(const Array &p_from) const {
  45. ArrayPrivate *_fp = p_from._p;
  46. ERR_FAIL_COND(!_fp); // should NOT happen.
  47. if (_fp == _p) {
  48. return; // whatever it is, nothing to do here move along
  49. }
  50. bool success = _fp->refcount.ref();
  51. ERR_FAIL_COND(!success); // should really not happen either
  52. _unref();
  53. _p = p_from._p;
  54. }
  55. void Array::_unref() const {
  56. if (!_p) {
  57. return;
  58. }
  59. if (_p->refcount.unref()) {
  60. memdelete(_p);
  61. }
  62. _p = nullptr;
  63. }
  64. Variant &Array::operator[](int p_idx) {
  65. return _p->array.write[p_idx];
  66. }
  67. const Variant &Array::operator[](int p_idx) const {
  68. return _p->array[p_idx];
  69. }
  70. int Array::size() const {
  71. return _p->array.size();
  72. }
  73. bool Array::is_empty() const {
  74. return _p->array.is_empty();
  75. }
  76. void Array::clear() {
  77. _p->array.clear();
  78. }
  79. bool Array::operator==(const Array &p_array) const {
  80. return _p == p_array._p;
  81. }
  82. bool Array::operator!=(const Array &p_array) const {
  83. return !operator==(p_array);
  84. }
  85. bool Array::operator<(const Array &p_array) const {
  86. int a_len = size();
  87. int b_len = p_array.size();
  88. int min_cmp = MIN(a_len, b_len);
  89. for (int i = 0; i < min_cmp; i++) {
  90. if (operator[](i) < p_array[i]) {
  91. return true;
  92. } else if (p_array[i] < operator[](i)) {
  93. return false;
  94. }
  95. }
  96. return a_len < b_len;
  97. }
  98. bool Array::operator<=(const Array &p_array) const {
  99. return !operator>(p_array);
  100. }
  101. bool Array::operator>(const Array &p_array) const {
  102. return p_array < *this;
  103. }
  104. bool Array::operator>=(const Array &p_array) const {
  105. return !operator<(p_array);
  106. }
  107. uint32_t Array::hash() const {
  108. uint32_t h = hash_djb2_one_32(0);
  109. for (int i = 0; i < _p->array.size(); i++) {
  110. h = hash_djb2_one_32(_p->array[i].hash(), h);
  111. }
  112. return h;
  113. }
  114. void Array::_assign(const Array &p_array) {
  115. if (_p->typed.type != Variant::OBJECT && _p->typed.type == p_array._p->typed.type) {
  116. //same type or untyped, just reference, should be fine
  117. _ref(p_array);
  118. } else if (_p->typed.type == Variant::NIL) { //from typed to untyped, must copy, but this is cheap anyway
  119. _p->array = p_array._p->array;
  120. } else if (p_array._p->typed.type == Variant::NIL) { //from untyped to typed, must try to check if they are all valid
  121. if (_p->typed.type == Variant::OBJECT) {
  122. //for objects, it needs full validation, either can be converted or fail
  123. for (int i = 0; i < p_array._p->array.size(); i++) {
  124. if (!_p->typed.validate(p_array._p->array[i], "assign")) {
  125. return;
  126. }
  127. }
  128. _p->array = p_array._p->array; //then just copy, which is cheap anyway
  129. } else {
  130. //for non objects, we need to check if there is a valid conversion, which needs to happen one by one, so this is the worst case.
  131. Vector<Variant> new_array;
  132. new_array.resize(p_array._p->array.size());
  133. for (int i = 0; i < p_array._p->array.size(); i++) {
  134. Variant src_val = p_array._p->array[i];
  135. if (src_val.get_type() == _p->typed.type) {
  136. new_array.write[i] = src_val;
  137. } else if (Variant::can_convert_strict(src_val.get_type(), _p->typed.type)) {
  138. Variant *ptr = &src_val;
  139. Callable::CallError ce;
  140. Variant::construct(_p->typed.type, new_array.write[i], (const Variant **)&ptr, 1, ce);
  141. if (ce.error != Callable::CallError::CALL_OK) {
  142. ERR_FAIL_MSG("Unable to convert array index " + itos(i) + " from '" + Variant::get_type_name(src_val.get_type()) + "' to '" + Variant::get_type_name(_p->typed.type) + "'.");
  143. }
  144. } else {
  145. ERR_FAIL_MSG("Unable to convert array index " + itos(i) + " from '" + Variant::get_type_name(src_val.get_type()) + "' to '" + Variant::get_type_name(_p->typed.type) + "'.");
  146. }
  147. }
  148. _p->array = new_array;
  149. }
  150. } else if (_p->typed.can_reference(p_array._p->typed)) { //same type or compatible
  151. _ref(p_array);
  152. } else {
  153. ERR_FAIL_MSG("Assignment of arrays of incompatible types.");
  154. }
  155. }
  156. void Array::operator=(const Array &p_array) {
  157. _assign(p_array);
  158. }
  159. void Array::push_back(const Variant &p_value) {
  160. ERR_FAIL_COND(!_p->typed.validate(p_value, "push_back"));
  161. _p->array.push_back(p_value);
  162. }
  163. void Array::append_array(const Array &p_array) {
  164. ERR_FAIL_COND(!_p->typed.validate(p_array, "append_array"));
  165. _p->array.append_array(p_array._p->array);
  166. }
  167. Error Array::resize(int p_new_size) {
  168. return _p->array.resize(p_new_size);
  169. }
  170. void Array::insert(int p_pos, const Variant &p_value) {
  171. ERR_FAIL_COND(!_p->typed.validate(p_value, "insert"));
  172. _p->array.insert(p_pos, p_value);
  173. }
  174. void Array::erase(const Variant &p_value) {
  175. ERR_FAIL_COND(!_p->typed.validate(p_value, "erase"));
  176. _p->array.erase(p_value);
  177. }
  178. Variant Array::front() const {
  179. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  180. return operator[](0);
  181. }
  182. Variant Array::back() const {
  183. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  184. return operator[](_p->array.size() - 1);
  185. }
  186. int Array::find(const Variant &p_value, int p_from) const {
  187. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find"), -1);
  188. return _p->array.find(p_value, p_from);
  189. }
  190. int Array::rfind(const Variant &p_value, int p_from) const {
  191. if (_p->array.size() == 0) {
  192. return -1;
  193. }
  194. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "rfind"), -1);
  195. if (p_from < 0) {
  196. // Relative offset from the end
  197. p_from = _p->array.size() + p_from;
  198. }
  199. if (p_from < 0 || p_from >= _p->array.size()) {
  200. // Limit to array boundaries
  201. p_from = _p->array.size() - 1;
  202. }
  203. for (int i = p_from; i >= 0; i--) {
  204. if (_p->array[i] == p_value) {
  205. return i;
  206. }
  207. }
  208. return -1;
  209. }
  210. int Array::find_last(const Variant &p_value) const {
  211. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find_last"), -1);
  212. return rfind(p_value);
  213. }
  214. int Array::count(const Variant &p_value) const {
  215. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "count"), 0);
  216. if (_p->array.size() == 0) {
  217. return 0;
  218. }
  219. int amount = 0;
  220. for (int i = 0; i < _p->array.size(); i++) {
  221. if (_p->array[i] == p_value) {
  222. amount++;
  223. }
  224. }
  225. return amount;
  226. }
  227. bool Array::has(const Variant &p_value) const {
  228. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "use 'has'"), false);
  229. return _p->array.find(p_value, 0) != -1;
  230. }
  231. void Array::remove(int p_pos) {
  232. _p->array.remove(p_pos);
  233. }
  234. void Array::set(int p_idx, const Variant &p_value) {
  235. ERR_FAIL_COND(!_p->typed.validate(p_value, "set"));
  236. operator[](p_idx) = p_value;
  237. }
  238. const Variant &Array::get(int p_idx) const {
  239. return operator[](p_idx);
  240. }
  241. Array Array::duplicate(bool p_deep) const {
  242. Array new_arr;
  243. int element_count = size();
  244. new_arr.resize(element_count);
  245. new_arr._p->typed = _p->typed;
  246. for (int i = 0; i < element_count; i++) {
  247. new_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i);
  248. }
  249. return new_arr;
  250. }
  251. int Array::_clamp_slice_index(int p_index) const {
  252. int arr_size = size();
  253. int fixed_index = CLAMP(p_index, -arr_size, arr_size - 1);
  254. if (fixed_index < 0) {
  255. fixed_index = arr_size + fixed_index;
  256. }
  257. return fixed_index;
  258. }
  259. Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const { // like python, but inclusive on upper bound
  260. Array new_arr;
  261. ERR_FAIL_COND_V_MSG(p_step == 0, new_arr, "Array slice step size cannot be zero.");
  262. if (is_empty()) { // Don't try to slice empty arrays.
  263. return new_arr;
  264. }
  265. if (p_step > 0) {
  266. if (p_begin >= size() || p_end < -size()) {
  267. return new_arr;
  268. }
  269. } else { // p_step < 0
  270. if (p_begin < -size() || p_end >= size()) {
  271. return new_arr;
  272. }
  273. }
  274. int begin = _clamp_slice_index(p_begin);
  275. int end = _clamp_slice_index(p_end);
  276. int new_arr_size = MAX(((end - begin + p_step) / p_step), 0);
  277. new_arr.resize(new_arr_size);
  278. if (p_step > 0) {
  279. int dest_idx = 0;
  280. for (int idx = begin; idx <= end; idx += p_step) {
  281. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  282. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  283. }
  284. } else { // p_step < 0
  285. int dest_idx = 0;
  286. for (int idx = begin; idx >= end; idx += p_step) {
  287. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  288. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  289. }
  290. }
  291. return new_arr;
  292. }
  293. struct _ArrayVariantSort {
  294. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  295. bool valid = false;
  296. Variant res;
  297. Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
  298. if (!valid) {
  299. res = false;
  300. }
  301. return res;
  302. }
  303. };
  304. void Array::sort() {
  305. _p->array.sort_custom<_ArrayVariantSort>();
  306. }
  307. struct _ArrayVariantSortCustom {
  308. Callable func;
  309. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  310. const Variant *args[2] = { &p_l, &p_r };
  311. Callable::CallError err;
  312. Variant res;
  313. func.call(args, 2, res, err);
  314. ERR_FAIL_COND_V_MSG(err.error != Callable::CallError::CALL_OK, false,
  315. "Error calling sorting method: " + Variant::get_callable_error_text(func, args, 1, err));
  316. return res;
  317. }
  318. };
  319. void Array::sort_custom(Callable p_callable) {
  320. SortArray<Variant, _ArrayVariantSortCustom, true> avs;
  321. avs.compare.func = p_callable;
  322. avs.sort(_p->array.ptrw(), _p->array.size());
  323. }
  324. void Array::shuffle() {
  325. const int n = _p->array.size();
  326. if (n < 2) {
  327. return;
  328. }
  329. Variant *data = _p->array.ptrw();
  330. for (int i = n - 1; i >= 1; i--) {
  331. const int j = Math::rand() % (i + 1);
  332. const Variant tmp = data[j];
  333. data[j] = data[i];
  334. data[i] = tmp;
  335. }
  336. }
  337. template <typename Less>
  338. _FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) {
  339. int lo = 0;
  340. int hi = p_array.size();
  341. if (p_before) {
  342. while (lo < hi) {
  343. const int mid = (lo + hi) / 2;
  344. if (p_less(p_array.get(mid), p_value)) {
  345. lo = mid + 1;
  346. } else {
  347. hi = mid;
  348. }
  349. }
  350. } else {
  351. while (lo < hi) {
  352. const int mid = (lo + hi) / 2;
  353. if (p_less(p_value, p_array.get(mid))) {
  354. hi = mid;
  355. } else {
  356. lo = mid + 1;
  357. }
  358. }
  359. }
  360. return lo;
  361. }
  362. int Array::bsearch(const Variant &p_value, bool p_before) {
  363. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "binary search"), -1);
  364. return bisect(_p->array, p_value, p_before, _ArrayVariantSort());
  365. }
  366. int Array::bsearch_custom(const Variant &p_value, Callable p_callable, bool p_before) {
  367. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "custom binary search"), -1);
  368. _ArrayVariantSortCustom less;
  369. less.func = p_callable;
  370. return bisect(_p->array, p_value, p_before, less);
  371. }
  372. void Array::invert() {
  373. _p->array.invert();
  374. }
  375. void Array::push_front(const Variant &p_value) {
  376. ERR_FAIL_COND(!_p->typed.validate(p_value, "push_front"));
  377. _p->array.insert(0, p_value);
  378. }
  379. Variant Array::pop_back() {
  380. if (!_p->array.is_empty()) {
  381. int n = _p->array.size() - 1;
  382. Variant ret = _p->array.get(n);
  383. _p->array.resize(n);
  384. return ret;
  385. }
  386. return Variant();
  387. }
  388. Variant Array::pop_front() {
  389. if (!_p->array.is_empty()) {
  390. Variant ret = _p->array.get(0);
  391. _p->array.remove(0);
  392. return ret;
  393. }
  394. return Variant();
  395. }
  396. Variant Array::min() const {
  397. Variant minval;
  398. for (int i = 0; i < size(); i++) {
  399. if (i == 0) {
  400. minval = get(i);
  401. } else {
  402. bool valid;
  403. Variant ret;
  404. Variant test = get(i);
  405. Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
  406. if (!valid) {
  407. return Variant(); //not a valid comparison
  408. }
  409. if (bool(ret)) {
  410. //is less
  411. minval = test;
  412. }
  413. }
  414. }
  415. return minval;
  416. }
  417. Variant Array::max() const {
  418. Variant maxval;
  419. for (int i = 0; i < size(); i++) {
  420. if (i == 0) {
  421. maxval = get(i);
  422. } else {
  423. bool valid;
  424. Variant ret;
  425. Variant test = get(i);
  426. Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
  427. if (!valid) {
  428. return Variant(); //not a valid comparison
  429. }
  430. if (bool(ret)) {
  431. //is less
  432. maxval = test;
  433. }
  434. }
  435. }
  436. return maxval;
  437. }
  438. const void *Array::id() const {
  439. return _p->array.ptr();
  440. }
  441. Array::Array(const Array &p_from, uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  442. _p = memnew(ArrayPrivate);
  443. _p->refcount.init();
  444. set_typed(p_type, p_class_name, p_script);
  445. _assign(p_from);
  446. }
  447. void Array::set_typed(uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  448. ERR_FAIL_COND_MSG(_p->array.size() > 0, "Type can only be set when array is empty.");
  449. ERR_FAIL_COND_MSG(_p->refcount.get() > 1, "Type can only be set when array has no more than one user.");
  450. ERR_FAIL_COND_MSG(_p->typed.type != Variant::NIL, "Type can only be set once.");
  451. ERR_FAIL_COND_MSG(p_class_name != StringName() && p_type != Variant::OBJECT, "Class names can only be set for type OBJECT");
  452. Ref<Script> script = p_script;
  453. ERR_FAIL_COND_MSG(script.is_valid() && p_class_name == StringName(), "Script class can only be set together with base class name");
  454. _p->typed.type = Variant::Type(p_type);
  455. _p->typed.class_name = p_class_name;
  456. _p->typed.script = script;
  457. _p->typed.where = "TypedArray";
  458. }
  459. Array::Array(const Array &p_from) {
  460. _p = nullptr;
  461. _ref(p_from);
  462. }
  463. Array::Array() {
  464. _p = memnew(ArrayPrivate);
  465. _p->refcount.init();
  466. }
  467. Array::~Array() {
  468. _unref();
  469. }